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