packet.hh revision 5315:30997e988446
1/*
2 * Copyright (c) 2006 The Regents of The University of Michigan
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met: redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer;
9 * redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution;
12 * neither the name of the copyright holders nor the names of its
13 * contributors may be used to endorse or promote products derived from
14 * this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 *
28 * Authors: Ron Dreslinski
29 *          Steve Reinhardt
30 *          Ali Saidi
31 */
32
33/**
34 * @file
35 * Declaration of the Packet class.
36 */
37
38#ifndef __MEM_PACKET_HH__
39#define __MEM_PACKET_HH__
40
41#include <cassert>
42#include <list>
43#include <bitset>
44
45#include "base/compiler.hh"
46#include "base/fast_alloc.hh"
47#include "base/misc.hh"
48#include "base/printable.hh"
49#include "mem/request.hh"
50#include "sim/host.hh"
51#include "sim/core.hh"
52
53
54struct Packet;
55typedef Packet *PacketPtr;
56typedef uint8_t* PacketDataPtr;
57typedef std::list<PacketPtr> PacketList;
58
59class MemCmd
60{
61  public:
62
63    /** List of all commands associated with a packet. */
64    enum Command
65    {
66        InvalidCmd,
67        ReadReq,
68        ReadResp,
69        WriteReq,
70        WriteResp,
71        Writeback,
72        SoftPFReq,
73        HardPFReq,
74        SoftPFResp,
75        HardPFResp,
76        WriteInvalidateReq,
77        WriteInvalidateResp,
78        UpgradeReq,
79        UpgradeResp,
80        ReadExReq,
81        ReadExResp,
82        LoadLockedReq,
83        LoadLockedResp,
84        StoreCondReq,
85        StoreCondResp,
86        SwapReq,
87        SwapResp,
88        // Error responses
89        // @TODO these should be classified as responses rather than
90        // requests; coding them as requests initially for backwards
91        // compatibility
92        NetworkNackError,  // nacked at network layer (not by protocol)
93        InvalidDestError,  // packet dest field invalid
94        BadAddressError,   // memory address invalid
95        // Fake simulator-only commands
96        PrintReq,       // Print state matching address
97        NUM_MEM_CMDS
98    };
99
100  private:
101    /** List of command attributes. */
102    enum Attribute
103    {
104        IsRead,         //!< Data flows from responder to requester
105        IsWrite,        //!< Data flows from requester to responder
106        IsPrefetch,     //!< Not a demand access
107        IsInvalidate,
108        NeedsExclusive, //!< Requires exclusive copy to complete in-cache
109        IsRequest,      //!< Issued by requester
110        IsResponse,     //!< Issue by responder
111        NeedsResponse,  //!< Requester needs response from target
112        IsSWPrefetch,
113        IsHWPrefetch,
114        IsLocked,       //!< Alpha/MIPS LL or SC access
115        HasData,        //!< There is an associated payload
116        IsError,        //!< Error response
117        IsPrint,        //!< Print state matching address (for debugging)
118        NUM_COMMAND_ATTRIBUTES
119    };
120
121    /** Structure that defines attributes and other data associated
122     * with a Command. */
123    struct CommandInfo {
124        /** Set of attribute flags. */
125        const std::bitset<NUM_COMMAND_ATTRIBUTES> attributes;
126        /** Corresponding response for requests; InvalidCmd if no
127         * response is applicable. */
128        const Command response;
129        /** String representation (for printing) */
130        const std::string str;
131    };
132
133    /** Array to map Command enum to associated info. */
134    static const CommandInfo commandInfo[];
135
136  private:
137
138    Command cmd;
139
140    bool testCmdAttrib(MemCmd::Attribute attrib) const {
141        return commandInfo[cmd].attributes[attrib] != 0;
142    }
143
144  public:
145
146    bool isRead() const         { return testCmdAttrib(IsRead); }
147    bool isWrite()  const       { return testCmdAttrib(IsWrite); }
148    bool isRequest() const      { return testCmdAttrib(IsRequest); }
149    bool isResponse() const     { return testCmdAttrib(IsResponse); }
150    bool needsExclusive() const { return testCmdAttrib(NeedsExclusive); }
151    bool needsResponse() const  { return testCmdAttrib(NeedsResponse); }
152    bool isInvalidate() const   { return testCmdAttrib(IsInvalidate); }
153    bool hasData() const        { return testCmdAttrib(HasData); }
154    bool isReadWrite() const    { return isRead() && isWrite(); }
155    bool isLocked() const       { return testCmdAttrib(IsLocked); }
156    bool isError() const        { return testCmdAttrib(IsError); }
157    bool isPrint() const        { return testCmdAttrib(IsPrint); }
158
159    const Command responseCommand() const {
160        return commandInfo[cmd].response;
161    }
162
163    /** Return the string to a cmd given by idx. */
164    const std::string &toString() const {
165        return commandInfo[cmd].str;
166    }
167
168    int toInt() const { return (int)cmd; }
169
170    MemCmd(Command _cmd)
171        : cmd(_cmd)
172    { }
173
174    MemCmd(int _cmd)
175        : cmd((Command)_cmd)
176    { }
177
178    MemCmd()
179        : cmd(InvalidCmd)
180    { }
181
182    bool operator==(MemCmd c2) { return (cmd == c2.cmd); }
183    bool operator!=(MemCmd c2) { return (cmd != c2.cmd); }
184
185    friend class Packet;
186};
187
188/**
189 * A Packet is used to encapsulate a transfer between two objects in
190 * the memory system (e.g., the L1 and L2 cache).  (In contrast, a
191 * single Request travels all the way from the requester to the
192 * ultimate destination and back, possibly being conveyed by several
193 * different Packets along the way.)
194 */
195class Packet : public FastAlloc, public Printable
196{
197  public:
198
199    typedef MemCmd::Command Command;
200
201    /** The command field of the packet. */
202    MemCmd cmd;
203
204    /** A pointer to the original request. */
205    RequestPtr req;
206
207  private:
208   /** A pointer to the data being transfered.  It can be differnt
209    *    sizes at each level of the heirarchy so it belongs in the
210    *    packet, not request. This may or may not be populated when a
211    *    responder recieves the packet. If not populated it memory
212    *    should be allocated.
213    */
214    PacketDataPtr data;
215
216    /** Is the data pointer set to a value that shouldn't be freed
217     *   when the packet is destroyed? */
218    bool staticData;
219    /** The data pointer points to a value that should be freed when
220     *   the packet is destroyed. */
221    bool dynamicData;
222    /** the data pointer points to an array (thus delete [] ) needs to
223     *   be called on it rather than simply delete.*/
224    bool arrayData;
225
226    /** The address of the request.  This address could be virtual or
227     *   physical, depending on the system configuration. */
228    Addr addr;
229
230     /** The size of the request or transfer. */
231    int size;
232
233    /** Device address (e.g., bus ID) of the source of the
234     *   transaction. The source is not responsible for setting this
235     *   field; it is set implicitly by the interconnect when the
236     *   packet is first sent.  */
237    short src;
238
239    /** Device address (e.g., bus ID) of the destination of the
240     *   transaction. The special value Broadcast indicates that the
241     *   packet should be routed based on its address. This field is
242     *   initialized in the constructor and is thus always valid
243     *   (unlike * addr, size, and src). */
244    short dest;
245
246    /** The original value of the command field.  Only valid when the
247     * current command field is an error condition; in that case, the
248     * previous contents of the command field are copied here.  This
249     * field is *not* set on non-error responses.
250     */
251    MemCmd origCmd;
252
253    /** Are the 'addr' and 'size' fields valid? */
254    bool addrSizeValid;
255    /** Is the 'src' field valid? */
256    bool srcValid;
257    bool destValid;
258
259    enum Flag {
260        // Snoop response flags
261        MemInhibit,
262        Shared,
263        // Special control flags
264        /// Special timing-mode atomic snoop for multi-level coherence.
265        ExpressSnoop,
266        /// Does supplier have exclusive copy?
267        /// Useful for multi-level coherence.
268        SupplyExclusive,
269        NUM_PACKET_FLAGS
270    };
271
272    /** Status flags */
273    std::bitset<NUM_PACKET_FLAGS> flags;
274
275  public:
276
277    /** Used to calculate latencies for each packet.*/
278    Tick time;
279
280    /** The time at which the packet will be fully transmitted */
281    Tick finishTime;
282
283    /** The time at which the first chunk of the packet will be transmitted */
284    Tick firstWordTime;
285
286    /** The special destination address indicating that the packet
287     *   should be routed based on its address. */
288    static const short Broadcast = -1;
289
290    /** A virtual base opaque structure used to hold state associated
291     *    with the packet but specific to the sending device (e.g., an
292     *    MSHR).  A pointer to this state is returned in the packet's
293     *    response so that the sender can quickly look up the state
294     *    needed to process it.  A specific subclass would be derived
295     *    from this to carry state specific to a particular sending
296     *    device.  */
297    class SenderState : public FastAlloc {
298      public:
299        virtual ~SenderState() {}
300    };
301
302    /**
303     * Object used to maintain state of a PrintReq.  The senderState
304     * field of a PrintReq should always be of this type.
305     */
306    class PrintReqState : public SenderState {
307        /** An entry in the label stack. */
308        class LabelStackEntry {
309          public:
310            const std::string label;
311            std::string *prefix;
312            bool labelPrinted;
313            LabelStackEntry(const std::string &_label,
314                            std::string *_prefix);
315        };
316
317        typedef std::list<LabelStackEntry> LabelStack;
318        LabelStack labelStack;
319
320        std::string *curPrefixPtr;
321
322      public:
323        std::ostream &os;
324        const int verbosity;
325
326        PrintReqState(std::ostream &os, int verbosity = 0);
327        ~PrintReqState();
328
329        /** Returns the current line prefix. */
330        const std::string &curPrefix() { return *curPrefixPtr; }
331
332        /** Push a label onto the label stack, and prepend the given
333         * prefix string onto the current prefix.  Labels will only be
334         * printed if an object within the label's scope is
335         * printed. */
336        void pushLabel(const std::string &lbl,
337                       const std::string &prefix = "  ");
338        /** Pop a label off the label stack. */
339        void popLabel();
340        /** Print all of the pending unprinted labels on the
341         * stack. Called by printObj(), so normally not called by
342         * users unless bypassing printObj(). */
343        void printLabels();
344        /** Print a Printable object to os, because it matched the
345         * address on a PrintReq. */
346        void printObj(Printable *obj);
347    };
348
349    /** This packet's sender state.  Devices should use dynamic_cast<>
350     *   to cast to the state appropriate to the sender. */
351    SenderState *senderState;
352
353    /** Return the string name of the cmd field (for debugging and
354     *   tracing). */
355    const std::string &cmdString() const { return cmd.toString(); }
356
357    /** Return the index of this command. */
358    inline int cmdToIndex() const { return cmd.toInt(); }
359
360    bool isRead() const         { return cmd.isRead(); }
361    bool isWrite()  const       { return cmd.isWrite(); }
362    bool isRequest() const      { return cmd.isRequest(); }
363    bool isResponse() const     { return cmd.isResponse(); }
364    bool needsExclusive() const { return cmd.needsExclusive(); }
365    bool needsResponse() const  { return cmd.needsResponse(); }
366    bool isInvalidate() const   { return cmd.isInvalidate(); }
367    bool hasData() const        { return cmd.hasData(); }
368    bool isReadWrite() const    { return cmd.isReadWrite(); }
369    bool isLocked() const       { return cmd.isLocked(); }
370    bool isError() const        { return cmd.isError(); }
371    bool isPrint() const        { return cmd.isPrint(); }
372
373    // Snoop flags
374    void assertMemInhibit()     { flags[MemInhibit] = true; }
375    bool memInhibitAsserted()   { return flags[MemInhibit]; }
376    void assertShared()         { flags[Shared] = true; }
377    bool sharedAsserted()       { return flags[Shared]; }
378
379    // Special control flags
380    void setExpressSnoop()      { flags[ExpressSnoop] = true; }
381    bool isExpressSnoop()       { return flags[ExpressSnoop]; }
382    void setSupplyExclusive()   { flags[SupplyExclusive] = true; }
383    bool isSupplyExclusive()    { return flags[SupplyExclusive]; }
384
385    // Network error conditions... encapsulate them as methods since
386    // their encoding keeps changing (from result field to command
387    // field, etc.)
388    void setNacked()     { assert(isResponse()); cmd = MemCmd::NetworkNackError; }
389    void setBadAddress() { assert(isResponse()); cmd = MemCmd::BadAddressError; }
390    bool wasNacked()     { return cmd == MemCmd::NetworkNackError; }
391    bool hadBadAddress() { return cmd == MemCmd::BadAddressError; }
392    void copyError(Packet *pkt) { assert(pkt->isError()); cmd = pkt->cmd; }
393
394    bool nic_pkt() { panic("Unimplemented"); M5_DUMMY_RETURN }
395
396    /** Accessor function that returns the source index of the packet. */
397    short getSrc() const    { assert(srcValid); return src; }
398    void setSrc(short _src) { src = _src; srcValid = true; }
399    /** Reset source field, e.g. to retransmit packet on different bus. */
400    void clearSrc() { srcValid = false; }
401
402    /** Accessor function that returns the destination index of
403        the packet. */
404    short getDest() const     { assert(destValid); return dest; }
405    void setDest(short _dest) { dest = _dest; destValid = true; }
406
407    Addr getAddr() const { assert(addrSizeValid); return addr; }
408    int getSize() const  { assert(addrSizeValid); return size; }
409    Addr getOffset(int blkSize) const { return addr & (Addr)(blkSize - 1); }
410
411    /** Constructor.  Note that a Request object must be constructed
412     *   first, but the Requests's physical address and size fields
413     *   need not be valid. The command and destination addresses
414     *   must be supplied.  */
415    Packet(Request *_req, MemCmd _cmd, short _dest)
416        :  cmd(_cmd), req(_req),
417           data(NULL), staticData(false), dynamicData(false), arrayData(false),
418           addr(_req->paddr), size(_req->size), dest(_dest),
419           addrSizeValid(_req->validPaddr), srcValid(false), destValid(true),
420           flags(0), time(curTick), senderState(NULL)
421    {
422    }
423
424    /** Alternate constructor if you are trying to create a packet with
425     *  a request that is for a whole block, not the address from the req.
426     *  this allows for overriding the size/addr of the req.*/
427    Packet(Request *_req, MemCmd _cmd, short _dest, int _blkSize)
428        :  cmd(_cmd), req(_req),
429           data(NULL), staticData(false), dynamicData(false), arrayData(false),
430           addr(_req->paddr & ~(_blkSize - 1)), size(_blkSize), dest(_dest),
431           addrSizeValid(_req->validPaddr), srcValid(false), destValid(true),
432           flags(0), time(curTick), senderState(NULL)
433    {
434    }
435
436    /** Alternate constructor for copying a packet.  Copy all fields
437     * *except* if the original packet's data was dynamic, don't copy
438     * that, as we can't guarantee that the new packet's lifetime is
439     * less than that of the original packet.  In this case the new
440     * packet should allocate its own data. */
441    Packet(Packet *origPkt, bool clearFlags = false)
442        :  cmd(origPkt->cmd), req(origPkt->req),
443           data(origPkt->staticData ? origPkt->data : NULL),
444           staticData(origPkt->staticData),
445           dynamicData(false), arrayData(false),
446           addr(origPkt->addr), size(origPkt->size),
447           src(origPkt->src), dest(origPkt->dest),
448           addrSizeValid(origPkt->addrSizeValid),
449           srcValid(origPkt->srcValid), destValid(origPkt->destValid),
450           flags(clearFlags ? 0 : origPkt->flags),
451           time(curTick), senderState(origPkt->senderState)
452    {
453    }
454
455    /** Destructor. */
456    ~Packet()
457    { if (staticData || dynamicData) deleteData(); }
458
459    /** Reinitialize packet address and size from the associated
460     *   Request object, and reset other fields that may have been
461     *   modified by a previous transaction.  Typically called when a
462     *   statically allocated Request/Packet pair is reused for
463     *   multiple transactions. */
464    void reinitFromRequest() {
465        assert(req->validPaddr);
466        flags = 0;
467        addr = req->paddr;
468        size = req->size;
469        time = req->time;
470        addrSizeValid = true;
471        if (dynamicData) {
472            deleteData();
473            dynamicData = false;
474            arrayData = false;
475        }
476    }
477
478    /**
479     * Take a request packet and modify it in place to be suitable for
480     * returning as a response to that request.  The source and
481     * destination fields are *not* modified, as is appropriate for
482     * atomic accesses.
483     */
484    void makeResponse()
485    {
486        assert(needsResponse());
487        assert(isRequest());
488        origCmd = cmd;
489        cmd = cmd.responseCommand();
490        dest = src;
491        destValid = srcValid;
492        srcValid = false;
493    }
494
495    void makeAtomicResponse()
496    {
497        makeResponse();
498    }
499
500    void makeTimingResponse()
501    {
502        makeResponse();
503    }
504
505    /**
506     * Take a request packet that has been returned as NACKED and
507     * modify it so that it can be sent out again. Only packets that
508     * need a response can be NACKED, so verify that that is true.
509     */
510    void
511    reinitNacked()
512    {
513        assert(wasNacked());
514        cmd = origCmd;
515        assert(needsResponse());
516        setDest(Broadcast);
517    }
518
519
520    /**
521     * Set the data pointer to the following value that should not be
522     * freed.
523     */
524    template <typename T>
525    void
526    dataStatic(T *p)
527    {
528        if(dynamicData)
529            dynamicData = false;
530        data = (PacketDataPtr)p;
531        staticData = true;
532    }
533
534    /**
535     * Set the data pointer to a value that should have delete []
536     * called on it.
537     */
538    template <typename T>
539    void
540    dataDynamicArray(T *p)
541    {
542        assert(!staticData && !dynamicData);
543        data = (PacketDataPtr)p;
544        dynamicData = true;
545        arrayData = true;
546    }
547
548    /**
549     * set the data pointer to a value that should have delete called
550     * on it.
551     */
552    template <typename T>
553    void
554    dataDynamic(T *p)
555    {
556        assert(!staticData && !dynamicData);
557        data = (PacketDataPtr)p;
558        dynamicData = true;
559        arrayData = false;
560    }
561
562    /** get a pointer to the data ptr. */
563    template <typename T>
564    T*
565    getPtr()
566    {
567        assert(staticData || dynamicData);
568        return (T*)data;
569    }
570
571    /** return the value of what is pointed to in the packet. */
572    template <typename T>
573    T get();
574
575    /** set the value in the data pointer to v. */
576    template <typename T>
577    void set(T v);
578
579    /**
580     * Copy data into the packet from the provided pointer.
581     */
582    void setData(uint8_t *p)
583    {
584        std::memcpy(getPtr<uint8_t>(), p, getSize());
585    }
586
587    /**
588     * Copy data into the packet from the provided block pointer,
589     * which is aligned to the given block size.
590     */
591    void setDataFromBlock(uint8_t *blk_data, int blkSize)
592    {
593        setData(blk_data + getOffset(blkSize));
594    }
595
596    /**
597     * Copy data from the packet to the provided block pointer, which
598     * is aligned to the given block size.
599     */
600    void writeData(uint8_t *p)
601    {
602        std::memcpy(p, getPtr<uint8_t>(), getSize());
603    }
604
605    /**
606     * Copy data from the packet to the memory at the provided pointer.
607     */
608    void writeDataToBlock(uint8_t *blk_data, int blkSize)
609    {
610        writeData(blk_data + getOffset(blkSize));
611    }
612
613    /**
614     * delete the data pointed to in the data pointer. Ok to call to
615     * matter how data was allocted.
616     */
617    void deleteData();
618
619    /** If there isn't data in the packet, allocate some. */
620    void allocate();
621
622    /**
623     * Check a functional request against a memory value represented
624     * by a base/size pair and an associated data array.  If the
625     * functional request is a read, it may be satisfied by the memory
626     * value.  If the functional request is a write, it may update the
627     * memory value.
628     */
629    bool checkFunctional(Printable *obj, Addr base, int size, uint8_t *data);
630
631    /**
632     * Check a functional request against a memory value stored in
633     * another packet (i.e. an in-transit request or response).
634     */
635    bool checkFunctional(PacketPtr otherPkt) {
636        return checkFunctional(otherPkt,
637                               otherPkt->getAddr(), otherPkt->getSize(),
638                               otherPkt->hasData() ?
639                                   otherPkt->getPtr<uint8_t>() : NULL);
640    }
641
642    /**
643     * Push label for PrintReq (safe to call unconditionally).
644     */
645    void pushLabel(const std::string &lbl) {
646        if (isPrint()) {
647            dynamic_cast<PrintReqState*>(senderState)->pushLabel(lbl);
648        }
649    }
650
651    /**
652     * Pop label for PrintReq (safe to call unconditionally).
653     */
654    void popLabel() {
655        if (isPrint()) {
656            dynamic_cast<PrintReqState*>(senderState)->popLabel();
657        }
658    }
659
660    void print(std::ostream &o, int verbosity = 0,
661               const std::string &prefix = "") const;
662};
663
664#endif //__MEM_PACKET_HH
665