mem: fix functional accesses to deal with coherence change
[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 (target->pkt->cmd == MemCmd::StoreCondReq &&
904 pkt->cmd == MemCmd::UpgradeFailResp) {
905 // failed StoreCond upgrade
906 completion_time = tags->getHitLatency() + pkt->finishTime;
907 target->pkt->req->setExtraData(0);
908 } else {
909 // not a cache fill, just forwarding response
910 completion_time = tags->getHitLatency() + pkt->finishTime;
911 if (pkt->isRead() && !is_error) {
912 target->pkt->setData(pkt->getPtr<uint8_t>());
913 }
914 }
915 target->pkt->makeTimingResponse();
916 // if this packet is an error copy that to the new packet
917 if (is_error)
918 target->pkt->copyError(pkt);
919 if (target->pkt->cmd == MemCmd::ReadResp &&
920 (pkt->isInvalidate() || mshr->hasPostInvalidate())) {
921 // If intermediate cache got ReadRespWithInvalidate,
922 // propagate that. Response should not have
923 // isInvalidate() set otherwise.
924 target->pkt->cmd = MemCmd::ReadRespWithInvalidate;
925 }
926 cpuSidePort->respond(target->pkt, completion_time);
927 break;
928
929 case MSHR::Target::FromPrefetcher:
930 assert(target->pkt->cmd == MemCmd::HardPFReq);
931 if (blk)
932 blk->status |= BlkHWPrefetched;
933 delete target->pkt->req;
934 delete target->pkt;
935 break;
936
937 case MSHR::Target::FromSnoop:
938 // I don't believe that a snoop can be in an error state
939 assert(!is_error);
940 // response to snoop request
941 DPRINTF(Cache, "processing deferred snoop...\n");
942 assert(!(pkt->isInvalidate() && !mshr->hasPostInvalidate()));
943 handleSnoop(target->pkt, blk, true, true,
944 mshr->hasPostInvalidate());
945 break;
946
947 default:
948 panic("Illegal target->source enum %d\n", target->source);
949 }
950
951 mshr->popTarget();
952 }
953
954 if (blk) {
955 if (pkt->isInvalidate() || mshr->hasPostInvalidate()) {
956 tags->invalidateBlk(blk);
957 } else if (mshr->hasPostDowngrade()) {
958 blk->status &= ~BlkWritable;
959 }
960 }
961
962 if (mshr->promoteDeferredTargets()) {
963 // avoid later read getting stale data while write miss is
964 // outstanding.. see comment in timingAccess()
965 if (blk) {
966 blk->status &= ~BlkReadable;
967 }
968 MSHRQueue *mq = mshr->queue;
969 mq->markPending(mshr);
970 requestMemSideBus((RequestCause)mq->index, pkt->finishTime);
971 } else {
972 mq->deallocate(mshr);
973 if (wasFull && !mq->isFull()) {
974 clearBlocked((BlockedCause)mq->index);
975 }
976 }
977
978 // copy writebacks to write buffer
979 while (!writebacks.empty()) {
980 PacketPtr wbPkt = writebacks.front();
981 allocateWriteBuffer(wbPkt, time, true);
982 writebacks.pop_front();
983 }
984 // if we used temp block, clear it out
985 if (blk == tempBlock) {
986 if (blk->isDirty()) {
987 allocateWriteBuffer(writebackBlk(blk), time, true);
988 }
989 tags->invalidateBlk(blk);
990 }
991
992 delete pkt;
993 }
994
995
996
997
998 template<class TagStore>
999 PacketPtr
1000 Cache<TagStore>::writebackBlk(BlkType *blk)
1001 {
1002 assert(blk && blk->isValid() && blk->isDirty());
1003
1004 writebacks[0/*pkt->req->threadId()*/]++;
1005
1006 Request *writebackReq =
1007 new Request(tags->regenerateBlkAddr(blk->tag, blk->set), blkSize, 0);
1008 PacketPtr writeback = new Packet(writebackReq, MemCmd::Writeback, -1);
1009 writeback->allocate();
1010 std::memcpy(writeback->getPtr<uint8_t>(), blk->data, blkSize);
1011
1012 blk->status &= ~BlkDirty;
1013 return writeback;
1014 }
1015
1016
1017 template<class TagStore>
1018 typename Cache<TagStore>::BlkType*
1019 Cache<TagStore>::allocateBlock(Addr addr, PacketList &writebacks)
1020 {
1021 BlkType *blk = tags->findVictim(addr, writebacks);
1022
1023 if (blk->isValid()) {
1024 Addr repl_addr = tags->regenerateBlkAddr(blk->tag, blk->set);
1025 MSHR *repl_mshr = mshrQueue.findMatch(repl_addr);
1026 if (repl_mshr) {
1027 // must be an outstanding upgrade request on block
1028 // we're about to replace...
1029 assert(!blk->isWritable());
1030 assert(repl_mshr->needsExclusive());
1031 // too hard to replace block with transient state
1032 // allocation failed, block not inserted
1033 return NULL;
1034 } else {
1035 DPRINTF(Cache, "replacement: replacing %x with %x: %s\n",
1036 repl_addr, addr,
1037 blk->isDirty() ? "writeback" : "clean");
1038
1039 if (blk->isDirty()) {
1040 // Save writeback packet for handling by caller
1041 writebacks.push_back(writebackBlk(blk));
1042 }
1043 }
1044 }
1045
1046 return blk;
1047 }
1048
1049
1050 // Note that the reason we return a list of writebacks rather than
1051 // inserting them directly in the write buffer is that this function
1052 // is called by both atomic and timing-mode accesses, and in atomic
1053 // mode we don't mess with the write buffer (we just perform the
1054 // writebacks atomically once the original request is complete).
1055 template<class TagStore>
1056 typename Cache<TagStore>::BlkType*
1057 Cache<TagStore>::handleFill(PacketPtr pkt, BlkType *blk,
1058 PacketList &writebacks)
1059 {
1060 Addr addr = pkt->getAddr();
1061 #if TRACING_ON
1062 CacheBlk::State old_state = blk ? blk->status : 0;
1063 #endif
1064
1065 if (blk == NULL) {
1066 // better have read new data...
1067 assert(pkt->hasData());
1068 // need to do a replacement
1069 blk = allocateBlock(addr, writebacks);
1070 if (blk == NULL) {
1071 // No replaceable block... just use temporary storage to
1072 // complete the current request and then get rid of it
1073 assert(!tempBlock->isValid());
1074 blk = tempBlock;
1075 tempBlock->set = tags->extractSet(addr);
1076 tempBlock->tag = tags->extractTag(addr);
1077 DPRINTF(Cache, "using temp block for %x\n", addr);
1078 } else {
1079 int id = pkt->req->hasContextId() ? pkt->req->contextId() : -1;
1080 tags->insertBlock(pkt->getAddr(), blk, id);
1081 }
1082
1083 // starting from scratch with a new block
1084 blk->status = 0;
1085 } else {
1086 // existing block... probably an upgrade
1087 assert(blk->tag == tags->extractTag(addr));
1088 // either we're getting new data or the block should already be valid
1089 assert(pkt->hasData() || blk->isValid());
1090 // don't clear block status... if block is already dirty we
1091 // don't want to lose that
1092 }
1093
1094 blk->status |= BlkValid | BlkReadable;
1095
1096 if (!pkt->sharedAsserted()) {
1097 blk->status |= BlkWritable;
1098 // If we got this via cache-to-cache transfer (i.e., from a
1099 // cache that was an owner) and took away that owner's copy,
1100 // then we need to write it back. Normally this happens
1101 // anyway as a side effect of getting a copy to write it, but
1102 // there are cases (such as failed store conditionals or
1103 // compare-and-swaps) where we'll demand an exclusive copy but
1104 // end up not writing it.
1105 if (pkt->memInhibitAsserted())
1106 blk->status |= BlkDirty;
1107 }
1108
1109 DPRINTF(Cache, "Block addr %x moving from state %i to %i\n",
1110 addr, old_state, blk->status);
1111
1112 // if we got new data, copy it in
1113 if (pkt->isRead()) {
1114 std::memcpy(blk->data, pkt->getPtr<uint8_t>(), blkSize);
1115 }
1116
1117 blk->whenReady = pkt->finishTime;
1118
1119 return blk;
1120 }
1121
1122
1123 /////////////////////////////////////////////////////
1124 //
1125 // Snoop path: requests coming in from the memory side
1126 //
1127 /////////////////////////////////////////////////////
1128
1129 template<class TagStore>
1130 void
1131 Cache<TagStore>::
1132 doTimingSupplyResponse(PacketPtr req_pkt, uint8_t *blk_data,
1133 bool already_copied, bool pending_inval)
1134 {
1135 // timing-mode snoop responses require a new packet, unless we
1136 // already made a copy...
1137 PacketPtr pkt = already_copied ? req_pkt : new Packet(req_pkt);
1138 assert(req_pkt->isInvalidate() || pkt->sharedAsserted());
1139 pkt->allocate();
1140 pkt->makeTimingResponse();
1141 if (pkt->isRead()) {
1142 pkt->setDataFromBlock(blk_data, blkSize);
1143 }
1144 if (pkt->cmd == MemCmd::ReadResp && pending_inval) {
1145 // Assume we defer a response to a read from a far-away cache
1146 // A, then later defer a ReadExcl from a cache B on the same
1147 // bus as us. We'll assert MemInhibit in both cases, but in
1148 // the latter case MemInhibit will keep the invalidation from
1149 // reaching cache A. This special response tells cache A that
1150 // it gets the block to satisfy its read, but must immediately
1151 // invalidate it.
1152 pkt->cmd = MemCmd::ReadRespWithInvalidate;
1153 }
1154 memSidePort->respond(pkt, curTick + hitLatency);
1155 }
1156
1157 template<class TagStore>
1158 void
1159 Cache<TagStore>::handleSnoop(PacketPtr pkt, BlkType *blk,
1160 bool is_timing, bool is_deferred,
1161 bool pending_inval)
1162 {
1163 // deferred snoops can only happen in timing mode
1164 assert(!(is_deferred && !is_timing));
1165 // pending_inval only makes sense on deferred snoops
1166 assert(!(pending_inval && !is_deferred));
1167 assert(pkt->isRequest());
1168
1169 // the packet may get modified if we or a forwarded snooper
1170 // responds in atomic mode, so remember a few things about the
1171 // original packet up front
1172 bool invalidate = pkt->isInvalidate();
1173 bool M5_VAR_USED needs_exclusive = pkt->needsExclusive();
1174
1175 if (forwardSnoops) {
1176 // first propagate snoop upward to see if anyone above us wants to
1177 // handle it. save & restore packet src since it will get
1178 // rewritten to be relative to cpu-side bus (if any)
1179 bool alreadyResponded = pkt->memInhibitAsserted();
1180 if (is_timing) {
1181 Packet *snoopPkt = new Packet(pkt, true); // clear flags
1182 snoopPkt->setExpressSnoop();
1183 snoopPkt->senderState = new ForwardResponseRecord(pkt, this);
1184 cpuSidePort->sendTiming(snoopPkt);
1185 if (snoopPkt->memInhibitAsserted()) {
1186 // cache-to-cache response from some upper cache
1187 assert(!alreadyResponded);
1188 pkt->assertMemInhibit();
1189 } else {
1190 delete snoopPkt->senderState;
1191 }
1192 if (snoopPkt->sharedAsserted()) {
1193 pkt->assertShared();
1194 }
1195 delete snoopPkt;
1196 } else {
1197 int origSrc = pkt->getSrc();
1198 cpuSidePort->sendAtomic(pkt);
1199 if (!alreadyResponded && pkt->memInhibitAsserted()) {
1200 // cache-to-cache response from some upper cache:
1201 // forward response to original requester
1202 assert(pkt->isResponse());
1203 }
1204 pkt->setSrc(origSrc);
1205 }
1206 }
1207
1208 if (!blk || !blk->isValid()) {
1209 return;
1210 }
1211
1212 // we may end up modifying both the block state and the packet (if
1213 // we respond in atomic mode), so just figure out what to do now
1214 // and then do it later
1215 bool respond = blk->isDirty() && pkt->needsResponse();
1216 bool have_exclusive = blk->isWritable();
1217
1218 if (pkt->isRead() && !invalidate) {
1219 assert(!needs_exclusive);
1220 pkt->assertShared();
1221 int bits_to_clear = BlkWritable;
1222 const bool haveOwnershipState = true; // for now
1223 if (!haveOwnershipState) {
1224 // if we don't support pure ownership (dirty && !writable),
1225 // have to clear dirty bit here, assume memory snarfs data
1226 // on cache-to-cache xfer
1227 bits_to_clear |= BlkDirty;
1228 }
1229 blk->status &= ~bits_to_clear;
1230 }
1231
1232 DPRINTF(Cache, "snooped a %s request for addr %x, %snew state is %i\n",
1233 pkt->cmdString(), blockAlign(pkt->getAddr()),
1234 respond ? "responding, " : "", invalidate ? 0 : blk->status);
1235
1236 if (respond) {
1237 assert(!pkt->memInhibitAsserted());
1238 pkt->assertMemInhibit();
1239 if (have_exclusive) {
1240 pkt->setSupplyExclusive();
1241 }
1242 if (is_timing) {
1243 doTimingSupplyResponse(pkt, blk->data, is_deferred, pending_inval);
1244 } else {
1245 pkt->makeAtomicResponse();
1246 pkt->setDataFromBlock(blk->data, blkSize);
1247 }
1248 } else if (is_timing && is_deferred) {
1249 // if it's a deferred timing snoop then we've made a copy of
1250 // the packet, and so if we're not using that copy to respond
1251 // then we need to delete it here.
1252 delete pkt;
1253 }
1254
1255 // Do this last in case it deallocates block data or something
1256 // like that
1257 if (invalidate) {
1258 tags->invalidateBlk(blk);
1259 }
1260 }
1261
1262
1263 template<class TagStore>
1264 void
1265 Cache<TagStore>::snoopTiming(PacketPtr pkt)
1266 {
1267 // Note that some deferred snoops don't have requests, since the
1268 // original access may have already completed
1269 if ((pkt->req && pkt->req->isUncacheable()) ||
1270 pkt->cmd == MemCmd::Writeback) {
1271 //Can't get a hit on an uncacheable address
1272 //Revisit this for multi level coherence
1273 return;
1274 }
1275
1276 BlkType *blk = tags->findBlock(pkt->getAddr());
1277
1278 Addr blk_addr = blockAlign(pkt->getAddr());
1279 MSHR *mshr = mshrQueue.findMatch(blk_addr);
1280
1281 // Let the MSHR itself track the snoop and decide whether we want
1282 // to go ahead and do the regular cache snoop
1283 if (mshr && mshr->handleSnoop(pkt, order++)) {
1284 DPRINTF(Cache, "Deferring snoop on in-service MSHR to blk %x\n",
1285 blk_addr);
1286 if (mshr->getNumTargets() > numTarget)
1287 warn("allocating bonus target for snoop"); //handle later
1288 return;
1289 }
1290
1291 //We also need to check the writeback buffers and handle those
1292 std::vector<MSHR *> writebacks;
1293 if (writeBuffer.findMatches(blk_addr, writebacks)) {
1294 DPRINTF(Cache, "Snoop hit in writeback to addr: %x\n",
1295 pkt->getAddr());
1296
1297 //Look through writebacks for any non-uncachable writes, use that
1298 for (int i = 0; i < writebacks.size(); i++) {
1299 mshr = writebacks[i];
1300 assert(!mshr->isUncacheable());
1301 assert(mshr->getNumTargets() == 1);
1302 PacketPtr wb_pkt = mshr->getTarget()->pkt;
1303 assert(wb_pkt->cmd == MemCmd::Writeback);
1304
1305 assert(!pkt->memInhibitAsserted());
1306 pkt->assertMemInhibit();
1307 if (!pkt->needsExclusive()) {
1308 pkt->assertShared();
1309 } else {
1310 // if we're not asserting the shared line, we need to
1311 // invalidate our copy. we'll do that below as long as
1312 // the packet's invalidate flag is set...
1313 assert(pkt->isInvalidate());
1314 }
1315 doTimingSupplyResponse(pkt, wb_pkt->getPtr<uint8_t>(),
1316 false, false);
1317
1318 if (pkt->isInvalidate()) {
1319 // Invalidation trumps our writeback... discard here
1320 markInService(mshr);
1321 delete wb_pkt;
1322 }
1323
1324 // If this was a shared writeback, there may still be
1325 // other shared copies above that require invalidation.
1326 // We could be more selective and return here if the
1327 // request is non-exclusive or if the writeback is
1328 // exclusive.
1329 break;
1330 }
1331 }
1332
1333 handleSnoop(pkt, blk, true, false, false);
1334 }
1335
1336
1337 template<class TagStore>
1338 Tick
1339 Cache<TagStore>::snoopAtomic(PacketPtr pkt)
1340 {
1341 if (pkt->req->isUncacheable() || pkt->cmd == MemCmd::Writeback) {
1342 // Can't get a hit on an uncacheable address
1343 // Revisit this for multi level coherence
1344 return hitLatency;
1345 }
1346
1347 BlkType *blk = tags->findBlock(pkt->getAddr());
1348 handleSnoop(pkt, blk, false, false, false);
1349 return hitLatency;
1350 }
1351
1352
1353 template<class TagStore>
1354 MSHR *
1355 Cache<TagStore>::getNextMSHR()
1356 {
1357 // Check both MSHR queue and write buffer for potential requests
1358 MSHR *miss_mshr = mshrQueue.getNextMSHR();
1359 MSHR *write_mshr = writeBuffer.getNextMSHR();
1360
1361 // Now figure out which one to send... some cases are easy
1362 if (miss_mshr && !write_mshr) {
1363 return miss_mshr;
1364 }
1365 if (write_mshr && !miss_mshr) {
1366 return write_mshr;
1367 }
1368
1369 if (miss_mshr && write_mshr) {
1370 // We have one of each... normally we favor the miss request
1371 // unless the write buffer is full
1372 if (writeBuffer.isFull() && writeBuffer.inServiceEntries == 0) {
1373 // Write buffer is full, so we'd like to issue a write;
1374 // need to search MSHR queue for conflicting earlier miss.
1375 MSHR *conflict_mshr =
1376 mshrQueue.findPending(write_mshr->addr, write_mshr->size);
1377
1378 if (conflict_mshr && conflict_mshr->order < write_mshr->order) {
1379 // Service misses in order until conflict is cleared.
1380 return conflict_mshr;
1381 }
1382
1383 // No conflicts; issue write
1384 return write_mshr;
1385 }
1386
1387 // Write buffer isn't full, but need to check it for
1388 // conflicting earlier writeback
1389 MSHR *conflict_mshr =
1390 writeBuffer.findPending(miss_mshr->addr, miss_mshr->size);
1391 if (conflict_mshr) {
1392 // not sure why we don't check order here... it was in the
1393 // original code but commented out.
1394
1395 // The only way this happens is if we are
1396 // doing a write and we didn't have permissions
1397 // then subsequently saw a writeback (owned got evicted)
1398 // We need to make sure to perform the writeback first
1399 // To preserve the dirty data, then we can issue the write
1400
1401 // should we return write_mshr here instead? I.e. do we
1402 // have to flush writes in order? I don't think so... not
1403 // for Alpha anyway. Maybe for x86?
1404 return conflict_mshr;
1405 }
1406
1407 // No conflicts; issue read
1408 return miss_mshr;
1409 }
1410
1411 // fall through... no pending requests. Try a prefetch.
1412 assert(!miss_mshr && !write_mshr);
1413 if (prefetcher && !mshrQueue.isFull()) {
1414 // If we have a miss queue slot, we can try a prefetch
1415 PacketPtr pkt = prefetcher->getPacket();
1416 if (pkt) {
1417 Addr pf_addr = blockAlign(pkt->getAddr());
1418 if (!tags->findBlock(pf_addr) && !mshrQueue.findMatch(pf_addr)) {
1419 // Update statistic on number of prefetches issued
1420 // (hwpf_mshr_misses)
1421 mshr_misses[pkt->cmdToIndex()][0/*pkt->req->threadId()*/]++;
1422 // Don't request bus, since we already have it
1423 return allocateMissBuffer(pkt, curTick, false);
1424 }
1425 }
1426 }
1427
1428 return NULL;
1429 }
1430
1431
1432 template<class TagStore>
1433 PacketPtr
1434 Cache<TagStore>::getTimingPacket()
1435 {
1436 MSHR *mshr = getNextMSHR();
1437
1438 if (mshr == NULL) {
1439 return NULL;
1440 }
1441
1442 // use request from 1st target
1443 PacketPtr tgt_pkt = mshr->getTarget()->pkt;
1444 PacketPtr pkt = NULL;
1445
1446 if (tgt_pkt->cmd == MemCmd::SCUpgradeFailReq) {
1447 // SCUpgradeReq saw invalidation while queued in MSHR, so now
1448 // that we are getting around to processing it, just treat it
1449 // as if we got a failure response
1450 pkt = new Packet(tgt_pkt);
1451 pkt->cmd = MemCmd::UpgradeFailResp;
1452 pkt->senderState = mshr;
1453 pkt->firstWordTime = pkt->finishTime = curTick;
1454 handleResponse(pkt);
1455 return NULL;
1456 } else if (mshr->isForwardNoResponse()) {
1457 // no response expected, just forward packet as it is
1458 assert(tags->findBlock(mshr->addr) == NULL);
1459 pkt = tgt_pkt;
1460 } else {
1461 BlkType *blk = tags->findBlock(mshr->addr);
1462 pkt = getBusPacket(tgt_pkt, blk, mshr->needsExclusive());
1463
1464 mshr->isForward = (pkt == NULL);
1465
1466 if (mshr->isForward) {
1467 // not a cache block request, but a response is expected
1468 // make copy of current packet to forward, keep current
1469 // copy for response handling
1470 pkt = new Packet(tgt_pkt);
1471 pkt->allocate();
1472 if (pkt->isWrite()) {
1473 pkt->setData(tgt_pkt->getPtr<uint8_t>());
1474 }
1475 }
1476 }
1477
1478 assert(pkt != NULL);
1479 pkt->senderState = mshr;
1480 return pkt;
1481 }
1482
1483
1484 template<class TagStore>
1485 Tick
1486 Cache<TagStore>::nextMSHRReadyTime()
1487 {
1488 Tick nextReady = std::min(mshrQueue.nextMSHRReadyTime(),
1489 writeBuffer.nextMSHRReadyTime());
1490
1491 if (prefetcher) {
1492 nextReady = std::min(nextReady,
1493 prefetcher->nextPrefetchReadyTime());
1494 }
1495
1496 return nextReady;
1497 }
1498
1499
1500 ///////////////
1501 //
1502 // CpuSidePort
1503 //
1504 ///////////////
1505
1506 template<class TagStore>
1507 void
1508 Cache<TagStore>::CpuSidePort::
1509 getDeviceAddressRanges(AddrRangeList &resp, bool &snoop)
1510 {
1511 // CPU side port doesn't snoop; it's a target only. It can
1512 // potentially respond to any address.
1513 snoop = false;
1514 resp.push_back(myCache()->getAddrRange());
1515 }
1516
1517
1518 template<class TagStore>
1519 bool
1520 Cache<TagStore>::CpuSidePort::recvTiming(PacketPtr pkt)
1521 {
1522 // illegal to block responses... can lead to deadlock
1523 if (pkt->isRequest() && !pkt->memInhibitAsserted() && blocked) {
1524 DPRINTF(Cache,"Scheduling a retry while blocked\n");
1525 mustSendRetry = true;
1526 return false;
1527 }
1528
1529 myCache()->timingAccess(pkt);
1530 return true;
1531 }
1532
1533
1534 template<class TagStore>
1535 Tick
1536 Cache<TagStore>::CpuSidePort::recvAtomic(PacketPtr pkt)
1537 {
1538 return myCache()->atomicAccess(pkt);
1539 }
1540
1541
1542 template<class TagStore>
1543 void
1544 Cache<TagStore>::CpuSidePort::recvFunctional(PacketPtr pkt)
1545 {
1546 myCache()->functionalAccess(pkt, this, otherPort);
1547 }
1548
1549
1550 template<class TagStore>
1551 Cache<TagStore>::
1552 CpuSidePort::CpuSidePort(const std::string &_name, Cache<TagStore> *_cache,
1553 const std::string &_label)
1554 : BaseCache::CachePort(_name, _cache, _label)
1555 {
1556 }
1557
1558 ///////////////
1559 //
1560 // MemSidePort
1561 //
1562 ///////////////
1563
1564 template<class TagStore>
1565 void
1566 Cache<TagStore>::MemSidePort::
1567 getDeviceAddressRanges(AddrRangeList &resp, bool &snoop)
1568 {
1569 // Memory-side port always snoops, but never passes requests
1570 // through to targets on the cpu side (so we don't add anything to
1571 // the address range list).
1572 snoop = true;
1573 }
1574
1575
1576 template<class TagStore>
1577 bool
1578 Cache<TagStore>::MemSidePort::recvTiming(PacketPtr pkt)
1579 {
1580 // this needs to be fixed so that the cache updates the mshr and sends the
1581 // packet back out on the link, but it probably won't happen so until this
1582 // gets fixed, just panic when it does
1583 if (pkt->wasNacked())
1584 panic("Need to implement cache resending nacked packets!\n");
1585
1586 if (pkt->isRequest() && blocked) {
1587 DPRINTF(Cache,"Scheduling a retry while blocked\n");
1588 mustSendRetry = true;
1589 return false;
1590 }
1591
1592 if (pkt->isResponse()) {
1593 myCache()->handleResponse(pkt);
1594 } else {
1595 myCache()->snoopTiming(pkt);
1596 }
1597 return true;
1598 }
1599
1600
1601 template<class TagStore>
1602 Tick
1603 Cache<TagStore>::MemSidePort::recvAtomic(PacketPtr pkt)
1604 {
1605 // in atomic mode, responses go back to the sender via the
1606 // function return from sendAtomic(), not via a separate
1607 // sendAtomic() from the responder. Thus we should never see a
1608 // response packet in recvAtomic() (anywhere, not just here).
1609 assert(!pkt->isResponse());
1610 return myCache()->snoopAtomic(pkt);
1611 }
1612
1613
1614 template<class TagStore>
1615 void
1616 Cache<TagStore>::MemSidePort::recvFunctional(PacketPtr pkt)
1617 {
1618 myCache()->functionalAccess(pkt, this, otherPort);
1619 }
1620
1621
1622
1623 template<class TagStore>
1624 void
1625 Cache<TagStore>::MemSidePort::sendPacket()
1626 {
1627 // if we have responses that are ready, they take precedence
1628 if (deferredPacketReady()) {
1629 bool success = sendTiming(transmitList.front().pkt);
1630
1631 if (success) {
1632 //send successful, remove packet
1633 transmitList.pop_front();
1634 }
1635
1636 waitingOnRetry = !success;
1637 } else {
1638 // check for non-response packets (requests & writebacks)
1639 PacketPtr pkt = myCache()->getTimingPacket();
1640 if (pkt == NULL) {
1641 // can happen if e.g. we attempt a writeback and fail, but
1642 // before the retry, the writeback is eliminated because
1643 // we snoop another cache's ReadEx.
1644 waitingOnRetry = false;
1645 } else {
1646 MSHR *mshr = dynamic_cast<MSHR*>(pkt->senderState);
1647
1648 bool success = sendTiming(pkt);
1649
1650 waitingOnRetry = !success;
1651 if (waitingOnRetry) {
1652 DPRINTF(CachePort, "now waiting on a retry\n");
1653 if (!mshr->isForwardNoResponse()) {
1654 delete pkt;
1655 }
1656 } else {
1657 myCache()->markInService(mshr, pkt);
1658 }
1659 }
1660 }
1661
1662
1663 // tried to send packet... if it was successful (no retry), see if
1664 // we need to rerequest bus or not
1665 if (!waitingOnRetry) {
1666 Tick nextReady = std::min(deferredPacketReadyTime(),
1667 myCache()->nextMSHRReadyTime());
1668 // @TODO: need to facotr in prefetch requests here somehow
1669 if (nextReady != MaxTick) {
1670 DPRINTF(CachePort, "more packets to send @ %d\n", nextReady);
1671 schedule(sendEvent, std::max(nextReady, curTick + 1));
1672 } else {
1673 // no more to send right now: if we're draining, we may be done
1674 if (drainEvent && !sendEvent->scheduled()) {
1675 drainEvent->process();
1676 drainEvent = NULL;
1677 }
1678 }
1679 }
1680 }
1681
1682 template<class TagStore>
1683 void
1684 Cache<TagStore>::MemSidePort::recvRetry()
1685 {
1686 assert(waitingOnRetry);
1687 sendPacket();
1688 }
1689
1690
1691 template<class TagStore>
1692 void
1693 Cache<TagStore>::MemSidePort::processSendEvent()
1694 {
1695 assert(!waitingOnRetry);
1696 sendPacket();
1697 }
1698
1699
1700 template<class TagStore>
1701 Cache<TagStore>::
1702 MemSidePort::MemSidePort(const std::string &_name, Cache<TagStore> *_cache,
1703 const std::string &_label)
1704 : BaseCache::CachePort(_name, _cache, _label)
1705 {
1706 // override default send event from SimpleTimingPort
1707 delete sendEvent;
1708 sendEvent = new SendEvent(this);
1709 }