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