base.cc revision 13750
1/* 2 * Copyright (c) 2012-2013, 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) 2003-2005 The Regents of The University of Michigan 15 * All rights reserved. 16 * 17 * Redistribution and use in source and binary forms, with or without 18 * modification, are permitted provided that the following conditions are 19 * met: redistributions of source code must retain the above copyright 20 * notice, this list of conditions and the following disclaimer; 21 * redistributions in binary form must reproduce the above copyright 22 * notice, this list of conditions and the following disclaimer in the 23 * documentation and/or other materials provided with the distribution; 24 * neither the name of the copyright holders nor the names of its 25 * contributors may be used to endorse or promote products derived from 26 * this software without specific prior written permission. 27 * 28 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 29 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 30 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 31 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 32 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 33 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 34 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 35 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 36 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 37 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 38 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 39 * 40 * Authors: Erik Hallnor 41 * Nikos Nikoleris 42 */ 43 44/** 45 * @file 46 * Definition of BaseCache functions. 47 */ 48 49#include "mem/cache/base.hh" 50 51#include "base/compiler.hh" 52#include "base/logging.hh" 53#include "debug/Cache.hh" 54#include "debug/CachePort.hh" 55#include "debug/CacheRepl.hh" 56#include "debug/CacheVerbose.hh" 57#include "mem/cache/mshr.hh" 58#include "mem/cache/prefetch/base.hh" 59#include "mem/cache/queue_entry.hh" 60#include "params/BaseCache.hh" 61#include "params/WriteAllocator.hh" 62#include "sim/core.hh" 63 64class BaseMasterPort; 65class BaseSlavePort; 66 67using namespace std; 68 69BaseCache::CacheSlavePort::CacheSlavePort(const std::string &_name, 70 BaseCache *_cache, 71 const std::string &_label) 72 : QueuedSlavePort(_name, _cache, queue), 73 queue(*_cache, *this, true, _label), 74 blocked(false), mustSendRetry(false), 75 sendRetryEvent([this]{ processSendRetry(); }, _name) 76{ 77} 78 79BaseCache::BaseCache(const BaseCacheParams *p, unsigned blk_size) 80 : MemObject(p), 81 cpuSidePort (p->name + ".cpu_side", this, "CpuSidePort"), 82 memSidePort(p->name + ".mem_side", this, "MemSidePort"), 83 mshrQueue("MSHRs", p->mshrs, 0, p->demand_mshr_reserve), // see below 84 writeBuffer("write buffer", p->write_buffers, p->mshrs), // see below 85 tags(p->tags), 86 prefetcher(p->prefetcher), 87 writeAllocator(p->write_allocator), 88 writebackClean(p->writeback_clean), 89 tempBlockWriteback(nullptr), 90 writebackTempBlockAtomicEvent([this]{ writebackTempBlockAtomic(); }, 91 name(), false, 92 EventBase::Delayed_Writeback_Pri), 93 blkSize(blk_size), 94 lookupLatency(p->tag_latency), 95 dataLatency(p->data_latency), 96 forwardLatency(p->tag_latency), 97 fillLatency(p->data_latency), 98 responseLatency(p->response_latency), 99 sequentialAccess(p->sequential_access), 100 numTarget(p->tgts_per_mshr), 101 forwardSnoops(true), 102 clusivity(p->clusivity), 103 isReadOnly(p->is_read_only), 104 blocked(0), 105 order(0), 106 noTargetMSHR(nullptr), 107 missCount(p->max_miss_count), 108 addrRanges(p->addr_ranges.begin(), p->addr_ranges.end()), 109 system(p->system) 110{ 111 // the MSHR queue has no reserve entries as we check the MSHR 112 // queue on every single allocation, whereas the write queue has 113 // as many reserve entries as we have MSHRs, since every MSHR may 114 // eventually require a writeback, and we do not check the write 115 // buffer before committing to an MSHR 116 117 // forward snoops is overridden in init() once we can query 118 // whether the connected master is actually snooping or not 119 120 tempBlock = new TempCacheBlk(blkSize); 121 122 tags->tagsInit(); 123 if (prefetcher) 124 prefetcher->setCache(this); 125} 126 127BaseCache::~BaseCache() 128{ 129 delete tempBlock; 130} 131 132void 133BaseCache::CacheSlavePort::setBlocked() 134{ 135 assert(!blocked); 136 DPRINTF(CachePort, "Port is blocking new requests\n"); 137 blocked = true; 138 // if we already scheduled a retry in this cycle, but it has not yet 139 // happened, cancel it 140 if (sendRetryEvent.scheduled()) { 141 owner.deschedule(sendRetryEvent); 142 DPRINTF(CachePort, "Port descheduled retry\n"); 143 mustSendRetry = true; 144 } 145} 146 147void 148BaseCache::CacheSlavePort::clearBlocked() 149{ 150 assert(blocked); 151 DPRINTF(CachePort, "Port is accepting new requests\n"); 152 blocked = false; 153 if (mustSendRetry) { 154 // @TODO: need to find a better time (next cycle?) 155 owner.schedule(sendRetryEvent, curTick() + 1); 156 } 157} 158 159void 160BaseCache::CacheSlavePort::processSendRetry() 161{ 162 DPRINTF(CachePort, "Port is sending retry\n"); 163 164 // reset the flag and call retry 165 mustSendRetry = false; 166 sendRetryReq(); 167} 168 169Addr 170BaseCache::regenerateBlkAddr(CacheBlk* blk) 171{ 172 if (blk != tempBlock) { 173 return tags->regenerateBlkAddr(blk); 174 } else { 175 return tempBlock->getAddr(); 176 } 177} 178 179void 180BaseCache::init() 181{ 182 if (!cpuSidePort.isConnected() || !memSidePort.isConnected()) 183 fatal("Cache ports on %s are not connected\n", name()); 184 cpuSidePort.sendRangeChange(); 185 forwardSnoops = cpuSidePort.isSnooping(); 186} 187 188BaseMasterPort & 189BaseCache::getMasterPort(const std::string &if_name, PortID idx) 190{ 191 if (if_name == "mem_side") { 192 return memSidePort; 193 } else { 194 return MemObject::getMasterPort(if_name, idx); 195 } 196} 197 198BaseSlavePort & 199BaseCache::getSlavePort(const std::string &if_name, PortID idx) 200{ 201 if (if_name == "cpu_side") { 202 return cpuSidePort; 203 } else { 204 return MemObject::getSlavePort(if_name, idx); 205 } 206} 207 208bool 209BaseCache::inRange(Addr addr) const 210{ 211 for (const auto& r : addrRanges) { 212 if (r.contains(addr)) { 213 return true; 214 } 215 } 216 return false; 217} 218 219void 220BaseCache::handleTimingReqHit(PacketPtr pkt, CacheBlk *blk, Tick request_time) 221{ 222 if (pkt->needsResponse()) { 223 // These delays should have been consumed by now 224 assert(pkt->headerDelay == 0); 225 assert(pkt->payloadDelay == 0); 226 227 pkt->makeTimingResponse(); 228 229 // In this case we are considering request_time that takes 230 // into account the delay of the xbar, if any, and just 231 // lat, neglecting responseLatency, modelling hit latency 232 // just as the value of lat overriden by access(), which calls 233 // the calculateAccessLatency() function. 234 cpuSidePort.schedTimingResp(pkt, request_time); 235 } else { 236 DPRINTF(Cache, "%s satisfied %s, no response needed\n", __func__, 237 pkt->print()); 238 239 // queue the packet for deletion, as the sending cache is 240 // still relying on it; if the block is found in access(), 241 // CleanEvict and Writeback messages will be deleted 242 // here as well 243 pendingDelete.reset(pkt); 244 } 245} 246 247void 248BaseCache::handleTimingReqMiss(PacketPtr pkt, MSHR *mshr, CacheBlk *blk, 249 Tick forward_time, Tick request_time) 250{ 251 if (writeAllocator && 252 pkt && pkt->isWrite() && !pkt->req->isUncacheable()) { 253 writeAllocator->updateMode(pkt->getAddr(), pkt->getSize(), 254 pkt->getBlockAddr(blkSize)); 255 } 256 257 if (mshr) { 258 /// MSHR hit 259 /// @note writebacks will be checked in getNextMSHR() 260 /// for any conflicting requests to the same block 261 262 //@todo remove hw_pf here 263 264 // Coalesce unless it was a software prefetch (see above). 265 if (pkt) { 266 assert(!pkt->isWriteback()); 267 // CleanEvicts corresponding to blocks which have 268 // outstanding requests in MSHRs are simply sunk here 269 if (pkt->cmd == MemCmd::CleanEvict) { 270 pendingDelete.reset(pkt); 271 } else if (pkt->cmd == MemCmd::WriteClean) { 272 // A WriteClean should never coalesce with any 273 // outstanding cache maintenance requests. 274 275 // We use forward_time here because there is an 276 // uncached memory write, forwarded to WriteBuffer. 277 allocateWriteBuffer(pkt, forward_time); 278 } else { 279 DPRINTF(Cache, "%s coalescing MSHR for %s\n", __func__, 280 pkt->print()); 281 282 assert(pkt->req->masterId() < system->maxMasters()); 283 mshr_hits[pkt->cmdToIndex()][pkt->req->masterId()]++; 284 285 // We use forward_time here because it is the same 286 // considering new targets. We have multiple 287 // requests for the same address here. It 288 // specifies the latency to allocate an internal 289 // buffer and to schedule an event to the queued 290 // port and also takes into account the additional 291 // delay of the xbar. 292 mshr->allocateTarget(pkt, forward_time, order++, 293 allocOnFill(pkt->cmd)); 294 if (mshr->getNumTargets() == numTarget) { 295 noTargetMSHR = mshr; 296 setBlocked(Blocked_NoTargets); 297 // need to be careful with this... if this mshr isn't 298 // ready yet (i.e. time > curTick()), we don't want to 299 // move it ahead of mshrs that are ready 300 // mshrQueue.moveToFront(mshr); 301 } 302 } 303 } 304 } else { 305 // no MSHR 306 assert(pkt->req->masterId() < system->maxMasters()); 307 mshr_misses[pkt->cmdToIndex()][pkt->req->masterId()]++; 308 309 if (pkt->isEviction() || pkt->cmd == MemCmd::WriteClean) { 310 // We use forward_time here because there is an 311 // writeback or writeclean, forwarded to WriteBuffer. 312 allocateWriteBuffer(pkt, forward_time); 313 } else { 314 if (blk && blk->isValid()) { 315 // If we have a write miss to a valid block, we 316 // need to mark the block non-readable. Otherwise 317 // if we allow reads while there's an outstanding 318 // write miss, the read could return stale data 319 // out of the cache block... a more aggressive 320 // system could detect the overlap (if any) and 321 // forward data out of the MSHRs, but we don't do 322 // that yet. Note that we do need to leave the 323 // block valid so that it stays in the cache, in 324 // case we get an upgrade response (and hence no 325 // new data) when the write miss completes. 326 // As long as CPUs do proper store/load forwarding 327 // internally, and have a sufficiently weak memory 328 // model, this is probably unnecessary, but at some 329 // point it must have seemed like we needed it... 330 assert((pkt->needsWritable() && !blk->isWritable()) || 331 pkt->req->isCacheMaintenance()); 332 blk->status &= ~BlkReadable; 333 } 334 // Here we are using forward_time, modelling the latency of 335 // a miss (outbound) just as forwardLatency, neglecting the 336 // lookupLatency component. 337 allocateMissBuffer(pkt, forward_time); 338 } 339 } 340} 341 342void 343BaseCache::recvTimingReq(PacketPtr pkt) 344{ 345 // anything that is merely forwarded pays for the forward latency and 346 // the delay provided by the crossbar 347 Tick forward_time = clockEdge(forwardLatency) + pkt->headerDelay; 348 349 Cycles lat; 350 CacheBlk *blk = nullptr; 351 bool satisfied = false; 352 { 353 PacketList writebacks; 354 // Note that lat is passed by reference here. The function 355 // access() will set the lat value. 356 satisfied = access(pkt, blk, lat, writebacks); 357 358 // After the evicted blocks are selected, they must be forwarded 359 // to the write buffer to ensure they logically precede anything 360 // happening below 361 doWritebacks(writebacks, clockEdge(lat + forwardLatency)); 362 } 363 364 // Here we charge the headerDelay that takes into account the latencies 365 // of the bus, if the packet comes from it. 366 // The latency charged is just the value set by the access() function. 367 // In case of a hit we are neglecting response latency. 368 // In case of a miss we are neglecting forward latency. 369 Tick request_time = clockEdge(lat); 370 // Here we reset the timing of the packet. 371 pkt->headerDelay = pkt->payloadDelay = 0; 372 373 if (satisfied) { 374 // notify before anything else as later handleTimingReqHit might turn 375 // the packet in a response 376 ppHit->notify(pkt); 377 378 if (prefetcher && blk && blk->wasPrefetched()) { 379 blk->status &= ~BlkHWPrefetched; 380 } 381 382 handleTimingReqHit(pkt, blk, request_time); 383 } else { 384 handleTimingReqMiss(pkt, blk, forward_time, request_time); 385 386 ppMiss->notify(pkt); 387 } 388 389 if (prefetcher) { 390 // track time of availability of next prefetch, if any 391 Tick next_pf_time = prefetcher->nextPrefetchReadyTime(); 392 if (next_pf_time != MaxTick) { 393 schedMemSideSendEvent(next_pf_time); 394 } 395 } 396} 397 398void 399BaseCache::handleUncacheableWriteResp(PacketPtr pkt) 400{ 401 Tick completion_time = clockEdge(responseLatency) + 402 pkt->headerDelay + pkt->payloadDelay; 403 404 // Reset the bus additional time as it is now accounted for 405 pkt->headerDelay = pkt->payloadDelay = 0; 406 407 cpuSidePort.schedTimingResp(pkt, completion_time); 408} 409 410void 411BaseCache::recvTimingResp(PacketPtr pkt) 412{ 413 assert(pkt->isResponse()); 414 415 // all header delay should be paid for by the crossbar, unless 416 // this is a prefetch response from above 417 panic_if(pkt->headerDelay != 0 && pkt->cmd != MemCmd::HardPFResp, 418 "%s saw a non-zero packet delay\n", name()); 419 420 const bool is_error = pkt->isError(); 421 422 if (is_error) { 423 DPRINTF(Cache, "%s: Cache received %s with error\n", __func__, 424 pkt->print()); 425 } 426 427 DPRINTF(Cache, "%s: Handling response %s\n", __func__, 428 pkt->print()); 429 430 // if this is a write, we should be looking at an uncacheable 431 // write 432 if (pkt->isWrite()) { 433 assert(pkt->req->isUncacheable()); 434 handleUncacheableWriteResp(pkt); 435 return; 436 } 437 438 // we have dealt with any (uncacheable) writes above, from here on 439 // we know we are dealing with an MSHR due to a miss or a prefetch 440 MSHR *mshr = dynamic_cast<MSHR*>(pkt->popSenderState()); 441 assert(mshr); 442 443 if (mshr == noTargetMSHR) { 444 // we always clear at least one target 445 clearBlocked(Blocked_NoTargets); 446 noTargetMSHR = nullptr; 447 } 448 449 // Initial target is used just for stats 450 MSHR::Target *initial_tgt = mshr->getTarget(); 451 int stats_cmd_idx = initial_tgt->pkt->cmdToIndex(); 452 Tick miss_latency = curTick() - initial_tgt->recvTime; 453 454 if (pkt->req->isUncacheable()) { 455 assert(pkt->req->masterId() < system->maxMasters()); 456 mshr_uncacheable_lat[stats_cmd_idx][pkt->req->masterId()] += 457 miss_latency; 458 } else { 459 assert(pkt->req->masterId() < system->maxMasters()); 460 mshr_miss_latency[stats_cmd_idx][pkt->req->masterId()] += 461 miss_latency; 462 } 463 464 PacketList writebacks; 465 466 bool is_fill = !mshr->isForward && 467 (pkt->isRead() || pkt->cmd == MemCmd::UpgradeResp || 468 mshr->wasWholeLineWrite); 469 470 // make sure that if the mshr was due to a whole line write then 471 // the response is an invalidation 472 assert(!mshr->wasWholeLineWrite || pkt->isInvalidate()); 473 474 CacheBlk *blk = tags->findBlock(pkt->getAddr(), pkt->isSecure()); 475 476 if (is_fill && !is_error) { 477 DPRINTF(Cache, "Block for addr %#llx being updated in Cache\n", 478 pkt->getAddr()); 479 480 const bool allocate = (writeAllocator && mshr->wasWholeLineWrite) ? 481 writeAllocator->allocate() : mshr->allocOnFill(); 482 blk = handleFill(pkt, blk, writebacks, allocate); 483 assert(blk != nullptr); 484 ppFill->notify(pkt); 485 } 486 487 if (blk && blk->isValid() && pkt->isClean() && !pkt->isInvalidate()) { 488 // The block was marked not readable while there was a pending 489 // cache maintenance operation, restore its flag. 490 blk->status |= BlkReadable; 491 492 // This was a cache clean operation (without invalidate) 493 // and we have a copy of the block already. Since there 494 // is no invalidation, we can promote targets that don't 495 // require a writable copy 496 mshr->promoteReadable(); 497 } 498 499 if (blk && blk->isWritable() && !pkt->req->isCacheInvalidate()) { 500 // If at this point the referenced block is writable and the 501 // response is not a cache invalidate, we promote targets that 502 // were deferred as we couldn't guarrantee a writable copy 503 mshr->promoteWritable(); 504 } 505 506 serviceMSHRTargets(mshr, pkt, blk); 507 508 if (mshr->promoteDeferredTargets()) { 509 // avoid later read getting stale data while write miss is 510 // outstanding.. see comment in timingAccess() 511 if (blk) { 512 blk->status &= ~BlkReadable; 513 } 514 mshrQueue.markPending(mshr); 515 schedMemSideSendEvent(clockEdge() + pkt->payloadDelay); 516 } else { 517 // while we deallocate an mshr from the queue we still have to 518 // check the isFull condition before and after as we might 519 // have been using the reserved entries already 520 const bool was_full = mshrQueue.isFull(); 521 mshrQueue.deallocate(mshr); 522 if (was_full && !mshrQueue.isFull()) { 523 clearBlocked(Blocked_NoMSHRs); 524 } 525 526 // Request the bus for a prefetch if this deallocation freed enough 527 // MSHRs for a prefetch to take place 528 if (prefetcher && mshrQueue.canPrefetch()) { 529 Tick next_pf_time = std::max(prefetcher->nextPrefetchReadyTime(), 530 clockEdge()); 531 if (next_pf_time != MaxTick) 532 schedMemSideSendEvent(next_pf_time); 533 } 534 } 535 536 // if we used temp block, check to see if its valid and then clear it out 537 if (blk == tempBlock && tempBlock->isValid()) { 538 evictBlock(blk, writebacks); 539 } 540 541 const Tick forward_time = clockEdge(forwardLatency) + pkt->headerDelay; 542 // copy writebacks to write buffer 543 doWritebacks(writebacks, forward_time); 544 545 DPRINTF(CacheVerbose, "%s: Leaving with %s\n", __func__, pkt->print()); 546 delete pkt; 547} 548 549 550Tick 551BaseCache::recvAtomic(PacketPtr pkt) 552{ 553 // should assert here that there are no outstanding MSHRs or 554 // writebacks... that would mean that someone used an atomic 555 // access in timing mode 556 557 // We use lookupLatency here because it is used to specify the latency 558 // to access. 559 Cycles lat = lookupLatency; 560 561 CacheBlk *blk = nullptr; 562 PacketList writebacks; 563 bool satisfied = access(pkt, blk, lat, writebacks); 564 565 if (pkt->isClean() && blk && blk->isDirty()) { 566 // A cache clean opearation is looking for a dirty 567 // block. If a dirty block is encountered a WriteClean 568 // will update any copies to the path to the memory 569 // until the point of reference. 570 DPRINTF(CacheVerbose, "%s: packet %s found block: %s\n", 571 __func__, pkt->print(), blk->print()); 572 PacketPtr wb_pkt = writecleanBlk(blk, pkt->req->getDest(), pkt->id); 573 writebacks.push_back(wb_pkt); 574 pkt->setSatisfied(); 575 } 576 577 // handle writebacks resulting from the access here to ensure they 578 // logically precede anything happening below 579 doWritebacksAtomic(writebacks); 580 assert(writebacks.empty()); 581 582 if (!satisfied) { 583 lat += handleAtomicReqMiss(pkt, blk, writebacks); 584 } 585 586 // Note that we don't invoke the prefetcher at all in atomic mode. 587 // It's not clear how to do it properly, particularly for 588 // prefetchers that aggressively generate prefetch candidates and 589 // rely on bandwidth contention to throttle them; these will tend 590 // to pollute the cache in atomic mode since there is no bandwidth 591 // contention. If we ever do want to enable prefetching in atomic 592 // mode, though, this is the place to do it... see timingAccess() 593 // for an example (though we'd want to issue the prefetch(es) 594 // immediately rather than calling requestMemSideBus() as we do 595 // there). 596 597 // do any writebacks resulting from the response handling 598 doWritebacksAtomic(writebacks); 599 600 // if we used temp block, check to see if its valid and if so 601 // clear it out, but only do so after the call to recvAtomic is 602 // finished so that any downstream observers (such as a snoop 603 // filter), first see the fill, and only then see the eviction 604 if (blk == tempBlock && tempBlock->isValid()) { 605 // the atomic CPU calls recvAtomic for fetch and load/store 606 // sequentuially, and we may already have a tempBlock 607 // writeback from the fetch that we have not yet sent 608 if (tempBlockWriteback) { 609 // if that is the case, write the prevoius one back, and 610 // do not schedule any new event 611 writebackTempBlockAtomic(); 612 } else { 613 // the writeback/clean eviction happens after the call to 614 // recvAtomic has finished (but before any successive 615 // calls), so that the response handling from the fill is 616 // allowed to happen first 617 schedule(writebackTempBlockAtomicEvent, curTick()); 618 } 619 620 tempBlockWriteback = evictBlock(blk); 621 } 622 623 if (pkt->needsResponse()) { 624 pkt->makeAtomicResponse(); 625 } 626 627 return lat * clockPeriod(); 628} 629 630void 631BaseCache::functionalAccess(PacketPtr pkt, bool from_cpu_side) 632{ 633 Addr blk_addr = pkt->getBlockAddr(blkSize); 634 bool is_secure = pkt->isSecure(); 635 CacheBlk *blk = tags->findBlock(pkt->getAddr(), is_secure); 636 MSHR *mshr = mshrQueue.findMatch(blk_addr, is_secure); 637 638 pkt->pushLabel(name()); 639 640 CacheBlkPrintWrapper cbpw(blk); 641 642 // Note that just because an L2/L3 has valid data doesn't mean an 643 // L1 doesn't have a more up-to-date modified copy that still 644 // needs to be found. As a result we always update the request if 645 // we have it, but only declare it satisfied if we are the owner. 646 647 // see if we have data at all (owned or otherwise) 648 bool have_data = blk && blk->isValid() 649 && pkt->trySatisfyFunctional(&cbpw, blk_addr, is_secure, blkSize, 650 blk->data); 651 652 // data we have is dirty if marked as such or if we have an 653 // in-service MSHR that is pending a modified line 654 bool have_dirty = 655 have_data && (blk->isDirty() || 656 (mshr && mshr->inService && mshr->isPendingModified())); 657 658 bool done = have_dirty || 659 cpuSidePort.trySatisfyFunctional(pkt) || 660 mshrQueue.trySatisfyFunctional(pkt, blk_addr) || 661 writeBuffer.trySatisfyFunctional(pkt, blk_addr) || 662 memSidePort.trySatisfyFunctional(pkt); 663 664 DPRINTF(CacheVerbose, "%s: %s %s%s%s\n", __func__, pkt->print(), 665 (blk && blk->isValid()) ? "valid " : "", 666 have_data ? "data " : "", done ? "done " : ""); 667 668 // We're leaving the cache, so pop cache->name() label 669 pkt->popLabel(); 670 671 if (done) { 672 pkt->makeResponse(); 673 } else { 674 // if it came as a request from the CPU side then make sure it 675 // continues towards the memory side 676 if (from_cpu_side) { 677 memSidePort.sendFunctional(pkt); 678 } else if (cpuSidePort.isSnooping()) { 679 // if it came from the memory side, it must be a snoop request 680 // and we should only forward it if we are forwarding snoops 681 cpuSidePort.sendFunctionalSnoop(pkt); 682 } 683 } 684} 685 686 687void 688BaseCache::cmpAndSwap(CacheBlk *blk, PacketPtr pkt) 689{ 690 assert(pkt->isRequest()); 691 692 uint64_t overwrite_val; 693 bool overwrite_mem; 694 uint64_t condition_val64; 695 uint32_t condition_val32; 696 697 int offset = pkt->getOffset(blkSize); 698 uint8_t *blk_data = blk->data + offset; 699 700 assert(sizeof(uint64_t) >= pkt->getSize()); 701 702 overwrite_mem = true; 703 // keep a copy of our possible write value, and copy what is at the 704 // memory address into the packet 705 pkt->writeData((uint8_t *)&overwrite_val); 706 pkt->setData(blk_data); 707 708 if (pkt->req->isCondSwap()) { 709 if (pkt->getSize() == sizeof(uint64_t)) { 710 condition_val64 = pkt->req->getExtraData(); 711 overwrite_mem = !std::memcmp(&condition_val64, blk_data, 712 sizeof(uint64_t)); 713 } else if (pkt->getSize() == sizeof(uint32_t)) { 714 condition_val32 = (uint32_t)pkt->req->getExtraData(); 715 overwrite_mem = !std::memcmp(&condition_val32, blk_data, 716 sizeof(uint32_t)); 717 } else 718 panic("Invalid size for conditional read/write\n"); 719 } 720 721 if (overwrite_mem) { 722 std::memcpy(blk_data, &overwrite_val, pkt->getSize()); 723 blk->status |= BlkDirty; 724 } 725} 726 727QueueEntry* 728BaseCache::getNextQueueEntry() 729{ 730 // Check both MSHR queue and write buffer for potential requests, 731 // note that null does not mean there is no request, it could 732 // simply be that it is not ready 733 MSHR *miss_mshr = mshrQueue.getNext(); 734 WriteQueueEntry *wq_entry = writeBuffer.getNext(); 735 736 // If we got a write buffer request ready, first priority is a 737 // full write buffer, otherwise we favour the miss requests 738 if (wq_entry && (writeBuffer.isFull() || !miss_mshr)) { 739 // need to search MSHR queue for conflicting earlier miss. 740 MSHR *conflict_mshr = 741 mshrQueue.findPending(wq_entry->blkAddr, 742 wq_entry->isSecure); 743 744 if (conflict_mshr && conflict_mshr->order < wq_entry->order) { 745 // Service misses in order until conflict is cleared. 746 return conflict_mshr; 747 748 // @todo Note that we ignore the ready time of the conflict here 749 } 750 751 // No conflicts; issue write 752 return wq_entry; 753 } else if (miss_mshr) { 754 // need to check for conflicting earlier writeback 755 WriteQueueEntry *conflict_mshr = 756 writeBuffer.findPending(miss_mshr->blkAddr, 757 miss_mshr->isSecure); 758 if (conflict_mshr) { 759 // not sure why we don't check order here... it was in the 760 // original code but commented out. 761 762 // The only way this happens is if we are 763 // doing a write and we didn't have permissions 764 // then subsequently saw a writeback (owned got evicted) 765 // We need to make sure to perform the writeback first 766 // To preserve the dirty data, then we can issue the write 767 768 // should we return wq_entry here instead? I.e. do we 769 // have to flush writes in order? I don't think so... not 770 // for Alpha anyway. Maybe for x86? 771 return conflict_mshr; 772 773 // @todo Note that we ignore the ready time of the conflict here 774 } 775 776 // No conflicts; issue read 777 return miss_mshr; 778 } 779 780 // fall through... no pending requests. Try a prefetch. 781 assert(!miss_mshr && !wq_entry); 782 if (prefetcher && mshrQueue.canPrefetch()) { 783 // If we have a miss queue slot, we can try a prefetch 784 PacketPtr pkt = prefetcher->getPacket(); 785 if (pkt) { 786 Addr pf_addr = pkt->getBlockAddr(blkSize); 787 if (!tags->findBlock(pf_addr, pkt->isSecure()) && 788 !mshrQueue.findMatch(pf_addr, pkt->isSecure()) && 789 !writeBuffer.findMatch(pf_addr, pkt->isSecure())) { 790 // Update statistic on number of prefetches issued 791 // (hwpf_mshr_misses) 792 assert(pkt->req->masterId() < system->maxMasters()); 793 mshr_misses[pkt->cmdToIndex()][pkt->req->masterId()]++; 794 795 // allocate an MSHR and return it, note 796 // that we send the packet straight away, so do not 797 // schedule the send 798 return allocateMissBuffer(pkt, curTick(), false); 799 } else { 800 // free the request and packet 801 delete pkt; 802 } 803 } 804 } 805 806 return nullptr; 807} 808 809void 810BaseCache::satisfyRequest(PacketPtr pkt, CacheBlk *blk, bool, bool) 811{ 812 assert(pkt->isRequest()); 813 814 assert(blk && blk->isValid()); 815 // Occasionally this is not true... if we are a lower-level cache 816 // satisfying a string of Read and ReadEx requests from 817 // upper-level caches, a Read will mark the block as shared but we 818 // can satisfy a following ReadEx anyway since we can rely on the 819 // Read requester(s) to have buffered the ReadEx snoop and to 820 // invalidate their blocks after receiving them. 821 // assert(!pkt->needsWritable() || blk->isWritable()); 822 assert(pkt->getOffset(blkSize) + pkt->getSize() <= blkSize); 823 824 // Check RMW operations first since both isRead() and 825 // isWrite() will be true for them 826 if (pkt->cmd == MemCmd::SwapReq) { 827 if (pkt->isAtomicOp()) { 828 // extract data from cache and save it into the data field in 829 // the packet as a return value from this atomic op 830 int offset = tags->extractBlkOffset(pkt->getAddr()); 831 uint8_t *blk_data = blk->data + offset; 832 pkt->setData(blk_data); 833 834 // execute AMO operation 835 (*(pkt->getAtomicOp()))(blk_data); 836 837 // set block status to dirty 838 blk->status |= BlkDirty; 839 } else { 840 cmpAndSwap(blk, pkt); 841 } 842 } else if (pkt->isWrite()) { 843 // we have the block in a writable state and can go ahead, 844 // note that the line may be also be considered writable in 845 // downstream caches along the path to memory, but always 846 // Exclusive, and never Modified 847 assert(blk->isWritable()); 848 // Write or WriteLine at the first cache with block in writable state 849 if (blk->checkWrite(pkt)) { 850 pkt->writeDataToBlock(blk->data, blkSize); 851 } 852 // Always mark the line as dirty (and thus transition to the 853 // Modified state) even if we are a failed StoreCond so we 854 // supply data to any snoops that have appended themselves to 855 // this cache before knowing the store will fail. 856 blk->status |= BlkDirty; 857 DPRINTF(CacheVerbose, "%s for %s (write)\n", __func__, pkt->print()); 858 } else if (pkt->isRead()) { 859 if (pkt->isLLSC()) { 860 blk->trackLoadLocked(pkt); 861 } 862 863 // all read responses have a data payload 864 assert(pkt->hasRespData()); 865 pkt->setDataFromBlock(blk->data, blkSize); 866 } else if (pkt->isUpgrade()) { 867 // sanity check 868 assert(!pkt->hasSharers()); 869 870 if (blk->isDirty()) { 871 // we were in the Owned state, and a cache above us that 872 // has the line in Shared state needs to be made aware 873 // that the data it already has is in fact dirty 874 pkt->setCacheResponding(); 875 blk->status &= ~BlkDirty; 876 } 877 } else if (pkt->isClean()) { 878 blk->status &= ~BlkDirty; 879 } else { 880 assert(pkt->isInvalidate()); 881 invalidateBlock(blk); 882 DPRINTF(CacheVerbose, "%s for %s (invalidation)\n", __func__, 883 pkt->print()); 884 } 885} 886 887///////////////////////////////////////////////////// 888// 889// Access path: requests coming in from the CPU side 890// 891///////////////////////////////////////////////////// 892Cycles 893BaseCache::calculateTagOnlyLatency(const uint32_t delay, 894 const Cycles lookup_lat) const 895{ 896 // A tag-only access has to wait for the packet to arrive in order to 897 // perform the tag lookup. 898 return ticksToCycles(delay) + lookup_lat; 899} 900 901Cycles 902BaseCache::calculateAccessLatency(const CacheBlk* blk, const uint32_t delay, 903 const Cycles lookup_lat) const 904{ 905 Cycles lat(0); 906 907 if (blk != nullptr) { 908 // As soon as the access arrives, for sequential accesses first access 909 // tags, then the data entry. In the case of parallel accesses the 910 // latency is dictated by the slowest of tag and data latencies. 911 if (sequentialAccess) { 912 lat = ticksToCycles(delay) + lookup_lat + dataLatency; 913 } else { 914 lat = ticksToCycles(delay) + std::max(lookup_lat, dataLatency); 915 } 916 917 // Check if the block to be accessed is available. If not, apply the 918 // access latency on top of when the block is ready to be accessed. 919 const Tick tick = curTick() + delay; 920 const Tick when_ready = blk->getWhenReady(); 921 if (when_ready > tick && 922 ticksToCycles(when_ready - tick) > lat) { 923 lat += ticksToCycles(when_ready - tick); 924 } 925 } else { 926 // In case of a miss, we neglect the data access in a parallel 927 // configuration (i.e., the data access will be stopped as soon as 928 // we find out it is a miss), and use the tag-only latency. 929 lat = calculateTagOnlyLatency(delay, lookup_lat); 930 } 931 932 return lat; 933} 934 935bool 936BaseCache::access(PacketPtr pkt, CacheBlk *&blk, Cycles &lat, 937 PacketList &writebacks) 938{ 939 // sanity check 940 assert(pkt->isRequest()); 941 942 chatty_assert(!(isReadOnly && pkt->isWrite()), 943 "Should never see a write in a read-only cache %s\n", 944 name()); 945 946 // Access block in the tags 947 Cycles tag_latency(0); 948 blk = tags->accessBlock(pkt->getAddr(), pkt->isSecure(), tag_latency); 949 950 DPRINTF(Cache, "%s for %s %s\n", __func__, pkt->print(), 951 blk ? "hit " + blk->print() : "miss"); 952 953 if (pkt->req->isCacheMaintenance()) { 954 // A cache maintenance operation is always forwarded to the 955 // memory below even if the block is found in dirty state. 956 957 // We defer any changes to the state of the block until we 958 // create and mark as in service the mshr for the downstream 959 // packet. 960 961 // Calculate access latency on top of when the packet arrives. This 962 // takes into account the bus delay. 963 lat = calculateTagOnlyLatency(pkt->headerDelay, tag_latency); 964 965 return false; 966 } 967 968 if (pkt->isEviction()) { 969 // We check for presence of block in above caches before issuing 970 // Writeback or CleanEvict to write buffer. Therefore the only 971 // possible cases can be of a CleanEvict packet coming from above 972 // encountering a Writeback generated in this cache peer cache and 973 // waiting in the write buffer. Cases of upper level peer caches 974 // generating CleanEvict and Writeback or simply CleanEvict and 975 // CleanEvict almost simultaneously will be caught by snoops sent out 976 // by crossbar. 977 WriteQueueEntry *wb_entry = writeBuffer.findMatch(pkt->getAddr(), 978 pkt->isSecure()); 979 if (wb_entry) { 980 assert(wb_entry->getNumTargets() == 1); 981 PacketPtr wbPkt = wb_entry->getTarget()->pkt; 982 assert(wbPkt->isWriteback()); 983 984 if (pkt->isCleanEviction()) { 985 // The CleanEvict and WritebackClean snoops into other 986 // peer caches of the same level while traversing the 987 // crossbar. If a copy of the block is found, the 988 // packet is deleted in the crossbar. Hence, none of 989 // the other upper level caches connected to this 990 // cache have the block, so we can clear the 991 // BLOCK_CACHED flag in the Writeback if set and 992 // discard the CleanEvict by returning true. 993 wbPkt->clearBlockCached(); 994 995 // A clean evict does not need to access the data array 996 lat = calculateTagOnlyLatency(pkt->headerDelay, tag_latency); 997 998 return true; 999 } else { 1000 assert(pkt->cmd == MemCmd::WritebackDirty); 1001 // Dirty writeback from above trumps our clean 1002 // writeback... discard here 1003 // Note: markInService will remove entry from writeback buffer. 1004 markInService(wb_entry); 1005 delete wbPkt; 1006 } 1007 } 1008 } 1009 1010 // Writeback handling is special case. We can write the block into 1011 // the cache without having a writeable copy (or any copy at all). 1012 if (pkt->isWriteback()) { 1013 assert(blkSize == pkt->getSize()); 1014 1015 // we could get a clean writeback while we are having 1016 // outstanding accesses to a block, do the simple thing for 1017 // now and drop the clean writeback so that we do not upset 1018 // any ordering/decisions about ownership already taken 1019 if (pkt->cmd == MemCmd::WritebackClean && 1020 mshrQueue.findMatch(pkt->getAddr(), pkt->isSecure())) { 1021 DPRINTF(Cache, "Clean writeback %#llx to block with MSHR, " 1022 "dropping\n", pkt->getAddr()); 1023 1024 // A writeback searches for the block, then writes the data. 1025 // As the writeback is being dropped, the data is not touched, 1026 // and we just had to wait for the time to find a match in the 1027 // MSHR. As of now assume a mshr queue search takes as long as 1028 // a tag lookup for simplicity. 1029 lat = calculateTagOnlyLatency(pkt->headerDelay, tag_latency); 1030 1031 return true; 1032 } 1033 1034 if (!blk) { 1035 // need to do a replacement 1036 blk = allocateBlock(pkt, writebacks); 1037 if (!blk) { 1038 // no replaceable block available: give up, fwd to next level. 1039 incMissCount(pkt); 1040 1041 // A writeback searches for the block, then writes the data. 1042 // As the block could not be found, it was a tag-only access. 1043 lat = calculateTagOnlyLatency(pkt->headerDelay, tag_latency); 1044 1045 return false; 1046 } 1047 1048 blk->status |= BlkReadable; 1049 } 1050 // only mark the block dirty if we got a writeback command, 1051 // and leave it as is for a clean writeback 1052 if (pkt->cmd == MemCmd::WritebackDirty) { 1053 // TODO: the coherent cache can assert(!blk->isDirty()); 1054 blk->status |= BlkDirty; 1055 } 1056 // if the packet does not have sharers, it is passing 1057 // writable, and we got the writeback in Modified or Exclusive 1058 // state, if not we are in the Owned or Shared state 1059 if (!pkt->hasSharers()) { 1060 blk->status |= BlkWritable; 1061 } 1062 // nothing else to do; writeback doesn't expect response 1063 assert(!pkt->needsResponse()); 1064 pkt->writeDataToBlock(blk->data, blkSize); 1065 DPRINTF(Cache, "%s new state is %s\n", __func__, blk->print()); 1066 incHitCount(pkt); 1067 1068 // When the packet metadata arrives, the tag lookup will be done while 1069 // the payload is arriving. Then the block will be ready to access as 1070 // soon as the fill is done 1071 blk->setWhenReady(clockEdge(fillLatency) + pkt->headerDelay + 1072 std::max(cyclesToTicks(tag_latency), (uint64_t)pkt->payloadDelay)); 1073 1074 // A writeback searches for the block, then writes the data 1075 lat = calculateAccessLatency(blk, pkt->headerDelay, tag_latency); 1076 1077 return true; 1078 } else if (pkt->cmd == MemCmd::CleanEvict) { 1079 // A CleanEvict does not need to access the data array 1080 lat = calculateTagOnlyLatency(pkt->headerDelay, tag_latency); 1081 1082 if (blk) { 1083 // Found the block in the tags, need to stop CleanEvict from 1084 // propagating further down the hierarchy. Returning true will 1085 // treat the CleanEvict like a satisfied write request and delete 1086 // it. 1087 return true; 1088 } 1089 // We didn't find the block here, propagate the CleanEvict further 1090 // down the memory hierarchy. Returning false will treat the CleanEvict 1091 // like a Writeback which could not find a replaceable block so has to 1092 // go to next level. 1093 return false; 1094 } else if (pkt->cmd == MemCmd::WriteClean) { 1095 // WriteClean handling is a special case. We can allocate a 1096 // block directly if it doesn't exist and we can update the 1097 // block immediately. The WriteClean transfers the ownership 1098 // of the block as well. 1099 assert(blkSize == pkt->getSize()); 1100 1101 if (!blk) { 1102 if (pkt->writeThrough()) { 1103 // A writeback searches for the block, then writes the data. 1104 // As the block could not be found, it was a tag-only access. 1105 lat = calculateTagOnlyLatency(pkt->headerDelay, tag_latency); 1106 1107 // if this is a write through packet, we don't try to 1108 // allocate if the block is not present 1109 return false; 1110 } else { 1111 // a writeback that misses needs to allocate a new block 1112 blk = allocateBlock(pkt, writebacks); 1113 if (!blk) { 1114 // no replaceable block available: give up, fwd to 1115 // next level. 1116 incMissCount(pkt); 1117 1118 // A writeback searches for the block, then writes the 1119 // data. As the block could not be found, it was a tag-only 1120 // access. 1121 lat = calculateTagOnlyLatency(pkt->headerDelay, 1122 tag_latency); 1123 1124 return false; 1125 } 1126 1127 blk->status |= BlkReadable; 1128 } 1129 } 1130 1131 // at this point either this is a writeback or a write-through 1132 // write clean operation and the block is already in this 1133 // cache, we need to update the data and the block flags 1134 assert(blk); 1135 // TODO: the coherent cache can assert(!blk->isDirty()); 1136 if (!pkt->writeThrough()) { 1137 blk->status |= BlkDirty; 1138 } 1139 // nothing else to do; writeback doesn't expect response 1140 assert(!pkt->needsResponse()); 1141 pkt->writeDataToBlock(blk->data, blkSize); 1142 DPRINTF(Cache, "%s new state is %s\n", __func__, blk->print()); 1143 1144 incHitCount(pkt); 1145 1146 // When the packet metadata arrives, the tag lookup will be done while 1147 // the payload is arriving. Then the block will be ready to access as 1148 // soon as the fill is done 1149 blk->setWhenReady(clockEdge(fillLatency) + pkt->headerDelay + 1150 std::max(cyclesToTicks(tag_latency), (uint64_t)pkt->payloadDelay)); 1151 1152 // A writeback searches for the block, then writes the data 1153 lat = calculateAccessLatency(blk, pkt->headerDelay, tag_latency); 1154 1155 // if this a write-through packet it will be sent to cache 1156 // below 1157 return !pkt->writeThrough(); 1158 } else if (blk && (pkt->needsWritable() ? blk->isWritable() : 1159 blk->isReadable())) { 1160 // OK to satisfy access 1161 incHitCount(pkt); 1162 satisfyRequest(pkt, blk); 1163 maintainClusivity(pkt->fromCache(), blk); 1164 1165 // Calculate access latency based on the need to access the data array 1166 if (pkt->isRead() || pkt->isWrite()) { 1167 lat = calculateAccessLatency(blk, pkt->headerDelay, tag_latency); 1168 } else { 1169 lat = calculateTagOnlyLatency(pkt->headerDelay, tag_latency); 1170 } 1171 1172 return true; 1173 } 1174 1175 // Can't satisfy access normally... either no block (blk == nullptr) 1176 // or have block but need writable 1177 1178 incMissCount(pkt); 1179 1180 lat = calculateAccessLatency(blk, pkt->headerDelay, tag_latency); 1181 1182 if (!blk && pkt->isLLSC() && pkt->isWrite()) { 1183 // complete miss on store conditional... just give up now 1184 pkt->req->setExtraData(0); 1185 return true; 1186 } 1187 1188 return false; 1189} 1190 1191void 1192BaseCache::maintainClusivity(bool from_cache, CacheBlk *blk) 1193{ 1194 if (from_cache && blk && blk->isValid() && !blk->isDirty() && 1195 clusivity == Enums::mostly_excl) { 1196 // if we have responded to a cache, and our block is still 1197 // valid, but not dirty, and this cache is mostly exclusive 1198 // with respect to the cache above, drop the block 1199 invalidateBlock(blk); 1200 } 1201} 1202 1203CacheBlk* 1204BaseCache::handleFill(PacketPtr pkt, CacheBlk *blk, PacketList &writebacks, 1205 bool allocate) 1206{ 1207 assert(pkt->isResponse()); 1208 Addr addr = pkt->getAddr(); 1209 bool is_secure = pkt->isSecure(); 1210#if TRACING_ON 1211 CacheBlk::State old_state = blk ? blk->status : 0; 1212#endif 1213 1214 // When handling a fill, we should have no writes to this line. 1215 assert(addr == pkt->getBlockAddr(blkSize)); 1216 assert(!writeBuffer.findMatch(addr, is_secure)); 1217 1218 if (!blk) { 1219 // better have read new data... 1220 assert(pkt->hasData() || pkt->cmd == MemCmd::InvalidateResp); 1221 1222 // need to do a replacement if allocating, otherwise we stick 1223 // with the temporary storage 1224 blk = allocate ? allocateBlock(pkt, writebacks) : nullptr; 1225 1226 if (!blk) { 1227 // No replaceable block or a mostly exclusive 1228 // cache... just use temporary storage to complete the 1229 // current request and then get rid of it 1230 blk = tempBlock; 1231 tempBlock->insert(addr, is_secure); 1232 DPRINTF(Cache, "using temp block for %#llx (%s)\n", addr, 1233 is_secure ? "s" : "ns"); 1234 } 1235 } else { 1236 // existing block... probably an upgrade 1237 // don't clear block status... if block is already dirty we 1238 // don't want to lose that 1239 } 1240 1241 // Block is guaranteed to be valid at this point 1242 assert(blk->isValid()); 1243 assert(blk->isSecure() == is_secure); 1244 assert(regenerateBlkAddr(blk) == addr); 1245 1246 blk->status |= BlkReadable; 1247 1248 // sanity check for whole-line writes, which should always be 1249 // marked as writable as part of the fill, and then later marked 1250 // dirty as part of satisfyRequest 1251 if (pkt->cmd == MemCmd::InvalidateResp) { 1252 assert(!pkt->hasSharers()); 1253 } 1254 1255 // here we deal with setting the appropriate state of the line, 1256 // and we start by looking at the hasSharers flag, and ignore the 1257 // cacheResponding flag (normally signalling dirty data) if the 1258 // packet has sharers, thus the line is never allocated as Owned 1259 // (dirty but not writable), and always ends up being either 1260 // Shared, Exclusive or Modified, see Packet::setCacheResponding 1261 // for more details 1262 if (!pkt->hasSharers()) { 1263 // we could get a writable line from memory (rather than a 1264 // cache) even in a read-only cache, note that we set this bit 1265 // even for a read-only cache, possibly revisit this decision 1266 blk->status |= BlkWritable; 1267 1268 // check if we got this via cache-to-cache transfer (i.e., from a 1269 // cache that had the block in Modified or Owned state) 1270 if (pkt->cacheResponding()) { 1271 // we got the block in Modified state, and invalidated the 1272 // owners copy 1273 blk->status |= BlkDirty; 1274 1275 chatty_assert(!isReadOnly, "Should never see dirty snoop response " 1276 "in read-only cache %s\n", name()); 1277 } 1278 } 1279 1280 DPRINTF(Cache, "Block addr %#llx (%s) moving from state %x to %s\n", 1281 addr, is_secure ? "s" : "ns", old_state, blk->print()); 1282 1283 // if we got new data, copy it in (checking for a read response 1284 // and a response that has data is the same in the end) 1285 if (pkt->isRead()) { 1286 // sanity checks 1287 assert(pkt->hasData()); 1288 assert(pkt->getSize() == blkSize); 1289 1290 pkt->writeDataToBlock(blk->data, blkSize); 1291 } 1292 // The block will be ready when the payload arrives and the fill is done 1293 blk->setWhenReady(clockEdge(fillLatency) + pkt->headerDelay + 1294 pkt->payloadDelay); 1295 1296 return blk; 1297} 1298 1299CacheBlk* 1300BaseCache::allocateBlock(const PacketPtr pkt, PacketList &writebacks) 1301{ 1302 // Get address 1303 const Addr addr = pkt->getAddr(); 1304 1305 // Get secure bit 1306 const bool is_secure = pkt->isSecure(); 1307 1308 // Find replacement victim 1309 std::vector<CacheBlk*> evict_blks; 1310 CacheBlk *victim = tags->findVictim(addr, is_secure, evict_blks); 1311 1312 // It is valid to return nullptr if there is no victim 1313 if (!victim) 1314 return nullptr; 1315 1316 // Print victim block's information 1317 DPRINTF(CacheRepl, "Replacement victim: %s\n", victim->print()); 1318 1319 // Check for transient state allocations. If any of the entries listed 1320 // for eviction has a transient state, the allocation fails 1321 for (const auto& blk : evict_blks) { 1322 if (blk->isValid()) { 1323 Addr repl_addr = regenerateBlkAddr(blk); 1324 MSHR *repl_mshr = mshrQueue.findMatch(repl_addr, blk->isSecure()); 1325 if (repl_mshr) { 1326 // must be an outstanding upgrade or clean request 1327 // on a block we're about to replace... 1328 assert((!blk->isWritable() && repl_mshr->needsWritable()) || 1329 repl_mshr->isCleaning()); 1330 1331 // too hard to replace block with transient state 1332 // allocation failed, block not inserted 1333 return nullptr; 1334 } 1335 } 1336 } 1337 1338 // The victim will be replaced by a new entry, so increase the replacement 1339 // counter if a valid block is being replaced 1340 if (victim->isValid()) { 1341 DPRINTF(Cache, "replacement: replacing %#llx (%s) with %#llx " 1342 "(%s): %s\n", regenerateBlkAddr(victim), 1343 victim->isSecure() ? "s" : "ns", 1344 addr, is_secure ? "s" : "ns", 1345 victim->isDirty() ? "writeback" : "clean"); 1346 1347 replacements++; 1348 } 1349 1350 // Evict valid blocks associated to this victim block 1351 for (const auto& blk : evict_blks) { 1352 if (blk->isValid()) { 1353 if (blk->wasPrefetched()) { 1354 unusedPrefetches++; 1355 } 1356 1357 evictBlock(blk, writebacks); 1358 } 1359 } 1360 1361 // Insert new block at victimized entry 1362 tags->insertBlock(addr, is_secure, pkt->req->masterId(), 1363 pkt->req->taskId(), victim); 1364 1365 return victim; 1366} 1367 1368void 1369BaseCache::invalidateBlock(CacheBlk *blk) 1370{ 1371 // If handling a block present in the Tags, let it do its invalidation 1372 // process, which will update stats and invalidate the block itself 1373 if (blk != tempBlock) { 1374 tags->invalidate(blk); 1375 } else { 1376 tempBlock->invalidate(); 1377 } 1378} 1379 1380void 1381BaseCache::evictBlock(CacheBlk *blk, PacketList &writebacks) 1382{ 1383 PacketPtr pkt = evictBlock(blk); 1384 if (pkt) { 1385 writebacks.push_back(pkt); 1386 } 1387} 1388 1389PacketPtr 1390BaseCache::writebackBlk(CacheBlk *blk) 1391{ 1392 chatty_assert(!isReadOnly || writebackClean, 1393 "Writeback from read-only cache"); 1394 assert(blk && blk->isValid() && (blk->isDirty() || writebackClean)); 1395 1396 writebacks[Request::wbMasterId]++; 1397 1398 RequestPtr req = std::make_shared<Request>( 1399 regenerateBlkAddr(blk), blkSize, 0, Request::wbMasterId); 1400 1401 if (blk->isSecure()) 1402 req->setFlags(Request::SECURE); 1403 1404 req->taskId(blk->task_id); 1405 1406 PacketPtr pkt = 1407 new Packet(req, blk->isDirty() ? 1408 MemCmd::WritebackDirty : MemCmd::WritebackClean); 1409 1410 DPRINTF(Cache, "Create Writeback %s writable: %d, dirty: %d\n", 1411 pkt->print(), blk->isWritable(), blk->isDirty()); 1412 1413 if (blk->isWritable()) { 1414 // not asserting shared means we pass the block in modified 1415 // state, mark our own block non-writeable 1416 blk->status &= ~BlkWritable; 1417 } else { 1418 // we are in the Owned state, tell the receiver 1419 pkt->setHasSharers(); 1420 } 1421 1422 // make sure the block is not marked dirty 1423 blk->status &= ~BlkDirty; 1424 1425 pkt->allocate(); 1426 pkt->setDataFromBlock(blk->data, blkSize); 1427 1428 return pkt; 1429} 1430 1431PacketPtr 1432BaseCache::writecleanBlk(CacheBlk *blk, Request::Flags dest, PacketId id) 1433{ 1434 RequestPtr req = std::make_shared<Request>( 1435 regenerateBlkAddr(blk), blkSize, 0, Request::wbMasterId); 1436 1437 if (blk->isSecure()) { 1438 req->setFlags(Request::SECURE); 1439 } 1440 req->taskId(blk->task_id); 1441 1442 PacketPtr pkt = new Packet(req, MemCmd::WriteClean, blkSize, id); 1443 1444 if (dest) { 1445 req->setFlags(dest); 1446 pkt->setWriteThrough(); 1447 } 1448 1449 DPRINTF(Cache, "Create %s writable: %d, dirty: %d\n", pkt->print(), 1450 blk->isWritable(), blk->isDirty()); 1451 1452 if (blk->isWritable()) { 1453 // not asserting shared means we pass the block in modified 1454 // state, mark our own block non-writeable 1455 blk->status &= ~BlkWritable; 1456 } else { 1457 // we are in the Owned state, tell the receiver 1458 pkt->setHasSharers(); 1459 } 1460 1461 // make sure the block is not marked dirty 1462 blk->status &= ~BlkDirty; 1463 1464 pkt->allocate(); 1465 pkt->setDataFromBlock(blk->data, blkSize); 1466 1467 return pkt; 1468} 1469 1470 1471void 1472BaseCache::memWriteback() 1473{ 1474 tags->forEachBlk([this](CacheBlk &blk) { writebackVisitor(blk); }); 1475} 1476 1477void 1478BaseCache::memInvalidate() 1479{ 1480 tags->forEachBlk([this](CacheBlk &blk) { invalidateVisitor(blk); }); 1481} 1482 1483bool 1484BaseCache::isDirty() const 1485{ 1486 return tags->anyBlk([](CacheBlk &blk) { return blk.isDirty(); }); 1487} 1488 1489bool 1490BaseCache::coalesce() const 1491{ 1492 return writeAllocator && writeAllocator->coalesce(); 1493} 1494 1495void 1496BaseCache::writebackVisitor(CacheBlk &blk) 1497{ 1498 if (blk.isDirty()) { 1499 assert(blk.isValid()); 1500 1501 RequestPtr request = std::make_shared<Request>( 1502 regenerateBlkAddr(&blk), blkSize, 0, Request::funcMasterId); 1503 1504 request->taskId(blk.task_id); 1505 if (blk.isSecure()) { 1506 request->setFlags(Request::SECURE); 1507 } 1508 1509 Packet packet(request, MemCmd::WriteReq); 1510 packet.dataStatic(blk.data); 1511 1512 memSidePort.sendFunctional(&packet); 1513 1514 blk.status &= ~BlkDirty; 1515 } 1516} 1517 1518void 1519BaseCache::invalidateVisitor(CacheBlk &blk) 1520{ 1521 if (blk.isDirty()) 1522 warn_once("Invalidating dirty cache lines. " \ 1523 "Expect things to break.\n"); 1524 1525 if (blk.isValid()) { 1526 assert(!blk.isDirty()); 1527 invalidateBlock(&blk); 1528 } 1529} 1530 1531Tick 1532BaseCache::nextQueueReadyTime() const 1533{ 1534 Tick nextReady = std::min(mshrQueue.nextReadyTime(), 1535 writeBuffer.nextReadyTime()); 1536 1537 // Don't signal prefetch ready time if no MSHRs available 1538 // Will signal once enoguh MSHRs are deallocated 1539 if (prefetcher && mshrQueue.canPrefetch()) { 1540 nextReady = std::min(nextReady, 1541 prefetcher->nextPrefetchReadyTime()); 1542 } 1543 1544 return nextReady; 1545} 1546 1547 1548bool 1549BaseCache::sendMSHRQueuePacket(MSHR* mshr) 1550{ 1551 assert(mshr); 1552 1553 // use request from 1st target 1554 PacketPtr tgt_pkt = mshr->getTarget()->pkt; 1555 1556 DPRINTF(Cache, "%s: MSHR %s\n", __func__, tgt_pkt->print()); 1557 1558 // if the cache is in write coalescing mode or (additionally) in 1559 // no allocation mode, and we have a write packet with an MSHR 1560 // that is not a whole-line write (due to incompatible flags etc), 1561 // then reset the write mode 1562 if (writeAllocator && writeAllocator->coalesce() && tgt_pkt->isWrite()) { 1563 if (!mshr->isWholeLineWrite()) { 1564 // if we are currently write coalescing, hold on the 1565 // MSHR as many cycles extra as we need to completely 1566 // write a cache line 1567 if (writeAllocator->delay(mshr->blkAddr)) { 1568 Tick delay = blkSize / tgt_pkt->getSize() * clockPeriod(); 1569 DPRINTF(CacheVerbose, "Delaying pkt %s %llu ticks to allow " 1570 "for write coalescing\n", tgt_pkt->print(), delay); 1571 mshrQueue.delay(mshr, delay); 1572 return false; 1573 } else { 1574 writeAllocator->reset(); 1575 } 1576 } else { 1577 writeAllocator->resetDelay(mshr->blkAddr); 1578 } 1579 } 1580 1581 CacheBlk *blk = tags->findBlock(mshr->blkAddr, mshr->isSecure); 1582 1583 // either a prefetch that is not present upstream, or a normal 1584 // MSHR request, proceed to get the packet to send downstream 1585 PacketPtr pkt = createMissPacket(tgt_pkt, blk, mshr->needsWritable(), 1586 mshr->isWholeLineWrite()); 1587 1588 mshr->isForward = (pkt == nullptr); 1589 1590 if (mshr->isForward) { 1591 // not a cache block request, but a response is expected 1592 // make copy of current packet to forward, keep current 1593 // copy for response handling 1594 pkt = new Packet(tgt_pkt, false, true); 1595 assert(!pkt->isWrite()); 1596 } 1597 1598 // play it safe and append (rather than set) the sender state, 1599 // as forwarded packets may already have existing state 1600 pkt->pushSenderState(mshr); 1601 1602 if (pkt->isClean() && blk && blk->isDirty()) { 1603 // A cache clean opearation is looking for a dirty block. Mark 1604 // the packet so that the destination xbar can determine that 1605 // there will be a follow-up write packet as well. 1606 pkt->setSatisfied(); 1607 } 1608 1609 if (!memSidePort.sendTimingReq(pkt)) { 1610 // we are awaiting a retry, but we 1611 // delete the packet and will be creating a new packet 1612 // when we get the opportunity 1613 delete pkt; 1614 1615 // note that we have now masked any requestBus and 1616 // schedSendEvent (we will wait for a retry before 1617 // doing anything), and this is so even if we do not 1618 // care about this packet and might override it before 1619 // it gets retried 1620 return true; 1621 } else { 1622 // As part of the call to sendTimingReq the packet is 1623 // forwarded to all neighbouring caches (and any caches 1624 // above them) as a snoop. Thus at this point we know if 1625 // any of the neighbouring caches are responding, and if 1626 // so, we know it is dirty, and we can determine if it is 1627 // being passed as Modified, making our MSHR the ordering 1628 // point 1629 bool pending_modified_resp = !pkt->hasSharers() && 1630 pkt->cacheResponding(); 1631 markInService(mshr, pending_modified_resp); 1632 1633 if (pkt->isClean() && blk && blk->isDirty()) { 1634 // A cache clean opearation is looking for a dirty 1635 // block. If a dirty block is encountered a WriteClean 1636 // will update any copies to the path to the memory 1637 // until the point of reference. 1638 DPRINTF(CacheVerbose, "%s: packet %s found block: %s\n", 1639 __func__, pkt->print(), blk->print()); 1640 PacketPtr wb_pkt = writecleanBlk(blk, pkt->req->getDest(), 1641 pkt->id); 1642 PacketList writebacks; 1643 writebacks.push_back(wb_pkt); 1644 doWritebacks(writebacks, 0); 1645 } 1646 1647 return false; 1648 } 1649} 1650 1651bool 1652BaseCache::sendWriteQueuePacket(WriteQueueEntry* wq_entry) 1653{ 1654 assert(wq_entry); 1655 1656 // always a single target for write queue entries 1657 PacketPtr tgt_pkt = wq_entry->getTarget()->pkt; 1658 1659 DPRINTF(Cache, "%s: write %s\n", __func__, tgt_pkt->print()); 1660 1661 // forward as is, both for evictions and uncacheable writes 1662 if (!memSidePort.sendTimingReq(tgt_pkt)) { 1663 // note that we have now masked any requestBus and 1664 // schedSendEvent (we will wait for a retry before 1665 // doing anything), and this is so even if we do not 1666 // care about this packet and might override it before 1667 // it gets retried 1668 return true; 1669 } else { 1670 markInService(wq_entry); 1671 return false; 1672 } 1673} 1674 1675void 1676BaseCache::serialize(CheckpointOut &cp) const 1677{ 1678 bool dirty(isDirty()); 1679 1680 if (dirty) { 1681 warn("*** The cache still contains dirty data. ***\n"); 1682 warn(" Make sure to drain the system using the correct flags.\n"); 1683 warn(" This checkpoint will not restore correctly " \ 1684 "and dirty data in the cache will be lost!\n"); 1685 } 1686 1687 // Since we don't checkpoint the data in the cache, any dirty data 1688 // will be lost when restoring from a checkpoint of a system that 1689 // wasn't drained properly. Flag the checkpoint as invalid if the 1690 // cache contains dirty data. 1691 bool bad_checkpoint(dirty); 1692 SERIALIZE_SCALAR(bad_checkpoint); 1693} 1694 1695void 1696BaseCache::unserialize(CheckpointIn &cp) 1697{ 1698 bool bad_checkpoint; 1699 UNSERIALIZE_SCALAR(bad_checkpoint); 1700 if (bad_checkpoint) { 1701 fatal("Restoring from checkpoints with dirty caches is not " 1702 "supported in the classic memory system. Please remove any " 1703 "caches or drain them properly before taking checkpoints.\n"); 1704 } 1705} 1706 1707void 1708BaseCache::regStats() 1709{ 1710 MemObject::regStats(); 1711 1712 using namespace Stats; 1713 1714 // Hit statistics 1715 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 1716 MemCmd cmd(access_idx); 1717 const string &cstr = cmd.toString(); 1718 1719 hits[access_idx] 1720 .init(system->maxMasters()) 1721 .name(name() + "." + cstr + "_hits") 1722 .desc("number of " + cstr + " hits") 1723 .flags(total | nozero | nonan) 1724 ; 1725 for (int i = 0; i < system->maxMasters(); i++) { 1726 hits[access_idx].subname(i, system->getMasterName(i)); 1727 } 1728 } 1729 1730// These macros make it easier to sum the right subset of commands and 1731// to change the subset of commands that are considered "demand" vs 1732// "non-demand" 1733#define SUM_DEMAND(s) \ 1734 (s[MemCmd::ReadReq] + s[MemCmd::WriteReq] + s[MemCmd::WriteLineReq] + \ 1735 s[MemCmd::ReadExReq] + s[MemCmd::ReadCleanReq] + s[MemCmd::ReadSharedReq]) 1736 1737// should writebacks be included here? prior code was inconsistent... 1738#define SUM_NON_DEMAND(s) \ 1739 (s[MemCmd::SoftPFReq] + s[MemCmd::HardPFReq] + s[MemCmd::SoftPFExReq]) 1740 1741 demandHits 1742 .name(name() + ".demand_hits") 1743 .desc("number of demand (read+write) hits") 1744 .flags(total | nozero | nonan) 1745 ; 1746 demandHits = SUM_DEMAND(hits); 1747 for (int i = 0; i < system->maxMasters(); i++) { 1748 demandHits.subname(i, system->getMasterName(i)); 1749 } 1750 1751 overallHits 1752 .name(name() + ".overall_hits") 1753 .desc("number of overall hits") 1754 .flags(total | nozero | nonan) 1755 ; 1756 overallHits = demandHits + SUM_NON_DEMAND(hits); 1757 for (int i = 0; i < system->maxMasters(); i++) { 1758 overallHits.subname(i, system->getMasterName(i)); 1759 } 1760 1761 // Miss statistics 1762 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 1763 MemCmd cmd(access_idx); 1764 const string &cstr = cmd.toString(); 1765 1766 misses[access_idx] 1767 .init(system->maxMasters()) 1768 .name(name() + "." + cstr + "_misses") 1769 .desc("number of " + cstr + " misses") 1770 .flags(total | nozero | nonan) 1771 ; 1772 for (int i = 0; i < system->maxMasters(); i++) { 1773 misses[access_idx].subname(i, system->getMasterName(i)); 1774 } 1775 } 1776 1777 demandMisses 1778 .name(name() + ".demand_misses") 1779 .desc("number of demand (read+write) misses") 1780 .flags(total | nozero | nonan) 1781 ; 1782 demandMisses = SUM_DEMAND(misses); 1783 for (int i = 0; i < system->maxMasters(); i++) { 1784 demandMisses.subname(i, system->getMasterName(i)); 1785 } 1786 1787 overallMisses 1788 .name(name() + ".overall_misses") 1789 .desc("number of overall misses") 1790 .flags(total | nozero | nonan) 1791 ; 1792 overallMisses = demandMisses + SUM_NON_DEMAND(misses); 1793 for (int i = 0; i < system->maxMasters(); i++) { 1794 overallMisses.subname(i, system->getMasterName(i)); 1795 } 1796 1797 // Miss latency statistics 1798 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 1799 MemCmd cmd(access_idx); 1800 const string &cstr = cmd.toString(); 1801 1802 missLatency[access_idx] 1803 .init(system->maxMasters()) 1804 .name(name() + "." + cstr + "_miss_latency") 1805 .desc("number of " + cstr + " miss cycles") 1806 .flags(total | nozero | nonan) 1807 ; 1808 for (int i = 0; i < system->maxMasters(); i++) { 1809 missLatency[access_idx].subname(i, system->getMasterName(i)); 1810 } 1811 } 1812 1813 demandMissLatency 1814 .name(name() + ".demand_miss_latency") 1815 .desc("number of demand (read+write) miss cycles") 1816 .flags(total | nozero | nonan) 1817 ; 1818 demandMissLatency = SUM_DEMAND(missLatency); 1819 for (int i = 0; i < system->maxMasters(); i++) { 1820 demandMissLatency.subname(i, system->getMasterName(i)); 1821 } 1822 1823 overallMissLatency 1824 .name(name() + ".overall_miss_latency") 1825 .desc("number of overall miss cycles") 1826 .flags(total | nozero | nonan) 1827 ; 1828 overallMissLatency = demandMissLatency + SUM_NON_DEMAND(missLatency); 1829 for (int i = 0; i < system->maxMasters(); i++) { 1830 overallMissLatency.subname(i, system->getMasterName(i)); 1831 } 1832 1833 // access formulas 1834 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 1835 MemCmd cmd(access_idx); 1836 const string &cstr = cmd.toString(); 1837 1838 accesses[access_idx] 1839 .name(name() + "." + cstr + "_accesses") 1840 .desc("number of " + cstr + " accesses(hits+misses)") 1841 .flags(total | nozero | nonan) 1842 ; 1843 accesses[access_idx] = hits[access_idx] + misses[access_idx]; 1844 1845 for (int i = 0; i < system->maxMasters(); i++) { 1846 accesses[access_idx].subname(i, system->getMasterName(i)); 1847 } 1848 } 1849 1850 demandAccesses 1851 .name(name() + ".demand_accesses") 1852 .desc("number of demand (read+write) accesses") 1853 .flags(total | nozero | nonan) 1854 ; 1855 demandAccesses = demandHits + demandMisses; 1856 for (int i = 0; i < system->maxMasters(); i++) { 1857 demandAccesses.subname(i, system->getMasterName(i)); 1858 } 1859 1860 overallAccesses 1861 .name(name() + ".overall_accesses") 1862 .desc("number of overall (read+write) accesses") 1863 .flags(total | nozero | nonan) 1864 ; 1865 overallAccesses = overallHits + overallMisses; 1866 for (int i = 0; i < system->maxMasters(); i++) { 1867 overallAccesses.subname(i, system->getMasterName(i)); 1868 } 1869 1870 // miss rate formulas 1871 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 1872 MemCmd cmd(access_idx); 1873 const string &cstr = cmd.toString(); 1874 1875 missRate[access_idx] 1876 .name(name() + "." + cstr + "_miss_rate") 1877 .desc("miss rate for " + cstr + " accesses") 1878 .flags(total | nozero | nonan) 1879 ; 1880 missRate[access_idx] = misses[access_idx] / accesses[access_idx]; 1881 1882 for (int i = 0; i < system->maxMasters(); i++) { 1883 missRate[access_idx].subname(i, system->getMasterName(i)); 1884 } 1885 } 1886 1887 demandMissRate 1888 .name(name() + ".demand_miss_rate") 1889 .desc("miss rate for demand accesses") 1890 .flags(total | nozero | nonan) 1891 ; 1892 demandMissRate = demandMisses / demandAccesses; 1893 for (int i = 0; i < system->maxMasters(); i++) { 1894 demandMissRate.subname(i, system->getMasterName(i)); 1895 } 1896 1897 overallMissRate 1898 .name(name() + ".overall_miss_rate") 1899 .desc("miss rate for overall accesses") 1900 .flags(total | nozero | nonan) 1901 ; 1902 overallMissRate = overallMisses / overallAccesses; 1903 for (int i = 0; i < system->maxMasters(); i++) { 1904 overallMissRate.subname(i, system->getMasterName(i)); 1905 } 1906 1907 // miss latency formulas 1908 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 1909 MemCmd cmd(access_idx); 1910 const string &cstr = cmd.toString(); 1911 1912 avgMissLatency[access_idx] 1913 .name(name() + "." + cstr + "_avg_miss_latency") 1914 .desc("average " + cstr + " miss latency") 1915 .flags(total | nozero | nonan) 1916 ; 1917 avgMissLatency[access_idx] = 1918 missLatency[access_idx] / misses[access_idx]; 1919 1920 for (int i = 0; i < system->maxMasters(); i++) { 1921 avgMissLatency[access_idx].subname(i, system->getMasterName(i)); 1922 } 1923 } 1924 1925 demandAvgMissLatency 1926 .name(name() + ".demand_avg_miss_latency") 1927 .desc("average overall miss latency") 1928 .flags(total | nozero | nonan) 1929 ; 1930 demandAvgMissLatency = demandMissLatency / demandMisses; 1931 for (int i = 0; i < system->maxMasters(); i++) { 1932 demandAvgMissLatency.subname(i, system->getMasterName(i)); 1933 } 1934 1935 overallAvgMissLatency 1936 .name(name() + ".overall_avg_miss_latency") 1937 .desc("average overall miss latency") 1938 .flags(total | nozero | nonan) 1939 ; 1940 overallAvgMissLatency = overallMissLatency / overallMisses; 1941 for (int i = 0; i < system->maxMasters(); i++) { 1942 overallAvgMissLatency.subname(i, system->getMasterName(i)); 1943 } 1944 1945 blocked_cycles.init(NUM_BLOCKED_CAUSES); 1946 blocked_cycles 1947 .name(name() + ".blocked_cycles") 1948 .desc("number of cycles access was blocked") 1949 .subname(Blocked_NoMSHRs, "no_mshrs") 1950 .subname(Blocked_NoTargets, "no_targets") 1951 ; 1952 1953 1954 blocked_causes.init(NUM_BLOCKED_CAUSES); 1955 blocked_causes 1956 .name(name() + ".blocked") 1957 .desc("number of cycles access was blocked") 1958 .subname(Blocked_NoMSHRs, "no_mshrs") 1959 .subname(Blocked_NoTargets, "no_targets") 1960 ; 1961 1962 avg_blocked 1963 .name(name() + ".avg_blocked_cycles") 1964 .desc("average number of cycles each access was blocked") 1965 .subname(Blocked_NoMSHRs, "no_mshrs") 1966 .subname(Blocked_NoTargets, "no_targets") 1967 ; 1968 1969 avg_blocked = blocked_cycles / blocked_causes; 1970 1971 unusedPrefetches 1972 .name(name() + ".unused_prefetches") 1973 .desc("number of HardPF blocks evicted w/o reference") 1974 .flags(nozero) 1975 ; 1976 1977 writebacks 1978 .init(system->maxMasters()) 1979 .name(name() + ".writebacks") 1980 .desc("number of writebacks") 1981 .flags(total | nozero | nonan) 1982 ; 1983 for (int i = 0; i < system->maxMasters(); i++) { 1984 writebacks.subname(i, system->getMasterName(i)); 1985 } 1986 1987 // MSHR statistics 1988 // MSHR hit statistics 1989 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 1990 MemCmd cmd(access_idx); 1991 const string &cstr = cmd.toString(); 1992 1993 mshr_hits[access_idx] 1994 .init(system->maxMasters()) 1995 .name(name() + "." + cstr + "_mshr_hits") 1996 .desc("number of " + cstr + " MSHR hits") 1997 .flags(total | nozero | nonan) 1998 ; 1999 for (int i = 0; i < system->maxMasters(); i++) { 2000 mshr_hits[access_idx].subname(i, system->getMasterName(i)); 2001 } 2002 } 2003 2004 demandMshrHits 2005 .name(name() + ".demand_mshr_hits") 2006 .desc("number of demand (read+write) MSHR hits") 2007 .flags(total | nozero | nonan) 2008 ; 2009 demandMshrHits = SUM_DEMAND(mshr_hits); 2010 for (int i = 0; i < system->maxMasters(); i++) { 2011 demandMshrHits.subname(i, system->getMasterName(i)); 2012 } 2013 2014 overallMshrHits 2015 .name(name() + ".overall_mshr_hits") 2016 .desc("number of overall MSHR hits") 2017 .flags(total | nozero | nonan) 2018 ; 2019 overallMshrHits = demandMshrHits + SUM_NON_DEMAND(mshr_hits); 2020 for (int i = 0; i < system->maxMasters(); i++) { 2021 overallMshrHits.subname(i, system->getMasterName(i)); 2022 } 2023 2024 // MSHR miss statistics 2025 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 2026 MemCmd cmd(access_idx); 2027 const string &cstr = cmd.toString(); 2028 2029 mshr_misses[access_idx] 2030 .init(system->maxMasters()) 2031 .name(name() + "." + cstr + "_mshr_misses") 2032 .desc("number of " + cstr + " MSHR misses") 2033 .flags(total | nozero | nonan) 2034 ; 2035 for (int i = 0; i < system->maxMasters(); i++) { 2036 mshr_misses[access_idx].subname(i, system->getMasterName(i)); 2037 } 2038 } 2039 2040 demandMshrMisses 2041 .name(name() + ".demand_mshr_misses") 2042 .desc("number of demand (read+write) MSHR misses") 2043 .flags(total | nozero | nonan) 2044 ; 2045 demandMshrMisses = SUM_DEMAND(mshr_misses); 2046 for (int i = 0; i < system->maxMasters(); i++) { 2047 demandMshrMisses.subname(i, system->getMasterName(i)); 2048 } 2049 2050 overallMshrMisses 2051 .name(name() + ".overall_mshr_misses") 2052 .desc("number of overall MSHR misses") 2053 .flags(total | nozero | nonan) 2054 ; 2055 overallMshrMisses = demandMshrMisses + SUM_NON_DEMAND(mshr_misses); 2056 for (int i = 0; i < system->maxMasters(); i++) { 2057 overallMshrMisses.subname(i, system->getMasterName(i)); 2058 } 2059 2060 // MSHR miss latency statistics 2061 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 2062 MemCmd cmd(access_idx); 2063 const string &cstr = cmd.toString(); 2064 2065 mshr_miss_latency[access_idx] 2066 .init(system->maxMasters()) 2067 .name(name() + "." + cstr + "_mshr_miss_latency") 2068 .desc("number of " + cstr + " MSHR miss cycles") 2069 .flags(total | nozero | nonan) 2070 ; 2071 for (int i = 0; i < system->maxMasters(); i++) { 2072 mshr_miss_latency[access_idx].subname(i, system->getMasterName(i)); 2073 } 2074 } 2075 2076 demandMshrMissLatency 2077 .name(name() + ".demand_mshr_miss_latency") 2078 .desc("number of demand (read+write) MSHR miss cycles") 2079 .flags(total | nozero | nonan) 2080 ; 2081 demandMshrMissLatency = SUM_DEMAND(mshr_miss_latency); 2082 for (int i = 0; i < system->maxMasters(); i++) { 2083 demandMshrMissLatency.subname(i, system->getMasterName(i)); 2084 } 2085 2086 overallMshrMissLatency 2087 .name(name() + ".overall_mshr_miss_latency") 2088 .desc("number of overall MSHR miss cycles") 2089 .flags(total | nozero | nonan) 2090 ; 2091 overallMshrMissLatency = 2092 demandMshrMissLatency + SUM_NON_DEMAND(mshr_miss_latency); 2093 for (int i = 0; i < system->maxMasters(); i++) { 2094 overallMshrMissLatency.subname(i, system->getMasterName(i)); 2095 } 2096 2097 // MSHR uncacheable statistics 2098 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 2099 MemCmd cmd(access_idx); 2100 const string &cstr = cmd.toString(); 2101 2102 mshr_uncacheable[access_idx] 2103 .init(system->maxMasters()) 2104 .name(name() + "." + cstr + "_mshr_uncacheable") 2105 .desc("number of " + cstr + " MSHR uncacheable") 2106 .flags(total | nozero | nonan) 2107 ; 2108 for (int i = 0; i < system->maxMasters(); i++) { 2109 mshr_uncacheable[access_idx].subname(i, system->getMasterName(i)); 2110 } 2111 } 2112 2113 overallMshrUncacheable 2114 .name(name() + ".overall_mshr_uncacheable_misses") 2115 .desc("number of overall MSHR uncacheable misses") 2116 .flags(total | nozero | nonan) 2117 ; 2118 overallMshrUncacheable = 2119 SUM_DEMAND(mshr_uncacheable) + SUM_NON_DEMAND(mshr_uncacheable); 2120 for (int i = 0; i < system->maxMasters(); i++) { 2121 overallMshrUncacheable.subname(i, system->getMasterName(i)); 2122 } 2123 2124 // MSHR miss latency statistics 2125 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 2126 MemCmd cmd(access_idx); 2127 const string &cstr = cmd.toString(); 2128 2129 mshr_uncacheable_lat[access_idx] 2130 .init(system->maxMasters()) 2131 .name(name() + "." + cstr + "_mshr_uncacheable_latency") 2132 .desc("number of " + cstr + " MSHR uncacheable cycles") 2133 .flags(total | nozero | nonan) 2134 ; 2135 for (int i = 0; i < system->maxMasters(); i++) { 2136 mshr_uncacheable_lat[access_idx].subname( 2137 i, system->getMasterName(i)); 2138 } 2139 } 2140 2141 overallMshrUncacheableLatency 2142 .name(name() + ".overall_mshr_uncacheable_latency") 2143 .desc("number of overall MSHR uncacheable cycles") 2144 .flags(total | nozero | nonan) 2145 ; 2146 overallMshrUncacheableLatency = 2147 SUM_DEMAND(mshr_uncacheable_lat) + 2148 SUM_NON_DEMAND(mshr_uncacheable_lat); 2149 for (int i = 0; i < system->maxMasters(); i++) { 2150 overallMshrUncacheableLatency.subname(i, system->getMasterName(i)); 2151 } 2152 2153#if 0 2154 // MSHR access formulas 2155 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 2156 MemCmd cmd(access_idx); 2157 const string &cstr = cmd.toString(); 2158 2159 mshrAccesses[access_idx] 2160 .name(name() + "." + cstr + "_mshr_accesses") 2161 .desc("number of " + cstr + " mshr accesses(hits+misses)") 2162 .flags(total | nozero | nonan) 2163 ; 2164 mshrAccesses[access_idx] = 2165 mshr_hits[access_idx] + mshr_misses[access_idx] 2166 + mshr_uncacheable[access_idx]; 2167 } 2168 2169 demandMshrAccesses 2170 .name(name() + ".demand_mshr_accesses") 2171 .desc("number of demand (read+write) mshr accesses") 2172 .flags(total | nozero | nonan) 2173 ; 2174 demandMshrAccesses = demandMshrHits + demandMshrMisses; 2175 2176 overallMshrAccesses 2177 .name(name() + ".overall_mshr_accesses") 2178 .desc("number of overall (read+write) mshr accesses") 2179 .flags(total | nozero | nonan) 2180 ; 2181 overallMshrAccesses = overallMshrHits + overallMshrMisses 2182 + overallMshrUncacheable; 2183#endif 2184 2185 // MSHR miss rate formulas 2186 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 2187 MemCmd cmd(access_idx); 2188 const string &cstr = cmd.toString(); 2189 2190 mshrMissRate[access_idx] 2191 .name(name() + "." + cstr + "_mshr_miss_rate") 2192 .desc("mshr miss rate for " + cstr + " accesses") 2193 .flags(total | nozero | nonan) 2194 ; 2195 mshrMissRate[access_idx] = 2196 mshr_misses[access_idx] / accesses[access_idx]; 2197 2198 for (int i = 0; i < system->maxMasters(); i++) { 2199 mshrMissRate[access_idx].subname(i, system->getMasterName(i)); 2200 } 2201 } 2202 2203 demandMshrMissRate 2204 .name(name() + ".demand_mshr_miss_rate") 2205 .desc("mshr miss rate for demand accesses") 2206 .flags(total | nozero | nonan) 2207 ; 2208 demandMshrMissRate = demandMshrMisses / demandAccesses; 2209 for (int i = 0; i < system->maxMasters(); i++) { 2210 demandMshrMissRate.subname(i, system->getMasterName(i)); 2211 } 2212 2213 overallMshrMissRate 2214 .name(name() + ".overall_mshr_miss_rate") 2215 .desc("mshr miss rate for overall accesses") 2216 .flags(total | nozero | nonan) 2217 ; 2218 overallMshrMissRate = overallMshrMisses / overallAccesses; 2219 for (int i = 0; i < system->maxMasters(); i++) { 2220 overallMshrMissRate.subname(i, system->getMasterName(i)); 2221 } 2222 2223 // mshrMiss latency formulas 2224 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 2225 MemCmd cmd(access_idx); 2226 const string &cstr = cmd.toString(); 2227 2228 avgMshrMissLatency[access_idx] 2229 .name(name() + "." + cstr + "_avg_mshr_miss_latency") 2230 .desc("average " + cstr + " mshr miss latency") 2231 .flags(total | nozero | nonan) 2232 ; 2233 avgMshrMissLatency[access_idx] = 2234 mshr_miss_latency[access_idx] / mshr_misses[access_idx]; 2235 2236 for (int i = 0; i < system->maxMasters(); i++) { 2237 avgMshrMissLatency[access_idx].subname( 2238 i, system->getMasterName(i)); 2239 } 2240 } 2241 2242 demandAvgMshrMissLatency 2243 .name(name() + ".demand_avg_mshr_miss_latency") 2244 .desc("average overall mshr miss latency") 2245 .flags(total | nozero | nonan) 2246 ; 2247 demandAvgMshrMissLatency = demandMshrMissLatency / demandMshrMisses; 2248 for (int i = 0; i < system->maxMasters(); i++) { 2249 demandAvgMshrMissLatency.subname(i, system->getMasterName(i)); 2250 } 2251 2252 overallAvgMshrMissLatency 2253 .name(name() + ".overall_avg_mshr_miss_latency") 2254 .desc("average overall mshr miss latency") 2255 .flags(total | nozero | nonan) 2256 ; 2257 overallAvgMshrMissLatency = overallMshrMissLatency / overallMshrMisses; 2258 for (int i = 0; i < system->maxMasters(); i++) { 2259 overallAvgMshrMissLatency.subname(i, system->getMasterName(i)); 2260 } 2261 2262 // mshrUncacheable latency formulas 2263 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 2264 MemCmd cmd(access_idx); 2265 const string &cstr = cmd.toString(); 2266 2267 avgMshrUncacheableLatency[access_idx] 2268 .name(name() + "." + cstr + "_avg_mshr_uncacheable_latency") 2269 .desc("average " + cstr + " mshr uncacheable latency") 2270 .flags(total | nozero | nonan) 2271 ; 2272 avgMshrUncacheableLatency[access_idx] = 2273 mshr_uncacheable_lat[access_idx] / mshr_uncacheable[access_idx]; 2274 2275 for (int i = 0; i < system->maxMasters(); i++) { 2276 avgMshrUncacheableLatency[access_idx].subname( 2277 i, system->getMasterName(i)); 2278 } 2279 } 2280 2281 overallAvgMshrUncacheableLatency 2282 .name(name() + ".overall_avg_mshr_uncacheable_latency") 2283 .desc("average overall mshr uncacheable latency") 2284 .flags(total | nozero | nonan) 2285 ; 2286 overallAvgMshrUncacheableLatency = 2287 overallMshrUncacheableLatency / overallMshrUncacheable; 2288 for (int i = 0; i < system->maxMasters(); i++) { 2289 overallAvgMshrUncacheableLatency.subname(i, system->getMasterName(i)); 2290 } 2291 2292 replacements 2293 .name(name() + ".replacements") 2294 .desc("number of replacements") 2295 ; 2296} 2297 2298void 2299BaseCache::regProbePoints() 2300{ 2301 ppHit = new ProbePointArg<PacketPtr>(this->getProbeManager(), "Hit"); 2302 ppMiss = new ProbePointArg<PacketPtr>(this->getProbeManager(), "Miss"); 2303 ppFill = new ProbePointArg<PacketPtr>(this->getProbeManager(), "Fill"); 2304} 2305 2306/////////////// 2307// 2308// CpuSidePort 2309// 2310/////////////// 2311bool 2312BaseCache::CpuSidePort::recvTimingSnoopResp(PacketPtr pkt) 2313{ 2314 // Snoops shouldn't happen when bypassing caches 2315 assert(!cache->system->bypassCaches()); 2316 2317 assert(pkt->isResponse()); 2318 2319 // Express snoop responses from master to slave, e.g., from L1 to L2 2320 cache->recvTimingSnoopResp(pkt); 2321 return true; 2322} 2323 2324 2325bool 2326BaseCache::CpuSidePort::tryTiming(PacketPtr pkt) 2327{ 2328 if (cache->system->bypassCaches() || pkt->isExpressSnoop()) { 2329 // always let express snoop packets through even if blocked 2330 return true; 2331 } else if (blocked || mustSendRetry) { 2332 // either already committed to send a retry, or blocked 2333 mustSendRetry = true; 2334 return false; 2335 } 2336 mustSendRetry = false; 2337 return true; 2338} 2339 2340bool 2341BaseCache::CpuSidePort::recvTimingReq(PacketPtr pkt) 2342{ 2343 assert(pkt->isRequest()); 2344 2345 if (cache->system->bypassCaches()) { 2346 // Just forward the packet if caches are disabled. 2347 // @todo This should really enqueue the packet rather 2348 bool M5_VAR_USED success = cache->memSidePort.sendTimingReq(pkt); 2349 assert(success); 2350 return true; 2351 } else if (tryTiming(pkt)) { 2352 cache->recvTimingReq(pkt); 2353 return true; 2354 } 2355 return false; 2356} 2357 2358Tick 2359BaseCache::CpuSidePort::recvAtomic(PacketPtr pkt) 2360{ 2361 if (cache->system->bypassCaches()) { 2362 // Forward the request if the system is in cache bypass mode. 2363 return cache->memSidePort.sendAtomic(pkt); 2364 } else { 2365 return cache->recvAtomic(pkt); 2366 } 2367} 2368 2369void 2370BaseCache::CpuSidePort::recvFunctional(PacketPtr pkt) 2371{ 2372 if (cache->system->bypassCaches()) { 2373 // The cache should be flushed if we are in cache bypass mode, 2374 // so we don't need to check if we need to update anything. 2375 cache->memSidePort.sendFunctional(pkt); 2376 return; 2377 } 2378 2379 // functional request 2380 cache->functionalAccess(pkt, true); 2381} 2382 2383AddrRangeList 2384BaseCache::CpuSidePort::getAddrRanges() const 2385{ 2386 return cache->getAddrRanges(); 2387} 2388 2389 2390BaseCache:: 2391CpuSidePort::CpuSidePort(const std::string &_name, BaseCache *_cache, 2392 const std::string &_label) 2393 : CacheSlavePort(_name, _cache, _label), cache(_cache) 2394{ 2395} 2396 2397/////////////// 2398// 2399// MemSidePort 2400// 2401/////////////// 2402bool 2403BaseCache::MemSidePort::recvTimingResp(PacketPtr pkt) 2404{ 2405 cache->recvTimingResp(pkt); 2406 return true; 2407} 2408 2409// Express snooping requests to memside port 2410void 2411BaseCache::MemSidePort::recvTimingSnoopReq(PacketPtr pkt) 2412{ 2413 // Snoops shouldn't happen when bypassing caches 2414 assert(!cache->system->bypassCaches()); 2415 2416 // handle snooping requests 2417 cache->recvTimingSnoopReq(pkt); 2418} 2419 2420Tick 2421BaseCache::MemSidePort::recvAtomicSnoop(PacketPtr pkt) 2422{ 2423 // Snoops shouldn't happen when bypassing caches 2424 assert(!cache->system->bypassCaches()); 2425 2426 return cache->recvAtomicSnoop(pkt); 2427} 2428 2429void 2430BaseCache::MemSidePort::recvFunctionalSnoop(PacketPtr pkt) 2431{ 2432 // Snoops shouldn't happen when bypassing caches 2433 assert(!cache->system->bypassCaches()); 2434 2435 // functional snoop (note that in contrast to atomic we don't have 2436 // a specific functionalSnoop method, as they have the same 2437 // behaviour regardless) 2438 cache->functionalAccess(pkt, false); 2439} 2440 2441void 2442BaseCache::CacheReqPacketQueue::sendDeferredPacket() 2443{ 2444 // sanity check 2445 assert(!waitingOnRetry); 2446 2447 // there should never be any deferred request packets in the 2448 // queue, instead we resly on the cache to provide the packets 2449 // from the MSHR queue or write queue 2450 assert(deferredPacketReadyTime() == MaxTick); 2451 2452 // check for request packets (requests & writebacks) 2453 QueueEntry* entry = cache.getNextQueueEntry(); 2454 2455 if (!entry) { 2456 // can happen if e.g. we attempt a writeback and fail, but 2457 // before the retry, the writeback is eliminated because 2458 // we snoop another cache's ReadEx. 2459 } else { 2460 // let our snoop responses go first if there are responses to 2461 // the same addresses 2462 if (checkConflictingSnoop(entry->blkAddr)) { 2463 return; 2464 } 2465 waitingOnRetry = entry->sendPacket(cache); 2466 } 2467 2468 // if we succeeded and are not waiting for a retry, schedule the 2469 // next send considering when the next queue is ready, note that 2470 // snoop responses have their own packet queue and thus schedule 2471 // their own events 2472 if (!waitingOnRetry) { 2473 schedSendEvent(cache.nextQueueReadyTime()); 2474 } 2475} 2476 2477BaseCache::MemSidePort::MemSidePort(const std::string &_name, 2478 BaseCache *_cache, 2479 const std::string &_label) 2480 : CacheMasterPort(_name, _cache, _reqQueue, _snoopRespQueue), 2481 _reqQueue(*_cache, *this, _snoopRespQueue, _label), 2482 _snoopRespQueue(*_cache, *this, true, _label), cache(_cache) 2483{ 2484} 2485 2486void 2487WriteAllocator::updateMode(Addr write_addr, unsigned write_size, 2488 Addr blk_addr) 2489{ 2490 // check if we are continuing where the last write ended 2491 if (nextAddr == write_addr) { 2492 delayCtr[blk_addr] = delayThreshold; 2493 // stop if we have already saturated 2494 if (mode != WriteMode::NO_ALLOCATE) { 2495 byteCount += write_size; 2496 // switch to streaming mode if we have passed the lower 2497 // threshold 2498 if (mode == WriteMode::ALLOCATE && 2499 byteCount > coalesceLimit) { 2500 mode = WriteMode::COALESCE; 2501 DPRINTF(Cache, "Switched to write coalescing\n"); 2502 } else if (mode == WriteMode::COALESCE && 2503 byteCount > noAllocateLimit) { 2504 // and continue and switch to non-allocating mode if we 2505 // pass the upper threshold 2506 mode = WriteMode::NO_ALLOCATE; 2507 DPRINTF(Cache, "Switched to write-no-allocate\n"); 2508 } 2509 } 2510 } else { 2511 // we did not see a write matching the previous one, start 2512 // over again 2513 byteCount = write_size; 2514 mode = WriteMode::ALLOCATE; 2515 resetDelay(blk_addr); 2516 } 2517 nextAddr = write_addr + write_size; 2518} 2519 2520WriteAllocator* 2521WriteAllocatorParams::create() 2522{ 2523 return new WriteAllocator(this); 2524} 2525