cache.cc revision 11600:a38c3f9c82d1
1/*
2 * Copyright (c) 2010-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) 2002-2005 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: Erik Hallnor
42 *          Dave Greene
43 *          Nathan Binkert
44 *          Steve Reinhardt
45 *          Ron Dreslinski
46 *          Andreas Sandberg
47 */
48
49/**
50 * @file
51 * Cache definitions.
52 */
53
54#include "mem/cache/cache.hh"
55
56#include "base/misc.hh"
57#include "base/types.hh"
58#include "debug/Cache.hh"
59#include "debug/CachePort.hh"
60#include "debug/CacheTags.hh"
61#include "debug/CacheVerbose.hh"
62#include "mem/cache/blk.hh"
63#include "mem/cache/mshr.hh"
64#include "mem/cache/prefetch/base.hh"
65#include "sim/sim_exit.hh"
66
67Cache::Cache(const CacheParams *p)
68    : BaseCache(p, p->system->cacheLineSize()),
69      tags(p->tags),
70      prefetcher(p->prefetcher),
71      doFastWrites(true),
72      prefetchOnAccess(p->prefetch_on_access),
73      clusivity(p->clusivity),
74      writebackClean(p->writeback_clean),
75      tempBlockWriteback(nullptr),
76      writebackTempBlockAtomicEvent(this, false,
77                                    EventBase::Delayed_Writeback_Pri)
78{
79    tempBlock = new CacheBlk();
80    tempBlock->data = new uint8_t[blkSize];
81
82    cpuSidePort = new CpuSidePort(p->name + ".cpu_side", this,
83                                  "CpuSidePort");
84    memSidePort = new MemSidePort(p->name + ".mem_side", this,
85                                  "MemSidePort");
86
87    tags->setCache(this);
88    if (prefetcher)
89        prefetcher->setCache(this);
90}
91
92Cache::~Cache()
93{
94    delete [] tempBlock->data;
95    delete tempBlock;
96
97    delete cpuSidePort;
98    delete memSidePort;
99}
100
101void
102Cache::regStats()
103{
104    BaseCache::regStats();
105}
106
107void
108Cache::cmpAndSwap(CacheBlk *blk, PacketPtr pkt)
109{
110    assert(pkt->isRequest());
111
112    uint64_t overwrite_val;
113    bool overwrite_mem;
114    uint64_t condition_val64;
115    uint32_t condition_val32;
116
117    int offset = tags->extractBlkOffset(pkt->getAddr());
118    uint8_t *blk_data = blk->data + offset;
119
120    assert(sizeof(uint64_t) >= pkt->getSize());
121
122    overwrite_mem = true;
123    // keep a copy of our possible write value, and copy what is at the
124    // memory address into the packet
125    pkt->writeData((uint8_t *)&overwrite_val);
126    pkt->setData(blk_data);
127
128    if (pkt->req->isCondSwap()) {
129        if (pkt->getSize() == sizeof(uint64_t)) {
130            condition_val64 = pkt->req->getExtraData();
131            overwrite_mem = !std::memcmp(&condition_val64, blk_data,
132                                         sizeof(uint64_t));
133        } else if (pkt->getSize() == sizeof(uint32_t)) {
134            condition_val32 = (uint32_t)pkt->req->getExtraData();
135            overwrite_mem = !std::memcmp(&condition_val32, blk_data,
136                                         sizeof(uint32_t));
137        } else
138            panic("Invalid size for conditional read/write\n");
139    }
140
141    if (overwrite_mem) {
142        std::memcpy(blk_data, &overwrite_val, pkt->getSize());
143        blk->status |= BlkDirty;
144    }
145}
146
147
148void
149Cache::satisfyCpuSideRequest(PacketPtr pkt, CacheBlk *blk,
150                             bool deferred_response, bool pending_downgrade)
151{
152    assert(pkt->isRequest());
153
154    assert(blk && blk->isValid());
155    // Occasionally this is not true... if we are a lower-level cache
156    // satisfying a string of Read and ReadEx requests from
157    // upper-level caches, a Read will mark the block as shared but we
158    // can satisfy a following ReadEx anyway since we can rely on the
159    // Read requester(s) to have buffered the ReadEx snoop and to
160    // invalidate their blocks after receiving them.
161    // assert(!pkt->needsWritable() || blk->isWritable());
162    assert(pkt->getOffset(blkSize) + pkt->getSize() <= blkSize);
163
164    // Check RMW operations first since both isRead() and
165    // isWrite() will be true for them
166    if (pkt->cmd == MemCmd::SwapReq) {
167        cmpAndSwap(blk, pkt);
168    } else if (pkt->isWrite()) {
169        // we have the block in a writable state and can go ahead,
170        // note that the line may be also be considered writable in
171        // downstream caches along the path to memory, but always
172        // Exclusive, and never Modified
173        assert(blk->isWritable());
174        // Write or WriteLine at the first cache with block in writable state
175        if (blk->checkWrite(pkt)) {
176            pkt->writeDataToBlock(blk->data, blkSize);
177        }
178        // Always mark the line as dirty (and thus transition to the
179        // Modified state) even if we are a failed StoreCond so we
180        // supply data to any snoops that have appended themselves to
181        // this cache before knowing the store will fail.
182        blk->status |= BlkDirty;
183        DPRINTF(CacheVerbose, "%s for %s addr %#llx size %d (write)\n",
184                __func__, pkt->cmdString(), pkt->getAddr(), pkt->getSize());
185    } else if (pkt->isRead()) {
186        if (pkt->isLLSC()) {
187            blk->trackLoadLocked(pkt);
188        }
189
190        // all read responses have a data payload
191        assert(pkt->hasRespData());
192        pkt->setDataFromBlock(blk->data, blkSize);
193
194        // determine if this read is from a (coherent) cache or not
195        if (pkt->fromCache()) {
196            assert(pkt->getSize() == blkSize);
197            // special handling for coherent block requests from
198            // upper-level caches
199            if (pkt->needsWritable()) {
200                // sanity check
201                assert(pkt->cmd == MemCmd::ReadExReq ||
202                       pkt->cmd == MemCmd::SCUpgradeFailReq);
203
204                // if we have a dirty copy, make sure the recipient
205                // keeps it marked dirty (in the modified state)
206                if (blk->isDirty()) {
207                    pkt->setCacheResponding();
208                }
209                // on ReadExReq we give up our copy unconditionally,
210                // even if this cache is mostly inclusive, we may want
211                // to revisit this
212                invalidateBlock(blk);
213            } else if (blk->isWritable() && !pending_downgrade &&
214                       !pkt->hasSharers() &&
215                       pkt->cmd != MemCmd::ReadCleanReq) {
216                // we can give the requester a writable copy on a read
217                // request if:
218                // - we have a writable copy at this level (& below)
219                // - we don't have a pending snoop from below
220                //   signaling another read request
221                // - no other cache above has a copy (otherwise it
222                //   would have set hasSharers flag when
223                //   snooping the packet)
224                // - the read has explicitly asked for a clean
225                //   copy of the line
226                if (blk->isDirty()) {
227                    // special considerations if we're owner:
228                    if (!deferred_response) {
229                        // respond with the line in Modified state
230                        // (cacheResponding set, hasSharers not set)
231                        pkt->setCacheResponding();
232
233                        if (clusivity == Enums::mostly_excl) {
234                            // if this cache is mostly exclusive with
235                            // respect to the cache above, drop the
236                            // block, no need to first unset the dirty
237                            // bit
238                            invalidateBlock(blk);
239                        } else {
240                            // if this cache is mostly inclusive, we
241                            // keep the block in the Exclusive state,
242                            // and pass it upwards as Modified
243                            // (writable and dirty), hence we have
244                            // multiple caches, all on the same path
245                            // towards memory, all considering the
246                            // same block writable, but only one
247                            // considering it Modified
248
249                            // we get away with multiple caches (on
250                            // the same path to memory) considering
251                            // the block writeable as we always enter
252                            // the cache hierarchy through a cache,
253                            // and first snoop upwards in all other
254                            // branches
255                            blk->status &= ~BlkDirty;
256                        }
257                    } else {
258                        // if we're responding after our own miss,
259                        // there's a window where the recipient didn't
260                        // know it was getting ownership and may not
261                        // have responded to snoops correctly, so we
262                        // have to respond with a shared line
263                        pkt->setHasSharers();
264                    }
265                }
266            } else {
267                // otherwise only respond with a shared copy
268                pkt->setHasSharers();
269            }
270        }
271    } else {
272        // Upgrade or Invalidate
273        assert(pkt->isUpgrade() || pkt->isInvalidate());
274
275        // for invalidations we could be looking at the temp block
276        // (for upgrades we always allocate)
277        invalidateBlock(blk);
278        DPRINTF(CacheVerbose, "%s for %s addr %#llx size %d (invalidation)\n",
279                __func__, pkt->cmdString(), pkt->getAddr(), pkt->getSize());
280    }
281}
282
283/////////////////////////////////////////////////////
284//
285// Access path: requests coming in from the CPU side
286//
287/////////////////////////////////////////////////////
288
289bool
290Cache::access(PacketPtr pkt, CacheBlk *&blk, Cycles &lat,
291              PacketList &writebacks)
292{
293    // sanity check
294    assert(pkt->isRequest());
295
296    chatty_assert(!(isReadOnly && pkt->isWrite()),
297                  "Should never see a write in a read-only cache %s\n",
298                  name());
299
300    DPRINTF(CacheVerbose, "%s for %s addr %#llx size %d\n", __func__,
301            pkt->cmdString(), pkt->getAddr(), pkt->getSize());
302
303    if (pkt->req->isUncacheable()) {
304        DPRINTF(Cache, "%s%s addr %#llx uncacheable\n", pkt->cmdString(),
305                pkt->req->isInstFetch() ? " (ifetch)" : "",
306                pkt->getAddr());
307
308        // flush and invalidate any existing block
309        CacheBlk *old_blk(tags->findBlock(pkt->getAddr(), pkt->isSecure()));
310        if (old_blk && old_blk->isValid()) {
311            if (old_blk->isDirty() || writebackClean)
312                writebacks.push_back(writebackBlk(old_blk));
313            else
314                writebacks.push_back(cleanEvictBlk(old_blk));
315            tags->invalidate(old_blk);
316            old_blk->invalidate();
317        }
318
319        blk = nullptr;
320        // lookupLatency is the latency in case the request is uncacheable.
321        lat = lookupLatency;
322        return false;
323    }
324
325    ContextID id = pkt->req->hasContextId() ?
326        pkt->req->contextId() : InvalidContextID;
327    // Here lat is the value passed as parameter to accessBlock() function
328    // that can modify its value.
329    blk = tags->accessBlock(pkt->getAddr(), pkt->isSecure(), lat, id);
330
331    DPRINTF(Cache, "%s%s addr %#llx size %d (%s) %s\n", pkt->cmdString(),
332            pkt->req->isInstFetch() ? " (ifetch)" : "",
333            pkt->getAddr(), pkt->getSize(), pkt->isSecure() ? "s" : "ns",
334            blk ? "hit " + blk->print() : "miss");
335
336
337    if (pkt->isEviction()) {
338        // We check for presence of block in above caches before issuing
339        // Writeback or CleanEvict to write buffer. Therefore the only
340        // possible cases can be of a CleanEvict packet coming from above
341        // encountering a Writeback generated in this cache peer cache and
342        // waiting in the write buffer. Cases of upper level peer caches
343        // generating CleanEvict and Writeback or simply CleanEvict and
344        // CleanEvict almost simultaneously will be caught by snoops sent out
345        // by crossbar.
346        WriteQueueEntry *wb_entry = writeBuffer.findMatch(pkt->getAddr(),
347                                                          pkt->isSecure());
348        if (wb_entry) {
349            assert(wb_entry->getNumTargets() == 1);
350            PacketPtr wbPkt = wb_entry->getTarget()->pkt;
351            assert(wbPkt->isWriteback());
352
353            if (pkt->isCleanEviction()) {
354                // The CleanEvict and WritebackClean snoops into other
355                // peer caches of the same level while traversing the
356                // crossbar. If a copy of the block is found, the
357                // packet is deleted in the crossbar. Hence, none of
358                // the other upper level caches connected to this
359                // cache have the block, so we can clear the
360                // BLOCK_CACHED flag in the Writeback if set and
361                // discard the CleanEvict by returning true.
362                wbPkt->clearBlockCached();
363                return true;
364            } else {
365                assert(pkt->cmd == MemCmd::WritebackDirty);
366                // Dirty writeback from above trumps our clean
367                // writeback... discard here
368                // Note: markInService will remove entry from writeback buffer.
369                markInService(wb_entry);
370                delete wbPkt;
371            }
372        }
373    }
374
375    // Writeback handling is special case.  We can write the block into
376    // the cache without having a writeable copy (or any copy at all).
377    if (pkt->isWriteback()) {
378        assert(blkSize == pkt->getSize());
379
380        // we could get a clean writeback while we are having
381        // outstanding accesses to a block, do the simple thing for
382        // now and drop the clean writeback so that we do not upset
383        // any ordering/decisions about ownership already taken
384        if (pkt->cmd == MemCmd::WritebackClean &&
385            mshrQueue.findMatch(pkt->getAddr(), pkt->isSecure())) {
386            DPRINTF(Cache, "Clean writeback %#llx to block with MSHR, "
387                    "dropping\n", pkt->getAddr());
388            return true;
389        }
390
391        if (blk == nullptr) {
392            // need to do a replacement
393            blk = allocateBlock(pkt->getAddr(), pkt->isSecure(), writebacks);
394            if (blk == nullptr) {
395                // no replaceable block available: give up, fwd to next level.
396                incMissCount(pkt);
397                return false;
398            }
399            tags->insertBlock(pkt, blk);
400
401            blk->status = (BlkValid | BlkReadable);
402            if (pkt->isSecure()) {
403                blk->status |= BlkSecure;
404            }
405        }
406        // only mark the block dirty if we got a writeback command,
407        // and leave it as is for a clean writeback
408        if (pkt->cmd == MemCmd::WritebackDirty) {
409            blk->status |= BlkDirty;
410        }
411        // if the packet does not have sharers, it is passing
412        // writable, and we got the writeback in Modified or Exclusive
413        // state, if not we are in the Owned or Shared state
414        if (!pkt->hasSharers()) {
415            blk->status |= BlkWritable;
416        }
417        // nothing else to do; writeback doesn't expect response
418        assert(!pkt->needsResponse());
419        std::memcpy(blk->data, pkt->getConstPtr<uint8_t>(), blkSize);
420        DPRINTF(Cache, "%s new state is %s\n", __func__, blk->print());
421        incHitCount(pkt);
422        return true;
423    } else if (pkt->cmd == MemCmd::CleanEvict) {
424        if (blk != nullptr) {
425            // Found the block in the tags, need to stop CleanEvict from
426            // propagating further down the hierarchy. Returning true will
427            // treat the CleanEvict like a satisfied write request and delete
428            // it.
429            return true;
430        }
431        // We didn't find the block here, propagate the CleanEvict further
432        // down the memory hierarchy. Returning false will treat the CleanEvict
433        // like a Writeback which could not find a replaceable block so has to
434        // go to next level.
435        return false;
436    } else if ((blk != nullptr) &&
437               (pkt->needsWritable() ? blk->isWritable() :
438                blk->isReadable())) {
439        // OK to satisfy access
440        incHitCount(pkt);
441        satisfyCpuSideRequest(pkt, blk);
442        return true;
443    }
444
445    // Can't satisfy access normally... either no block (blk == nullptr)
446    // or have block but need writable
447
448    incMissCount(pkt);
449
450    if (blk == nullptr && pkt->isLLSC() && pkt->isWrite()) {
451        // complete miss on store conditional... just give up now
452        pkt->req->setExtraData(0);
453        return true;
454    }
455
456    return false;
457}
458
459void
460Cache::doWritebacks(PacketList& writebacks, Tick forward_time)
461{
462    while (!writebacks.empty()) {
463        PacketPtr wbPkt = writebacks.front();
464        // We use forwardLatency here because we are copying writebacks to
465        // write buffer.  Call isCachedAbove for both Writebacks and
466        // CleanEvicts. If isCachedAbove returns true we set BLOCK_CACHED flag
467        // in Writebacks and discard CleanEvicts.
468        if (isCachedAbove(wbPkt)) {
469            if (wbPkt->cmd == MemCmd::CleanEvict) {
470                // Delete CleanEvict because cached copies exist above. The
471                // packet destructor will delete the request object because
472                // this is a non-snoop request packet which does not require a
473                // response.
474                delete wbPkt;
475            } else if (wbPkt->cmd == MemCmd::WritebackClean) {
476                // clean writeback, do not send since the block is
477                // still cached above
478                assert(writebackClean);
479                delete wbPkt;
480            } else {
481                assert(wbPkt->cmd == MemCmd::WritebackDirty);
482                // Set BLOCK_CACHED flag in Writeback and send below, so that
483                // the Writeback does not reset the bit corresponding to this
484                // address in the snoop filter below.
485                wbPkt->setBlockCached();
486                allocateWriteBuffer(wbPkt, forward_time);
487            }
488        } else {
489            // If the block is not cached above, send packet below. Both
490            // CleanEvict and Writeback with BLOCK_CACHED flag cleared will
491            // reset the bit corresponding to this address in the snoop filter
492            // below.
493            allocateWriteBuffer(wbPkt, forward_time);
494        }
495        writebacks.pop_front();
496    }
497}
498
499void
500Cache::doWritebacksAtomic(PacketList& writebacks)
501{
502    while (!writebacks.empty()) {
503        PacketPtr wbPkt = writebacks.front();
504        // Call isCachedAbove for both Writebacks and CleanEvicts. If
505        // isCachedAbove returns true we set BLOCK_CACHED flag in Writebacks
506        // and discard CleanEvicts.
507        if (isCachedAbove(wbPkt, false)) {
508            if (wbPkt->cmd == MemCmd::WritebackDirty) {
509                // Set BLOCK_CACHED flag in Writeback and send below,
510                // so that the Writeback does not reset the bit
511                // corresponding to this address in the snoop filter
512                // below. We can discard CleanEvicts because cached
513                // copies exist above. Atomic mode isCachedAbove
514                // modifies packet to set BLOCK_CACHED flag
515                memSidePort->sendAtomic(wbPkt);
516            }
517        } else {
518            // If the block is not cached above, send packet below. Both
519            // CleanEvict and Writeback with BLOCK_CACHED flag cleared will
520            // reset the bit corresponding to this address in the snoop filter
521            // below.
522            memSidePort->sendAtomic(wbPkt);
523        }
524        writebacks.pop_front();
525        // In case of CleanEvicts, the packet destructor will delete the
526        // request object because this is a non-snoop request packet which
527        // does not require a response.
528        delete wbPkt;
529    }
530}
531
532
533void
534Cache::recvTimingSnoopResp(PacketPtr pkt)
535{
536    DPRINTF(Cache, "%s for %s addr %#llx size %d\n", __func__,
537            pkt->cmdString(), pkt->getAddr(), pkt->getSize());
538
539    assert(pkt->isResponse());
540    assert(!system->bypassCaches());
541
542    // determine if the response is from a snoop request we created
543    // (in which case it should be in the outstandingSnoop), or if we
544    // merely forwarded someone else's snoop request
545    const bool forwardAsSnoop = outstandingSnoop.find(pkt->req) ==
546        outstandingSnoop.end();
547
548    if (!forwardAsSnoop) {
549        // the packet came from this cache, so sink it here and do not
550        // forward it
551        assert(pkt->cmd == MemCmd::HardPFResp);
552
553        outstandingSnoop.erase(pkt->req);
554
555        DPRINTF(Cache, "Got prefetch response from above for addr "
556                "%#llx (%s)\n", pkt->getAddr(), pkt->isSecure() ? "s" : "ns");
557        recvTimingResp(pkt);
558        return;
559    }
560
561    // forwardLatency is set here because there is a response from an
562    // upper level cache.
563    // To pay the delay that occurs if the packet comes from the bus,
564    // we charge also headerDelay.
565    Tick snoop_resp_time = clockEdge(forwardLatency) + pkt->headerDelay;
566    // Reset the timing of the packet.
567    pkt->headerDelay = pkt->payloadDelay = 0;
568    memSidePort->schedTimingSnoopResp(pkt, snoop_resp_time);
569}
570
571void
572Cache::promoteWholeLineWrites(PacketPtr pkt)
573{
574    // Cache line clearing instructions
575    if (doFastWrites && (pkt->cmd == MemCmd::WriteReq) &&
576        (pkt->getSize() == blkSize) && (pkt->getOffset(blkSize) == 0)) {
577        pkt->cmd = MemCmd::WriteLineReq;
578        DPRINTF(Cache, "packet promoted from Write to WriteLineReq\n");
579    }
580}
581
582bool
583Cache::recvTimingReq(PacketPtr pkt)
584{
585    DPRINTF(CacheTags, "%s tags: %s\n", __func__, tags->print());
586
587    assert(pkt->isRequest());
588
589    // Just forward the packet if caches are disabled.
590    if (system->bypassCaches()) {
591        // @todo This should really enqueue the packet rather
592        bool M5_VAR_USED success = memSidePort->sendTimingReq(pkt);
593        assert(success);
594        return true;
595    }
596
597    promoteWholeLineWrites(pkt);
598
599    if (pkt->cacheResponding()) {
600        // a cache above us (but not where the packet came from) is
601        // responding to the request, in other words it has the line
602        // in Modified or Owned state
603        DPRINTF(Cache, "Cache above responding to %#llx (%s): "
604                "not responding\n",
605                pkt->getAddr(), pkt->isSecure() ? "s" : "ns");
606
607        // if the packet needs the block to be writable, and the cache
608        // that has promised to respond (setting the cache responding
609        // flag) is not providing writable (it is in Owned rather than
610        // the Modified state), we know that there may be other Shared
611        // copies in the system; go out and invalidate them all
612        assert(pkt->needsWritable() && !pkt->responderHadWritable());
613
614        // an upstream cache that had the line in Owned state
615        // (dirty, but not writable), is responding and thus
616        // transferring the dirty line from one branch of the
617        // cache hierarchy to another
618
619        // send out an express snoop and invalidate all other
620        // copies (snooping a packet that needs writable is the
621        // same as an invalidation), thus turning the Owned line
622        // into a Modified line, note that we don't invalidate the
623        // block in the current cache or any other cache on the
624        // path to memory
625
626        // create a downstream express snoop with cleared packet
627        // flags, there is no need to allocate any data as the
628        // packet is merely used to co-ordinate state transitions
629        Packet *snoop_pkt = new Packet(pkt, true, false);
630
631        // also reset the bus time that the original packet has
632        // not yet paid for
633        snoop_pkt->headerDelay = snoop_pkt->payloadDelay = 0;
634
635        // make this an instantaneous express snoop, and let the
636        // other caches in the system know that the another cache
637        // is responding, because we have found the authorative
638        // copy (Modified or Owned) that will supply the right
639        // data
640        snoop_pkt->setExpressSnoop();
641        snoop_pkt->setCacheResponding();
642
643        // this express snoop travels towards the memory, and at
644        // every crossbar it is snooped upwards thus reaching
645        // every cache in the system
646        bool M5_VAR_USED success = memSidePort->sendTimingReq(snoop_pkt);
647        // express snoops always succeed
648        assert(success);
649
650        // main memory will delete the snoop packet
651
652        // queue for deletion, as opposed to immediate deletion, as
653        // the sending cache is still relying on the packet
654        pendingDelete.reset(pkt);
655
656        // no need to take any further action in this particular cache
657        // as an upstram cache has already committed to responding,
658        // and we have already sent out any express snoops in the
659        // section above to ensure all other copies in the system are
660        // invalidated
661        return true;
662    }
663
664    // anything that is merely forwarded pays for the forward latency and
665    // the delay provided by the crossbar
666    Tick forward_time = clockEdge(forwardLatency) + pkt->headerDelay;
667
668    // We use lookupLatency here because it is used to specify the latency
669    // to access.
670    Cycles lat = lookupLatency;
671    CacheBlk *blk = nullptr;
672    bool satisfied = false;
673    {
674        PacketList writebacks;
675        // Note that lat is passed by reference here. The function
676        // access() calls accessBlock() which can modify lat value.
677        satisfied = access(pkt, blk, lat, writebacks);
678
679        // copy writebacks to write buffer here to ensure they logically
680        // proceed anything happening below
681        doWritebacks(writebacks, forward_time);
682    }
683
684    // Here we charge the headerDelay that takes into account the latencies
685    // of the bus, if the packet comes from it.
686    // The latency charged it is just lat that is the value of lookupLatency
687    // modified by access() function, or if not just lookupLatency.
688    // In case of a hit we are neglecting response latency.
689    // In case of a miss we are neglecting forward latency.
690    Tick request_time = clockEdge(lat) + pkt->headerDelay;
691    // Here we reset the timing of the packet.
692    pkt->headerDelay = pkt->payloadDelay = 0;
693
694    // track time of availability of next prefetch, if any
695    Tick next_pf_time = MaxTick;
696
697    bool needsResponse = pkt->needsResponse();
698
699    if (satisfied) {
700        // should never be satisfying an uncacheable access as we
701        // flush and invalidate any existing block as part of the
702        // lookup
703        assert(!pkt->req->isUncacheable());
704
705        // hit (for all other request types)
706
707        if (prefetcher && (prefetchOnAccess ||
708                           (blk && blk->wasPrefetched()))) {
709            if (blk)
710                blk->status &= ~BlkHWPrefetched;
711
712            // Don't notify on SWPrefetch
713            if (!pkt->cmd.isSWPrefetch())
714                next_pf_time = prefetcher->notify(pkt);
715        }
716
717        if (needsResponse) {
718            pkt->makeTimingResponse();
719            // @todo: Make someone pay for this
720            pkt->headerDelay = pkt->payloadDelay = 0;
721
722            // In this case we are considering request_time that takes
723            // into account the delay of the xbar, if any, and just
724            // lat, neglecting responseLatency, modelling hit latency
725            // just as lookupLatency or or the value of lat overriden
726            // by access(), that calls accessBlock() function.
727            cpuSidePort->schedTimingResp(pkt, request_time, true);
728        } else {
729            DPRINTF(Cache, "%s satisfied %s addr %#llx, no response needed\n",
730                    __func__, pkt->cmdString(), pkt->getAddr());
731
732            // queue the packet for deletion, as the sending cache is
733            // still relying on it; if the block is found in access(),
734            // CleanEvict and Writeback messages will be deleted
735            // here as well
736            pendingDelete.reset(pkt);
737        }
738    } else {
739        // miss
740
741        Addr blk_addr = blockAlign(pkt->getAddr());
742
743        // ignore any existing MSHR if we are dealing with an
744        // uncacheable request
745        MSHR *mshr = pkt->req->isUncacheable() ? nullptr :
746            mshrQueue.findMatch(blk_addr, pkt->isSecure());
747
748        // Software prefetch handling:
749        // To keep the core from waiting on data it won't look at
750        // anyway, send back a response with dummy data. Miss handling
751        // will continue asynchronously. Unfortunately, the core will
752        // insist upon freeing original Packet/Request, so we have to
753        // create a new pair with a different lifecycle. Note that this
754        // processing happens before any MSHR munging on the behalf of
755        // this request because this new Request will be the one stored
756        // into the MSHRs, not the original.
757        if (pkt->cmd.isSWPrefetch()) {
758            assert(needsResponse);
759            assert(pkt->req->hasPaddr());
760            assert(!pkt->req->isUncacheable());
761
762            // There's no reason to add a prefetch as an additional target
763            // to an existing MSHR. If an outstanding request is already
764            // in progress, there is nothing for the prefetch to do.
765            // If this is the case, we don't even create a request at all.
766            PacketPtr pf = nullptr;
767
768            if (!mshr) {
769                // copy the request and create a new SoftPFReq packet
770                RequestPtr req = new Request(pkt->req->getPaddr(),
771                                             pkt->req->getSize(),
772                                             pkt->req->getFlags(),
773                                             pkt->req->masterId());
774                pf = new Packet(req, pkt->cmd);
775                pf->allocate();
776                assert(pf->getAddr() == pkt->getAddr());
777                assert(pf->getSize() == pkt->getSize());
778            }
779
780            pkt->makeTimingResponse();
781
782            // request_time is used here, taking into account lat and the delay
783            // charged if the packet comes from the xbar.
784            cpuSidePort->schedTimingResp(pkt, request_time, true);
785
786            // If an outstanding request is in progress (we found an
787            // MSHR) this is set to null
788            pkt = pf;
789        }
790
791        if (mshr) {
792            /// MSHR hit
793            /// @note writebacks will be checked in getNextMSHR()
794            /// for any conflicting requests to the same block
795
796            //@todo remove hw_pf here
797
798            // Coalesce unless it was a software prefetch (see above).
799            if (pkt) {
800                assert(!pkt->isWriteback());
801                // CleanEvicts corresponding to blocks which have
802                // outstanding requests in MSHRs are simply sunk here
803                if (pkt->cmd == MemCmd::CleanEvict) {
804                    pendingDelete.reset(pkt);
805                } else {
806                    DPRINTF(Cache, "%s coalescing MSHR for %s addr %#llx "
807                            "size %d\n", __func__, pkt->cmdString(),
808                            pkt->getAddr(), pkt->getSize());
809
810                    assert(pkt->req->masterId() < system->maxMasters());
811                    mshr_hits[pkt->cmdToIndex()][pkt->req->masterId()]++;
812                    // We use forward_time here because it is the same
813                    // considering new targets. We have multiple
814                    // requests for the same address here. It
815                    // specifies the latency to allocate an internal
816                    // buffer and to schedule an event to the queued
817                    // port and also takes into account the additional
818                    // delay of the xbar.
819                    mshr->allocateTarget(pkt, forward_time, order++,
820                                         allocOnFill(pkt->cmd));
821                    if (mshr->getNumTargets() == numTarget) {
822                        noTargetMSHR = mshr;
823                        setBlocked(Blocked_NoTargets);
824                        // need to be careful with this... if this mshr isn't
825                        // ready yet (i.e. time > curTick()), we don't want to
826                        // move it ahead of mshrs that are ready
827                        // mshrQueue.moveToFront(mshr);
828                    }
829                }
830                // We should call the prefetcher reguardless if the request is
831                // satisfied or not, reguardless if the request is in the MSHR
832                // or not.  The request could be a ReadReq hit, but still not
833                // satisfied (potentially because of a prior write to the same
834                // cache line.  So, even when not satisfied, tehre is an MSHR
835                // already allocated for this, we need to let the prefetcher
836                // know about the request
837                if (prefetcher) {
838                    // Don't notify on SWPrefetch
839                    if (!pkt->cmd.isSWPrefetch())
840                        next_pf_time = prefetcher->notify(pkt);
841                }
842            }
843        } else {
844            // no MSHR
845            assert(pkt->req->masterId() < system->maxMasters());
846            if (pkt->req->isUncacheable()) {
847                mshr_uncacheable[pkt->cmdToIndex()][pkt->req->masterId()]++;
848            } else {
849                mshr_misses[pkt->cmdToIndex()][pkt->req->masterId()]++;
850            }
851
852            if (pkt->isEviction() ||
853                (pkt->req->isUncacheable() && pkt->isWrite())) {
854                // We use forward_time here because there is an
855                // uncached memory write, forwarded to WriteBuffer.
856                allocateWriteBuffer(pkt, forward_time);
857            } else {
858                if (blk && blk->isValid()) {
859                    // should have flushed and have no valid block
860                    assert(!pkt->req->isUncacheable());
861
862                    // If we have a write miss to a valid block, we
863                    // need to mark the block non-readable.  Otherwise
864                    // if we allow reads while there's an outstanding
865                    // write miss, the read could return stale data
866                    // out of the cache block... a more aggressive
867                    // system could detect the overlap (if any) and
868                    // forward data out of the MSHRs, but we don't do
869                    // that yet.  Note that we do need to leave the
870                    // block valid so that it stays in the cache, in
871                    // case we get an upgrade response (and hence no
872                    // new data) when the write miss completes.
873                    // As long as CPUs do proper store/load forwarding
874                    // internally, and have a sufficiently weak memory
875                    // model, this is probably unnecessary, but at some
876                    // point it must have seemed like we needed it...
877                    assert(pkt->needsWritable());
878                    assert(!blk->isWritable());
879                    blk->status &= ~BlkReadable;
880                }
881                // Here we are using forward_time, modelling the latency of
882                // a miss (outbound) just as forwardLatency, neglecting the
883                // lookupLatency component.
884                allocateMissBuffer(pkt, forward_time);
885            }
886
887            if (prefetcher) {
888                // Don't notify on SWPrefetch
889                if (!pkt->cmd.isSWPrefetch())
890                    next_pf_time = prefetcher->notify(pkt);
891            }
892        }
893    }
894
895    if (next_pf_time != MaxTick)
896        schedMemSideSendEvent(next_pf_time);
897
898    return true;
899}
900
901PacketPtr
902Cache::createMissPacket(PacketPtr cpu_pkt, CacheBlk *blk,
903                        bool needsWritable) const
904{
905    // should never see evictions here
906    assert(!cpu_pkt->isEviction());
907
908    bool blkValid = blk && blk->isValid();
909
910    if (cpu_pkt->req->isUncacheable() ||
911        (!blkValid && cpu_pkt->isUpgrade())) {
912        // uncacheable requests and upgrades from upper-level caches
913        // that missed completely just go through as is
914        return nullptr;
915    }
916
917    assert(cpu_pkt->needsResponse());
918
919    MemCmd cmd;
920    // @TODO make useUpgrades a parameter.
921    // Note that ownership protocols require upgrade, otherwise a
922    // write miss on a shared owned block will generate a ReadExcl,
923    // which will clobber the owned copy.
924    const bool useUpgrades = true;
925    if (blkValid && useUpgrades) {
926        // only reason to be here is that blk is read only and we need
927        // it to be writable
928        assert(needsWritable);
929        assert(!blk->isWritable());
930        cmd = cpu_pkt->isLLSC() ? MemCmd::SCUpgradeReq : MemCmd::UpgradeReq;
931    } else if (cpu_pkt->cmd == MemCmd::SCUpgradeFailReq ||
932               cpu_pkt->cmd == MemCmd::StoreCondFailReq) {
933        // Even though this SC will fail, we still need to send out the
934        // request and get the data to supply it to other snoopers in the case
935        // where the determination the StoreCond fails is delayed due to
936        // all caches not being on the same local bus.
937        cmd = MemCmd::SCUpgradeFailReq;
938    } else if (cpu_pkt->cmd == MemCmd::WriteLineReq ||
939               cpu_pkt->cmd == MemCmd::InvalidateReq) {
940        // forward as invalidate to all other caches, this gives us
941        // the line in Exclusive state, and invalidates all other
942        // copies
943        cmd = MemCmd::InvalidateReq;
944    } else {
945        // block is invalid
946        cmd = needsWritable ? MemCmd::ReadExReq :
947            (isReadOnly ? MemCmd::ReadCleanReq : MemCmd::ReadSharedReq);
948    }
949    PacketPtr pkt = new Packet(cpu_pkt->req, cmd, blkSize);
950
951    // if there are upstream caches that have already marked the
952    // packet as having sharers (not passing writable), pass that info
953    // downstream
954    if (cpu_pkt->hasSharers()) {
955        // note that cpu_pkt may have spent a considerable time in the
956        // MSHR queue and that the information could possibly be out
957        // of date, however, there is no harm in conservatively
958        // assuming the block has sharers
959        pkt->setHasSharers();
960        DPRINTF(Cache, "%s passing hasSharers from %s to %s addr %#llx "
961                "size %d\n",
962                __func__, cpu_pkt->cmdString(), pkt->cmdString(),
963                pkt->getAddr(), pkt->getSize());
964    }
965
966    // the packet should be block aligned
967    assert(pkt->getAddr() == blockAlign(pkt->getAddr()));
968
969    pkt->allocate();
970    DPRINTF(Cache, "%s created %s from %s for  addr %#llx size %d\n",
971            __func__, pkt->cmdString(), cpu_pkt->cmdString(), pkt->getAddr(),
972            pkt->getSize());
973    return pkt;
974}
975
976
977Tick
978Cache::recvAtomic(PacketPtr pkt)
979{
980    // We are in atomic mode so we pay just for lookupLatency here.
981    Cycles lat = lookupLatency;
982
983    // Forward the request if the system is in cache bypass mode.
984    if (system->bypassCaches())
985        return ticksToCycles(memSidePort->sendAtomic(pkt));
986
987    promoteWholeLineWrites(pkt);
988
989    // follow the same flow as in recvTimingReq, and check if a cache
990    // above us is responding
991    if (pkt->cacheResponding()) {
992        DPRINTF(Cache, "Cache above responding to %#llx (%s): "
993                "not responding\n",
994                pkt->getAddr(), pkt->isSecure() ? "s" : "ns");
995
996        // if a cache is responding, and it had the line in Owned
997        // rather than Modified state, we need to invalidate any
998        // copies that are not on the same path to memory
999        assert(pkt->needsWritable() && !pkt->responderHadWritable());
1000        lat += ticksToCycles(memSidePort->sendAtomic(pkt));
1001
1002        return lat * clockPeriod();
1003    }
1004
1005    // should assert here that there are no outstanding MSHRs or
1006    // writebacks... that would mean that someone used an atomic
1007    // access in timing mode
1008
1009    CacheBlk *blk = nullptr;
1010    PacketList writebacks;
1011    bool satisfied = access(pkt, blk, lat, writebacks);
1012
1013    // handle writebacks resulting from the access here to ensure they
1014    // logically proceed anything happening below
1015    doWritebacksAtomic(writebacks);
1016
1017    if (!satisfied) {
1018        // MISS
1019
1020        // deal with the packets that go through the write path of
1021        // the cache, i.e. any evictions and uncacheable writes
1022        if (pkt->isEviction() ||
1023            (pkt->req->isUncacheable() && pkt->isWrite())) {
1024            lat += ticksToCycles(memSidePort->sendAtomic(pkt));
1025            return lat * clockPeriod();
1026        }
1027        // only misses left
1028
1029        PacketPtr bus_pkt = createMissPacket(pkt, blk, pkt->needsWritable());
1030
1031        bool is_forward = (bus_pkt == nullptr);
1032
1033        if (is_forward) {
1034            // just forwarding the same request to the next level
1035            // no local cache operation involved
1036            bus_pkt = pkt;
1037        }
1038
1039        DPRINTF(Cache, "Sending an atomic %s for %#llx (%s)\n",
1040                bus_pkt->cmdString(), bus_pkt->getAddr(),
1041                bus_pkt->isSecure() ? "s" : "ns");
1042
1043#if TRACING_ON
1044        CacheBlk::State old_state = blk ? blk->status : 0;
1045#endif
1046
1047        lat += ticksToCycles(memSidePort->sendAtomic(bus_pkt));
1048
1049        bool is_invalidate = bus_pkt->isInvalidate();
1050
1051        // We are now dealing with the response handling
1052        DPRINTF(Cache, "Receive response: %s for addr %#llx (%s) in "
1053                "state %i\n", bus_pkt->cmdString(), bus_pkt->getAddr(),
1054                bus_pkt->isSecure() ? "s" : "ns",
1055                old_state);
1056
1057        // If packet was a forward, the response (if any) is already
1058        // in place in the bus_pkt == pkt structure, so we don't need
1059        // to do anything.  Otherwise, use the separate bus_pkt to
1060        // generate response to pkt and then delete it.
1061        if (!is_forward) {
1062            if (pkt->needsResponse()) {
1063                assert(bus_pkt->isResponse());
1064                if (bus_pkt->isError()) {
1065                    pkt->makeAtomicResponse();
1066                    pkt->copyError(bus_pkt);
1067                } else if (pkt->cmd == MemCmd::WriteLineReq) {
1068                    // note the use of pkt, not bus_pkt here.
1069
1070                    // write-line request to the cache that promoted
1071                    // the write to a whole line
1072                    blk = handleFill(pkt, blk, writebacks,
1073                                     allocOnFill(pkt->cmd));
1074                    assert(blk != NULL);
1075                    is_invalidate = false;
1076                    satisfyCpuSideRequest(pkt, blk);
1077                } else if (bus_pkt->isRead() ||
1078                           bus_pkt->cmd == MemCmd::UpgradeResp) {
1079                    // we're updating cache state to allow us to
1080                    // satisfy the upstream request from the cache
1081                    blk = handleFill(bus_pkt, blk, writebacks,
1082                                     allocOnFill(pkt->cmd));
1083                    satisfyCpuSideRequest(pkt, blk);
1084                } else {
1085                    // we're satisfying the upstream request without
1086                    // modifying cache state, e.g., a write-through
1087                    pkt->makeAtomicResponse();
1088                }
1089            }
1090            delete bus_pkt;
1091        }
1092
1093        if (is_invalidate && blk && blk->isValid()) {
1094            invalidateBlock(blk);
1095        }
1096    }
1097
1098    // Note that we don't invoke the prefetcher at all in atomic mode.
1099    // It's not clear how to do it properly, particularly for
1100    // prefetchers that aggressively generate prefetch candidates and
1101    // rely on bandwidth contention to throttle them; these will tend
1102    // to pollute the cache in atomic mode since there is no bandwidth
1103    // contention.  If we ever do want to enable prefetching in atomic
1104    // mode, though, this is the place to do it... see timingAccess()
1105    // for an example (though we'd want to issue the prefetch(es)
1106    // immediately rather than calling requestMemSideBus() as we do
1107    // there).
1108
1109    // do any writebacks resulting from the response handling
1110    doWritebacksAtomic(writebacks);
1111
1112    // if we used temp block, check to see if its valid and if so
1113    // clear it out, but only do so after the call to recvAtomic is
1114    // finished so that any downstream observers (such as a snoop
1115    // filter), first see the fill, and only then see the eviction
1116    if (blk == tempBlock && tempBlock->isValid()) {
1117        // the atomic CPU calls recvAtomic for fetch and load/store
1118        // sequentuially, and we may already have a tempBlock
1119        // writeback from the fetch that we have not yet sent
1120        if (tempBlockWriteback) {
1121            // if that is the case, write the prevoius one back, and
1122            // do not schedule any new event
1123            writebackTempBlockAtomic();
1124        } else {
1125            // the writeback/clean eviction happens after the call to
1126            // recvAtomic has finished (but before any successive
1127            // calls), so that the response handling from the fill is
1128            // allowed to happen first
1129            schedule(writebackTempBlockAtomicEvent, curTick());
1130        }
1131
1132        tempBlockWriteback = (blk->isDirty() || writebackClean) ?
1133            writebackBlk(blk) : cleanEvictBlk(blk);
1134        blk->invalidate();
1135    }
1136
1137    if (pkt->needsResponse()) {
1138        pkt->makeAtomicResponse();
1139    }
1140
1141    return lat * clockPeriod();
1142}
1143
1144
1145void
1146Cache::functionalAccess(PacketPtr pkt, bool fromCpuSide)
1147{
1148    if (system->bypassCaches()) {
1149        // Packets from the memory side are snoop request and
1150        // shouldn't happen in bypass mode.
1151        assert(fromCpuSide);
1152
1153        // The cache should be flushed if we are in cache bypass mode,
1154        // so we don't need to check if we need to update anything.
1155        memSidePort->sendFunctional(pkt);
1156        return;
1157    }
1158
1159    Addr blk_addr = blockAlign(pkt->getAddr());
1160    bool is_secure = pkt->isSecure();
1161    CacheBlk *blk = tags->findBlock(pkt->getAddr(), is_secure);
1162    MSHR *mshr = mshrQueue.findMatch(blk_addr, is_secure);
1163
1164    pkt->pushLabel(name());
1165
1166    CacheBlkPrintWrapper cbpw(blk);
1167
1168    // Note that just because an L2/L3 has valid data doesn't mean an
1169    // L1 doesn't have a more up-to-date modified copy that still
1170    // needs to be found.  As a result we always update the request if
1171    // we have it, but only declare it satisfied if we are the owner.
1172
1173    // see if we have data at all (owned or otherwise)
1174    bool have_data = blk && blk->isValid()
1175        && pkt->checkFunctional(&cbpw, blk_addr, is_secure, blkSize,
1176                                blk->data);
1177
1178    // data we have is dirty if marked as such or if we have an
1179    // in-service MSHR that is pending a modified line
1180    bool have_dirty =
1181        have_data && (blk->isDirty() ||
1182                      (mshr && mshr->inService && mshr->isPendingModified()));
1183
1184    bool done = have_dirty
1185        || cpuSidePort->checkFunctional(pkt)
1186        || mshrQueue.checkFunctional(pkt, blk_addr)
1187        || writeBuffer.checkFunctional(pkt, blk_addr)
1188        || memSidePort->checkFunctional(pkt);
1189
1190    DPRINTF(CacheVerbose, "functional %s %#llx (%s) %s%s%s\n",
1191            pkt->cmdString(), pkt->getAddr(), is_secure ? "s" : "ns",
1192            (blk && blk->isValid()) ? "valid " : "",
1193            have_data ? "data " : "", done ? "done " : "");
1194
1195    // We're leaving the cache, so pop cache->name() label
1196    pkt->popLabel();
1197
1198    if (done) {
1199        pkt->makeResponse();
1200    } else {
1201        // if it came as a request from the CPU side then make sure it
1202        // continues towards the memory side
1203        if (fromCpuSide) {
1204            memSidePort->sendFunctional(pkt);
1205        } else if (cpuSidePort->isSnooping()) {
1206            // if it came from the memory side, it must be a snoop request
1207            // and we should only forward it if we are forwarding snoops
1208            cpuSidePort->sendFunctionalSnoop(pkt);
1209        }
1210    }
1211}
1212
1213
1214/////////////////////////////////////////////////////
1215//
1216// Response handling: responses from the memory side
1217//
1218/////////////////////////////////////////////////////
1219
1220
1221void
1222Cache::handleUncacheableWriteResp(PacketPtr pkt)
1223{
1224    Tick completion_time = clockEdge(responseLatency) +
1225        pkt->headerDelay + pkt->payloadDelay;
1226
1227    // Reset the bus additional time as it is now accounted for
1228    pkt->headerDelay = pkt->payloadDelay = 0;
1229
1230    cpuSidePort->schedTimingResp(pkt, completion_time, true);
1231}
1232
1233void
1234Cache::recvTimingResp(PacketPtr pkt)
1235{
1236    assert(pkt->isResponse());
1237
1238    // all header delay should be paid for by the crossbar, unless
1239    // this is a prefetch response from above
1240    panic_if(pkt->headerDelay != 0 && pkt->cmd != MemCmd::HardPFResp,
1241             "%s saw a non-zero packet delay\n", name());
1242
1243    bool is_error = pkt->isError();
1244
1245    if (is_error) {
1246        DPRINTF(Cache, "Cache received packet with error for addr %#llx (%s), "
1247                "cmd: %s\n", pkt->getAddr(), pkt->isSecure() ? "s" : "ns",
1248                pkt->cmdString());
1249    }
1250
1251    DPRINTF(Cache, "Handling response %s for addr %#llx size %d (%s)\n",
1252            pkt->cmdString(), pkt->getAddr(), pkt->getSize(),
1253            pkt->isSecure() ? "s" : "ns");
1254
1255    // if this is a write, we should be looking at an uncacheable
1256    // write
1257    if (pkt->isWrite()) {
1258        assert(pkt->req->isUncacheable());
1259        handleUncacheableWriteResp(pkt);
1260        return;
1261    }
1262
1263    // we have dealt with any (uncacheable) writes above, from here on
1264    // we know we are dealing with an MSHR due to a miss or a prefetch
1265    MSHR *mshr = dynamic_cast<MSHR*>(pkt->popSenderState());
1266    assert(mshr);
1267
1268    if (mshr == noTargetMSHR) {
1269        // we always clear at least one target
1270        clearBlocked(Blocked_NoTargets);
1271        noTargetMSHR = nullptr;
1272    }
1273
1274    // Initial target is used just for stats
1275    MSHR::Target *initial_tgt = mshr->getTarget();
1276    int stats_cmd_idx = initial_tgt->pkt->cmdToIndex();
1277    Tick miss_latency = curTick() - initial_tgt->recvTime;
1278
1279    if (pkt->req->isUncacheable()) {
1280        assert(pkt->req->masterId() < system->maxMasters());
1281        mshr_uncacheable_lat[stats_cmd_idx][pkt->req->masterId()] +=
1282            miss_latency;
1283    } else {
1284        assert(pkt->req->masterId() < system->maxMasters());
1285        mshr_miss_latency[stats_cmd_idx][pkt->req->masterId()] +=
1286            miss_latency;
1287    }
1288
1289    bool wasFull = mshrQueue.isFull();
1290
1291    PacketList writebacks;
1292
1293    Tick forward_time = clockEdge(forwardLatency) + pkt->headerDelay;
1294
1295    // upgrade deferred targets if the response has no sharers, and is
1296    // thus passing writable
1297    if (!pkt->hasSharers()) {
1298        mshr->promoteWritable();
1299    }
1300
1301    bool is_fill = !mshr->isForward &&
1302        (pkt->isRead() || pkt->cmd == MemCmd::UpgradeResp);
1303
1304    CacheBlk *blk = tags->findBlock(pkt->getAddr(), pkt->isSecure());
1305
1306    if (is_fill && !is_error) {
1307        DPRINTF(Cache, "Block for addr %#llx being updated in Cache\n",
1308                pkt->getAddr());
1309
1310        blk = handleFill(pkt, blk, writebacks, mshr->allocOnFill);
1311        assert(blk != nullptr);
1312    }
1313
1314    // allow invalidation responses originating from write-line
1315    // requests to be discarded
1316    bool is_invalidate = pkt->isInvalidate();
1317
1318    // First offset for critical word first calculations
1319    int initial_offset = initial_tgt->pkt->getOffset(blkSize);
1320
1321    while (mshr->hasTargets()) {
1322        MSHR::Target *target = mshr->getTarget();
1323        Packet *tgt_pkt = target->pkt;
1324
1325        switch (target->source) {
1326          case MSHR::Target::FromCPU:
1327            Tick completion_time;
1328            // Here we charge on completion_time the delay of the xbar if the
1329            // packet comes from it, charged on headerDelay.
1330            completion_time = pkt->headerDelay;
1331
1332            // Software prefetch handling for cache closest to core
1333            if (tgt_pkt->cmd.isSWPrefetch()) {
1334                // a software prefetch would have already been ack'd
1335                // immediately with dummy data so the core would be able to
1336                // retire it. This request completes right here, so we
1337                // deallocate it.
1338                delete tgt_pkt->req;
1339                delete tgt_pkt;
1340                break; // skip response
1341            }
1342
1343            // unlike the other packet flows, where data is found in other
1344            // caches or memory and brought back, write-line requests always
1345            // have the data right away, so the above check for "is fill?"
1346            // cannot actually be determined until examining the stored MSHR
1347            // state. We "catch up" with that logic here, which is duplicated
1348            // from above.
1349            if (tgt_pkt->cmd == MemCmd::WriteLineReq) {
1350                assert(!is_error);
1351                // we got the block in a writable state, so promote
1352                // any deferred targets if possible
1353                mshr->promoteWritable();
1354                // NB: we use the original packet here and not the response!
1355                blk = handleFill(tgt_pkt, blk, writebacks, mshr->allocOnFill);
1356                assert(blk != nullptr);
1357
1358                // treat as a fill, and discard the invalidation
1359                // response
1360                is_fill = true;
1361                is_invalidate = false;
1362            }
1363
1364            if (is_fill) {
1365                satisfyCpuSideRequest(tgt_pkt, blk,
1366                                      true, mshr->hasPostDowngrade());
1367
1368                // How many bytes past the first request is this one
1369                int transfer_offset =
1370                    tgt_pkt->getOffset(blkSize) - initial_offset;
1371                if (transfer_offset < 0) {
1372                    transfer_offset += blkSize;
1373                }
1374
1375                // If not critical word (offset) return payloadDelay.
1376                // responseLatency is the latency of the return path
1377                // from lower level caches/memory to an upper level cache or
1378                // the core.
1379                completion_time += clockEdge(responseLatency) +
1380                    (transfer_offset ? pkt->payloadDelay : 0);
1381
1382                assert(!tgt_pkt->req->isUncacheable());
1383
1384                assert(tgt_pkt->req->masterId() < system->maxMasters());
1385                missLatency[tgt_pkt->cmdToIndex()][tgt_pkt->req->masterId()] +=
1386                    completion_time - target->recvTime;
1387            } else if (pkt->cmd == MemCmd::UpgradeFailResp) {
1388                // failed StoreCond upgrade
1389                assert(tgt_pkt->cmd == MemCmd::StoreCondReq ||
1390                       tgt_pkt->cmd == MemCmd::StoreCondFailReq ||
1391                       tgt_pkt->cmd == MemCmd::SCUpgradeFailReq);
1392                // responseLatency is the latency of the return path
1393                // from lower level caches/memory to an upper level cache or
1394                // the core.
1395                completion_time += clockEdge(responseLatency) +
1396                    pkt->payloadDelay;
1397                tgt_pkt->req->setExtraData(0);
1398            } else {
1399                // not a cache fill, just forwarding response
1400                // responseLatency is the latency of the return path
1401                // from lower level cahces/memory to the core.
1402                completion_time += clockEdge(responseLatency) +
1403                    pkt->payloadDelay;
1404                if (pkt->isRead() && !is_error) {
1405                    // sanity check
1406                    assert(pkt->getAddr() == tgt_pkt->getAddr());
1407                    assert(pkt->getSize() >= tgt_pkt->getSize());
1408
1409                    tgt_pkt->setData(pkt->getConstPtr<uint8_t>());
1410                }
1411            }
1412            tgt_pkt->makeTimingResponse();
1413            // if this packet is an error copy that to the new packet
1414            if (is_error)
1415                tgt_pkt->copyError(pkt);
1416            if (tgt_pkt->cmd == MemCmd::ReadResp &&
1417                (is_invalidate || mshr->hasPostInvalidate())) {
1418                // If intermediate cache got ReadRespWithInvalidate,
1419                // propagate that.  Response should not have
1420                // isInvalidate() set otherwise.
1421                tgt_pkt->cmd = MemCmd::ReadRespWithInvalidate;
1422                DPRINTF(Cache, "%s updated cmd to %s for addr %#llx\n",
1423                        __func__, tgt_pkt->cmdString(), tgt_pkt->getAddr());
1424            }
1425            // Reset the bus additional time as it is now accounted for
1426            tgt_pkt->headerDelay = tgt_pkt->payloadDelay = 0;
1427            cpuSidePort->schedTimingResp(tgt_pkt, completion_time, true);
1428            break;
1429
1430          case MSHR::Target::FromPrefetcher:
1431            assert(tgt_pkt->cmd == MemCmd::HardPFReq);
1432            if (blk)
1433                blk->status |= BlkHWPrefetched;
1434            delete tgt_pkt->req;
1435            delete tgt_pkt;
1436            break;
1437
1438          case MSHR::Target::FromSnoop:
1439            // I don't believe that a snoop can be in an error state
1440            assert(!is_error);
1441            // response to snoop request
1442            DPRINTF(Cache, "processing deferred snoop...\n");
1443            assert(!(is_invalidate && !mshr->hasPostInvalidate()));
1444            handleSnoop(tgt_pkt, blk, true, true, mshr->hasPostInvalidate());
1445            break;
1446
1447          default:
1448            panic("Illegal target->source enum %d\n", target->source);
1449        }
1450
1451        mshr->popTarget();
1452    }
1453
1454    if (blk && blk->isValid()) {
1455        // an invalidate response stemming from a write line request
1456        // should not invalidate the block, so check if the
1457        // invalidation should be discarded
1458        if (is_invalidate || mshr->hasPostInvalidate()) {
1459            invalidateBlock(blk);
1460        } else if (mshr->hasPostDowngrade()) {
1461            blk->status &= ~BlkWritable;
1462        }
1463    }
1464
1465    if (mshr->promoteDeferredTargets()) {
1466        // avoid later read getting stale data while write miss is
1467        // outstanding.. see comment in timingAccess()
1468        if (blk) {
1469            blk->status &= ~BlkReadable;
1470        }
1471        mshrQueue.markPending(mshr);
1472        schedMemSideSendEvent(clockEdge() + pkt->payloadDelay);
1473    } else {
1474        mshrQueue.deallocate(mshr);
1475        if (wasFull && !mshrQueue.isFull()) {
1476            clearBlocked(Blocked_NoMSHRs);
1477        }
1478
1479        // Request the bus for a prefetch if this deallocation freed enough
1480        // MSHRs for a prefetch to take place
1481        if (prefetcher && mshrQueue.canPrefetch()) {
1482            Tick next_pf_time = std::max(prefetcher->nextPrefetchReadyTime(),
1483                                         clockEdge());
1484            if (next_pf_time != MaxTick)
1485                schedMemSideSendEvent(next_pf_time);
1486        }
1487    }
1488    // reset the xbar additional timinig  as it is now accounted for
1489    pkt->headerDelay = pkt->payloadDelay = 0;
1490
1491    // copy writebacks to write buffer
1492    doWritebacks(writebacks, forward_time);
1493
1494    // if we used temp block, check to see if its valid and then clear it out
1495    if (blk == tempBlock && tempBlock->isValid()) {
1496        // We use forwardLatency here because we are copying
1497        // Writebacks/CleanEvicts to write buffer. It specifies the latency to
1498        // allocate an internal buffer and to schedule an event to the
1499        // queued port.
1500        if (blk->isDirty() || writebackClean) {
1501            PacketPtr wbPkt = writebackBlk(blk);
1502            allocateWriteBuffer(wbPkt, forward_time);
1503            // Set BLOCK_CACHED flag if cached above.
1504            if (isCachedAbove(wbPkt))
1505                wbPkt->setBlockCached();
1506        } else {
1507            PacketPtr wcPkt = cleanEvictBlk(blk);
1508            // Check to see if block is cached above. If not allocate
1509            // write buffer
1510            if (isCachedAbove(wcPkt))
1511                delete wcPkt;
1512            else
1513                allocateWriteBuffer(wcPkt, forward_time);
1514        }
1515        blk->invalidate();
1516    }
1517
1518    DPRINTF(CacheVerbose, "Leaving %s with %s for addr %#llx\n", __func__,
1519            pkt->cmdString(), pkt->getAddr());
1520    delete pkt;
1521}
1522
1523PacketPtr
1524Cache::writebackBlk(CacheBlk *blk)
1525{
1526    chatty_assert(!isReadOnly || writebackClean,
1527                  "Writeback from read-only cache");
1528    assert(blk && blk->isValid() && (blk->isDirty() || writebackClean));
1529
1530    writebacks[Request::wbMasterId]++;
1531
1532    Request *req = new Request(tags->regenerateBlkAddr(blk->tag, blk->set),
1533                               blkSize, 0, Request::wbMasterId);
1534    if (blk->isSecure())
1535        req->setFlags(Request::SECURE);
1536
1537    req->taskId(blk->task_id);
1538    blk->task_id= ContextSwitchTaskId::Unknown;
1539    blk->tickInserted = curTick();
1540
1541    PacketPtr pkt =
1542        new Packet(req, blk->isDirty() ?
1543                   MemCmd::WritebackDirty : MemCmd::WritebackClean);
1544
1545    DPRINTF(Cache, "Create Writeback %#llx writable: %d, dirty: %d\n",
1546            pkt->getAddr(), blk->isWritable(), blk->isDirty());
1547
1548    if (blk->isWritable()) {
1549        // not asserting shared means we pass the block in modified
1550        // state, mark our own block non-writeable
1551        blk->status &= ~BlkWritable;
1552    } else {
1553        // we are in the Owned state, tell the receiver
1554        pkt->setHasSharers();
1555    }
1556
1557    // make sure the block is not marked dirty
1558    blk->status &= ~BlkDirty;
1559
1560    pkt->allocate();
1561    std::memcpy(pkt->getPtr<uint8_t>(), blk->data, blkSize);
1562
1563    return pkt;
1564}
1565
1566PacketPtr
1567Cache::cleanEvictBlk(CacheBlk *blk)
1568{
1569    assert(!writebackClean);
1570    assert(blk && blk->isValid() && !blk->isDirty());
1571    // Creating a zero sized write, a message to the snoop filter
1572    Request *req =
1573        new Request(tags->regenerateBlkAddr(blk->tag, blk->set), blkSize, 0,
1574                    Request::wbMasterId);
1575    if (blk->isSecure())
1576        req->setFlags(Request::SECURE);
1577
1578    req->taskId(blk->task_id);
1579    blk->task_id = ContextSwitchTaskId::Unknown;
1580    blk->tickInserted = curTick();
1581
1582    PacketPtr pkt = new Packet(req, MemCmd::CleanEvict);
1583    pkt->allocate();
1584    DPRINTF(Cache, "%s%s %x Create CleanEvict\n", pkt->cmdString(),
1585            pkt->req->isInstFetch() ? " (ifetch)" : "",
1586            pkt->getAddr());
1587
1588    return pkt;
1589}
1590
1591void
1592Cache::memWriteback()
1593{
1594    CacheBlkVisitorWrapper visitor(*this, &Cache::writebackVisitor);
1595    tags->forEachBlk(visitor);
1596}
1597
1598void
1599Cache::memInvalidate()
1600{
1601    CacheBlkVisitorWrapper visitor(*this, &Cache::invalidateVisitor);
1602    tags->forEachBlk(visitor);
1603}
1604
1605bool
1606Cache::isDirty() const
1607{
1608    CacheBlkIsDirtyVisitor visitor;
1609    tags->forEachBlk(visitor);
1610
1611    return visitor.isDirty();
1612}
1613
1614bool
1615Cache::writebackVisitor(CacheBlk &blk)
1616{
1617    if (blk.isDirty()) {
1618        assert(blk.isValid());
1619
1620        Request request(tags->regenerateBlkAddr(blk.tag, blk.set),
1621                        blkSize, 0, Request::funcMasterId);
1622        request.taskId(blk.task_id);
1623
1624        Packet packet(&request, MemCmd::WriteReq);
1625        packet.dataStatic(blk.data);
1626
1627        memSidePort->sendFunctional(&packet);
1628
1629        blk.status &= ~BlkDirty;
1630    }
1631
1632    return true;
1633}
1634
1635bool
1636Cache::invalidateVisitor(CacheBlk &blk)
1637{
1638
1639    if (blk.isDirty())
1640        warn_once("Invalidating dirty cache lines. Expect things to break.\n");
1641
1642    if (blk.isValid()) {
1643        assert(!blk.isDirty());
1644        tags->invalidate(&blk);
1645        blk.invalidate();
1646    }
1647
1648    return true;
1649}
1650
1651CacheBlk*
1652Cache::allocateBlock(Addr addr, bool is_secure, PacketList &writebacks)
1653{
1654    CacheBlk *blk = tags->findVictim(addr);
1655
1656    // It is valid to return nullptr if there is no victim
1657    if (!blk)
1658        return nullptr;
1659
1660    if (blk->isValid()) {
1661        Addr repl_addr = tags->regenerateBlkAddr(blk->tag, blk->set);
1662        MSHR *repl_mshr = mshrQueue.findMatch(repl_addr, blk->isSecure());
1663        if (repl_mshr) {
1664            // must be an outstanding upgrade request
1665            // on a block we're about to replace...
1666            assert(!blk->isWritable() || blk->isDirty());
1667            assert(repl_mshr->needsWritable());
1668            // too hard to replace block with transient state
1669            // allocation failed, block not inserted
1670            return nullptr;
1671        } else {
1672            DPRINTF(Cache, "replacement: replacing %#llx (%s) with %#llx "
1673                    "(%s): %s\n", repl_addr, blk->isSecure() ? "s" : "ns",
1674                    addr, is_secure ? "s" : "ns",
1675                    blk->isDirty() ? "writeback" : "clean");
1676
1677            if (blk->wasPrefetched()) {
1678                unusedPrefetches++;
1679            }
1680            // Will send up Writeback/CleanEvict snoops via isCachedAbove
1681            // when pushing this writeback list into the write buffer.
1682            if (blk->isDirty() || writebackClean) {
1683                // Save writeback packet for handling by caller
1684                writebacks.push_back(writebackBlk(blk));
1685            } else {
1686                writebacks.push_back(cleanEvictBlk(blk));
1687            }
1688        }
1689    }
1690
1691    return blk;
1692}
1693
1694void
1695Cache::invalidateBlock(CacheBlk *blk)
1696{
1697    if (blk != tempBlock)
1698        tags->invalidate(blk);
1699    blk->invalidate();
1700}
1701
1702// Note that the reason we return a list of writebacks rather than
1703// inserting them directly in the write buffer is that this function
1704// is called by both atomic and timing-mode accesses, and in atomic
1705// mode we don't mess with the write buffer (we just perform the
1706// writebacks atomically once the original request is complete).
1707CacheBlk*
1708Cache::handleFill(PacketPtr pkt, CacheBlk *blk, PacketList &writebacks,
1709                  bool allocate)
1710{
1711    assert(pkt->isResponse() || pkt->cmd == MemCmd::WriteLineReq);
1712    Addr addr = pkt->getAddr();
1713    bool is_secure = pkt->isSecure();
1714#if TRACING_ON
1715    CacheBlk::State old_state = blk ? blk->status : 0;
1716#endif
1717
1718    // When handling a fill, we should have no writes to this line.
1719    assert(addr == blockAlign(addr));
1720    assert(!writeBuffer.findMatch(addr, is_secure));
1721
1722    if (blk == nullptr) {
1723        // better have read new data...
1724        assert(pkt->hasData());
1725
1726        // only read responses and write-line requests have data;
1727        // note that we don't write the data here for write-line - that
1728        // happens in the subsequent satisfyCpuSideRequest.
1729        assert(pkt->isRead() || pkt->cmd == MemCmd::WriteLineReq);
1730
1731        // need to do a replacement if allocating, otherwise we stick
1732        // with the temporary storage
1733        blk = allocate ? allocateBlock(addr, is_secure, writebacks) : nullptr;
1734
1735        if (blk == nullptr) {
1736            // No replaceable block or a mostly exclusive
1737            // cache... just use temporary storage to complete the
1738            // current request and then get rid of it
1739            assert(!tempBlock->isValid());
1740            blk = tempBlock;
1741            tempBlock->set = tags->extractSet(addr);
1742            tempBlock->tag = tags->extractTag(addr);
1743            // @todo: set security state as well...
1744            DPRINTF(Cache, "using temp block for %#llx (%s)\n", addr,
1745                    is_secure ? "s" : "ns");
1746        } else {
1747            tags->insertBlock(pkt, blk);
1748        }
1749
1750        // we should never be overwriting a valid block
1751        assert(!blk->isValid());
1752    } else {
1753        // existing block... probably an upgrade
1754        assert(blk->tag == tags->extractTag(addr));
1755        // either we're getting new data or the block should already be valid
1756        assert(pkt->hasData() || blk->isValid());
1757        // don't clear block status... if block is already dirty we
1758        // don't want to lose that
1759    }
1760
1761    if (is_secure)
1762        blk->status |= BlkSecure;
1763    blk->status |= BlkValid | BlkReadable;
1764
1765    // sanity check for whole-line writes, which should always be
1766    // marked as writable as part of the fill, and then later marked
1767    // dirty as part of satisfyCpuSideRequest
1768    if (pkt->cmd == MemCmd::WriteLineReq) {
1769        assert(!pkt->hasSharers());
1770        // at the moment other caches do not respond to the
1771        // invalidation requests corresponding to a whole-line write
1772        assert(!pkt->cacheResponding());
1773    }
1774
1775    // here we deal with setting the appropriate state of the line,
1776    // and we start by looking at the hasSharers flag, and ignore the
1777    // cacheResponding flag (normally signalling dirty data) if the
1778    // packet has sharers, thus the line is never allocated as Owned
1779    // (dirty but not writable), and always ends up being either
1780    // Shared, Exclusive or Modified, see Packet::setCacheResponding
1781    // for more details
1782    if (!pkt->hasSharers()) {
1783        // we could get a writable line from memory (rather than a
1784        // cache) even in a read-only cache, note that we set this bit
1785        // even for a read-only cache, possibly revisit this decision
1786        blk->status |= BlkWritable;
1787
1788        // check if we got this via cache-to-cache transfer (i.e., from a
1789        // cache that had the block in Modified or Owned state)
1790        if (pkt->cacheResponding()) {
1791            // we got the block in Modified state, and invalidated the
1792            // owners copy
1793            blk->status |= BlkDirty;
1794
1795            chatty_assert(!isReadOnly, "Should never see dirty snoop response "
1796                          "in read-only cache %s\n", name());
1797        }
1798    }
1799
1800    DPRINTF(Cache, "Block addr %#llx (%s) moving from state %x to %s\n",
1801            addr, is_secure ? "s" : "ns", old_state, blk->print());
1802
1803    // if we got new data, copy it in (checking for a read response
1804    // and a response that has data is the same in the end)
1805    if (pkt->isRead()) {
1806        // sanity checks
1807        assert(pkt->hasData());
1808        assert(pkt->getSize() == blkSize);
1809
1810        std::memcpy(blk->data, pkt->getConstPtr<uint8_t>(), blkSize);
1811    }
1812    // We pay for fillLatency here.
1813    blk->whenReady = clockEdge() + fillLatency * clockPeriod() +
1814        pkt->payloadDelay;
1815
1816    return blk;
1817}
1818
1819
1820/////////////////////////////////////////////////////
1821//
1822// Snoop path: requests coming in from the memory side
1823//
1824/////////////////////////////////////////////////////
1825
1826void
1827Cache::doTimingSupplyResponse(PacketPtr req_pkt, const uint8_t *blk_data,
1828                              bool already_copied, bool pending_inval)
1829{
1830    // sanity check
1831    assert(req_pkt->isRequest());
1832    assert(req_pkt->needsResponse());
1833
1834    DPRINTF(Cache, "%s for %s addr %#llx size %d\n", __func__,
1835            req_pkt->cmdString(), req_pkt->getAddr(), req_pkt->getSize());
1836    // timing-mode snoop responses require a new packet, unless we
1837    // already made a copy...
1838    PacketPtr pkt = req_pkt;
1839    if (!already_copied)
1840        // do not clear flags, and allocate space for data if the
1841        // packet needs it (the only packets that carry data are read
1842        // responses)
1843        pkt = new Packet(req_pkt, false, req_pkt->isRead());
1844
1845    assert(req_pkt->req->isUncacheable() || req_pkt->isInvalidate() ||
1846           pkt->hasSharers());
1847    pkt->makeTimingResponse();
1848    if (pkt->isRead()) {
1849        pkt->setDataFromBlock(blk_data, blkSize);
1850    }
1851    if (pkt->cmd == MemCmd::ReadResp && pending_inval) {
1852        // Assume we defer a response to a read from a far-away cache
1853        // A, then later defer a ReadExcl from a cache B on the same
1854        // bus as us. We'll assert cacheResponding in both cases, but
1855        // in the latter case cacheResponding will keep the
1856        // invalidation from reaching cache A. This special response
1857        // tells cache A that it gets the block to satisfy its read,
1858        // but must immediately invalidate it.
1859        pkt->cmd = MemCmd::ReadRespWithInvalidate;
1860    }
1861    // Here we consider forward_time, paying for just forward latency and
1862    // also charging the delay provided by the xbar.
1863    // forward_time is used as send_time in next allocateWriteBuffer().
1864    Tick forward_time = clockEdge(forwardLatency) + pkt->headerDelay;
1865    // Here we reset the timing of the packet.
1866    pkt->headerDelay = pkt->payloadDelay = 0;
1867    DPRINTF(CacheVerbose,
1868            "%s created response: %s addr %#llx size %d tick: %lu\n",
1869            __func__, pkt->cmdString(), pkt->getAddr(), pkt->getSize(),
1870            forward_time);
1871    memSidePort->schedTimingSnoopResp(pkt, forward_time, true);
1872}
1873
1874uint32_t
1875Cache::handleSnoop(PacketPtr pkt, CacheBlk *blk, bool is_timing,
1876                   bool is_deferred, bool pending_inval)
1877{
1878    DPRINTF(CacheVerbose, "%s for %s addr %#llx size %d\n", __func__,
1879            pkt->cmdString(), pkt->getAddr(), pkt->getSize());
1880    // deferred snoops can only happen in timing mode
1881    assert(!(is_deferred && !is_timing));
1882    // pending_inval only makes sense on deferred snoops
1883    assert(!(pending_inval && !is_deferred));
1884    assert(pkt->isRequest());
1885
1886    // the packet may get modified if we or a forwarded snooper
1887    // responds in atomic mode, so remember a few things about the
1888    // original packet up front
1889    bool invalidate = pkt->isInvalidate();
1890    bool M5_VAR_USED needs_writable = pkt->needsWritable();
1891
1892    // at the moment we could get an uncacheable write which does not
1893    // have the invalidate flag, and we need a suitable way of dealing
1894    // with this case
1895    panic_if(invalidate && pkt->req->isUncacheable(),
1896             "%s got an invalidating uncacheable snoop request %s to %#llx",
1897             name(), pkt->cmdString(), pkt->getAddr());
1898
1899    uint32_t snoop_delay = 0;
1900
1901    if (forwardSnoops) {
1902        // first propagate snoop upward to see if anyone above us wants to
1903        // handle it.  save & restore packet src since it will get
1904        // rewritten to be relative to cpu-side bus (if any)
1905        bool alreadyResponded = pkt->cacheResponding();
1906        if (is_timing) {
1907            // copy the packet so that we can clear any flags before
1908            // forwarding it upwards, we also allocate data (passing
1909            // the pointer along in case of static data), in case
1910            // there is a snoop hit in upper levels
1911            Packet snoopPkt(pkt, true, true);
1912            snoopPkt.setExpressSnoop();
1913            // the snoop packet does not need to wait any additional
1914            // time
1915            snoopPkt.headerDelay = snoopPkt.payloadDelay = 0;
1916            cpuSidePort->sendTimingSnoopReq(&snoopPkt);
1917
1918            // add the header delay (including crossbar and snoop
1919            // delays) of the upward snoop to the snoop delay for this
1920            // cache
1921            snoop_delay += snoopPkt.headerDelay;
1922
1923            if (snoopPkt.cacheResponding()) {
1924                // cache-to-cache response from some upper cache
1925                assert(!alreadyResponded);
1926                pkt->setCacheResponding();
1927            }
1928            // upstream cache has the block, or has an outstanding
1929            // MSHR, pass the flag on
1930            if (snoopPkt.hasSharers()) {
1931                pkt->setHasSharers();
1932            }
1933            // If this request is a prefetch or clean evict and an upper level
1934            // signals block present, make sure to propagate the block
1935            // presence to the requester.
1936            if (snoopPkt.isBlockCached()) {
1937                pkt->setBlockCached();
1938            }
1939        } else {
1940            cpuSidePort->sendAtomicSnoop(pkt);
1941            if (!alreadyResponded && pkt->cacheResponding()) {
1942                // cache-to-cache response from some upper cache:
1943                // forward response to original requester
1944                assert(pkt->isResponse());
1945            }
1946        }
1947    }
1948
1949    if (!blk || !blk->isValid()) {
1950        if (is_deferred) {
1951            // we no longer have the block, and will not respond, but a
1952            // packet was allocated in MSHR::handleSnoop and we have
1953            // to delete it
1954            assert(pkt->needsResponse());
1955
1956            // we have passed the block to a cache upstream, that
1957            // cache should be responding
1958            assert(pkt->cacheResponding());
1959
1960            delete pkt;
1961        }
1962
1963        DPRINTF(CacheVerbose, "%s snoop miss for %s addr %#llx size %d\n",
1964                __func__, pkt->cmdString(), pkt->getAddr(), pkt->getSize());
1965        return snoop_delay;
1966    } else {
1967        DPRINTF(Cache, "%s snoop hit for %s addr %#llx size %d, "
1968                "old state is %s\n", __func__, pkt->cmdString(),
1969                pkt->getAddr(), pkt->getSize(), blk->print());
1970    }
1971
1972    chatty_assert(!(isReadOnly && blk->isDirty()),
1973                  "Should never have a dirty block in a read-only cache %s\n",
1974                  name());
1975
1976    // We may end up modifying both the block state and the packet (if
1977    // we respond in atomic mode), so just figure out what to do now
1978    // and then do it later. If we find dirty data while snooping for
1979    // an invalidate, we don't need to send a response. The
1980    // invalidation itself is taken care of below.
1981    bool respond = blk->isDirty() && pkt->needsResponse() &&
1982        pkt->cmd != MemCmd::InvalidateReq;
1983    bool have_writable = blk->isWritable();
1984
1985    // Invalidate any prefetch's from below that would strip write permissions
1986    // MemCmd::HardPFReq is only observed by upstream caches.  After missing
1987    // above and in it's own cache, a new MemCmd::ReadReq is created that
1988    // downstream caches observe.
1989    if (pkt->mustCheckAbove()) {
1990        DPRINTF(Cache, "Found addr %#llx in upper level cache for snoop %s "
1991                "from lower cache\n", pkt->getAddr(), pkt->cmdString());
1992        pkt->setBlockCached();
1993        return snoop_delay;
1994    }
1995
1996    if (pkt->isRead() && !invalidate) {
1997        // reading without requiring the line in a writable state
1998        assert(!needs_writable);
1999        pkt->setHasSharers();
2000
2001        // if the requesting packet is uncacheable, retain the line in
2002        // the current state, otherwhise unset the writable flag,
2003        // which means we go from Modified to Owned (and will respond
2004        // below), remain in Owned (and will respond below), from
2005        // Exclusive to Shared, or remain in Shared
2006        if (!pkt->req->isUncacheable())
2007            blk->status &= ~BlkWritable;
2008    }
2009
2010    if (respond) {
2011        // prevent anyone else from responding, cache as well as
2012        // memory, and also prevent any memory from even seeing the
2013        // request
2014        pkt->setCacheResponding();
2015        if (have_writable) {
2016            // inform the cache hierarchy that this cache had the line
2017            // in the Modified state so that we avoid unnecessary
2018            // invalidations (see Packet::setResponderHadWritable)
2019            pkt->setResponderHadWritable();
2020
2021            // in the case of an uncacheable request there is no point
2022            // in setting the responderHadWritable flag, but since the
2023            // recipient does not care there is no harm in doing so
2024        } else {
2025            // if the packet has needsWritable set we invalidate our
2026            // copy below and all other copies will be invalidates
2027            // through express snoops, and if needsWritable is not set
2028            // we already called setHasSharers above
2029        }
2030
2031        // if we are returning a writable and dirty (Modified) line,
2032        // we should be invalidating the line
2033        panic_if(!invalidate && !pkt->hasSharers(),
2034                 "%s is passing a Modified line through %s to %#llx, "
2035                 "but keeping the block",
2036                 name(), pkt->cmdString(), pkt->getAddr());
2037
2038        if (is_timing) {
2039            doTimingSupplyResponse(pkt, blk->data, is_deferred, pending_inval);
2040        } else {
2041            pkt->makeAtomicResponse();
2042            // packets such as upgrades do not actually have any data
2043            // payload
2044            if (pkt->hasData())
2045                pkt->setDataFromBlock(blk->data, blkSize);
2046        }
2047    }
2048
2049    if (!respond && is_timing && is_deferred) {
2050        // if it's a deferred timing snoop to which we are not
2051        // responding, then we've made a copy of both the request and
2052        // the packet, delete them here
2053        assert(pkt->needsResponse());
2054        assert(!pkt->cacheResponding());
2055        delete pkt->req;
2056        delete pkt;
2057    }
2058
2059    // Do this last in case it deallocates block data or something
2060    // like that
2061    if (invalidate) {
2062        invalidateBlock(blk);
2063    }
2064
2065    DPRINTF(Cache, "new state is %s\n", blk->print());
2066
2067    return snoop_delay;
2068}
2069
2070
2071void
2072Cache::recvTimingSnoopReq(PacketPtr pkt)
2073{
2074    DPRINTF(CacheVerbose, "%s for %s addr %#llx size %d\n", __func__,
2075            pkt->cmdString(), pkt->getAddr(), pkt->getSize());
2076
2077    // Snoops shouldn't happen when bypassing caches
2078    assert(!system->bypassCaches());
2079
2080    // no need to snoop requests that are not in range
2081    if (!inRange(pkt->getAddr())) {
2082        return;
2083    }
2084
2085    bool is_secure = pkt->isSecure();
2086    CacheBlk *blk = tags->findBlock(pkt->getAddr(), is_secure);
2087
2088    Addr blk_addr = blockAlign(pkt->getAddr());
2089    MSHR *mshr = mshrQueue.findMatch(blk_addr, is_secure);
2090
2091    // Update the latency cost of the snoop so that the crossbar can
2092    // account for it. Do not overwrite what other neighbouring caches
2093    // have already done, rather take the maximum. The update is
2094    // tentative, for cases where we return before an upward snoop
2095    // happens below.
2096    pkt->snoopDelay = std::max<uint32_t>(pkt->snoopDelay,
2097                                         lookupLatency * clockPeriod());
2098
2099    // Inform request(Prefetch, CleanEvict or Writeback) from below of
2100    // MSHR hit, set setBlockCached.
2101    if (mshr && pkt->mustCheckAbove()) {
2102        DPRINTF(Cache, "Setting block cached for %s from"
2103                "lower cache on mshr hit %#x\n",
2104                pkt->cmdString(), pkt->getAddr());
2105        pkt->setBlockCached();
2106        return;
2107    }
2108
2109    // Let the MSHR itself track the snoop and decide whether we want
2110    // to go ahead and do the regular cache snoop
2111    if (mshr && mshr->handleSnoop(pkt, order++)) {
2112        DPRINTF(Cache, "Deferring snoop on in-service MSHR to blk %#llx (%s)."
2113                "mshrs: %s\n", blk_addr, is_secure ? "s" : "ns",
2114                mshr->print());
2115
2116        if (mshr->getNumTargets() > numTarget)
2117            warn("allocating bonus target for snoop"); //handle later
2118        return;
2119    }
2120
2121    //We also need to check the writeback buffers and handle those
2122    WriteQueueEntry *wb_entry = writeBuffer.findMatch(blk_addr, is_secure);
2123    if (wb_entry) {
2124        DPRINTF(Cache, "Snoop hit in writeback to addr %#llx (%s)\n",
2125                pkt->getAddr(), is_secure ? "s" : "ns");
2126        // Expect to see only Writebacks and/or CleanEvicts here, both of
2127        // which should not be generated for uncacheable data.
2128        assert(!wb_entry->isUncacheable());
2129        // There should only be a single request responsible for generating
2130        // Writebacks/CleanEvicts.
2131        assert(wb_entry->getNumTargets() == 1);
2132        PacketPtr wb_pkt = wb_entry->getTarget()->pkt;
2133        assert(wb_pkt->isEviction());
2134
2135        if (pkt->isEviction()) {
2136            // if the block is found in the write queue, set the BLOCK_CACHED
2137            // flag for Writeback/CleanEvict snoop. On return the snoop will
2138            // propagate the BLOCK_CACHED flag in Writeback packets and prevent
2139            // any CleanEvicts from travelling down the memory hierarchy.
2140            pkt->setBlockCached();
2141            DPRINTF(Cache, "Squashing %s from lower cache on writequeue hit"
2142                    " %#x\n", pkt->cmdString(), pkt->getAddr());
2143            return;
2144        }
2145
2146        // conceptually writebacks are no different to other blocks in
2147        // this cache, so the behaviour is modelled after handleSnoop,
2148        // the difference being that instead of querying the block
2149        // state to determine if it is dirty and writable, we use the
2150        // command and fields of the writeback packet
2151        bool respond = wb_pkt->cmd == MemCmd::WritebackDirty &&
2152            pkt->needsResponse() && pkt->cmd != MemCmd::InvalidateReq;
2153        bool have_writable = !wb_pkt->hasSharers();
2154        bool invalidate = pkt->isInvalidate();
2155
2156        if (!pkt->req->isUncacheable() && pkt->isRead() && !invalidate) {
2157            assert(!pkt->needsWritable());
2158            pkt->setHasSharers();
2159            wb_pkt->setHasSharers();
2160        }
2161
2162        if (respond) {
2163            pkt->setCacheResponding();
2164
2165            if (have_writable) {
2166                pkt->setResponderHadWritable();
2167            }
2168
2169            doTimingSupplyResponse(pkt, wb_pkt->getConstPtr<uint8_t>(),
2170                                   false, false);
2171        }
2172
2173        if (invalidate) {
2174            // Invalidation trumps our writeback... discard here
2175            // Note: markInService will remove entry from writeback buffer.
2176            markInService(wb_entry);
2177            delete wb_pkt;
2178        }
2179    }
2180
2181    // If this was a shared writeback, there may still be
2182    // other shared copies above that require invalidation.
2183    // We could be more selective and return here if the
2184    // request is non-exclusive or if the writeback is
2185    // exclusive.
2186    uint32_t snoop_delay = handleSnoop(pkt, blk, true, false, false);
2187
2188    // Override what we did when we first saw the snoop, as we now
2189    // also have the cost of the upwards snoops to account for
2190    pkt->snoopDelay = std::max<uint32_t>(pkt->snoopDelay, snoop_delay +
2191                                         lookupLatency * clockPeriod());
2192}
2193
2194bool
2195Cache::CpuSidePort::recvTimingSnoopResp(PacketPtr pkt)
2196{
2197    // Express snoop responses from master to slave, e.g., from L1 to L2
2198    cache->recvTimingSnoopResp(pkt);
2199    return true;
2200}
2201
2202Tick
2203Cache::recvAtomicSnoop(PacketPtr pkt)
2204{
2205    // Snoops shouldn't happen when bypassing caches
2206    assert(!system->bypassCaches());
2207
2208    // no need to snoop requests that are not in range.
2209    if (!inRange(pkt->getAddr())) {
2210        return 0;
2211    }
2212
2213    CacheBlk *blk = tags->findBlock(pkt->getAddr(), pkt->isSecure());
2214    uint32_t snoop_delay = handleSnoop(pkt, blk, false, false, false);
2215    return snoop_delay + lookupLatency * clockPeriod();
2216}
2217
2218
2219QueueEntry*
2220Cache::getNextQueueEntry()
2221{
2222    // Check both MSHR queue and write buffer for potential requests,
2223    // note that null does not mean there is no request, it could
2224    // simply be that it is not ready
2225    MSHR *miss_mshr  = mshrQueue.getNext();
2226    WriteQueueEntry *wq_entry = writeBuffer.getNext();
2227
2228    // If we got a write buffer request ready, first priority is a
2229    // full write buffer, otherwise we favour the miss requests
2230    if (wq_entry && (writeBuffer.isFull() || !miss_mshr)) {
2231        // need to search MSHR queue for conflicting earlier miss.
2232        MSHR *conflict_mshr =
2233            mshrQueue.findPending(wq_entry->blkAddr,
2234                                  wq_entry->isSecure);
2235
2236        if (conflict_mshr && conflict_mshr->order < wq_entry->order) {
2237            // Service misses in order until conflict is cleared.
2238            return conflict_mshr;
2239
2240            // @todo Note that we ignore the ready time of the conflict here
2241        }
2242
2243        // No conflicts; issue write
2244        return wq_entry;
2245    } else if (miss_mshr) {
2246        // need to check for conflicting earlier writeback
2247        WriteQueueEntry *conflict_mshr =
2248            writeBuffer.findPending(miss_mshr->blkAddr,
2249                                    miss_mshr->isSecure);
2250        if (conflict_mshr) {
2251            // not sure why we don't check order here... it was in the
2252            // original code but commented out.
2253
2254            // The only way this happens is if we are
2255            // doing a write and we didn't have permissions
2256            // then subsequently saw a writeback (owned got evicted)
2257            // We need to make sure to perform the writeback first
2258            // To preserve the dirty data, then we can issue the write
2259
2260            // should we return wq_entry here instead?  I.e. do we
2261            // have to flush writes in order?  I don't think so... not
2262            // for Alpha anyway.  Maybe for x86?
2263            return conflict_mshr;
2264
2265            // @todo Note that we ignore the ready time of the conflict here
2266        }
2267
2268        // No conflicts; issue read
2269        return miss_mshr;
2270    }
2271
2272    // fall through... no pending requests.  Try a prefetch.
2273    assert(!miss_mshr && !wq_entry);
2274    if (prefetcher && mshrQueue.canPrefetch()) {
2275        // If we have a miss queue slot, we can try a prefetch
2276        PacketPtr pkt = prefetcher->getPacket();
2277        if (pkt) {
2278            Addr pf_addr = blockAlign(pkt->getAddr());
2279            if (!tags->findBlock(pf_addr, pkt->isSecure()) &&
2280                !mshrQueue.findMatch(pf_addr, pkt->isSecure()) &&
2281                !writeBuffer.findMatch(pf_addr, pkt->isSecure())) {
2282                // Update statistic on number of prefetches issued
2283                // (hwpf_mshr_misses)
2284                assert(pkt->req->masterId() < system->maxMasters());
2285                mshr_misses[pkt->cmdToIndex()][pkt->req->masterId()]++;
2286
2287                // allocate an MSHR and return it, note
2288                // that we send the packet straight away, so do not
2289                // schedule the send
2290                return allocateMissBuffer(pkt, curTick(), false);
2291            } else {
2292                // free the request and packet
2293                delete pkt->req;
2294                delete pkt;
2295            }
2296        }
2297    }
2298
2299    return nullptr;
2300}
2301
2302bool
2303Cache::isCachedAbove(PacketPtr pkt, bool is_timing) const
2304{
2305    if (!forwardSnoops)
2306        return false;
2307    // Mirroring the flow of HardPFReqs, the cache sends CleanEvict and
2308    // Writeback snoops into upper level caches to check for copies of the
2309    // same block. Using the BLOCK_CACHED flag with the Writeback/CleanEvict
2310    // packet, the cache can inform the crossbar below of presence or absence
2311    // of the block.
2312    if (is_timing) {
2313        Packet snoop_pkt(pkt, true, false);
2314        snoop_pkt.setExpressSnoop();
2315        // Assert that packet is either Writeback or CleanEvict and not a
2316        // prefetch request because prefetch requests need an MSHR and may
2317        // generate a snoop response.
2318        assert(pkt->isEviction());
2319        snoop_pkt.senderState = nullptr;
2320        cpuSidePort->sendTimingSnoopReq(&snoop_pkt);
2321        // Writeback/CleanEvict snoops do not generate a snoop response.
2322        assert(!(snoop_pkt.cacheResponding()));
2323        return snoop_pkt.isBlockCached();
2324    } else {
2325        cpuSidePort->sendAtomicSnoop(pkt);
2326        return pkt->isBlockCached();
2327    }
2328}
2329
2330Tick
2331Cache::nextQueueReadyTime() const
2332{
2333    Tick nextReady = std::min(mshrQueue.nextReadyTime(),
2334                              writeBuffer.nextReadyTime());
2335
2336    // Don't signal prefetch ready time if no MSHRs available
2337    // Will signal once enoguh MSHRs are deallocated
2338    if (prefetcher && mshrQueue.canPrefetch()) {
2339        nextReady = std::min(nextReady,
2340                             prefetcher->nextPrefetchReadyTime());
2341    }
2342
2343    return nextReady;
2344}
2345
2346bool
2347Cache::sendMSHRQueuePacket(MSHR* mshr)
2348{
2349    assert(mshr);
2350
2351    // use request from 1st target
2352    PacketPtr tgt_pkt = mshr->getTarget()->pkt;
2353
2354    DPRINTF(Cache, "%s MSHR %s for addr %#llx size %d\n", __func__,
2355            tgt_pkt->cmdString(), tgt_pkt->getAddr(),
2356            tgt_pkt->getSize());
2357
2358    CacheBlk *blk = tags->findBlock(mshr->blkAddr, mshr->isSecure);
2359
2360    if (tgt_pkt->cmd == MemCmd::HardPFReq && forwardSnoops) {
2361        // we should never have hardware prefetches to allocated
2362        // blocks
2363        assert(blk == nullptr);
2364
2365        // We need to check the caches above us to verify that
2366        // they don't have a copy of this block in the dirty state
2367        // at the moment. Without this check we could get a stale
2368        // copy from memory that might get used in place of the
2369        // dirty one.
2370        Packet snoop_pkt(tgt_pkt, true, false);
2371        snoop_pkt.setExpressSnoop();
2372        // We are sending this packet upwards, but if it hits we will
2373        // get a snoop response that we end up treating just like a
2374        // normal response, hence it needs the MSHR as its sender
2375        // state
2376        snoop_pkt.senderState = mshr;
2377        cpuSidePort->sendTimingSnoopReq(&snoop_pkt);
2378
2379        // Check to see if the prefetch was squashed by an upper cache (to
2380        // prevent us from grabbing the line) or if a Check to see if a
2381        // writeback arrived between the time the prefetch was placed in
2382        // the MSHRs and when it was selected to be sent or if the
2383        // prefetch was squashed by an upper cache.
2384
2385        // It is important to check cacheResponding before
2386        // prefetchSquashed. If another cache has committed to
2387        // responding, it will be sending a dirty response which will
2388        // arrive at the MSHR allocated for this request. Checking the
2389        // prefetchSquash first may result in the MSHR being
2390        // prematurely deallocated.
2391        if (snoop_pkt.cacheResponding()) {
2392            auto M5_VAR_USED r = outstandingSnoop.insert(snoop_pkt.req);
2393            assert(r.second);
2394
2395            // if we are getting a snoop response with no sharers it
2396            // will be allocated as Modified
2397            bool pending_modified_resp = !snoop_pkt.hasSharers();
2398            markInService(mshr, pending_modified_resp);
2399
2400            DPRINTF(Cache, "Upward snoop of prefetch for addr"
2401                    " %#x (%s) hit\n",
2402                    tgt_pkt->getAddr(), tgt_pkt->isSecure()? "s": "ns");
2403            return false;
2404        }
2405
2406        if (snoop_pkt.isBlockCached()) {
2407            DPRINTF(Cache, "Block present, prefetch squashed by cache.  "
2408                    "Deallocating mshr target %#x.\n",
2409                    mshr->blkAddr);
2410
2411            // Deallocate the mshr target
2412            if (mshrQueue.forceDeallocateTarget(mshr)) {
2413                // Clear block if this deallocation resulted freed an
2414                // mshr when all had previously been utilized
2415                clearBlocked(Blocked_NoMSHRs);
2416            }
2417            return false;
2418        }
2419    }
2420
2421    // either a prefetch that is not present upstream, or a normal
2422    // MSHR request, proceed to get the packet to send downstream
2423    PacketPtr pkt = createMissPacket(tgt_pkt, blk, mshr->needsWritable());
2424
2425    mshr->isForward = (pkt == nullptr);
2426
2427    if (mshr->isForward) {
2428        // not a cache block request, but a response is expected
2429        // make copy of current packet to forward, keep current
2430        // copy for response handling
2431        pkt = new Packet(tgt_pkt, false, true);
2432        assert(!pkt->isWrite());
2433    }
2434
2435    // play it safe and append (rather than set) the sender state,
2436    // as forwarded packets may already have existing state
2437    pkt->pushSenderState(mshr);
2438
2439    if (!memSidePort->sendTimingReq(pkt)) {
2440        // we are awaiting a retry, but we
2441        // delete the packet and will be creating a new packet
2442        // when we get the opportunity
2443        delete pkt;
2444
2445        // note that we have now masked any requestBus and
2446        // schedSendEvent (we will wait for a retry before
2447        // doing anything), and this is so even if we do not
2448        // care about this packet and might override it before
2449        // it gets retried
2450        return true;
2451    } else {
2452        // As part of the call to sendTimingReq the packet is
2453        // forwarded to all neighbouring caches (and any caches
2454        // above them) as a snoop. Thus at this point we know if
2455        // any of the neighbouring caches are responding, and if
2456        // so, we know it is dirty, and we can determine if it is
2457        // being passed as Modified, making our MSHR the ordering
2458        // point
2459        bool pending_modified_resp = !pkt->hasSharers() &&
2460            pkt->cacheResponding();
2461        markInService(mshr, pending_modified_resp);
2462        return false;
2463    }
2464}
2465
2466bool
2467Cache::sendWriteQueuePacket(WriteQueueEntry* wq_entry)
2468{
2469    assert(wq_entry);
2470
2471    // always a single target for write queue entries
2472    PacketPtr tgt_pkt = wq_entry->getTarget()->pkt;
2473
2474    DPRINTF(Cache, "%s write %s for addr %#llx size %d\n", __func__,
2475            tgt_pkt->cmdString(), tgt_pkt->getAddr(),
2476            tgt_pkt->getSize());
2477
2478    // forward as is, both for evictions and uncacheable writes
2479    if (!memSidePort->sendTimingReq(tgt_pkt)) {
2480        // note that we have now masked any requestBus and
2481        // schedSendEvent (we will wait for a retry before
2482        // doing anything), and this is so even if we do not
2483        // care about this packet and might override it before
2484        // it gets retried
2485        return true;
2486    } else {
2487        markInService(wq_entry);
2488        return false;
2489    }
2490}
2491
2492void
2493Cache::serialize(CheckpointOut &cp) const
2494{
2495    bool dirty(isDirty());
2496
2497    if (dirty) {
2498        warn("*** The cache still contains dirty data. ***\n");
2499        warn("    Make sure to drain the system using the correct flags.\n");
2500        warn("    This checkpoint will not restore correctly and dirty data "
2501             "    in the cache will be lost!\n");
2502    }
2503
2504    // Since we don't checkpoint the data in the cache, any dirty data
2505    // will be lost when restoring from a checkpoint of a system that
2506    // wasn't drained properly. Flag the checkpoint as invalid if the
2507    // cache contains dirty data.
2508    bool bad_checkpoint(dirty);
2509    SERIALIZE_SCALAR(bad_checkpoint);
2510}
2511
2512void
2513Cache::unserialize(CheckpointIn &cp)
2514{
2515    bool bad_checkpoint;
2516    UNSERIALIZE_SCALAR(bad_checkpoint);
2517    if (bad_checkpoint) {
2518        fatal("Restoring from checkpoints with dirty caches is not supported "
2519              "in the classic memory system. Please remove any caches or "
2520              " drain them properly before taking checkpoints.\n");
2521    }
2522}
2523
2524///////////////
2525//
2526// CpuSidePort
2527//
2528///////////////
2529
2530AddrRangeList
2531Cache::CpuSidePort::getAddrRanges() const
2532{
2533    return cache->getAddrRanges();
2534}
2535
2536bool
2537Cache::CpuSidePort::recvTimingReq(PacketPtr pkt)
2538{
2539    assert(!cache->system->bypassCaches());
2540
2541    bool success = false;
2542
2543    // always let express snoop packets through if even if blocked
2544    if (pkt->isExpressSnoop()) {
2545        // do not change the current retry state
2546        bool M5_VAR_USED bypass_success = cache->recvTimingReq(pkt);
2547        assert(bypass_success);
2548        return true;
2549    } else if (blocked || mustSendRetry) {
2550        // either already committed to send a retry, or blocked
2551        success = false;
2552    } else {
2553        // pass it on to the cache, and let the cache decide if we
2554        // have to retry or not
2555        success = cache->recvTimingReq(pkt);
2556    }
2557
2558    // remember if we have to retry
2559    mustSendRetry = !success;
2560    return success;
2561}
2562
2563Tick
2564Cache::CpuSidePort::recvAtomic(PacketPtr pkt)
2565{
2566    return cache->recvAtomic(pkt);
2567}
2568
2569void
2570Cache::CpuSidePort::recvFunctional(PacketPtr pkt)
2571{
2572    // functional request
2573    cache->functionalAccess(pkt, true);
2574}
2575
2576Cache::
2577CpuSidePort::CpuSidePort(const std::string &_name, Cache *_cache,
2578                         const std::string &_label)
2579    : BaseCache::CacheSlavePort(_name, _cache, _label), cache(_cache)
2580{
2581}
2582
2583Cache*
2584CacheParams::create()
2585{
2586    assert(tags);
2587
2588    return new Cache(this);
2589}
2590///////////////
2591//
2592// MemSidePort
2593//
2594///////////////
2595
2596bool
2597Cache::MemSidePort::recvTimingResp(PacketPtr pkt)
2598{
2599    cache->recvTimingResp(pkt);
2600    return true;
2601}
2602
2603// Express snooping requests to memside port
2604void
2605Cache::MemSidePort::recvTimingSnoopReq(PacketPtr pkt)
2606{
2607    // handle snooping requests
2608    cache->recvTimingSnoopReq(pkt);
2609}
2610
2611Tick
2612Cache::MemSidePort::recvAtomicSnoop(PacketPtr pkt)
2613{
2614    return cache->recvAtomicSnoop(pkt);
2615}
2616
2617void
2618Cache::MemSidePort::recvFunctionalSnoop(PacketPtr pkt)
2619{
2620    // functional snoop (note that in contrast to atomic we don't have
2621    // a specific functionalSnoop method, as they have the same
2622    // behaviour regardless)
2623    cache->functionalAccess(pkt, false);
2624}
2625
2626void
2627Cache::CacheReqPacketQueue::sendDeferredPacket()
2628{
2629    // sanity check
2630    assert(!waitingOnRetry);
2631
2632    // there should never be any deferred request packets in the
2633    // queue, instead we resly on the cache to provide the packets
2634    // from the MSHR queue or write queue
2635    assert(deferredPacketReadyTime() == MaxTick);
2636
2637    // check for request packets (requests & writebacks)
2638    QueueEntry* entry = cache.getNextQueueEntry();
2639
2640    if (!entry) {
2641        // can happen if e.g. we attempt a writeback and fail, but
2642        // before the retry, the writeback is eliminated because
2643        // we snoop another cache's ReadEx.
2644    } else {
2645        // let our snoop responses go first if there are responses to
2646        // the same addresses
2647        if (checkConflictingSnoop(entry->blkAddr)) {
2648            return;
2649        }
2650        waitingOnRetry = entry->sendPacket(cache);
2651    }
2652
2653    // if we succeeded and are not waiting for a retry, schedule the
2654    // next send considering when the next queue is ready, note that
2655    // snoop responses have their own packet queue and thus schedule
2656    // their own events
2657    if (!waitingOnRetry) {
2658        schedSendEvent(cache.nextQueueReadyTime());
2659    }
2660}
2661
2662Cache::
2663MemSidePort::MemSidePort(const std::string &_name, Cache *_cache,
2664                         const std::string &_label)
2665    : BaseCache::CacheMasterPort(_name, _cache, _reqQueue, _snoopRespQueue),
2666      _reqQueue(*_cache, *this, _snoopRespQueue, _label),
2667      _snoopRespQueue(*_cache, *this, _label), cache(_cache)
2668{
2669}
2670