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