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