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