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