packet.cc revision 12347:c4bb52d1aba4
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    /* Cache Clean Request -- Update with the latest data all existing
188       copies of the block down to the point indicated by the
189       request */
190    { SET4(IsRequest, IsClean, NeedsResponse, FromCache),
191      CleanSharedResp, "CleanSharedReq" },
192    /* Cache Clean Response - Indicates that all caches up to the
193       specified point of reference have a up-to-date copy of the
194       cache block or no copy at all */
195    { SET2(IsResponse, IsClean), InvalidCmd, "CleanSharedResp" },
196    /* Cache Clean and Invalidate Request -- Invalidate all existing
197       copies down to the point indicated by the request */
198    { SET5(IsRequest, IsInvalidate, IsClean, NeedsResponse, FromCache),
199      CleanInvalidResp, "CleanInvalidReq" },
200     /* Cache Clean and Invalidate Respose -- Indicates that no cache
201        above the specified point holds the block and that the block
202        was written to a memory below the specified point. */
203    { SET3(IsResponse, IsInvalidate, IsClean),
204      InvalidCmd, "CleanInvalidResp" },
205    /* InvalidDestError  -- packet dest field invalid */
206    { SET2(IsResponse, IsError), InvalidCmd, "InvalidDestError" },
207    /* BadAddressError   -- memory address invalid */
208    { SET2(IsResponse, IsError), InvalidCmd, "BadAddressError" },
209    /* FunctionalReadError */
210    { SET3(IsRead, IsResponse, IsError), InvalidCmd, "FunctionalReadError" },
211    /* FunctionalWriteError */
212    { SET3(IsWrite, IsResponse, IsError), InvalidCmd, "FunctionalWriteError" },
213    /* PrintReq */
214    { SET2(IsRequest, IsPrint), InvalidCmd, "PrintReq" },
215    /* Flush Request */
216    { SET3(IsRequest, IsFlush, NeedsWritable), InvalidCmd, "FlushReq" },
217    /* Invalidation Request */
218    { SET5(IsInvalidate, IsRequest, NeedsWritable, NeedsResponse, FromCache),
219      InvalidateResp, "InvalidateReq" },
220    /* Invalidation Response */
221    { SET2(IsInvalidate, IsResponse),
222      InvalidCmd, "InvalidateResp" }
223};
224
225bool
226Packet::checkFunctional(Printable *obj, Addr addr, bool is_secure, int size,
227                        uint8_t *_data)
228{
229    Addr func_start = getAddr();
230    Addr func_end   = getAddr() + getSize() - 1;
231    Addr val_start  = addr;
232    Addr val_end    = val_start + size - 1;
233
234    if (is_secure != _isSecure || func_start > val_end ||
235        val_start > func_end) {
236        // no intersection
237        return false;
238    }
239
240    // check print first since it doesn't require data
241    if (isPrint()) {
242        assert(!_data);
243        safe_cast<PrintReqState*>(senderState)->printObj(obj);
244        return false;
245    }
246
247    // we allow the caller to pass NULL to signify the other packet
248    // has no data
249    if (!_data) {
250        return false;
251    }
252
253    // offset of functional request into supplied value (could be
254    // negative if partial overlap)
255    int offset = func_start - val_start;
256
257    if (isRead()) {
258        if (func_start >= val_start && func_end <= val_end) {
259            memcpy(getPtr<uint8_t>(), _data + offset, getSize());
260            if (bytesValid.empty())
261                bytesValid.resize(getSize(), true);
262            // complete overlap, and as the current packet is a read
263            // we are done
264            return true;
265        } else {
266            // Offsets and sizes to copy in case of partial overlap
267            int func_offset;
268            int val_offset;
269            int overlap_size;
270
271            // calculate offsets and copy sizes for the two byte arrays
272            if (val_start < func_start && val_end <= func_end) {
273                // the one we are checking against starts before and
274                // ends before or the same
275                val_offset = func_start - val_start;
276                func_offset = 0;
277                overlap_size = val_end - func_start;
278            } else if (val_start >= func_start && val_end > func_end) {
279                // the one we are checking against starts after or the
280                // same, and ends after
281                val_offset = 0;
282                func_offset = val_start - func_start;
283                overlap_size = func_end - val_start;
284            } else if (val_start >= func_start && val_end <= func_end) {
285                // the one we are checking against is completely
286                // subsumed in the current packet, possibly starting
287                // and ending at the same address
288                val_offset = 0;
289                func_offset = val_start - func_start;
290                overlap_size = size;
291            } else if (val_start < func_start && val_end > func_end) {
292                // the current packet is completely subsumed in the
293                // one we are checking against
294                val_offset = func_start - val_start;
295                func_offset = 0;
296                overlap_size = func_end - func_start;
297            } else {
298                panic("Missed a case for checkFunctional with "
299                      " %s 0x%x size %d, against 0x%x size %d\n",
300                      cmdString(), getAddr(), getSize(), addr, size);
301            }
302
303            // copy partial data into the packet's data array
304            uint8_t *dest = getPtr<uint8_t>() + func_offset;
305            uint8_t *src = _data + val_offset;
306            memcpy(dest, src, overlap_size);
307
308            // initialise the tracking of valid bytes if we have not
309            // used it already
310            if (bytesValid.empty())
311                bytesValid.resize(getSize(), false);
312
313            // track if we are done filling the functional access
314            bool all_bytes_valid = true;
315
316            int i = 0;
317
318            // check up to func_offset
319            for (; all_bytes_valid && i < func_offset; ++i)
320                all_bytes_valid &= bytesValid[i];
321
322            // update the valid bytes
323            for (i = func_offset; i < func_offset + overlap_size; ++i)
324                bytesValid[i] = true;
325
326            // check the bit after the update we just made
327            for (; all_bytes_valid && i < getSize(); ++i)
328                all_bytes_valid &= bytesValid[i];
329
330            return all_bytes_valid;
331        }
332    } else if (isWrite()) {
333        if (offset >= 0) {
334            memcpy(_data + offset, getConstPtr<uint8_t>(),
335                   (min(func_end, val_end) - func_start) + 1);
336        } else {
337            // val_start > func_start
338            memcpy(_data, getConstPtr<uint8_t>() - offset,
339                   (min(func_end, val_end) - val_start) + 1);
340        }
341    } else {
342        panic("Don't know how to handle command %s\n", cmdString());
343    }
344
345    // keep going with request by default
346    return false;
347}
348
349void
350Packet::pushSenderState(Packet::SenderState *sender_state)
351{
352    assert(sender_state != NULL);
353    sender_state->predecessor = senderState;
354    senderState = sender_state;
355}
356
357Packet::SenderState *
358Packet::popSenderState()
359{
360    assert(senderState != NULL);
361    SenderState *sender_state = senderState;
362    senderState = sender_state->predecessor;
363    sender_state->predecessor = NULL;
364    return sender_state;
365}
366
367void
368Packet::print(ostream &o, const int verbosity, const string &prefix) const
369{
370    ccprintf(o, "%s%s [%x:%x]%s%s%s%s%s%s", prefix, cmdString(),
371             getAddr(), getAddr() + getSize() - 1,
372             req->isSecure() ? " (s)" : "",
373             req->isInstFetch() ? " IF" : "",
374             req->isUncacheable() ? " UC" : "",
375             isExpressSnoop() ? " ES" : "",
376             req->isToPOC() ? " PoC" : "",
377             req->isToPOU() ? " PoU" : "");
378}
379
380std::string
381Packet::print() const {
382    ostringstream str;
383    print(str);
384    return str.str();
385}
386
387Packet::PrintReqState::PrintReqState(ostream &_os, int _verbosity)
388    : curPrefixPtr(new string("")), os(_os), verbosity(_verbosity)
389{
390    labelStack.push_back(LabelStackEntry("", curPrefixPtr));
391}
392
393Packet::PrintReqState::~PrintReqState()
394{
395    labelStack.pop_back();
396    assert(labelStack.empty());
397    delete curPrefixPtr;
398}
399
400Packet::PrintReqState::
401LabelStackEntry::LabelStackEntry(const string &_label, string *_prefix)
402    : label(_label), prefix(_prefix), labelPrinted(false)
403{
404}
405
406void
407Packet::PrintReqState::pushLabel(const string &lbl, const string &prefix)
408{
409    labelStack.push_back(LabelStackEntry(lbl, curPrefixPtr));
410    curPrefixPtr = new string(*curPrefixPtr);
411    *curPrefixPtr += prefix;
412}
413
414void
415Packet::PrintReqState::popLabel()
416{
417    delete curPrefixPtr;
418    curPrefixPtr = labelStack.back().prefix;
419    labelStack.pop_back();
420    assert(!labelStack.empty());
421}
422
423void
424Packet::PrintReqState::printLabels()
425{
426    if (!labelStack.back().labelPrinted) {
427        LabelStack::iterator i = labelStack.begin();
428        LabelStack::iterator end = labelStack.end();
429        while (i != end) {
430            if (!i->labelPrinted) {
431                ccprintf(os, "%s%s\n", *(i->prefix), i->label);
432                i->labelPrinted = true;
433            }
434            i++;
435        }
436    }
437}
438
439
440void
441Packet::PrintReqState::printObj(Printable *obj)
442{
443    printLabels();
444    obj->print(os, verbosity, curPrefix());
445}
446