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