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