packet.hh revision 4905:0ccda2bb3be7
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 "mem/request.hh"
49#include "sim/host.hh"
50#include "sim/core.hh"
51
52
53struct Packet;
54typedef Packet *PacketPtr;
55typedef uint8_t* PacketDataPtr;
56typedef std::list<PacketPtr> PacketList;
57
58class MemCmd
59{
60  public:
61
62    /** List of all commands associated with a packet. */
63    enum Command
64    {
65        InvalidCmd,
66        ReadReq,
67        ReadResp,
68        WriteReq,
69        WriteResp,
70        Writeback,
71        SoftPFReq,
72        HardPFReq,
73        SoftPFResp,
74        HardPFResp,
75        WriteInvalidateReq,
76        WriteInvalidateResp,
77        UpgradeReq,
78        UpgradeResp,
79        ReadExReq,
80        ReadExResp,
81        LoadLockedReq,
82        LoadLockedResp,
83        StoreCondReq,
84        StoreCondResp,
85        SwapReq,
86        SwapResp,
87        // Error responses
88        // @TODO these should be classified as responses rather than
89        // requests; coding them as requests initially for backwards
90        // compatibility
91        NetworkNackError,  // nacked at network layer (not by protocol)
92        InvalidDestError,  // packet dest field invalid
93        BadAddressError,   // memory address invalid
94        NUM_MEM_CMDS
95    };
96
97  private:
98    /** List of command attributes. */
99    enum Attribute
100    {
101        IsRead,         //!< Data flows from responder to requester
102        IsWrite,        //!< Data flows from requester to responder
103        IsPrefetch,     //!< Not a demand access
104        IsInvalidate,
105        NeedsExclusive, //!< Requires exclusive copy to complete in-cache
106        IsRequest,      //!< Issued by requester
107        IsResponse,     //!< Issue by responder
108        NeedsResponse,  //!< Requester needs response from target
109        IsSWPrefetch,
110        IsHWPrefetch,
111        IsLocked,       //!< Alpha/MIPS LL or SC access
112        HasData,        //!< There is an associated payload
113        IsError,        //!< Error response
114        NUM_COMMAND_ATTRIBUTES
115    };
116
117    /** Structure that defines attributes and other data associated
118     * with a Command. */
119    struct CommandInfo {
120        /** Set of attribute flags. */
121        const std::bitset<NUM_COMMAND_ATTRIBUTES> attributes;
122        /** Corresponding response for requests; InvalidCmd if no
123         * response is applicable. */
124        const Command response;
125        /** String representation (for printing) */
126        const std::string str;
127    };
128
129    /** Array to map Command enum to associated info. */
130    static const CommandInfo commandInfo[];
131
132  private:
133
134    Command cmd;
135
136    bool testCmdAttrib(MemCmd::Attribute attrib) const {
137        return commandInfo[cmd].attributes[attrib] != 0;
138    }
139
140  public:
141
142    bool isRead() const         { return testCmdAttrib(IsRead); }
143    bool isWrite()  const       { return testCmdAttrib(IsWrite); }
144    bool isRequest() const      { return testCmdAttrib(IsRequest); }
145    bool isResponse() const     { return testCmdAttrib(IsResponse); }
146    bool needsExclusive() const { return testCmdAttrib(NeedsExclusive); }
147    bool needsResponse() const  { return testCmdAttrib(NeedsResponse); }
148    bool isInvalidate() const   { return testCmdAttrib(IsInvalidate); }
149    bool hasData() const        { return testCmdAttrib(HasData); }
150    bool isReadWrite() const    { return isRead() && isWrite(); }
151    bool isLocked() const       { return testCmdAttrib(IsLocked); }
152    bool isError() const        { return testCmdAttrib(IsError); }
153
154    const Command responseCommand() const {
155        return commandInfo[cmd].response;
156    }
157
158    /** Return the string to a cmd given by idx. */
159    const std::string &toString() const {
160        return commandInfo[cmd].str;
161    }
162
163    int toInt() const { return (int)cmd; }
164
165    MemCmd(Command _cmd)
166        : cmd(_cmd)
167    { }
168
169    MemCmd(int _cmd)
170        : cmd((Command)_cmd)
171    { }
172
173    MemCmd()
174        : cmd(InvalidCmd)
175    { }
176
177    bool operator==(MemCmd c2) { return (cmd == c2.cmd); }
178    bool operator!=(MemCmd c2) { return (cmd != c2.cmd); }
179
180    friend class Packet;
181};
182
183/**
184 * A Packet is used to encapsulate a transfer between two objects in
185 * the memory system (e.g., the L1 and L2 cache).  (In contrast, a
186 * single Request travels all the way from the requester to the
187 * ultimate destination and back, possibly being conveyed by several
188 * different Packets along the way.)
189 */
190class Packet : public FastAlloc
191{
192  public:
193
194    typedef MemCmd::Command Command;
195
196    /** The command field of the packet. */
197    MemCmd cmd;
198
199    /** A pointer to the original request. */
200    RequestPtr req;
201
202  private:
203   /** A pointer to the data being transfered.  It can be differnt
204    *    sizes at each level of the heirarchy so it belongs in the
205    *    packet, not request. This may or may not be populated when a
206    *    responder recieves the packet. If not populated it memory
207    *    should be allocated.
208    */
209    PacketDataPtr data;
210
211    /** Is the data pointer set to a value that shouldn't be freed
212     *   when the packet is destroyed? */
213    bool staticData;
214    /** The data pointer points to a value that should be freed when
215     *   the packet is destroyed. */
216    bool dynamicData;
217    /** the data pointer points to an array (thus delete [] ) needs to
218     *   be called on it rather than simply delete.*/
219    bool arrayData;
220
221    /** The address of the request.  This address could be virtual or
222     *   physical, depending on the system configuration. */
223    Addr addr;
224
225     /** The size of the request or transfer. */
226    int size;
227
228    /** Device address (e.g., bus ID) of the source of the
229     *   transaction. The source is not responsible for setting this
230     *   field; it is set implicitly by the interconnect when the
231     *   packet is first sent.  */
232    short src;
233
234    /** Device address (e.g., bus ID) of the destination of the
235     *   transaction. The special value Broadcast indicates that the
236     *   packet should be routed based on its address. This field is
237     *   initialized in the constructor and is thus always valid
238     *   (unlike * addr, size, and src). */
239    short dest;
240
241    /** The original value of the command field.  Only valid when the
242     * current command field is an error condition; in that case, the
243     * previous contents of the command field are copied here.  This
244     * field is *not* set on non-error responses.
245     */
246    MemCmd origCmd;
247
248    /** Are the 'addr' and 'size' fields valid? */
249    bool addrSizeValid;
250    /** Is the 'src' field valid? */
251    bool srcValid;
252    bool destValid;
253
254    enum Flag {
255        // Snoop response flags
256        MemInhibit,
257        Shared,
258        // Special control flags
259        ExpressSnoop,
260        LowerMSHRPending,  // not yet in service
261        NUM_PACKET_FLAGS
262    };
263
264    /** Status flags */
265    std::bitset<NUM_PACKET_FLAGS> flags;
266
267  public:
268
269    /** Used to calculate latencies for each packet.*/
270    Tick time;
271
272    /** The time at which the packet will be fully transmitted */
273    Tick finishTime;
274
275    /** The time at which the first chunk of the packet will be transmitted */
276    Tick firstWordTime;
277
278    /** The special destination address indicating that the packet
279     *   should be routed based on its address. */
280    static const short Broadcast = -1;
281
282    /** A virtual base opaque structure used to hold state associated
283     *    with the packet but specific to the sending device (e.g., an
284     *    MSHR).  A pointer to this state is returned in the packet's
285     *    response so that the sender can quickly look up the state
286     *    needed to process it.  A specific subclass would be derived
287     *    from this to carry state specific to a particular sending
288     *    device.  */
289    class SenderState : public FastAlloc {
290      public:
291        virtual ~SenderState() {}
292    };
293
294    /** This packet's sender state.  Devices should use dynamic_cast<>
295     *   to cast to the state appropriate to the sender. */
296    SenderState *senderState;
297
298    /** Return the string name of the cmd field (for debugging and
299     *   tracing). */
300    const std::string &cmdString() const { return cmd.toString(); }
301
302    /** Return the index of this command. */
303    inline int cmdToIndex() const { return cmd.toInt(); }
304
305    bool isRead() const         { return cmd.isRead(); }
306    bool isWrite()  const       { return cmd.isWrite(); }
307    bool isRequest() const      { return cmd.isRequest(); }
308    bool isResponse() const     { return cmd.isResponse(); }
309    bool needsExclusive() const { return cmd.needsExclusive(); }
310    bool needsResponse() const  { return cmd.needsResponse(); }
311    bool isInvalidate() const   { return cmd.isInvalidate(); }
312    bool hasData() const        { return cmd.hasData(); }
313    bool isReadWrite() const    { return cmd.isReadWrite(); }
314    bool isLocked() const       { return cmd.isLocked(); }
315    bool isError() const        { return cmd.isError(); }
316
317    // Snoop flags
318    void assertMemInhibit()     { flags[MemInhibit] = true; }
319    void assertShared()         { flags[Shared] = true; }
320    bool memInhibitAsserted()   { return flags[MemInhibit]; }
321    bool sharedAsserted()       { return flags[Shared]; }
322
323    // Special control flags
324    void setExpressSnoop()      { flags[ExpressSnoop] = true; }
325    bool isExpressSnoop()       { return flags[ExpressSnoop]; }
326    void setLowerMSHRPending()  { flags[LowerMSHRPending] = true; }
327    bool lowerMSHRPending()     { return flags[LowerMSHRPending]; }
328
329    // Network error conditions... encapsulate them as methods since
330    // their encoding keeps changing (from result field to command
331    // field, etc.)
332    void setNacked()     { origCmd = cmd; cmd = MemCmd::NetworkNackError; }
333    void setBadAddress() { origCmd = cmd; cmd = MemCmd::BadAddressError; }
334    bool wasNacked()     { return cmd == MemCmd::NetworkNackError; }
335    bool hadBadAddress() { return cmd == MemCmd::BadAddressError; }
336
337    bool nic_pkt() { panic("Unimplemented"); M5_DUMMY_RETURN }
338
339    /** Accessor function that returns the source index of the packet. */
340    short getSrc() const    { assert(srcValid); return src; }
341    void setSrc(short _src) { src = _src; srcValid = true; }
342    /** Reset source field, e.g. to retransmit packet on different bus. */
343    void clearSrc() { srcValid = false; }
344
345    /** Accessor function that returns the destination index of
346        the packet. */
347    short getDest() const     { assert(destValid); return dest; }
348    void setDest(short _dest) { dest = _dest; destValid = true; }
349
350    Addr getAddr() const { assert(addrSizeValid); return addr; }
351    int getSize() const  { assert(addrSizeValid); return size; }
352    Addr getOffset(int blkSize) const { return addr & (Addr)(blkSize - 1); }
353
354    /** Constructor.  Note that a Request object must be constructed
355     *   first, but the Requests's physical address and size fields
356     *   need not be valid. The command and destination addresses
357     *   must be supplied.  */
358    Packet(Request *_req, MemCmd _cmd, short _dest)
359        :  cmd(_cmd), req(_req),
360           data(NULL), staticData(false), dynamicData(false), arrayData(false),
361           addr(_req->paddr), size(_req->size), dest(_dest),
362           addrSizeValid(_req->validPaddr), srcValid(false), destValid(true),
363           flags(0), time(curTick), senderState(NULL)
364    {
365    }
366
367    /** Alternate constructor if you are trying to create a packet with
368     *  a request that is for a whole block, not the address from the req.
369     *  this allows for overriding the size/addr of the req.*/
370    Packet(Request *_req, MemCmd _cmd, short _dest, int _blkSize)
371        :  cmd(_cmd), req(_req),
372           data(NULL), staticData(false), dynamicData(false), arrayData(false),
373           addr(_req->paddr & ~(_blkSize - 1)), size(_blkSize), dest(_dest),
374           addrSizeValid(_req->validPaddr), srcValid(false), destValid(true),
375           flags(0), time(curTick), senderState(NULL)
376    {
377    }
378
379    /** Alternate constructor for copying a packet.  Copy all fields
380     * *except* if the original packet's data was dynamic, don't copy
381     * that, as we can't guarantee that the new packet's lifetime is
382     * less than that of the original packet.  In this case the new
383     * packet should allocate its own data. */
384    Packet(Packet *origPkt, bool clearFlags = false)
385        :  cmd(origPkt->cmd), req(origPkt->req),
386           data(origPkt->staticData ? origPkt->data : NULL),
387           staticData(origPkt->staticData),
388           dynamicData(false), arrayData(false),
389           addr(origPkt->addr), size(origPkt->size),
390           src(origPkt->src), dest(origPkt->dest),
391           addrSizeValid(origPkt->addrSizeValid),
392           srcValid(origPkt->srcValid), destValid(origPkt->destValid),
393           flags(clearFlags ? 0 : origPkt->flags),
394           time(curTick), senderState(origPkt->senderState)
395    {
396    }
397
398    /** Destructor. */
399    ~Packet()
400    { if (staticData || dynamicData) deleteData(); }
401
402    /** Reinitialize packet address and size from the associated
403     *   Request object, and reset other fields that may have been
404     *   modified by a previous transaction.  Typically called when a
405     *   statically allocated Request/Packet pair is reused for
406     *   multiple transactions. */
407    void reinitFromRequest() {
408        assert(req->validPaddr);
409        flags = 0;
410        addr = req->paddr;
411        size = req->size;
412        time = req->time;
413        addrSizeValid = true;
414        if (dynamicData) {
415            deleteData();
416            dynamicData = false;
417            arrayData = false;
418        }
419    }
420
421    /**
422     * Take a request packet and modify it in place to be suitable for
423     * returning as a response to that request.  The source and
424     * destination fields are *not* modified, as is appropriate for
425     * atomic accesses.
426     */
427    void makeResponse()
428    {
429        assert(needsResponse());
430        assert(isRequest());
431        cmd = cmd.responseCommand();
432        dest = src;
433        destValid = srcValid;
434        srcValid = false;
435    }
436
437    void makeAtomicResponse()
438    {
439        makeResponse();
440    }
441
442    void makeTimingResponse()
443    {
444        makeResponse();
445    }
446
447    /**
448     * Take a request packet that has been returned as NACKED and
449     * modify it so that it can be sent out again. Only packets that
450     * need a response can be NACKED, so verify that that is true.
451     */
452    void
453    reinitNacked()
454    {
455        assert(wasNacked());
456        cmd = origCmd;
457        assert(needsResponse());
458        setDest(Broadcast);
459    }
460
461
462    /**
463     * Set the data pointer to the following value that should not be
464     * freed.
465     */
466    template <typename T>
467    void
468    dataStatic(T *p)
469    {
470        if(dynamicData)
471            dynamicData = false;
472        data = (PacketDataPtr)p;
473        staticData = true;
474    }
475
476    /**
477     * Set the data pointer to a value that should have delete []
478     * called on it.
479     */
480    template <typename T>
481    void
482    dataDynamicArray(T *p)
483    {
484        assert(!staticData && !dynamicData);
485        data = (PacketDataPtr)p;
486        dynamicData = true;
487        arrayData = true;
488    }
489
490    /**
491     * set the data pointer to a value that should have delete called
492     * on it.
493     */
494    template <typename T>
495    void
496    dataDynamic(T *p)
497    {
498        assert(!staticData && !dynamicData);
499        data = (PacketDataPtr)p;
500        dynamicData = true;
501        arrayData = false;
502    }
503
504    /** get a pointer to the data ptr. */
505    template <typename T>
506    T*
507    getPtr()
508    {
509        assert(staticData || dynamicData);
510        return (T*)data;
511    }
512
513    /** return the value of what is pointed to in the packet. */
514    template <typename T>
515    T get();
516
517    /** set the value in the data pointer to v. */
518    template <typename T>
519    void set(T v);
520
521    /**
522     * Copy data into the packet from the provided pointer.
523     */
524    void setData(uint8_t *p)
525    {
526        std::memcpy(getPtr<uint8_t>(), p, getSize());
527    }
528
529    /**
530     * Copy data into the packet from the provided block pointer,
531     * which is aligned to the given block size.
532     */
533    void setDataFromBlock(uint8_t *blk_data, int blkSize)
534    {
535        setData(blk_data + getOffset(blkSize));
536    }
537
538    /**
539     * Copy data from the packet to the provided block pointer, which
540     * is aligned to the given block size.
541     */
542    void writeData(uint8_t *p)
543    {
544        std::memcpy(p, getPtr<uint8_t>(), getSize());
545    }
546
547    /**
548     * Copy data from the packet to the memory at the provided pointer.
549     */
550    void writeDataToBlock(uint8_t *blk_data, int blkSize)
551    {
552        writeData(blk_data + getOffset(blkSize));
553    }
554
555    /**
556     * delete the data pointed to in the data pointer. Ok to call to
557     * matter how data was allocted.
558     */
559    void deleteData();
560
561    /** If there isn't data in the packet, allocate some. */
562    void allocate();
563
564    /** Do the packet modify the same addresses. */
565    bool intersect(PacketPtr p);
566
567    /**
568     * Check a functional request against a memory value represented
569     * by a base/size pair and an associated data array.  If the
570     * functional request is a read, it may be satisfied by the memory
571     * value.  If the functional request is a write, it may update the
572     * memory value.
573     */
574    bool checkFunctional(Addr base, int size, uint8_t *data);
575
576    /**
577     * Check a functional request against a memory value stored in
578     * another packet (i.e. an in-transit request or response).
579     */
580    bool checkFunctional(PacketPtr otherPkt) {
581        return (otherPkt->hasData() &&
582                checkFunctional(otherPkt->getAddr(), otherPkt->getSize(),
583                                otherPkt->getPtr<uint8_t>()));
584    }
585};
586
587std::ostream & operator<<(std::ostream &o, const Packet &p);
588
589#endif //__MEM_PACKET_HH
590