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