packet.cc revision 12344:57364c030de3
1/*
2 * Copyright (c) 2011-2017 ARM Limited
3 * All rights reserved
4 *
5 * The license below extends only to copyright in the software and shall
6 * not be construed as granting a license to any other intellectual
7 * property including but not limited to intellectual property relating
8 * to a hardware implementation of the functionality of the software
9 * licensed hereunder.  You may use the software subject to the license
10 * terms below provided that you ensure that this notice is replicated
11 * unmodified and in its entirety in all distributions of the software,
12 * modified or unmodified, in source code or in binary form.
13 *
14 * Copyright (c) 2006 The Regents of The University of Michigan
15 * Copyright (c) 2010,2015 Advanced Micro Devices, Inc.
16 * All rights reserved.
17 *
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions are
20 * met: redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer;
22 * redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution;
25 * neither the name of the copyright holders nor the names of its
26 * contributors may be used to endorse or promote products derived from
27 * this software without specific prior written permission.
28 *
29 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
30 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
31 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
32 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
33 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
34 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
35 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
39 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 *
41 * Authors: Ali Saidi
42 *          Steve Reinhardt
43 */
44
45/**
46 * @file
47 * Definition of the Packet Class, a packet is a transaction occuring
48 * between a single level of the memory heirarchy (ie L1->L2).
49 */
50
51#include "mem/packet.hh"
52
53#include <cstring>
54#include <iostream>
55
56#include "base/cprintf.hh"
57#include "base/logging.hh"
58#include "base/trace.hh"
59
60using namespace std;
61
62// The one downside to bitsets is that static initializers can get ugly.
63#define SET1(a1)                     (1 << (a1))
64#define SET2(a1, a2)                 (SET1(a1) | SET1(a2))
65#define SET3(a1, a2, a3)             (SET2(a1, a2) | SET1(a3))
66#define SET4(a1, a2, a3, a4)         (SET3(a1, a2, a3) | SET1(a4))
67#define SET5(a1, a2, a3, a4, a5)     (SET4(a1, a2, a3, a4) | SET1(a5))
68#define SET6(a1, a2, a3, a4, a5, a6) (SET5(a1, a2, a3, a4, a5) | SET1(a6))
69#define SET7(a1, a2, a3, a4, a5, a6, a7) (SET6(a1, a2, a3, a4, a5, a6) | \
70                                          SET1(a7))
71
72const MemCmd::CommandInfo
73MemCmd::commandInfo[] =
74{
75    /* InvalidCmd */
76    { 0, InvalidCmd, "InvalidCmd" },
77    /* ReadReq - Read issued by a non-caching agent such as a CPU or
78     * device, with no restrictions on alignment. */
79    { SET3(IsRead, IsRequest, NeedsResponse), ReadResp, "ReadReq" },
80    /* ReadResp */
81    { SET3(IsRead, IsResponse, HasData), InvalidCmd, "ReadResp" },
82    /* ReadRespWithInvalidate */
83    { SET4(IsRead, IsResponse, HasData, IsInvalidate),
84            InvalidCmd, "ReadRespWithInvalidate" },
85    /* WriteReq */
86    { SET5(IsWrite, NeedsWritable, IsRequest, NeedsResponse, HasData),
87            WriteResp, "WriteReq" },
88    /* WriteResp */
89    { SET2(IsWrite, IsResponse), InvalidCmd, "WriteResp" },
90    /* WritebackDirty */
91    { SET5(IsWrite, IsRequest, IsEviction, HasData, FromCache),
92            InvalidCmd, "WritebackDirty" },
93    /* WritebackClean - This allows the upstream cache to writeback a
94     * line to the downstream cache without it being considered
95     * dirty. */
96    { SET5(IsWrite, IsRequest, IsEviction, HasData, FromCache),
97            InvalidCmd, "WritebackClean" },
98    /* WriteClean - This allows a cache to write a dirty block to a memory
99       below without evicting its copy. */
100    { SET4(IsWrite, IsRequest, HasData, FromCache), InvalidCmd, "WriteClean" },
101    /* CleanEvict */
102    { SET3(IsRequest, IsEviction, FromCache), InvalidCmd, "CleanEvict" },
103    /* SoftPFReq */
104    { SET4(IsRead, IsRequest, IsSWPrefetch, NeedsResponse),
105            SoftPFResp, "SoftPFReq" },
106    /* HardPFReq */
107    { SET5(IsRead, IsRequest, IsHWPrefetch, NeedsResponse, FromCache),
108            HardPFResp, "HardPFReq" },
109    /* SoftPFResp */
110    { SET4(IsRead, IsResponse, IsSWPrefetch, HasData),
111            InvalidCmd, "SoftPFResp" },
112    /* HardPFResp */
113    { SET4(IsRead, IsResponse, IsHWPrefetch, HasData),
114            InvalidCmd, "HardPFResp" },
115    /* WriteLineReq */
116    { SET5(IsWrite, NeedsWritable, IsRequest, NeedsResponse, HasData),
117            WriteResp, "WriteLineReq" },
118    /* UpgradeReq */
119    { SET6(IsInvalidate, NeedsWritable, IsUpgrade, IsRequest, NeedsResponse,
120            FromCache),
121            UpgradeResp, "UpgradeReq" },
122    /* SCUpgradeReq: response could be UpgradeResp or UpgradeFailResp */
123    { SET7(IsInvalidate, NeedsWritable, IsUpgrade, IsLlsc,
124           IsRequest, NeedsResponse, FromCache),
125            UpgradeResp, "SCUpgradeReq" },
126    /* UpgradeResp */
127    { SET2(IsUpgrade, IsResponse),
128            InvalidCmd, "UpgradeResp" },
129    /* SCUpgradeFailReq: generates UpgradeFailResp but still gets the data */
130    { SET7(IsRead, NeedsWritable, IsInvalidate,
131           IsLlsc, IsRequest, NeedsResponse, FromCache),
132            UpgradeFailResp, "SCUpgradeFailReq" },
133    /* UpgradeFailResp - Behaves like a ReadExReq, but notifies an SC
134     * that it has failed, acquires line as Dirty*/
135    { SET3(IsRead, IsResponse, HasData),
136            InvalidCmd, "UpgradeFailResp" },
137    /* ReadExReq - Read issues by a cache, always cache-line aligned,
138     * and the response is guaranteed to be writeable (exclusive or
139     * even modified) */
140    { SET6(IsRead, NeedsWritable, IsInvalidate, IsRequest, NeedsResponse,
141            FromCache),
142            ReadExResp, "ReadExReq" },
143    /* ReadExResp - Response matching a read exclusive, as we check
144     * the need for exclusive also on responses */
145    { SET3(IsRead, IsResponse, HasData),
146            InvalidCmd, "ReadExResp" },
147    /* ReadCleanReq - Read issued by a cache, always cache-line
148     * aligned, and the response is guaranteed to not contain dirty data
149     * (exclusive or shared).*/
150    { SET4(IsRead, IsRequest, NeedsResponse, FromCache),
151            ReadResp, "ReadCleanReq" },
152    /* ReadSharedReq - Read issued by a cache, always cache-line
153     * aligned, response is shared, possibly exclusive, owned or even
154     * modified. */
155    { SET4(IsRead, IsRequest, NeedsResponse, FromCache),
156            ReadResp, "ReadSharedReq" },
157    /* LoadLockedReq: note that we use plain ReadResp as response, so that
158     *                we can also use ReadRespWithInvalidate when needed */
159    { SET4(IsRead, IsLlsc, IsRequest, NeedsResponse),
160            ReadResp, "LoadLockedReq" },
161    /* StoreCondReq */
162    { SET6(IsWrite, NeedsWritable, IsLlsc,
163           IsRequest, NeedsResponse, HasData),
164            StoreCondResp, "StoreCondReq" },
165    /* StoreCondFailReq: generates failing StoreCondResp */
166    { SET6(IsWrite, NeedsWritable, IsLlsc,
167           IsRequest, NeedsResponse, HasData),
168            StoreCondResp, "StoreCondFailReq" },
169    /* StoreCondResp */
170    { SET3(IsWrite, IsLlsc, IsResponse),
171            InvalidCmd, "StoreCondResp" },
172    /* SwapReq -- for Swap ldstub type operations */
173    { SET6(IsRead, IsWrite, NeedsWritable, IsRequest, HasData, NeedsResponse),
174        SwapResp, "SwapReq" },
175    /* SwapResp -- for Swap ldstub type operations */
176    { SET4(IsRead, IsWrite, IsResponse, HasData),
177            InvalidCmd, "SwapResp" },
178    /* IntReq -- for interrupts */
179    { SET4(IsWrite, IsRequest, NeedsResponse, HasData),
180        MessageResp, "MessageReq" },
181    /* IntResp -- for interrupts */
182    { SET2(IsWrite, IsResponse), InvalidCmd, "MessageResp" },
183    /* MemFenceReq -- for synchronization requests */
184    {SET2(IsRequest, NeedsResponse), MemFenceResp, "MemFenceReq"},
185    /* MemFenceResp -- for synchronization responses */
186    {SET1(IsResponse), InvalidCmd, "MemFenceResp"},
187    /* InvalidDestError  -- packet dest field invalid */
188    { SET2(IsResponse, IsError), InvalidCmd, "InvalidDestError" },
189    /* BadAddressError   -- memory address invalid */
190    { SET2(IsResponse, IsError), InvalidCmd, "BadAddressError" },
191    /* FunctionalReadError */
192    { SET3(IsRead, IsResponse, IsError), InvalidCmd, "FunctionalReadError" },
193    /* FunctionalWriteError */
194    { SET3(IsWrite, IsResponse, IsError), InvalidCmd, "FunctionalWriteError" },
195    /* PrintReq */
196    { SET2(IsRequest, IsPrint), InvalidCmd, "PrintReq" },
197    /* Flush Request */
198    { SET3(IsRequest, IsFlush, NeedsWritable), InvalidCmd, "FlushReq" },
199    /* Invalidation Request */
200    { SET5(IsInvalidate, IsRequest, NeedsWritable, NeedsResponse, FromCache),
201      InvalidateResp, "InvalidateReq" },
202    /* Invalidation Response */
203    { SET2(IsInvalidate, IsResponse),
204      InvalidCmd, "InvalidateResp" }
205};
206
207bool
208Packet::checkFunctional(Printable *obj, Addr addr, bool is_secure, int size,
209                        uint8_t *_data)
210{
211    Addr func_start = getAddr();
212    Addr func_end   = getAddr() + getSize() - 1;
213    Addr val_start  = addr;
214    Addr val_end    = val_start + size - 1;
215
216    if (is_secure != _isSecure || func_start > val_end ||
217        val_start > func_end) {
218        // no intersection
219        return false;
220    }
221
222    // check print first since it doesn't require data
223    if (isPrint()) {
224        assert(!_data);
225        safe_cast<PrintReqState*>(senderState)->printObj(obj);
226        return false;
227    }
228
229    // we allow the caller to pass NULL to signify the other packet
230    // has no data
231    if (!_data) {
232        return false;
233    }
234
235    // offset of functional request into supplied value (could be
236    // negative if partial overlap)
237    int offset = func_start - val_start;
238
239    if (isRead()) {
240        if (func_start >= val_start && func_end <= val_end) {
241            memcpy(getPtr<uint8_t>(), _data + offset, getSize());
242            if (bytesValid.empty())
243                bytesValid.resize(getSize(), true);
244            // complete overlap, and as the current packet is a read
245            // we are done
246            return true;
247        } else {
248            // Offsets and sizes to copy in case of partial overlap
249            int func_offset;
250            int val_offset;
251            int overlap_size;
252
253            // calculate offsets and copy sizes for the two byte arrays
254            if (val_start < func_start && val_end <= func_end) {
255                // the one we are checking against starts before and
256                // ends before or the same
257                val_offset = func_start - val_start;
258                func_offset = 0;
259                overlap_size = val_end - func_start;
260            } else if (val_start >= func_start && val_end > func_end) {
261                // the one we are checking against starts after or the
262                // same, and ends after
263                val_offset = 0;
264                func_offset = val_start - func_start;
265                overlap_size = func_end - val_start;
266            } else if (val_start >= func_start && val_end <= func_end) {
267                // the one we are checking against is completely
268                // subsumed in the current packet, possibly starting
269                // and ending at the same address
270                val_offset = 0;
271                func_offset = val_start - func_start;
272                overlap_size = size;
273            } else if (val_start < func_start && val_end > func_end) {
274                // the current packet is completely subsumed in the
275                // one we are checking against
276                val_offset = func_start - val_start;
277                func_offset = 0;
278                overlap_size = func_end - func_start;
279            } else {
280                panic("Missed a case for checkFunctional with "
281                      " %s 0x%x size %d, against 0x%x size %d\n",
282                      cmdString(), getAddr(), getSize(), addr, size);
283            }
284
285            // copy partial data into the packet's data array
286            uint8_t *dest = getPtr<uint8_t>() + func_offset;
287            uint8_t *src = _data + val_offset;
288            memcpy(dest, src, overlap_size);
289
290            // initialise the tracking of valid bytes if we have not
291            // used it already
292            if (bytesValid.empty())
293                bytesValid.resize(getSize(), false);
294
295            // track if we are done filling the functional access
296            bool all_bytes_valid = true;
297
298            int i = 0;
299
300            // check up to func_offset
301            for (; all_bytes_valid && i < func_offset; ++i)
302                all_bytes_valid &= bytesValid[i];
303
304            // update the valid bytes
305            for (i = func_offset; i < func_offset + overlap_size; ++i)
306                bytesValid[i] = true;
307
308            // check the bit after the update we just made
309            for (; all_bytes_valid && i < getSize(); ++i)
310                all_bytes_valid &= bytesValid[i];
311
312            return all_bytes_valid;
313        }
314    } else if (isWrite()) {
315        if (offset >= 0) {
316            memcpy(_data + offset, getConstPtr<uint8_t>(),
317                   (min(func_end, val_end) - func_start) + 1);
318        } else {
319            // val_start > func_start
320            memcpy(_data, getConstPtr<uint8_t>() - offset,
321                   (min(func_end, val_end) - val_start) + 1);
322        }
323    } else {
324        panic("Don't know how to handle command %s\n", cmdString());
325    }
326
327    // keep going with request by default
328    return false;
329}
330
331void
332Packet::pushSenderState(Packet::SenderState *sender_state)
333{
334    assert(sender_state != NULL);
335    sender_state->predecessor = senderState;
336    senderState = sender_state;
337}
338
339Packet::SenderState *
340Packet::popSenderState()
341{
342    assert(senderState != NULL);
343    SenderState *sender_state = senderState;
344    senderState = sender_state->predecessor;
345    sender_state->predecessor = NULL;
346    return sender_state;
347}
348
349void
350Packet::print(ostream &o, const int verbosity, const string &prefix) const
351{
352    ccprintf(o, "%s%s [%x:%x]%s%s%s%s", prefix, cmdString(),
353             getAddr(), getAddr() + getSize() - 1,
354             req->isSecure() ? " (s)" : "",
355             req->isInstFetch() ? " IF" : "",
356             req->isUncacheable() ? " UC" : "",
357             isExpressSnoop() ? " ES" : "");
358}
359
360std::string
361Packet::print() const {
362    ostringstream str;
363    print(str);
364    return str.str();
365}
366
367Packet::PrintReqState::PrintReqState(ostream &_os, int _verbosity)
368    : curPrefixPtr(new string("")), os(_os), verbosity(_verbosity)
369{
370    labelStack.push_back(LabelStackEntry("", curPrefixPtr));
371}
372
373Packet::PrintReqState::~PrintReqState()
374{
375    labelStack.pop_back();
376    assert(labelStack.empty());
377    delete curPrefixPtr;
378}
379
380Packet::PrintReqState::
381LabelStackEntry::LabelStackEntry(const string &_label, string *_prefix)
382    : label(_label), prefix(_prefix), labelPrinted(false)
383{
384}
385
386void
387Packet::PrintReqState::pushLabel(const string &lbl, const string &prefix)
388{
389    labelStack.push_back(LabelStackEntry(lbl, curPrefixPtr));
390    curPrefixPtr = new string(*curPrefixPtr);
391    *curPrefixPtr += prefix;
392}
393
394void
395Packet::PrintReqState::popLabel()
396{
397    delete curPrefixPtr;
398    curPrefixPtr = labelStack.back().prefix;
399    labelStack.pop_back();
400    assert(!labelStack.empty());
401}
402
403void
404Packet::PrintReqState::printLabels()
405{
406    if (!labelStack.back().labelPrinted) {
407        LabelStack::iterator i = labelStack.begin();
408        LabelStack::iterator end = labelStack.end();
409        while (i != end) {
410            if (!i->labelPrinted) {
411                ccprintf(os, "%s%s\n", *(i->prefix), i->label);
412                i->labelPrinted = true;
413            }
414            i++;
415        }
416    }
417}
418
419
420void
421Packet::PrintReqState::printObj(Printable *obj)
422{
423    printLabels();
424    obj->print(os, verbosity, curPrefix());
425}
426