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