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