Cache: Only invalidate a line in the cache when an uncacheable write is seen.
[gem5.git] / src / mem / cache / cache_impl.hh
1 /*
2 * Copyright (c) 2010-2012 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 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 */
47
48 /**
49 * @file
50 * Cache definitions.
51 */
52
53 #include "base/misc.hh"
54 #include "base/range.hh"
55 #include "base/types.hh"
56 #include "debug/Cache.hh"
57 #include "debug/CachePort.hh"
58 #include "mem/cache/prefetch/base.hh"
59 #include "mem/cache/blk.hh"
60 #include "mem/cache/cache.hh"
61 #include "mem/cache/mshr.hh"
62 #include "sim/sim_exit.hh"
63
64 template<class TagStore>
65 Cache<TagStore>::Cache(const Params *p, TagStore *tags)
66 : BaseCache(p),
67 tags(tags),
68 prefetcher(p->prefetcher),
69 doFastWrites(true),
70 prefetchOnAccess(p->prefetch_on_access)
71 {
72 tempBlock = new BlkType();
73 tempBlock->data = new uint8_t[blkSize];
74
75 cpuSidePort = new CpuSidePort(p->name + "-cpu_side_port", this,
76 "CpuSidePort");
77 memSidePort = new MemSidePort(p->name + "-mem_side_port", this,
78 "MemSidePort");
79
80 tags->setCache(this);
81 if (prefetcher)
82 prefetcher->setCache(this);
83 }
84
85 template<class TagStore>
86 void
87 Cache<TagStore>::regStats()
88 {
89 BaseCache::regStats();
90 tags->regStats(name());
91 }
92
93 template<class TagStore>
94 void
95 Cache<TagStore>::cmpAndSwap(BlkType *blk, PacketPtr pkt)
96 {
97 uint64_t overwrite_val;
98 bool overwrite_mem;
99 uint64_t condition_val64;
100 uint32_t condition_val32;
101
102 int offset = tags->extractBlkOffset(pkt->getAddr());
103 uint8_t *blk_data = blk->data + offset;
104
105 assert(sizeof(uint64_t) >= pkt->getSize());
106
107 overwrite_mem = true;
108 // keep a copy of our possible write value, and copy what is at the
109 // memory address into the packet
110 pkt->writeData((uint8_t *)&overwrite_val);
111 pkt->setData(blk_data);
112
113 if (pkt->req->isCondSwap()) {
114 if (pkt->getSize() == sizeof(uint64_t)) {
115 condition_val64 = pkt->req->getExtraData();
116 overwrite_mem = !std::memcmp(&condition_val64, blk_data,
117 sizeof(uint64_t));
118 } else if (pkt->getSize() == sizeof(uint32_t)) {
119 condition_val32 = (uint32_t)pkt->req->getExtraData();
120 overwrite_mem = !std::memcmp(&condition_val32, blk_data,
121 sizeof(uint32_t));
122 } else
123 panic("Invalid size for conditional read/write\n");
124 }
125
126 if (overwrite_mem) {
127 std::memcpy(blk_data, &overwrite_val, pkt->getSize());
128 blk->status |= BlkDirty;
129 }
130 }
131
132
133 template<class TagStore>
134 void
135 Cache<TagStore>::satisfyCpuSideRequest(PacketPtr pkt, BlkType *blk,
136 bool deferred_response,
137 bool pending_downgrade)
138 {
139 assert(blk && blk->isValid());
140 // Occasionally this is not true... if we are a lower-level cache
141 // satisfying a string of Read and ReadEx requests from
142 // upper-level caches, a Read will mark the block as shared but we
143 // can satisfy a following ReadEx anyway since we can rely on the
144 // Read requester(s) to have buffered the ReadEx snoop and to
145 // invalidate their blocks after receiving them.
146 // assert(!pkt->needsExclusive() || blk->isWritable());
147 assert(pkt->getOffset(blkSize) + pkt->getSize() <= blkSize);
148
149 // Check RMW operations first since both isRead() and
150 // isWrite() will be true for them
151 if (pkt->cmd == MemCmd::SwapReq) {
152 cmpAndSwap(blk, pkt);
153 } else if (pkt->isWrite()) {
154 if (blk->checkWrite(pkt)) {
155 pkt->writeDataToBlock(blk->data, blkSize);
156 blk->status |= BlkDirty;
157 }
158 } else if (pkt->isRead()) {
159 if (pkt->isLLSC()) {
160 blk->trackLoadLocked(pkt);
161 }
162 pkt->setDataFromBlock(blk->data, blkSize);
163 if (pkt->getSize() == blkSize) {
164 // special handling for coherent block requests from
165 // upper-level caches
166 if (pkt->needsExclusive()) {
167 // if we have a dirty copy, make sure the recipient
168 // keeps it marked dirty
169 if (blk->isDirty()) {
170 pkt->assertMemInhibit();
171 }
172 // on ReadExReq we give up our copy unconditionally
173 tags->invalidateBlk(blk);
174 } else if (blk->isWritable() && !pending_downgrade
175 && !pkt->sharedAsserted()) {
176 // we can give the requester an exclusive copy (by not
177 // asserting shared line) on a read request if:
178 // - we have an exclusive copy at this level (& below)
179 // - we don't have a pending snoop from below
180 // signaling another read request
181 // - no other cache above has a copy (otherwise it
182 // would have asseretd shared line on request)
183
184 if (blk->isDirty()) {
185 // special considerations if we're owner:
186 if (!deferred_response && !isTopLevel) {
187 // if we are responding immediately and can
188 // signal that we're transferring ownership
189 // along with exclusivity, do so
190 pkt->assertMemInhibit();
191 blk->status &= ~BlkDirty;
192 } else {
193 // if we're responding after our own miss,
194 // there's a window where the recipient didn't
195 // know it was getting ownership and may not
196 // have responded to snoops correctly, so we
197 // can't pass off ownership *or* exclusivity
198 pkt->assertShared();
199 }
200 }
201 } else {
202 // otherwise only respond with a shared copy
203 pkt->assertShared();
204 }
205 }
206 } else {
207 // Not a read or write... must be an upgrade. it's OK
208 // to just ack those as long as we have an exclusive
209 // copy at this level.
210 assert(pkt->isUpgrade());
211 tags->invalidateBlk(blk);
212 }
213 }
214
215
216 /////////////////////////////////////////////////////
217 //
218 // MSHR helper functions
219 //
220 /////////////////////////////////////////////////////
221
222
223 template<class TagStore>
224 void
225 Cache<TagStore>::markInService(MSHR *mshr, PacketPtr pkt)
226 {
227 markInServiceInternal(mshr, pkt);
228 #if 0
229 if (mshr->originalCmd == MemCmd::HardPFReq) {
230 DPRINTF(HWPrefetch, "%s:Marking a HW_PF in service\n",
231 name());
232 //Also clear pending if need be
233 if (!prefetcher->havePending())
234 {
235 deassertMemSideBusRequest(Request_PF);
236 }
237 }
238 #endif
239 }
240
241
242 template<class TagStore>
243 void
244 Cache<TagStore>::squash(int threadNum)
245 {
246 bool unblock = false;
247 BlockedCause cause = NUM_BLOCKED_CAUSES;
248
249 if (noTargetMSHR && noTargetMSHR->threadNum == threadNum) {
250 noTargetMSHR = NULL;
251 unblock = true;
252 cause = Blocked_NoTargets;
253 }
254 if (mshrQueue.isFull()) {
255 unblock = true;
256 cause = Blocked_NoMSHRs;
257 }
258 mshrQueue.squash(threadNum);
259 if (unblock && !mshrQueue.isFull()) {
260 clearBlocked(cause);
261 }
262 }
263
264 /////////////////////////////////////////////////////
265 //
266 // Access path: requests coming in from the CPU side
267 //
268 /////////////////////////////////////////////////////
269
270 template<class TagStore>
271 bool
272 Cache<TagStore>::access(PacketPtr pkt, BlkType *&blk,
273 int &lat, PacketList &writebacks)
274 {
275 if (pkt->req->isUncacheable()) {
276 if (pkt->req->isClearLL()) {
277 tags->clearLocks();
278 } else if (pkt->isWrite()) {
279 blk = tags->findBlock(pkt->getAddr());
280 if (blk != NULL) {
281 tags->invalidateBlk(blk);
282 }
283 }
284
285 blk = NULL;
286 lat = hitLatency;
287 return false;
288 }
289
290 int id = pkt->req->hasContextId() ? pkt->req->contextId() : -1;
291 blk = tags->accessBlock(pkt->getAddr(), lat, id);
292
293 DPRINTF(Cache, "%s%s %x %s\n", pkt->cmdString(),
294 pkt->req->isInstFetch() ? " (ifetch)" : "",
295 pkt->getAddr(), (blk) ? "hit" : "miss");
296
297 if (blk != NULL) {
298
299 if (pkt->needsExclusive() ? blk->isWritable() : blk->isReadable()) {
300 // OK to satisfy access
301 incHitCount(pkt);
302 satisfyCpuSideRequest(pkt, blk);
303 return true;
304 }
305 }
306
307 // Can't satisfy access normally... either no block (blk == NULL)
308 // or have block but need exclusive & only have shared.
309
310 // Writeback handling is special case. We can write the block
311 // into the cache without having a writeable copy (or any copy at
312 // all).
313 if (pkt->cmd == MemCmd::Writeback) {
314 assert(blkSize == pkt->getSize());
315 if (blk == NULL) {
316 // need to do a replacement
317 blk = allocateBlock(pkt->getAddr(), writebacks);
318 if (blk == NULL) {
319 // no replaceable block available, give up.
320 // writeback will be forwarded to next level.
321 incMissCount(pkt);
322 return false;
323 }
324 int id = pkt->req->masterId();
325 tags->insertBlock(pkt->getAddr(), blk, id);
326 blk->status = BlkValid | BlkReadable;
327 }
328 std::memcpy(blk->data, pkt->getPtr<uint8_t>(), blkSize);
329 blk->status |= BlkDirty;
330 if (pkt->isSupplyExclusive()) {
331 blk->status |= BlkWritable;
332 }
333 // nothing else to do; writeback doesn't expect response
334 assert(!pkt->needsResponse());
335 incHitCount(pkt);
336 return true;
337 }
338
339 incMissCount(pkt);
340
341 if (blk == NULL && pkt->isLLSC() && pkt->isWrite()) {
342 // complete miss on store conditional... just give up now
343 pkt->req->setExtraData(0);
344 return true;
345 }
346
347 return false;
348 }
349
350
351 class ForwardResponseRecord : public Packet::SenderState
352 {
353 Packet::SenderState *prevSenderState;
354 PortID prevSrc;
355 #ifndef NDEBUG
356 BaseCache *cache;
357 #endif
358 public:
359 ForwardResponseRecord(Packet *pkt, BaseCache *_cache)
360 : prevSenderState(pkt->senderState), prevSrc(pkt->getSrc())
361 #ifndef NDEBUG
362 , cache(_cache)
363 #endif
364 {}
365 void restore(Packet *pkt, BaseCache *_cache)
366 {
367 assert(_cache == cache);
368 pkt->senderState = prevSenderState;
369 pkt->setDest(prevSrc);
370 }
371 };
372
373
374 template<class TagStore>
375 bool
376 Cache<TagStore>::timingAccess(PacketPtr pkt)
377 {
378 //@todo Add back in MemDebug Calls
379 // MemDebug::cacheAccess(pkt);
380
381
382 /// @todo temporary hack to deal with memory corruption issue until
383 /// 4-phase transactions are complete
384 for (int x = 0; x < pendingDelete.size(); x++)
385 delete pendingDelete[x];
386 pendingDelete.clear();
387
388 // we charge hitLatency for doing just about anything here
389 Tick time = curTick() + hitLatency;
390
391 if (pkt->isResponse()) {
392 // must be cache-to-cache response from upper to lower level
393 ForwardResponseRecord *rec =
394 dynamic_cast<ForwardResponseRecord *>(pkt->senderState);
395
396 if (rec == NULL) {
397 assert(pkt->cmd == MemCmd::HardPFResp);
398 // Check if it's a prefetch response and handle it. We shouldn't
399 // get any other kinds of responses without FRRs.
400 DPRINTF(Cache, "Got prefetch response from above for addr %#x\n",
401 pkt->getAddr());
402 handleResponse(pkt);
403 return true;
404 }
405
406 rec->restore(pkt, this);
407 delete rec;
408 memSidePort->respond(pkt, time);
409 return true;
410 }
411
412 assert(pkt->isRequest());
413
414 if (pkt->memInhibitAsserted()) {
415 DPRINTF(Cache, "mem inhibited on 0x%x: not responding\n",
416 pkt->getAddr());
417 assert(!pkt->req->isUncacheable());
418 // Special tweak for multilevel coherence: snoop downward here
419 // on invalidates since there may be other caches below here
420 // that have shared copies. Not necessary if we know that
421 // supplier had exclusive copy to begin with.
422 if (pkt->needsExclusive() && !pkt->isSupplyExclusive()) {
423 Packet *snoopPkt = new Packet(pkt, true); // clear flags
424 snoopPkt->setExpressSnoop();
425 snoopPkt->assertMemInhibit();
426 memSidePort->sendTimingReq(snoopPkt);
427 // main memory will delete snoopPkt
428 }
429 // since we're the official target but we aren't responding,
430 // delete the packet now.
431
432 /// @todo nominally we should just delete the packet here,
433 /// however, until 4-phase stuff we can't because sending
434 /// cache is still relying on it
435 pendingDelete.push_back(pkt);
436 return true;
437 }
438
439 if (pkt->req->isUncacheable()) {
440 if (pkt->req->isClearLL()) {
441 tags->clearLocks();
442 } else if (pkt->isWrite()) {
443 BlkType *blk = tags->findBlock(pkt->getAddr());
444 if (blk != NULL) {
445 tags->invalidateBlk(blk);
446 }
447 }
448
449 // writes go in write buffer, reads use MSHR
450 if (pkt->isWrite() && !pkt->isRead()) {
451 allocateWriteBuffer(pkt, time, true);
452 } else {
453 allocateUncachedReadBuffer(pkt, time, true);
454 }
455 assert(pkt->needsResponse()); // else we should delete it here??
456 return true;
457 }
458
459 int lat = hitLatency;
460 BlkType *blk = NULL;
461 PacketList writebacks;
462
463 bool satisfied = access(pkt, blk, lat, writebacks);
464
465 #if 0
466 /** @todo make the fast write alloc (wh64) work with coherence. */
467
468 // If this is a block size write/hint (WH64) allocate the block here
469 // if the coherence protocol allows it.
470 if (!blk && pkt->getSize() >= blkSize && coherence->allowFastWrites() &&
471 (pkt->cmd == MemCmd::WriteReq
472 || pkt->cmd == MemCmd::WriteInvalidateReq) ) {
473 // not outstanding misses, can do this
474 MSHR *outstanding_miss = mshrQueue.findMatch(pkt->getAddr());
475 if (pkt->cmd == MemCmd::WriteInvalidateReq || !outstanding_miss) {
476 if (outstanding_miss) {
477 warn("WriteInv doing a fastallocate"
478 "with an outstanding miss to the same address\n");
479 }
480 blk = handleFill(NULL, pkt, BlkValid | BlkWritable,
481 writebacks);
482 ++fastWrites;
483 }
484 }
485 #endif
486
487 // track time of availability of next prefetch, if any
488 Tick next_pf_time = 0;
489
490 bool needsResponse = pkt->needsResponse();
491
492 if (satisfied) {
493 if (prefetcher && (prefetchOnAccess || (blk && blk->wasPrefetched()))) {
494 if (blk)
495 blk->status &= ~BlkHWPrefetched;
496 next_pf_time = prefetcher->notify(pkt, time);
497 }
498
499 if (needsResponse) {
500 pkt->makeTimingResponse();
501 cpuSidePort->respond(pkt, curTick()+lat);
502 } else {
503 /// @todo nominally we should just delete the packet here,
504 /// however, until 4-phase stuff we can't because sending
505 /// cache is still relying on it
506 pendingDelete.push_back(pkt);
507 }
508 } else {
509 // miss
510
511 Addr blk_addr = blockAlign(pkt->getAddr());
512 MSHR *mshr = mshrQueue.findMatch(blk_addr);
513
514 if (mshr) {
515 // MSHR hit
516 //@todo remove hw_pf here
517 assert(pkt->req->masterId() < system->maxMasters());
518 mshr_hits[pkt->cmdToIndex()][pkt->req->masterId()]++;
519 if (mshr->threadNum != 0/*pkt->req->threadId()*/) {
520 mshr->threadNum = -1;
521 }
522 mshr->allocateTarget(pkt, time, order++);
523 if (mshr->getNumTargets() == numTarget) {
524 noTargetMSHR = mshr;
525 setBlocked(Blocked_NoTargets);
526 // need to be careful with this... if this mshr isn't
527 // ready yet (i.e. time > curTick()_, we don't want to
528 // move it ahead of mshrs that are ready
529 // mshrQueue.moveToFront(mshr);
530 }
531 } else {
532 // no MSHR
533 assert(pkt->req->masterId() < system->maxMasters());
534 mshr_misses[pkt->cmdToIndex()][pkt->req->masterId()]++;
535 // always mark as cache fill for now... if we implement
536 // no-write-allocate or bypass accesses this will have to
537 // be changed.
538 if (pkt->cmd == MemCmd::Writeback) {
539 allocateWriteBuffer(pkt, time, true);
540 } else {
541 if (blk && blk->isValid()) {
542 // If we have a write miss to a valid block, we
543 // need to mark the block non-readable. Otherwise
544 // if we allow reads while there's an outstanding
545 // write miss, the read could return stale data
546 // out of the cache block... a more aggressive
547 // system could detect the overlap (if any) and
548 // forward data out of the MSHRs, but we don't do
549 // that yet. Note that we do need to leave the
550 // block valid so that it stays in the cache, in
551 // case we get an upgrade response (and hence no
552 // new data) when the write miss completes.
553 // As long as CPUs do proper store/load forwarding
554 // internally, and have a sufficiently weak memory
555 // model, this is probably unnecessary, but at some
556 // point it must have seemed like we needed it...
557 assert(pkt->needsExclusive() && !blk->isWritable());
558 blk->status &= ~BlkReadable;
559 }
560
561 allocateMissBuffer(pkt, time, true);
562 }
563
564 if (prefetcher) {
565 next_pf_time = prefetcher->notify(pkt, time);
566 }
567 }
568 }
569
570 if (next_pf_time != 0)
571 requestMemSideBus(Request_PF, std::max(time, next_pf_time));
572
573 // copy writebacks to write buffer
574 while (!writebacks.empty()) {
575 PacketPtr wbPkt = writebacks.front();
576 allocateWriteBuffer(wbPkt, time, true);
577 writebacks.pop_front();
578 }
579
580 return true;
581 }
582
583
584 // See comment in cache.hh.
585 template<class TagStore>
586 PacketPtr
587 Cache<TagStore>::getBusPacket(PacketPtr cpu_pkt, BlkType *blk,
588 bool needsExclusive)
589 {
590 bool blkValid = blk && blk->isValid();
591
592 if (cpu_pkt->req->isUncacheable()) {
593 //assert(blk == NULL);
594 return NULL;
595 }
596
597 if (!blkValid &&
598 (cpu_pkt->cmd == MemCmd::Writeback || cpu_pkt->isUpgrade())) {
599 // Writebacks that weren't allocated in access() and upgrades
600 // from upper-level caches that missed completely just go
601 // through.
602 return NULL;
603 }
604
605 assert(cpu_pkt->needsResponse());
606
607 MemCmd cmd;
608 // @TODO make useUpgrades a parameter.
609 // Note that ownership protocols require upgrade, otherwise a
610 // write miss on a shared owned block will generate a ReadExcl,
611 // which will clobber the owned copy.
612 const bool useUpgrades = true;
613 if (blkValid && useUpgrades) {
614 // only reason to be here is that blk is shared
615 // (read-only) and we need exclusive
616 assert(needsExclusive && !blk->isWritable());
617 cmd = cpu_pkt->isLLSC() ? MemCmd::SCUpgradeReq : MemCmd::UpgradeReq;
618 } else {
619 // block is invalid
620 cmd = needsExclusive ? MemCmd::ReadExReq : MemCmd::ReadReq;
621 }
622 PacketPtr pkt = new Packet(cpu_pkt->req, cmd, blkSize);
623
624 pkt->allocate();
625 return pkt;
626 }
627
628
629 template<class TagStore>
630 Tick
631 Cache<TagStore>::atomicAccess(PacketPtr pkt)
632 {
633 int lat = hitLatency;
634
635 // @TODO: make this a parameter
636 bool last_level_cache = false;
637
638 if (pkt->memInhibitAsserted()) {
639 assert(!pkt->req->isUncacheable());
640 // have to invalidate ourselves and any lower caches even if
641 // upper cache will be responding
642 if (pkt->isInvalidate()) {
643 BlkType *blk = tags->findBlock(pkt->getAddr());
644 if (blk && blk->isValid()) {
645 tags->invalidateBlk(blk);
646 DPRINTF(Cache, "rcvd mem-inhibited %s on 0x%x: invalidating\n",
647 pkt->cmdString(), pkt->getAddr());
648 }
649 if (!last_level_cache) {
650 DPRINTF(Cache, "forwarding mem-inhibited %s on 0x%x\n",
651 pkt->cmdString(), pkt->getAddr());
652 lat += memSidePort->sendAtomic(pkt);
653 }
654 } else {
655 DPRINTF(Cache, "rcvd mem-inhibited %s on 0x%x: not responding\n",
656 pkt->cmdString(), pkt->getAddr());
657 }
658
659 return lat;
660 }
661
662 // should assert here that there are no outstanding MSHRs or
663 // writebacks... that would mean that someone used an atomic
664 // access in timing mode
665
666 BlkType *blk = NULL;
667 PacketList writebacks;
668
669 if (!access(pkt, blk, lat, writebacks)) {
670 // MISS
671 PacketPtr bus_pkt = getBusPacket(pkt, blk, pkt->needsExclusive());
672
673 bool is_forward = (bus_pkt == NULL);
674
675 if (is_forward) {
676 // just forwarding the same request to the next level
677 // no local cache operation involved
678 bus_pkt = pkt;
679 }
680
681 DPRINTF(Cache, "Sending an atomic %s for %x\n",
682 bus_pkt->cmdString(), bus_pkt->getAddr());
683
684 #if TRACING_ON
685 CacheBlk::State old_state = blk ? blk->status : 0;
686 #endif
687
688 lat += memSidePort->sendAtomic(bus_pkt);
689
690 DPRINTF(Cache, "Receive response: %s for addr %x in state %i\n",
691 bus_pkt->cmdString(), bus_pkt->getAddr(), old_state);
692
693 assert(!bus_pkt->wasNacked());
694
695 // If packet was a forward, the response (if any) is already
696 // in place in the bus_pkt == pkt structure, so we don't need
697 // to do anything. Otherwise, use the separate bus_pkt to
698 // generate response to pkt and then delete it.
699 if (!is_forward) {
700 if (pkt->needsResponse()) {
701 assert(bus_pkt->isResponse());
702 if (bus_pkt->isError()) {
703 pkt->makeAtomicResponse();
704 pkt->copyError(bus_pkt);
705 } else if (bus_pkt->isRead() ||
706 bus_pkt->cmd == MemCmd::UpgradeResp) {
707 // we're updating cache state to allow us to
708 // satisfy the upstream request from the cache
709 blk = handleFill(bus_pkt, blk, writebacks);
710 satisfyCpuSideRequest(pkt, blk);
711 } else {
712 // we're satisfying the upstream request without
713 // modifying cache state, e.g., a write-through
714 pkt->makeAtomicResponse();
715 }
716 }
717 delete bus_pkt;
718 }
719 }
720
721 // Note that we don't invoke the prefetcher at all in atomic mode.
722 // It's not clear how to do it properly, particularly for
723 // prefetchers that aggressively generate prefetch candidates and
724 // rely on bandwidth contention to throttle them; these will tend
725 // to pollute the cache in atomic mode since there is no bandwidth
726 // contention. If we ever do want to enable prefetching in atomic
727 // mode, though, this is the place to do it... see timingAccess()
728 // for an example (though we'd want to issue the prefetch(es)
729 // immediately rather than calling requestMemSideBus() as we do
730 // there).
731
732 // Handle writebacks if needed
733 while (!writebacks.empty()){
734 PacketPtr wbPkt = writebacks.front();
735 memSidePort->sendAtomic(wbPkt);
736 writebacks.pop_front();
737 delete wbPkt;
738 }
739
740 // We now have the block one way or another (hit or completed miss)
741
742 if (pkt->needsResponse()) {
743 pkt->makeAtomicResponse();
744 }
745
746 return lat;
747 }
748
749
750 template<class TagStore>
751 void
752 Cache<TagStore>::functionalAccess(PacketPtr pkt, bool fromCpuSide)
753 {
754 Addr blk_addr = blockAlign(pkt->getAddr());
755 BlkType *blk = tags->findBlock(pkt->getAddr());
756 MSHR *mshr = mshrQueue.findMatch(blk_addr);
757
758 pkt->pushLabel(name());
759
760 CacheBlkPrintWrapper cbpw(blk);
761
762 // Note that just because an L2/L3 has valid data doesn't mean an
763 // L1 doesn't have a more up-to-date modified copy that still
764 // needs to be found. As a result we always update the request if
765 // we have it, but only declare it satisfied if we are the owner.
766
767 // see if we have data at all (owned or otherwise)
768 bool have_data = blk && blk->isValid()
769 && pkt->checkFunctional(&cbpw, blk_addr, blkSize, blk->data);
770
771 // data we have is dirty if marked as such or if valid & ownership
772 // pending due to outstanding UpgradeReq
773 bool have_dirty =
774 have_data && (blk->isDirty() ||
775 (mshr && mshr->inService && mshr->isPendingDirty()));
776
777 bool done = have_dirty
778 || cpuSidePort->checkFunctional(pkt)
779 || mshrQueue.checkFunctional(pkt, blk_addr)
780 || writeBuffer.checkFunctional(pkt, blk_addr)
781 || memSidePort->checkFunctional(pkt);
782
783 DPRINTF(Cache, "functional %s %x %s%s%s\n",
784 pkt->cmdString(), pkt->getAddr(),
785 (blk && blk->isValid()) ? "valid " : "",
786 have_data ? "data " : "", done ? "done " : "");
787
788 // We're leaving the cache, so pop cache->name() label
789 pkt->popLabel();
790
791 if (done) {
792 pkt->makeResponse();
793 } else {
794 // if it came as a request from the CPU side then make sure it
795 // continues towards the memory side
796 if (fromCpuSide) {
797 memSidePort->sendFunctional(pkt);
798 } else if (forwardSnoops && cpuSidePort->getMasterPort().isSnooping()) {
799 // if it came from the memory side, it must be a snoop request
800 // and we should only forward it if we are forwarding snoops
801 cpuSidePort->sendFunctionalSnoop(pkt);
802 }
803 }
804 }
805
806
807 /////////////////////////////////////////////////////
808 //
809 // Response handling: responses from the memory side
810 //
811 /////////////////////////////////////////////////////
812
813
814 template<class TagStore>
815 void
816 Cache<TagStore>::handleResponse(PacketPtr pkt)
817 {
818 Tick time = curTick() + hitLatency;
819 MSHR *mshr = dynamic_cast<MSHR*>(pkt->senderState);
820 bool is_error = pkt->isError();
821
822 assert(mshr);
823
824 if (pkt->wasNacked()) {
825 //pkt->reinitFromRequest();
826 warn("NACKs from devices not connected to the same bus "
827 "not implemented\n");
828 return;
829 }
830 if (is_error) {
831 DPRINTF(Cache, "Cache received packet with error for address %x, "
832 "cmd: %s\n", pkt->getAddr(), pkt->cmdString());
833 }
834
835 DPRINTF(Cache, "Handling response to %x\n", pkt->getAddr());
836
837 MSHRQueue *mq = mshr->queue;
838 bool wasFull = mq->isFull();
839
840 if (mshr == noTargetMSHR) {
841 // we always clear at least one target
842 clearBlocked(Blocked_NoTargets);
843 noTargetMSHR = NULL;
844 }
845
846 // Initial target is used just for stats
847 MSHR::Target *initial_tgt = mshr->getTarget();
848 BlkType *blk = tags->findBlock(pkt->getAddr());
849 int stats_cmd_idx = initial_tgt->pkt->cmdToIndex();
850 Tick miss_latency = curTick() - initial_tgt->recvTime;
851 PacketList writebacks;
852
853 if (pkt->req->isUncacheable()) {
854 assert(pkt->req->masterId() < system->maxMasters());
855 mshr_uncacheable_lat[stats_cmd_idx][pkt->req->masterId()] +=
856 miss_latency;
857 } else {
858 assert(pkt->req->masterId() < system->maxMasters());
859 mshr_miss_latency[stats_cmd_idx][pkt->req->masterId()] +=
860 miss_latency;
861 }
862
863 bool is_fill = !mshr->isForward &&
864 (pkt->isRead() || pkt->cmd == MemCmd::UpgradeResp);
865
866 if (is_fill && !is_error) {
867 DPRINTF(Cache, "Block for addr %x being updated in Cache\n",
868 pkt->getAddr());
869
870 // give mshr a chance to do some dirty work
871 mshr->handleFill(pkt, blk);
872
873 blk = handleFill(pkt, blk, writebacks);
874 assert(blk != NULL);
875 }
876
877 // First offset for critical word first calculations
878 int initial_offset = 0;
879
880 if (mshr->hasTargets()) {
881 initial_offset = mshr->getTarget()->pkt->getOffset(blkSize);
882 }
883
884 while (mshr->hasTargets()) {
885 MSHR::Target *target = mshr->getTarget();
886
887 switch (target->source) {
888 case MSHR::Target::FromCPU:
889 Tick completion_time;
890 if (is_fill) {
891 satisfyCpuSideRequest(target->pkt, blk,
892 true, mshr->hasPostDowngrade());
893 // How many bytes past the first request is this one
894 int transfer_offset =
895 target->pkt->getOffset(blkSize) - initial_offset;
896 if (transfer_offset < 0) {
897 transfer_offset += blkSize;
898 }
899
900 // If critical word (no offset) return first word time
901 completion_time = tags->getHitLatency() +
902 (transfer_offset ? pkt->finishTime : pkt->firstWordTime);
903
904 assert(!target->pkt->req->isUncacheable());
905
906 assert(pkt->req->masterId() < system->maxMasters());
907 missLatency[target->pkt->cmdToIndex()][target->pkt->req->masterId()] +=
908 completion_time - target->recvTime;
909 } else if (pkt->cmd == MemCmd::UpgradeFailResp) {
910 // failed StoreCond upgrade
911 assert(target->pkt->cmd == MemCmd::StoreCondReq ||
912 target->pkt->cmd == MemCmd::StoreCondFailReq ||
913 target->pkt->cmd == MemCmd::SCUpgradeFailReq);
914 completion_time = tags->getHitLatency() + pkt->finishTime;
915 target->pkt->req->setExtraData(0);
916 } else {
917 // not a cache fill, just forwarding response
918 completion_time = tags->getHitLatency() + pkt->finishTime;
919 if (pkt->isRead() && !is_error) {
920 target->pkt->setData(pkt->getPtr<uint8_t>());
921 }
922 }
923 target->pkt->makeTimingResponse();
924 // if this packet is an error copy that to the new packet
925 if (is_error)
926 target->pkt->copyError(pkt);
927 if (target->pkt->cmd == MemCmd::ReadResp &&
928 (pkt->isInvalidate() || mshr->hasPostInvalidate())) {
929 // If intermediate cache got ReadRespWithInvalidate,
930 // propagate that. Response should not have
931 // isInvalidate() set otherwise.
932 target->pkt->cmd = MemCmd::ReadRespWithInvalidate;
933 }
934 cpuSidePort->respond(target->pkt, completion_time);
935 break;
936
937 case MSHR::Target::FromPrefetcher:
938 assert(target->pkt->cmd == MemCmd::HardPFReq);
939 if (blk)
940 blk->status |= BlkHWPrefetched;
941 delete target->pkt->req;
942 delete target->pkt;
943 break;
944
945 case MSHR::Target::FromSnoop:
946 // I don't believe that a snoop can be in an error state
947 assert(!is_error);
948 // response to snoop request
949 DPRINTF(Cache, "processing deferred snoop...\n");
950 assert(!(pkt->isInvalidate() && !mshr->hasPostInvalidate()));
951 handleSnoop(target->pkt, blk, true, true,
952 mshr->hasPostInvalidate());
953 break;
954
955 default:
956 panic("Illegal target->source enum %d\n", target->source);
957 }
958
959 mshr->popTarget();
960 }
961
962 if (blk) {
963 if (pkt->isInvalidate() || mshr->hasPostInvalidate()) {
964 tags->invalidateBlk(blk);
965 } else if (mshr->hasPostDowngrade()) {
966 blk->status &= ~BlkWritable;
967 }
968 }
969
970 if (mshr->promoteDeferredTargets()) {
971 // avoid later read getting stale data while write miss is
972 // outstanding.. see comment in timingAccess()
973 if (blk) {
974 blk->status &= ~BlkReadable;
975 }
976 MSHRQueue *mq = mshr->queue;
977 mq->markPending(mshr);
978 requestMemSideBus((RequestCause)mq->index, pkt->finishTime);
979 } else {
980 mq->deallocate(mshr);
981 if (wasFull && !mq->isFull()) {
982 clearBlocked((BlockedCause)mq->index);
983 }
984 }
985
986 // copy writebacks to write buffer
987 while (!writebacks.empty()) {
988 PacketPtr wbPkt = writebacks.front();
989 allocateWriteBuffer(wbPkt, time, true);
990 writebacks.pop_front();
991 }
992 // if we used temp block, clear it out
993 if (blk == tempBlock) {
994 if (blk->isDirty()) {
995 allocateWriteBuffer(writebackBlk(blk), time, true);
996 }
997 blk->status &= ~BlkValid;
998 tags->invalidateBlk(blk);
999 }
1000
1001 delete pkt;
1002 }
1003
1004
1005
1006
1007 template<class TagStore>
1008 PacketPtr
1009 Cache<TagStore>::writebackBlk(BlkType *blk)
1010 {
1011 assert(blk && blk->isValid() && blk->isDirty());
1012
1013 writebacks[Request::wbMasterId]++;
1014
1015 Request *writebackReq =
1016 new Request(tags->regenerateBlkAddr(blk->tag, blk->set), blkSize, 0,
1017 Request::wbMasterId);
1018 PacketPtr writeback = new Packet(writebackReq, MemCmd::Writeback);
1019 if (blk->isWritable()) {
1020 writeback->setSupplyExclusive();
1021 }
1022 writeback->allocate();
1023 std::memcpy(writeback->getPtr<uint8_t>(), blk->data, blkSize);
1024
1025 blk->status &= ~BlkDirty;
1026 return writeback;
1027 }
1028
1029
1030 template<class TagStore>
1031 typename Cache<TagStore>::BlkType*
1032 Cache<TagStore>::allocateBlock(Addr addr, PacketList &writebacks)
1033 {
1034 BlkType *blk = tags->findVictim(addr, writebacks);
1035
1036 if (blk->isValid()) {
1037 Addr repl_addr = tags->regenerateBlkAddr(blk->tag, blk->set);
1038 MSHR *repl_mshr = mshrQueue.findMatch(repl_addr);
1039 if (repl_mshr) {
1040 // must be an outstanding upgrade request on block
1041 // we're about to replace...
1042 assert(!blk->isWritable());
1043 assert(repl_mshr->needsExclusive());
1044 // too hard to replace block with transient state
1045 // allocation failed, block not inserted
1046 return NULL;
1047 } else {
1048 DPRINTF(Cache, "replacement: replacing %x with %x: %s\n",
1049 repl_addr, addr,
1050 blk->isDirty() ? "writeback" : "clean");
1051
1052 if (blk->isDirty()) {
1053 // Save writeback packet for handling by caller
1054 writebacks.push_back(writebackBlk(blk));
1055 }
1056 }
1057 }
1058
1059 return blk;
1060 }
1061
1062
1063 // Note that the reason we return a list of writebacks rather than
1064 // inserting them directly in the write buffer is that this function
1065 // is called by both atomic and timing-mode accesses, and in atomic
1066 // mode we don't mess with the write buffer (we just perform the
1067 // writebacks atomically once the original request is complete).
1068 template<class TagStore>
1069 typename Cache<TagStore>::BlkType*
1070 Cache<TagStore>::handleFill(PacketPtr pkt, BlkType *blk,
1071 PacketList &writebacks)
1072 {
1073 Addr addr = pkt->getAddr();
1074 #if TRACING_ON
1075 CacheBlk::State old_state = blk ? blk->status : 0;
1076 #endif
1077
1078 if (blk == NULL) {
1079 // better have read new data...
1080 assert(pkt->hasData());
1081 // need to do a replacement
1082 blk = allocateBlock(addr, writebacks);
1083 if (blk == NULL) {
1084 // No replaceable block... just use temporary storage to
1085 // complete the current request and then get rid of it
1086 assert(!tempBlock->isValid());
1087 blk = tempBlock;
1088 tempBlock->set = tags->extractSet(addr);
1089 tempBlock->tag = tags->extractTag(addr);
1090 DPRINTF(Cache, "using temp block for %x\n", addr);
1091 } else {
1092 int id = pkt->req->masterId();
1093 tags->insertBlock(pkt->getAddr(), blk, id);
1094 }
1095
1096 // starting from scratch with a new block
1097 blk->status = 0;
1098 } else {
1099 // existing block... probably an upgrade
1100 assert(blk->tag == tags->extractTag(addr));
1101 // either we're getting new data or the block should already be valid
1102 assert(pkt->hasData() || blk->isValid());
1103 // don't clear block status... if block is already dirty we
1104 // don't want to lose that
1105 }
1106
1107 blk->status |= BlkValid | BlkReadable;
1108
1109 if (!pkt->sharedAsserted()) {
1110 blk->status |= BlkWritable;
1111 // If we got this via cache-to-cache transfer (i.e., from a
1112 // cache that was an owner) and took away that owner's copy,
1113 // then we need to write it back. Normally this happens
1114 // anyway as a side effect of getting a copy to write it, but
1115 // there are cases (such as failed store conditionals or
1116 // compare-and-swaps) where we'll demand an exclusive copy but
1117 // end up not writing it.
1118 if (pkt->memInhibitAsserted())
1119 blk->status |= BlkDirty;
1120 }
1121
1122 DPRINTF(Cache, "Block addr %x moving from state %i to %i\n",
1123 addr, old_state, blk->status);
1124
1125 // if we got new data, copy it in
1126 if (pkt->isRead()) {
1127 std::memcpy(blk->data, pkt->getPtr<uint8_t>(), blkSize);
1128 }
1129
1130 blk->whenReady = pkt->finishTime;
1131
1132 return blk;
1133 }
1134
1135
1136 /////////////////////////////////////////////////////
1137 //
1138 // Snoop path: requests coming in from the memory side
1139 //
1140 /////////////////////////////////////////////////////
1141
1142 template<class TagStore>
1143 void
1144 Cache<TagStore>::
1145 doTimingSupplyResponse(PacketPtr req_pkt, uint8_t *blk_data,
1146 bool already_copied, bool pending_inval)
1147 {
1148 // timing-mode snoop responses require a new packet, unless we
1149 // already made a copy...
1150 PacketPtr pkt = already_copied ? req_pkt : new Packet(req_pkt);
1151 assert(req_pkt->isInvalidate() || pkt->sharedAsserted());
1152 pkt->allocate();
1153 pkt->makeTimingResponse();
1154 if (pkt->isRead()) {
1155 pkt->setDataFromBlock(blk_data, blkSize);
1156 }
1157 if (pkt->cmd == MemCmd::ReadResp && pending_inval) {
1158 // Assume we defer a response to a read from a far-away cache
1159 // A, then later defer a ReadExcl from a cache B on the same
1160 // bus as us. We'll assert MemInhibit in both cases, but in
1161 // the latter case MemInhibit will keep the invalidation from
1162 // reaching cache A. This special response tells cache A that
1163 // it gets the block to satisfy its read, but must immediately
1164 // invalidate it.
1165 pkt->cmd = MemCmd::ReadRespWithInvalidate;
1166 }
1167 memSidePort->respond(pkt, curTick() + hitLatency);
1168 }
1169
1170 template<class TagStore>
1171 void
1172 Cache<TagStore>::handleSnoop(PacketPtr pkt, BlkType *blk,
1173 bool is_timing, bool is_deferred,
1174 bool pending_inval)
1175 {
1176 // deferred snoops can only happen in timing mode
1177 assert(!(is_deferred && !is_timing));
1178 // pending_inval only makes sense on deferred snoops
1179 assert(!(pending_inval && !is_deferred));
1180 assert(pkt->isRequest());
1181
1182 // the packet may get modified if we or a forwarded snooper
1183 // responds in atomic mode, so remember a few things about the
1184 // original packet up front
1185 bool invalidate = pkt->isInvalidate();
1186 bool M5_VAR_USED needs_exclusive = pkt->needsExclusive();
1187
1188 if (forwardSnoops) {
1189 // first propagate snoop upward to see if anyone above us wants to
1190 // handle it. save & restore packet src since it will get
1191 // rewritten to be relative to cpu-side bus (if any)
1192 bool alreadyResponded = pkt->memInhibitAsserted();
1193 if (is_timing) {
1194 Packet snoopPkt(pkt, true); // clear flags
1195 snoopPkt.setExpressSnoop();
1196 snoopPkt.senderState = new ForwardResponseRecord(pkt, this);
1197 cpuSidePort->sendTimingSnoopReq(&snoopPkt);
1198 if (snoopPkt.memInhibitAsserted()) {
1199 // cache-to-cache response from some upper cache
1200 assert(!alreadyResponded);
1201 pkt->assertMemInhibit();
1202 } else {
1203 delete snoopPkt.senderState;
1204 }
1205 if (snoopPkt.sharedAsserted()) {
1206 pkt->assertShared();
1207 }
1208 } else {
1209 cpuSidePort->sendAtomicSnoop(pkt);
1210 if (!alreadyResponded && pkt->memInhibitAsserted()) {
1211 // cache-to-cache response from some upper cache:
1212 // forward response to original requester
1213 assert(pkt->isResponse());
1214 }
1215 }
1216 }
1217
1218 if (!blk || !blk->isValid()) {
1219 return;
1220 }
1221
1222 // we may end up modifying both the block state and the packet (if
1223 // we respond in atomic mode), so just figure out what to do now
1224 // and then do it later
1225 bool respond = blk->isDirty() && pkt->needsResponse();
1226 bool have_exclusive = blk->isWritable();
1227
1228 if (pkt->isRead() && !invalidate) {
1229 assert(!needs_exclusive);
1230 pkt->assertShared();
1231 int bits_to_clear = BlkWritable;
1232 const bool haveOwnershipState = true; // for now
1233 if (!haveOwnershipState) {
1234 // if we don't support pure ownership (dirty && !writable),
1235 // have to clear dirty bit here, assume memory snarfs data
1236 // on cache-to-cache xfer
1237 bits_to_clear |= BlkDirty;
1238 }
1239 blk->status &= ~bits_to_clear;
1240 }
1241
1242 DPRINTF(Cache, "snooped a %s request for addr %x, %snew state is %i\n",
1243 pkt->cmdString(), blockAlign(pkt->getAddr()),
1244 respond ? "responding, " : "", invalidate ? 0 : blk->status);
1245
1246 if (respond) {
1247 assert(!pkt->memInhibitAsserted());
1248 pkt->assertMemInhibit();
1249 if (have_exclusive) {
1250 pkt->setSupplyExclusive();
1251 }
1252 if (is_timing) {
1253 doTimingSupplyResponse(pkt, blk->data, is_deferred, pending_inval);
1254 } else {
1255 pkt->makeAtomicResponse();
1256 pkt->setDataFromBlock(blk->data, blkSize);
1257 }
1258 } else if (is_timing && is_deferred) {
1259 // if it's a deferred timing snoop then we've made a copy of
1260 // the packet, and so if we're not using that copy to respond
1261 // then we need to delete it here.
1262 delete pkt;
1263 }
1264
1265 // Do this last in case it deallocates block data or something
1266 // like that
1267 if (invalidate) {
1268 tags->invalidateBlk(blk);
1269 }
1270 }
1271
1272
1273 template<class TagStore>
1274 void
1275 Cache<TagStore>::snoopTiming(PacketPtr pkt)
1276 {
1277 // Note that some deferred snoops don't have requests, since the
1278 // original access may have already completed
1279 if ((pkt->req && pkt->req->isUncacheable()) ||
1280 pkt->cmd == MemCmd::Writeback) {
1281 //Can't get a hit on an uncacheable address
1282 //Revisit this for multi level coherence
1283 return;
1284 }
1285
1286 BlkType *blk = tags->findBlock(pkt->getAddr());
1287
1288 Addr blk_addr = blockAlign(pkt->getAddr());
1289 MSHR *mshr = mshrQueue.findMatch(blk_addr);
1290
1291 // Let the MSHR itself track the snoop and decide whether we want
1292 // to go ahead and do the regular cache snoop
1293 if (mshr && mshr->handleSnoop(pkt, order++)) {
1294 DPRINTF(Cache, "Deferring snoop on in-service MSHR to blk %x\n",
1295 blk_addr);
1296 if (mshr->getNumTargets() > numTarget)
1297 warn("allocating bonus target for snoop"); //handle later
1298 return;
1299 }
1300
1301 //We also need to check the writeback buffers and handle those
1302 std::vector<MSHR *> writebacks;
1303 if (writeBuffer.findMatches(blk_addr, writebacks)) {
1304 DPRINTF(Cache, "Snoop hit in writeback to addr: %x\n",
1305 pkt->getAddr());
1306
1307 //Look through writebacks for any non-uncachable writes, use that
1308 if (writebacks.size()) {
1309 // We should only ever find a single match
1310 assert(writebacks.size() == 1);
1311 mshr = writebacks[0];
1312 assert(!mshr->isUncacheable());
1313 assert(mshr->getNumTargets() == 1);
1314 PacketPtr wb_pkt = mshr->getTarget()->pkt;
1315 assert(wb_pkt->cmd == MemCmd::Writeback);
1316
1317 assert(!pkt->memInhibitAsserted());
1318 pkt->assertMemInhibit();
1319 if (!pkt->needsExclusive()) {
1320 pkt->assertShared();
1321 // the writeback is no longer the exclusive copy in the system
1322 wb_pkt->clearSupplyExclusive();
1323 } else {
1324 // if we're not asserting the shared line, we need to
1325 // invalidate our copy. we'll do that below as long as
1326 // the packet's invalidate flag is set...
1327 assert(pkt->isInvalidate());
1328 }
1329 doTimingSupplyResponse(pkt, wb_pkt->getPtr<uint8_t>(),
1330 false, false);
1331
1332 if (pkt->isInvalidate()) {
1333 // Invalidation trumps our writeback... discard here
1334 markInService(mshr);
1335 delete wb_pkt;
1336 }
1337 } // writebacks.size()
1338 }
1339
1340 // If this was a shared writeback, there may still be
1341 // other shared copies above that require invalidation.
1342 // We could be more selective and return here if the
1343 // request is non-exclusive or if the writeback is
1344 // exclusive.
1345 handleSnoop(pkt, blk, true, false, false);
1346 }
1347
1348 template<class TagStore>
1349 bool
1350 Cache<TagStore>::CpuSidePort::recvTimingSnoopResp(PacketPtr pkt)
1351 {
1352 // Express snoop responses from master to slave, e.g., from L1 to L2
1353 cache->timingAccess(pkt);
1354 return true;
1355 }
1356
1357 template<class TagStore>
1358 Tick
1359 Cache<TagStore>::snoopAtomic(PacketPtr pkt)
1360 {
1361 if (pkt->req->isUncacheable() || pkt->cmd == MemCmd::Writeback) {
1362 // Can't get a hit on an uncacheable address
1363 // Revisit this for multi level coherence
1364 return hitLatency;
1365 }
1366
1367 BlkType *blk = tags->findBlock(pkt->getAddr());
1368 handleSnoop(pkt, blk, false, false, false);
1369 return hitLatency;
1370 }
1371
1372
1373 template<class TagStore>
1374 MSHR *
1375 Cache<TagStore>::getNextMSHR()
1376 {
1377 // Check both MSHR queue and write buffer for potential requests
1378 MSHR *miss_mshr = mshrQueue.getNextMSHR();
1379 MSHR *write_mshr = writeBuffer.getNextMSHR();
1380
1381 // Now figure out which one to send... some cases are easy
1382 if (miss_mshr && !write_mshr) {
1383 return miss_mshr;
1384 }
1385 if (write_mshr && !miss_mshr) {
1386 return write_mshr;
1387 }
1388
1389 if (miss_mshr && write_mshr) {
1390 // We have one of each... normally we favor the miss request
1391 // unless the write buffer is full
1392 if (writeBuffer.isFull() && writeBuffer.inServiceEntries == 0) {
1393 // Write buffer is full, so we'd like to issue a write;
1394 // need to search MSHR queue for conflicting earlier miss.
1395 MSHR *conflict_mshr =
1396 mshrQueue.findPending(write_mshr->addr, write_mshr->size);
1397
1398 if (conflict_mshr && conflict_mshr->order < write_mshr->order) {
1399 // Service misses in order until conflict is cleared.
1400 return conflict_mshr;
1401 }
1402
1403 // No conflicts; issue write
1404 return write_mshr;
1405 }
1406
1407 // Write buffer isn't full, but need to check it for
1408 // conflicting earlier writeback
1409 MSHR *conflict_mshr =
1410 writeBuffer.findPending(miss_mshr->addr, miss_mshr->size);
1411 if (conflict_mshr) {
1412 // not sure why we don't check order here... it was in the
1413 // original code but commented out.
1414
1415 // The only way this happens is if we are
1416 // doing a write and we didn't have permissions
1417 // then subsequently saw a writeback (owned got evicted)
1418 // We need to make sure to perform the writeback first
1419 // To preserve the dirty data, then we can issue the write
1420
1421 // should we return write_mshr here instead? I.e. do we
1422 // have to flush writes in order? I don't think so... not
1423 // for Alpha anyway. Maybe for x86?
1424 return conflict_mshr;
1425 }
1426
1427 // No conflicts; issue read
1428 return miss_mshr;
1429 }
1430
1431 // fall through... no pending requests. Try a prefetch.
1432 assert(!miss_mshr && !write_mshr);
1433 if (prefetcher && !mshrQueue.isFull()) {
1434 // If we have a miss queue slot, we can try a prefetch
1435 PacketPtr pkt = prefetcher->getPacket();
1436 if (pkt) {
1437 Addr pf_addr = blockAlign(pkt->getAddr());
1438 if (!tags->findBlock(pf_addr) && !mshrQueue.findMatch(pf_addr) &&
1439 !writeBuffer.findMatch(pf_addr)) {
1440 // Update statistic on number of prefetches issued
1441 // (hwpf_mshr_misses)
1442 assert(pkt->req->masterId() < system->maxMasters());
1443 mshr_misses[pkt->cmdToIndex()][pkt->req->masterId()]++;
1444 // Don't request bus, since we already have it
1445 return allocateMissBuffer(pkt, curTick(), false);
1446 } else {
1447 // free the request and packet
1448 delete pkt->req;
1449 delete pkt;
1450 }
1451 }
1452 }
1453
1454 return NULL;
1455 }
1456
1457
1458 template<class TagStore>
1459 PacketPtr
1460 Cache<TagStore>::getTimingPacket()
1461 {
1462 MSHR *mshr = getNextMSHR();
1463
1464 if (mshr == NULL) {
1465 return NULL;
1466 }
1467
1468 // use request from 1st target
1469 PacketPtr tgt_pkt = mshr->getTarget()->pkt;
1470 PacketPtr pkt = NULL;
1471
1472 if (tgt_pkt->cmd == MemCmd::SCUpgradeFailReq ||
1473 tgt_pkt->cmd == MemCmd::StoreCondFailReq) {
1474 // SCUpgradeReq or StoreCondReq saw invalidation while queued
1475 // in MSHR, so now that we are getting around to processing
1476 // it, just treat it as if we got a failure response
1477 pkt = new Packet(tgt_pkt);
1478 pkt->cmd = MemCmd::UpgradeFailResp;
1479 pkt->senderState = mshr;
1480 pkt->firstWordTime = pkt->finishTime = curTick();
1481 handleResponse(pkt);
1482 return NULL;
1483 } else if (mshr->isForwardNoResponse()) {
1484 // no response expected, just forward packet as it is
1485 assert(tags->findBlock(mshr->addr) == NULL);
1486 pkt = tgt_pkt;
1487 } else {
1488 BlkType *blk = tags->findBlock(mshr->addr);
1489
1490 if (tgt_pkt->cmd == MemCmd::HardPFReq) {
1491 // It might be possible for a writeback to arrive between
1492 // the time the prefetch is placed in the MSHRs and when
1493 // it's selected to send... if so, this assert will catch
1494 // that, and then we'll have to figure out what to do.
1495 assert(blk == NULL);
1496
1497 // We need to check the caches above us to verify that they don't have
1498 // a copy of this block in the dirty state at the moment. Without this
1499 // check we could get a stale copy from memory that might get used
1500 // in place of the dirty one.
1501 PacketPtr snoop_pkt = new Packet(tgt_pkt, true);
1502 snoop_pkt->setExpressSnoop();
1503 snoop_pkt->senderState = mshr;
1504 cpuSidePort->sendTimingSnoopReq(snoop_pkt);
1505
1506 if (snoop_pkt->memInhibitAsserted()) {
1507 markInService(mshr, snoop_pkt);
1508 DPRINTF(Cache, "Upward snoop of prefetch for addr %#x hit\n",
1509 tgt_pkt->getAddr());
1510 delete snoop_pkt;
1511 return NULL;
1512 }
1513 delete snoop_pkt;
1514 }
1515
1516 pkt = getBusPacket(tgt_pkt, blk, mshr->needsExclusive());
1517
1518 mshr->isForward = (pkt == NULL);
1519
1520 if (mshr->isForward) {
1521 // not a cache block request, but a response is expected
1522 // make copy of current packet to forward, keep current
1523 // copy for response handling
1524 pkt = new Packet(tgt_pkt);
1525 pkt->allocate();
1526 if (pkt->isWrite()) {
1527 pkt->setData(tgt_pkt->getPtr<uint8_t>());
1528 }
1529 }
1530 }
1531
1532 assert(pkt != NULL);
1533 pkt->senderState = mshr;
1534 return pkt;
1535 }
1536
1537
1538 template<class TagStore>
1539 Tick
1540 Cache<TagStore>::nextMSHRReadyTime()
1541 {
1542 Tick nextReady = std::min(mshrQueue.nextMSHRReadyTime(),
1543 writeBuffer.nextMSHRReadyTime());
1544
1545 if (prefetcher) {
1546 nextReady = std::min(nextReady,
1547 prefetcher->nextPrefetchReadyTime());
1548 }
1549
1550 return nextReady;
1551 }
1552
1553 template<class TagStore>
1554 void
1555 Cache<TagStore>::serialize(std::ostream &os)
1556 {
1557 warn("*** Creating checkpoints with caches is not supported. ***\n");
1558 warn(" Remove any caches before taking checkpoints\n");
1559 warn(" This checkpoint will not restore correctly and dirty data in "
1560 "the cache will be lost!\n");
1561
1562 // Since we don't write back the data dirty in the caches to the physical
1563 // memory if caches exist in the system we won't be able to restore
1564 // from the checkpoint as any data dirty in the caches will be lost.
1565
1566 bool bad_checkpoint = true;
1567 SERIALIZE_SCALAR(bad_checkpoint);
1568 }
1569
1570 template<class TagStore>
1571 void
1572 Cache<TagStore>::unserialize(Checkpoint *cp, const std::string &section)
1573 {
1574 bool bad_checkpoint;
1575 UNSERIALIZE_SCALAR(bad_checkpoint);
1576 if (bad_checkpoint) {
1577 fatal("Restoring from checkpoints with caches is not supported in the "
1578 "classic memory system. Please remove any caches before taking "
1579 "checkpoints.\n");
1580 }
1581 }
1582
1583 ///////////////
1584 //
1585 // CpuSidePort
1586 //
1587 ///////////////
1588
1589 template<class TagStore>
1590 AddrRangeList
1591 Cache<TagStore>::CpuSidePort::getAddrRanges()
1592 {
1593 return cache->getAddrRanges();
1594 }
1595
1596 template<class TagStore>
1597 bool
1598 Cache<TagStore>::CpuSidePort::recvTimingReq(PacketPtr pkt)
1599 {
1600 // always let inhibited requests through even if blocked
1601 if (!pkt->memInhibitAsserted() && blocked) {
1602 DPRINTF(Cache,"Scheduling a retry while blocked\n");
1603 mustSendRetry = true;
1604 return false;
1605 }
1606
1607 cache->timingAccess(pkt);
1608 return true;
1609 }
1610
1611 template<class TagStore>
1612 Tick
1613 Cache<TagStore>::CpuSidePort::recvAtomic(PacketPtr pkt)
1614 {
1615 // atomic request
1616 return cache->atomicAccess(pkt);
1617 }
1618
1619 template<class TagStore>
1620 void
1621 Cache<TagStore>::CpuSidePort::recvFunctional(PacketPtr pkt)
1622 {
1623 // functional request
1624 cache->functionalAccess(pkt, true);
1625 }
1626
1627 template<class TagStore>
1628 Cache<TagStore>::
1629 CpuSidePort::CpuSidePort(const std::string &_name, Cache<TagStore> *_cache,
1630 const std::string &_label)
1631 : BaseCache::CacheSlavePort(_name, _cache, _label), cache(_cache)
1632 {
1633 }
1634
1635 ///////////////
1636 //
1637 // MemSidePort
1638 //
1639 ///////////////
1640
1641 template<class TagStore>
1642 bool
1643 Cache<TagStore>::MemSidePort::recvTimingResp(PacketPtr pkt)
1644 {
1645 // this needs to be fixed so that the cache updates the mshr and sends the
1646 // packet back out on the link, but it probably won't happen so until this
1647 // gets fixed, just panic when it does
1648 if (pkt->wasNacked())
1649 panic("Need to implement cache resending nacked packets!\n");
1650
1651 cache->handleResponse(pkt);
1652 return true;
1653 }
1654
1655 // Express snooping requests to memside port
1656 template<class TagStore>
1657 void
1658 Cache<TagStore>::MemSidePort::recvTimingSnoopReq(PacketPtr pkt)
1659 {
1660 // handle snooping requests
1661 cache->snoopTiming(pkt);
1662 }
1663
1664 template<class TagStore>
1665 Tick
1666 Cache<TagStore>::MemSidePort::recvAtomicSnoop(PacketPtr pkt)
1667 {
1668 // atomic snoop
1669 return cache->snoopAtomic(pkt);
1670 }
1671
1672 template<class TagStore>
1673 void
1674 Cache<TagStore>::MemSidePort::recvFunctionalSnoop(PacketPtr pkt)
1675 {
1676 // functional snoop (note that in contrast to atomic we don't have
1677 // a specific functionalSnoop method, as they have the same
1678 // behaviour regardless)
1679 cache->functionalAccess(pkt, false);
1680 }
1681
1682 template<class TagStore>
1683 void
1684 Cache<TagStore>::MemSidePacketQueue::sendDeferredPacket()
1685 {
1686 // if we have a response packet waiting we have to start with that
1687 if (deferredPacketReady()) {
1688 // use the normal approach from the timing port
1689 trySendTiming();
1690 } else {
1691 // check for request packets (requests & writebacks)
1692 PacketPtr pkt = cache.getTimingPacket();
1693 if (pkt == NULL) {
1694 // can happen if e.g. we attempt a writeback and fail, but
1695 // before the retry, the writeback is eliminated because
1696 // we snoop another cache's ReadEx.
1697 waitingOnRetry = false;
1698 } else {
1699 MSHR *mshr = dynamic_cast<MSHR*>(pkt->senderState);
1700
1701 waitingOnRetry = !masterPort.sendTimingReq(pkt);
1702
1703 if (waitingOnRetry) {
1704 DPRINTF(CachePort, "now waiting on a retry\n");
1705 if (!mshr->isForwardNoResponse()) {
1706 // we are awaiting a retry, but we
1707 // delete the packet and will be creating a new packet
1708 // when we get the opportunity
1709 delete pkt;
1710 }
1711 // note that we have now masked any requestBus and
1712 // schedSendEvent (we will wait for a retry before
1713 // doing anything), and this is so even if we do not
1714 // care about this packet and might override it before
1715 // it gets retried
1716 } else {
1717 cache.markInService(mshr, pkt);
1718 }
1719 }
1720 }
1721
1722 // if we succeeded and are not waiting for a retry, schedule the
1723 // next send, not only looking at the response transmit list, but
1724 // also considering when the next MSHR is ready
1725 if (!waitingOnRetry) {
1726 scheduleSend(cache.nextMSHRReadyTime());
1727 }
1728 }
1729
1730 template<class TagStore>
1731 Cache<TagStore>::
1732 MemSidePort::MemSidePort(const std::string &_name, Cache<TagStore> *_cache,
1733 const std::string &_label)
1734 : BaseCache::CacheMasterPort(_name, _cache, _queue),
1735 _queue(*_cache, *this, _label), cache(_cache)
1736 {
1737 }