packet.hh revision 4022:c422464ca16e
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/misc.hh"
46#include "mem/request.hh"
47#include "sim/host.hh"
48#include "sim/root.hh"
49
50
51struct Packet;
52typedef Packet *PacketPtr;
53typedef uint8_t* PacketDataPtr;
54typedef std::list<PacketPtr> PacketList;
55
56//Coherence Flags
57#define NACKED_LINE     (1 << 0)
58#define SATISFIED       (1 << 1)
59#define SHARED_LINE     (1 << 2)
60#define CACHE_LINE_FILL (1 << 3)
61#define COMPRESSED      (1 << 4)
62#define NO_ALLOCATE     (1 << 5)
63#define SNOOP_COMMIT    (1 << 6)
64
65
66class MemCmd
67{
68  public:
69
70    /** List of all commands associated with a packet. */
71    enum Command
72    {
73        InvalidCmd,
74        ReadReq,
75        WriteReq,
76        WriteReqNoAck,
77        ReadResp,
78        WriteResp,
79        Writeback,
80        SoftPFReq,
81        HardPFReq,
82        SoftPFResp,
83        HardPFResp,
84        InvalidateReq,
85        WriteInvalidateReq,
86        WriteInvalidateResp,
87        UpgradeReq,
88        ReadExReq,
89        ReadExResp,
90        NUM_MEM_CMDS
91    };
92
93  private:
94    /** List of command attributes. */
95    enum Attribute
96    {
97        IsRead,
98        IsWrite,
99        IsPrefetch,
100        IsInvalidate,
101        IsRequest,
102        IsResponse,
103        NeedsResponse,
104        IsSWPrefetch,
105        IsHWPrefetch,
106        IsUpgrade,
107        HasData,
108        NUM_COMMAND_ATTRIBUTES
109    };
110
111    /** Structure that defines attributes and other data associated
112     * with a Command. */
113    struct CommandInfo {
114        /** Set of attribute flags. */
115        const std::bitset<NUM_COMMAND_ATTRIBUTES> attributes;
116        /** Corresponding response for requests; InvalidCmd if no
117         * response is applicable. */
118        const Command response;
119        /** String representation (for printing) */
120        const std::string str;
121    };
122
123    /** Array to map Command enum to associated info. */
124    static const CommandInfo commandInfo[];
125
126  private:
127
128    Command cmd;
129
130    bool testCmdAttrib(MemCmd::Attribute attrib) const {
131        return commandInfo[cmd].attributes[attrib] != 0;
132    }
133
134  public:
135
136    bool isRead() const         { return testCmdAttrib(IsRead); }
137    bool isWrite()  const       { return testCmdAttrib(IsWrite); }
138    bool isRequest() const      { return testCmdAttrib(IsRequest); }
139    bool isResponse() const     { return testCmdAttrib(IsResponse); }
140    bool needsResponse() const  { return testCmdAttrib(NeedsResponse); }
141    bool isInvalidate() const   { return testCmdAttrib(IsInvalidate); }
142    bool hasData() const        { return testCmdAttrib(HasData); }
143
144    const Command responseCommand() const {
145        return commandInfo[cmd].response;
146    }
147
148    /** Return the string to a cmd given by idx. */
149    const std::string &toString() const {
150        return commandInfo[cmd].str;
151    }
152
153    int toInt() const { return (int)cmd; }
154
155    MemCmd(Command _cmd)
156        : cmd(_cmd)
157    { }
158
159    MemCmd(int _cmd)
160        : cmd((Command)_cmd)
161    { }
162
163    MemCmd()
164        : cmd(InvalidCmd)
165    { }
166
167    bool operator==(MemCmd c2) { return (cmd == c2.cmd); }
168    bool operator!=(MemCmd c2) { return (cmd != c2.cmd); }
169
170    friend class Packet;
171};
172
173/**
174 * A Packet is used to encapsulate a transfer between two objects in
175 * the memory system (e.g., the L1 and L2 cache).  (In contrast, a
176 * single Request travels all the way from the requester to the
177 * ultimate destination and back, possibly being conveyed by several
178 * different Packets along the way.)
179 */
180class Packet
181{
182  public:
183
184    typedef MemCmd::Command Command;
185
186    /** Temporary FLAGS field until cache gets working, this should be in coherence/sender state. */
187    uint64_t flags;
188
189  private:
190   /** A pointer to the data being transfered.  It can be differnt
191    *    sizes at each level of the heirarchy so it belongs in the
192    *    packet, not request. This may or may not be populated when a
193    *    responder recieves the packet. If not populated it memory
194    *    should be allocated.
195    */
196    PacketDataPtr data;
197
198    /** Is the data pointer set to a value that shouldn't be freed
199     *   when the packet is destroyed? */
200    bool staticData;
201    /** The data pointer points to a value that should be freed when
202     *   the packet is destroyed. */
203    bool dynamicData;
204    /** the data pointer points to an array (thus delete [] ) needs to
205     *   be called on it rather than simply delete.*/
206    bool arrayData;
207
208    /** The address of the request.  This address could be virtual or
209     *   physical, depending on the system configuration. */
210    Addr addr;
211
212     /** The size of the request or transfer. */
213    int size;
214
215    /** Device address (e.g., bus ID) of the source of the
216     *   transaction. The source is not responsible for setting this
217     *   field; it is set implicitly by the interconnect when the
218     *   packet is first sent.  */
219    short src;
220
221    /** Device address (e.g., bus ID) of the destination of the
222     *   transaction. The special value Broadcast indicates that the
223     *   packet should be routed based on its address. This field is
224     *   initialized in the constructor and is thus always valid
225     *   (unlike * addr, size, and src). */
226    short dest;
227
228    /** Are the 'addr' and 'size' fields valid? */
229    bool addrSizeValid;
230    /** Is the 'src' field valid? */
231    bool srcValid;
232
233
234  public:
235
236    /** Used to calculate latencies for each packet.*/
237    Tick time;
238
239    /** The time at which the packet will be fully transmitted */
240    Tick finishTime;
241
242    /** The time at which the first chunk of the packet will be transmitted */
243    Tick firstWordTime;
244
245    /** The special destination address indicating that the packet
246     *   should be routed based on its address. */
247    static const short Broadcast = -1;
248
249    /** A pointer to the original request. */
250    RequestPtr req;
251
252    /** A virtual base opaque structure used to hold coherence-related
253     *    state.  A specific subclass would be derived from this to
254     *    carry state specific to a particular coherence protocol.  */
255    class CoherenceState {
256      public:
257        virtual ~CoherenceState() {}
258    };
259
260    /** This packet's coherence state.  Caches should use
261     *   dynamic_cast<> to cast to the state appropriate for the
262     *   system's coherence protocol.  */
263    CoherenceState *coherence;
264
265    /** A virtual base opaque structure used to hold state associated
266     *    with the packet but specific to the sending device (e.g., an
267     *    MSHR).  A pointer to this state is returned in the packet's
268     *    response so that the sender can quickly look up the state
269     *    needed to process it.  A specific subclass would be derived
270     *    from this to carry state specific to a particular sending
271     *    device.  */
272    class SenderState {
273      public:
274        virtual ~SenderState() {}
275    };
276
277    /** This packet's sender state.  Devices should use dynamic_cast<>
278     *   to cast to the state appropriate to the sender. */
279    SenderState *senderState;
280
281  public:
282
283    /** The command field of the packet. */
284    MemCmd cmd;
285
286    /** Return the string name of the cmd field (for debugging and
287     *   tracing). */
288    const std::string &cmdString() const { return cmd.toString(); }
289
290    /** Return the index of this command. */
291    inline int cmdToIndex() const { return cmd.toInt(); }
292
293  public:
294
295    bool isRead() const         { return cmd.isRead(); }
296    bool isWrite()  const       { return cmd.isWrite(); }
297    bool isRequest() const      { return cmd.isRequest(); }
298    bool isResponse() const     { return cmd.isResponse(); }
299    bool needsResponse() const  { return cmd.needsResponse(); }
300    bool isInvalidate() const   { return cmd.isInvalidate(); }
301    bool hasData() const        { return cmd.hasData(); }
302
303    bool isCacheFill() const    { return (flags & CACHE_LINE_FILL) != 0; }
304    bool isNoAllocate() const   { return (flags & NO_ALLOCATE) != 0; }
305    bool isCompressed() const   { return (flags & COMPRESSED) != 0; }
306
307    bool nic_pkt() { panic("Unimplemented"); M5_DUMMY_RETURN }
308
309    /** Possible results of a packet's request. */
310    enum Result
311    {
312        Success,
313        BadAddress,
314        Nacked,
315        Unknown
316    };
317
318    /** The result of this packet's request. */
319    Result result;
320
321    /** Accessor function that returns the source index of the packet. */
322    short getSrc() const { assert(srcValid); return src; }
323    void setSrc(short _src) { src = _src; srcValid = true; }
324
325    /** Accessor function that returns the destination index of
326        the packet. */
327    short getDest() const { return dest; }
328    void setDest(short _dest) { dest = _dest; }
329
330    Addr getAddr() const { assert(addrSizeValid); return addr; }
331    int getSize() const { assert(addrSizeValid); return size; }
332    Addr getOffset(int blkSize) const { return addr & (Addr)(blkSize - 1); }
333
334    void addrOverride(Addr newAddr) { assert(addrSizeValid); addr = newAddr; }
335    void cmdOverride(MemCmd newCmd) { cmd = newCmd; }
336
337    /** Constructor.  Note that a Request object must be constructed
338     *   first, but the Requests's physical address and size fields
339     *   need not be valid. The command and destination addresses
340     *   must be supplied.  */
341    Packet(Request *_req, MemCmd _cmd, short _dest)
342        :  data(NULL), staticData(false), dynamicData(false), arrayData(false),
343           addr(_req->paddr), size(_req->size), dest(_dest),
344           addrSizeValid(_req->validPaddr),
345           srcValid(false),
346           req(_req), coherence(NULL), senderState(NULL), cmd(_cmd),
347           result(Unknown)
348    {
349        flags = 0;
350        time = curTick;
351    }
352
353    /** Alternate constructor if you are trying to create a packet with
354     *  a request that is for a whole block, not the address from the req.
355     *  this allows for overriding the size/addr of the req.*/
356    Packet(Request *_req, MemCmd _cmd, short _dest, int _blkSize)
357        :  data(NULL), staticData(false), dynamicData(false), arrayData(false),
358           addr(_req->paddr & ~(_blkSize - 1)), size(_blkSize),
359           dest(_dest),
360           addrSizeValid(_req->validPaddr), srcValid(false),
361           req(_req), coherence(NULL), senderState(NULL), cmd(_cmd),
362           result(Unknown)
363    {
364        flags = 0;
365        time = curTick;
366    }
367
368    /** Destructor. */
369    ~Packet()
370    { if (staticData || dynamicData) deleteData(); }
371
372    /** Reinitialize packet address and size from the associated
373     *   Request object, and reset other fields that may have been
374     *   modified by a previous transaction.  Typically called when a
375     *   statically allocated Request/Packet pair is reused for
376     *   multiple transactions. */
377    void reinitFromRequest() {
378        assert(req->validPaddr);
379        flags = 0;
380        addr = req->paddr;
381        size = req->size;
382        time = req->time;
383        addrSizeValid = true;
384        result = Unknown;
385        if (dynamicData) {
386            deleteData();
387            dynamicData = false;
388            arrayData = false;
389        }
390    }
391
392    /** Take a request packet and modify it in place to be suitable
393     *   for returning as a response to that request.  Used for timing
394     *   accesses only.  For atomic and functional accesses, the
395     *   request packet is always implicitly passed back *without*
396     *   modifying the destination fields, so this function
397     *   should not be called. */
398    void makeTimingResponse() {
399        assert(needsResponse());
400        assert(isRequest());
401        cmd = cmd.responseCommand();
402        dest = src;
403        srcValid = false;
404    }
405
406    /**
407     * Take a request packet and modify it in place to be suitable for
408     * returning as a response to that request.
409     */
410    void makeAtomicResponse()
411    {
412        assert(needsResponse());
413        assert(isRequest());
414        cmd = cmd.responseCommand();
415    }
416
417    /**
418     * Take a request packet that has been returned as NACKED and
419     * modify it so that it can be sent out again. Only packets that
420     * need a response can be NACKED, so verify that that is true.
421     */
422    void
423    reinitNacked()
424    {
425        assert(needsResponse() && result == Nacked);
426        dest =  Broadcast;
427        result = Unknown;
428    }
429
430
431    /**
432     * Set the data pointer to the following value that should not be
433     * freed.
434     */
435    template <typename T>
436    void
437    dataStatic(T *p)
438    {
439        if(dynamicData)
440            dynamicData = false;
441        data = (PacketDataPtr)p;
442        staticData = true;
443    }
444
445    /**
446     * Set the data pointer to a value that should have delete []
447     * called on it.
448     */
449    template <typename T>
450    void
451    dataDynamicArray(T *p)
452    {
453        assert(!staticData && !dynamicData);
454        data = (PacketDataPtr)p;
455        dynamicData = true;
456        arrayData = true;
457    }
458
459    /**
460     * set the data pointer to a value that should have delete called
461     * on it.
462     */
463    template <typename T>
464    void
465    dataDynamic(T *p)
466    {
467        assert(!staticData && !dynamicData);
468        data = (PacketDataPtr)p;
469        dynamicData = true;
470        arrayData = false;
471    }
472
473    /** get a pointer to the data ptr. */
474    template <typename T>
475    T*
476    getPtr()
477    {
478        assert(staticData || dynamicData);
479        return (T*)data;
480    }
481
482    /** return the value of what is pointed to in the packet. */
483    template <typename T>
484    T get();
485
486    /** set the value in the data pointer to v. */
487    template <typename T>
488    void set(T v);
489
490    /**
491     * delete the data pointed to in the data pointer. Ok to call to
492     * matter how data was allocted.
493     */
494    void deleteData();
495
496    /** If there isn't data in the packet, allocate some. */
497    void allocate();
498
499    /** Do the packet modify the same addresses. */
500    bool intersect(PacketPtr p);
501};
502
503/** This function given a functional packet and a timing packet either satisfies
504 * the timing packet, or updates the timing packet to reflect the updated state
505 * in the timing packet. It returns if the functional packet should continue to
506 * traverse the memory hierarchy or not.
507 */
508bool fixPacket(PacketPtr func, PacketPtr timing);
509
510/** This function is a wrapper for the fixPacket field that toggles the hasData bit
511 * it is used when a response is waiting in the caches, but hasn't been marked as a
512 * response yet (so the fixPacket needs to get the correct value for the hasData)
513 */
514bool fixDelayedResponsePacket(PacketPtr func, PacketPtr timing);
515
516std::ostream & operator<<(std::ostream &o, const Packet &p);
517
518#endif //__MEM_PACKET_HH
519