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