packet.cc revision 11744:5d33c6972dda
1/*
2 * Copyright (c) 2011-2016 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 <cstring>
52#include <iostream>
53
54#include "base/cprintf.hh"
55#include "base/misc.hh"
56#include "base/trace.hh"
57#include "mem/packet.hh"
58
59using namespace std;
60
61// The one downside to bitsets is that static initializers can get ugly.
62#define SET1(a1)                     (1 << (a1))
63#define SET2(a1, a2)                 (SET1(a1) | SET1(a2))
64#define SET3(a1, a2, a3)             (SET2(a1, a2) | SET1(a3))
65#define SET4(a1, a2, a3, a4)         (SET3(a1, a2, a3) | SET1(a4))
66#define SET5(a1, a2, a3, a4, a5)     (SET4(a1, a2, a3, a4) | SET1(a5))
67#define SET6(a1, a2, a3, a4, a5, a6) (SET5(a1, a2, a3, a4, a5) | SET1(a6))
68#define SET7(a1, a2, a3, a4, a5, a6, a7) (SET6(a1, a2, a3, a4, a5, a6) | \
69                                          SET1(a7))
70
71const MemCmd::CommandInfo
72MemCmd::commandInfo[] =
73{
74    /* InvalidCmd */
75    { 0, InvalidCmd, "InvalidCmd" },
76    /* ReadReq - Read issued by a non-caching agent such as a CPU or
77     * device, with no restrictions on alignment. */
78    { SET3(IsRead, IsRequest, NeedsResponse), ReadResp, "ReadReq" },
79    /* ReadResp */
80    { SET3(IsRead, IsResponse, HasData), InvalidCmd, "ReadResp" },
81    /* ReadRespWithInvalidate */
82    { SET4(IsRead, IsResponse, HasData, IsInvalidate),
83            InvalidCmd, "ReadRespWithInvalidate" },
84    /* WriteReq */
85    { SET5(IsWrite, NeedsWritable, IsRequest, NeedsResponse, HasData),
86            WriteResp, "WriteReq" },
87    /* WriteResp */
88    { SET2(IsWrite, IsResponse), InvalidCmd, "WriteResp" },
89    /* WritebackDirty */
90    { SET5(IsWrite, IsRequest, IsEviction, HasData, FromCache),
91            InvalidCmd, "WritebackDirty" },
92    /* WritebackClean - This allows the upstream cache to writeback a
93     * line to the downstream cache without it being considered
94     * dirty. */
95    { SET5(IsWrite, IsRequest, IsEviction, HasData, FromCache),
96            InvalidCmd, "WritebackClean" },
97    /* CleanEvict */
98    { SET3(IsRequest, IsEviction, FromCache), InvalidCmd, "CleanEvict" },
99    /* SoftPFReq */
100    { SET4(IsRead, IsRequest, IsSWPrefetch, NeedsResponse),
101            SoftPFResp, "SoftPFReq" },
102    /* HardPFReq */
103    { SET5(IsRead, IsRequest, IsHWPrefetch, NeedsResponse, FromCache),
104            HardPFResp, "HardPFReq" },
105    /* SoftPFResp */
106    { SET4(IsRead, IsResponse, IsSWPrefetch, HasData),
107            InvalidCmd, "SoftPFResp" },
108    /* HardPFResp */
109    { SET4(IsRead, IsResponse, IsHWPrefetch, HasData),
110            InvalidCmd, "HardPFResp" },
111    /* WriteLineReq */
112    { SET5(IsWrite, NeedsWritable, IsRequest, NeedsResponse, HasData),
113            WriteResp, "WriteLineReq" },
114    /* UpgradeReq */
115    { SET6(IsInvalidate, NeedsWritable, IsUpgrade, IsRequest, NeedsResponse,
116            FromCache),
117            UpgradeResp, "UpgradeReq" },
118    /* SCUpgradeReq: response could be UpgradeResp or UpgradeFailResp */
119    { SET7(IsInvalidate, NeedsWritable, IsUpgrade, IsLlsc,
120           IsRequest, NeedsResponse, FromCache),
121            UpgradeResp, "SCUpgradeReq" },
122    /* UpgradeResp */
123    { SET2(IsUpgrade, IsResponse),
124            InvalidCmd, "UpgradeResp" },
125    /* SCUpgradeFailReq: generates UpgradeFailResp but still gets the data */
126    { SET7(IsRead, NeedsWritable, IsInvalidate,
127           IsLlsc, IsRequest, NeedsResponse, FromCache),
128            UpgradeFailResp, "SCUpgradeFailReq" },
129    /* UpgradeFailResp - Behaves like a ReadExReq, but notifies an SC
130     * that it has failed, acquires line as Dirty*/
131    { SET3(IsRead, IsResponse, HasData),
132            InvalidCmd, "UpgradeFailResp" },
133    /* ReadExReq - Read issues by a cache, always cache-line aligned,
134     * and the response is guaranteed to be writeable (exclusive or
135     * even modified) */
136    { SET6(IsRead, NeedsWritable, IsInvalidate, IsRequest, NeedsResponse,
137            FromCache),
138            ReadExResp, "ReadExReq" },
139    /* ReadExResp - Response matching a read exclusive, as we check
140     * the need for exclusive also on responses */
141    { SET3(IsRead, IsResponse, HasData),
142            InvalidCmd, "ReadExResp" },
143    /* ReadCleanReq - Read issued by a cache, always cache-line
144     * aligned, and the response is guaranteed to not contain dirty data
145     * (exclusive or shared).*/
146    { SET4(IsRead, IsRequest, NeedsResponse, FromCache),
147            ReadResp, "ReadCleanReq" },
148    /* ReadSharedReq - Read issued by a cache, always cache-line
149     * aligned, response is shared, possibly exclusive, owned or even
150     * modified. */
151    { SET4(IsRead, IsRequest, NeedsResponse, FromCache),
152            ReadResp, "ReadSharedReq" },
153    /* LoadLockedReq: note that we use plain ReadResp as response, so that
154     *                we can also use ReadRespWithInvalidate when needed */
155    { SET4(IsRead, IsLlsc, IsRequest, NeedsResponse),
156            ReadResp, "LoadLockedReq" },
157    /* StoreCondReq */
158    { SET6(IsWrite, NeedsWritable, IsLlsc,
159           IsRequest, NeedsResponse, HasData),
160            StoreCondResp, "StoreCondReq" },
161    /* StoreCondFailReq: generates failing StoreCondResp */
162    { SET6(IsWrite, NeedsWritable, IsLlsc,
163           IsRequest, NeedsResponse, HasData),
164            StoreCondResp, "StoreCondFailReq" },
165    /* StoreCondResp */
166    { SET3(IsWrite, IsLlsc, IsResponse),
167            InvalidCmd, "StoreCondResp" },
168    /* SwapReq -- for Swap ldstub type operations */
169    { SET6(IsRead, IsWrite, NeedsWritable, IsRequest, HasData, NeedsResponse),
170        SwapResp, "SwapReq" },
171    /* SwapResp -- for Swap ldstub type operations */
172    { SET4(IsRead, IsWrite, IsResponse, HasData),
173            InvalidCmd, "SwapResp" },
174    /* IntReq -- for interrupts */
175    { SET4(IsWrite, IsRequest, NeedsResponse, HasData),
176        MessageResp, "MessageReq" },
177    /* IntResp -- for interrupts */
178    { SET2(IsWrite, IsResponse), InvalidCmd, "MessageResp" },
179    /* MemFenceReq -- for synchronization requests */
180    {SET2(IsRequest, NeedsResponse), MemFenceResp, "MemFenceReq"},
181    /* MemFenceResp -- for synchronization responses */
182    {SET1(IsResponse), InvalidCmd, "MemFenceResp"},
183    /* InvalidDestError  -- packet dest field invalid */
184    { SET2(IsResponse, IsError), InvalidCmd, "InvalidDestError" },
185    /* BadAddressError   -- memory address invalid */
186    { SET2(IsResponse, IsError), InvalidCmd, "BadAddressError" },
187    /* FunctionalReadError */
188    { SET3(IsRead, IsResponse, IsError), InvalidCmd, "FunctionalReadError" },
189    /* FunctionalWriteError */
190    { SET3(IsWrite, IsResponse, IsError), InvalidCmd, "FunctionalWriteError" },
191    /* PrintReq */
192    { SET2(IsRequest, IsPrint), InvalidCmd, "PrintReq" },
193    /* Flush Request */
194    { SET3(IsRequest, IsFlush, NeedsWritable), InvalidCmd, "FlushReq" },
195    /* Invalidation Request */
196    { SET5(IsInvalidate, IsRequest, NeedsWritable, NeedsResponse, FromCache),
197      InvalidateResp, "InvalidateReq" },
198    /* Invalidation Response */
199    { SET2(IsInvalidate, IsResponse),
200      InvalidCmd, "InvalidateResp" }
201};
202
203bool
204Packet::checkFunctional(Printable *obj, Addr addr, bool is_secure, int size,
205                        uint8_t *_data)
206{
207    Addr func_start = getAddr();
208    Addr func_end   = getAddr() + getSize() - 1;
209    Addr val_start  = addr;
210    Addr val_end    = val_start + size - 1;
211
212    if (is_secure != _isSecure || func_start > val_end ||
213        val_start > func_end) {
214        // no intersection
215        return false;
216    }
217
218    // check print first since it doesn't require data
219    if (isPrint()) {
220        assert(!_data);
221        safe_cast<PrintReqState*>(senderState)->printObj(obj);
222        return false;
223    }
224
225    // we allow the caller to pass NULL to signify the other packet
226    // has no data
227    if (!_data) {
228        return false;
229    }
230
231    // offset of functional request into supplied value (could be
232    // negative if partial overlap)
233    int offset = func_start - val_start;
234
235    if (isRead()) {
236        if (func_start >= val_start && func_end <= val_end) {
237            memcpy(getPtr<uint8_t>(), _data + offset, getSize());
238            if (bytesValid.empty())
239                bytesValid.resize(getSize(), true);
240            // complete overlap, and as the current packet is a read
241            // we are done
242            return true;
243        } else {
244            // Offsets and sizes to copy in case of partial overlap
245            int func_offset;
246            int val_offset;
247            int overlap_size;
248
249            // calculate offsets and copy sizes for the two byte arrays
250            if (val_start < func_start && val_end <= func_end) {
251                // the one we are checking against starts before and
252                // ends before or the same
253                val_offset = func_start - val_start;
254                func_offset = 0;
255                overlap_size = val_end - func_start;
256            } else if (val_start >= func_start && val_end > func_end) {
257                // the one we are checking against starts after or the
258                // same, and ends after
259                val_offset = 0;
260                func_offset = val_start - func_start;
261                overlap_size = func_end - val_start;
262            } else if (val_start >= func_start && val_end <= func_end) {
263                // the one we are checking against is completely
264                // subsumed in the current packet, possibly starting
265                // and ending at the same address
266                val_offset = 0;
267                func_offset = val_start - func_start;
268                overlap_size = size;
269            } else if (val_start < func_start && val_end > func_end) {
270                // the current packet is completely subsumed in the
271                // one we are checking against
272                val_offset = func_start - val_start;
273                func_offset = 0;
274                overlap_size = func_end - func_start;
275            } else {
276                panic("Missed a case for checkFunctional with "
277                      " %s 0x%x size %d, against 0x%x size %d\n",
278                      cmdString(), getAddr(), getSize(), addr, size);
279            }
280
281            // copy partial data into the packet's data array
282            uint8_t *dest = getPtr<uint8_t>() + func_offset;
283            uint8_t *src = _data + val_offset;
284            memcpy(dest, src, overlap_size);
285
286            // initialise the tracking of valid bytes if we have not
287            // used it already
288            if (bytesValid.empty())
289                bytesValid.resize(getSize(), false);
290
291            // track if we are done filling the functional access
292            bool all_bytes_valid = true;
293
294            int i = 0;
295
296            // check up to func_offset
297            for (; all_bytes_valid && i < func_offset; ++i)
298                all_bytes_valid &= bytesValid[i];
299
300            // update the valid bytes
301            for (i = func_offset; i < func_offset + overlap_size; ++i)
302                bytesValid[i] = true;
303
304            // check the bit after the update we just made
305            for (; all_bytes_valid && i < getSize(); ++i)
306                all_bytes_valid &= bytesValid[i];
307
308            return all_bytes_valid;
309        }
310    } else if (isWrite()) {
311        if (offset >= 0) {
312            memcpy(_data + offset, getConstPtr<uint8_t>(),
313                   (min(func_end, val_end) - func_start) + 1);
314        } else {
315            // val_start > func_start
316            memcpy(_data, getConstPtr<uint8_t>() - offset,
317                   (min(func_end, val_end) - val_start) + 1);
318        }
319    } else {
320        panic("Don't know how to handle command %s\n", cmdString());
321    }
322
323    // keep going with request by default
324    return false;
325}
326
327void
328Packet::pushSenderState(Packet::SenderState *sender_state)
329{
330    assert(sender_state != NULL);
331    sender_state->predecessor = senderState;
332    senderState = sender_state;
333}
334
335Packet::SenderState *
336Packet::popSenderState()
337{
338    assert(senderState != NULL);
339    SenderState *sender_state = senderState;
340    senderState = sender_state->predecessor;
341    sender_state->predecessor = NULL;
342    return sender_state;
343}
344
345void
346Packet::print(ostream &o, const int verbosity, const string &prefix) const
347{
348    ccprintf(o, "%s%s [%x:%x]%s%s%s%s", prefix, cmdString(),
349             getAddr(), getAddr() + getSize() - 1,
350             req->isSecure() ? " (s)" : "",
351             req->isInstFetch() ? " IF" : "",
352             req->isUncacheable() ? " UC" : "",
353             isExpressSnoop() ? " ES" : "");
354}
355
356std::string
357Packet::print() const {
358    ostringstream str;
359    print(str);
360    return str.str();
361}
362
363Packet::PrintReqState::PrintReqState(ostream &_os, int _verbosity)
364    : curPrefixPtr(new string("")), os(_os), verbosity(_verbosity)
365{
366    labelStack.push_back(LabelStackEntry("", curPrefixPtr));
367}
368
369Packet::PrintReqState::~PrintReqState()
370{
371    labelStack.pop_back();
372    assert(labelStack.empty());
373    delete curPrefixPtr;
374}
375
376Packet::PrintReqState::
377LabelStackEntry::LabelStackEntry(const string &_label, string *_prefix)
378    : label(_label), prefix(_prefix), labelPrinted(false)
379{
380}
381
382void
383Packet::PrintReqState::pushLabel(const string &lbl, const string &prefix)
384{
385    labelStack.push_back(LabelStackEntry(lbl, curPrefixPtr));
386    curPrefixPtr = new string(*curPrefixPtr);
387    *curPrefixPtr += prefix;
388}
389
390void
391Packet::PrintReqState::popLabel()
392{
393    delete curPrefixPtr;
394    curPrefixPtr = labelStack.back().prefix;
395    labelStack.pop_back();
396    assert(!labelStack.empty());
397}
398
399void
400Packet::PrintReqState::printLabels()
401{
402    if (!labelStack.back().labelPrinted) {
403        LabelStack::iterator i = labelStack.begin();
404        LabelStack::iterator end = labelStack.end();
405        while (i != end) {
406            if (!i->labelPrinted) {
407                ccprintf(os, "%s%s\n", *(i->prefix), i->label);
408                i->labelPrinted = true;
409            }
410            i++;
411        }
412    }
413}
414
415
416void
417Packet::PrintReqState::printObj(Printable *obj)
418{
419    printLabels();
420    obj->print(os, verbosity, curPrefix());
421}
422