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