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