cache.cc (12723:530dc4bf1a00) cache.cc (12724:4f6fac3191d2)
1/*
2 * Copyright (c) 2010-2018 ARM Limited
3 * All rights reserved.
4 *
5 * The license below extends only to copyright in the software and shall
6 * not be construed as granting a license to any other intellectual
7 * property including but not limited to intellectual property relating
8 * to a hardware implementation of the functionality of the software
9 * licensed hereunder. You may use the software subject to the license
10 * terms below provided that you ensure that this notice is replicated
11 * unmodified and in its entirety in all distributions of the software,
12 * modified or unmodified, in source code or in binary form.
13 *
14 * Copyright (c) 2002-2005 The Regents of The University of Michigan
15 * Copyright (c) 2010,2015 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 * Andreas Sandberg
47 * Nikos Nikoleris
48 */
49
50/**
51 * @file
52 * Cache definitions.
53 */
54
55#include "mem/cache/cache.hh"
56
1/*
2 * Copyright (c) 2010-2018 ARM Limited
3 * All rights reserved.
4 *
5 * The license below extends only to copyright in the software and shall
6 * not be construed as granting a license to any other intellectual
7 * property including but not limited to intellectual property relating
8 * to a hardware implementation of the functionality of the software
9 * licensed hereunder. You may use the software subject to the license
10 * terms below provided that you ensure that this notice is replicated
11 * unmodified and in its entirety in all distributions of the software,
12 * modified or unmodified, in source code or in binary form.
13 *
14 * Copyright (c) 2002-2005 The Regents of The University of Michigan
15 * Copyright (c) 2010,2015 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 * Andreas Sandberg
47 * Nikos Nikoleris
48 */
49
50/**
51 * @file
52 * Cache definitions.
53 */
54
55#include "mem/cache/cache.hh"
56
57#include <cassert>
58
59#include "base/compiler.hh"
57#include "base/logging.hh"
60#include "base/logging.hh"
61#include "base/trace.hh"
58#include "base/types.hh"
59#include "debug/Cache.hh"
62#include "base/types.hh"
63#include "debug/Cache.hh"
60#include "debug/CachePort.hh"
61#include "debug/CacheTags.hh"
62#include "debug/CacheVerbose.hh"
64#include "debug/CacheTags.hh"
65#include "debug/CacheVerbose.hh"
66#include "enums/Clusivity.hh"
63#include "mem/cache/blk.hh"
64#include "mem/cache/mshr.hh"
67#include "mem/cache/blk.hh"
68#include "mem/cache/mshr.hh"
65#include "mem/cache/prefetch/base.hh"
66#include "sim/sim_exit.hh"
69#include "mem/cache/tags/base.hh"
70#include "mem/cache/write_queue_entry.hh"
71#include "mem/request.hh"
72#include "params/Cache.hh"
67
68Cache::Cache(const CacheParams *p)
69 : BaseCache(p, p->system->cacheLineSize()),
73
74Cache::Cache(const CacheParams *p)
75 : BaseCache(p, p->system->cacheLineSize()),
70 tags(p->tags),
71 prefetcher(p->prefetcher),
72 doFastWrites(true),
73 prefetchOnAccess(p->prefetch_on_access),
74 clusivity(p->clusivity),
75 writebackClean(p->writeback_clean),
76 tempBlockWriteback(nullptr),
77 writebackTempBlockAtomicEvent([this]{ writebackTempBlockAtomic(); },
78 name(), false,
79 EventBase::Delayed_Writeback_Pri)
76 doFastWrites(true)
80{
77{
81 tempBlock = new CacheBlk();
82 tempBlock->data = new uint8_t[blkSize];
83
84 cpuSidePort = new CpuSidePort(p->name + ".cpu_side", this,
85 "CpuSidePort");
86 memSidePort = new MemSidePort(p->name + ".mem_side", this,
87 "MemSidePort");
88
89 tags->setCache(this);
90 if (prefetcher)
91 prefetcher->setCache(this);
92}
93
78}
79
94Cache::~Cache()
95{
96 delete [] tempBlock->data;
97 delete tempBlock;
98
99 delete cpuSidePort;
100 delete memSidePort;
101}
102
103void
80void
104Cache::regStats()
105{
106 BaseCache::regStats();
107}
108
109void
110Cache::cmpAndSwap(CacheBlk *blk, PacketPtr pkt)
111{
112 assert(pkt->isRequest());
113
114 uint64_t overwrite_val;
115 bool overwrite_mem;
116 uint64_t condition_val64;
117 uint32_t condition_val32;
118
119 int offset = tags->extractBlkOffset(pkt->getAddr());
120 uint8_t *blk_data = blk->data + offset;
121
122 assert(sizeof(uint64_t) >= pkt->getSize());
123
124 overwrite_mem = true;
125 // keep a copy of our possible write value, and copy what is at the
126 // memory address into the packet
127 pkt->writeData((uint8_t *)&overwrite_val);
128 pkt->setData(blk_data);
129
130 if (pkt->req->isCondSwap()) {
131 if (pkt->getSize() == sizeof(uint64_t)) {
132 condition_val64 = pkt->req->getExtraData();
133 overwrite_mem = !std::memcmp(&condition_val64, blk_data,
134 sizeof(uint64_t));
135 } else if (pkt->getSize() == sizeof(uint32_t)) {
136 condition_val32 = (uint32_t)pkt->req->getExtraData();
137 overwrite_mem = !std::memcmp(&condition_val32, blk_data,
138 sizeof(uint32_t));
139 } else
140 panic("Invalid size for conditional read/write\n");
141 }
142
143 if (overwrite_mem) {
144 std::memcpy(blk_data, &overwrite_val, pkt->getSize());
145 blk->status |= BlkDirty;
146 }
147}
148
149
150void
151Cache::satisfyRequest(PacketPtr pkt, CacheBlk *blk,
152 bool deferred_response, bool pending_downgrade)
153{
81Cache::satisfyRequest(PacketPtr pkt, CacheBlk *blk,
82 bool deferred_response, bool pending_downgrade)
83{
154 assert(pkt->isRequest());
84 BaseCache::satisfyRequest(pkt, blk);
155
85
156 assert(blk && blk->isValid());
157 // Occasionally this is not true... if we are a lower-level cache
158 // satisfying a string of Read and ReadEx requests from
159 // upper-level caches, a Read will mark the block as shared but we
160 // can satisfy a following ReadEx anyway since we can rely on the
161 // Read requester(s) to have buffered the ReadEx snoop and to
162 // invalidate their blocks after receiving them.
163 // assert(!pkt->needsWritable() || blk->isWritable());
164 assert(pkt->getOffset(blkSize) + pkt->getSize() <= blkSize);
165
166 // Check RMW operations first since both isRead() and
167 // isWrite() will be true for them
168 if (pkt->cmd == MemCmd::SwapReq) {
169 cmpAndSwap(blk, pkt);
170 } else if (pkt->isWrite()) {
171 // we have the block in a writable state and can go ahead,
172 // note that the line may be also be considered writable in
173 // downstream caches along the path to memory, but always
174 // Exclusive, and never Modified
175 assert(blk->isWritable());
176 // Write or WriteLine at the first cache with block in writable state
177 if (blk->checkWrite(pkt)) {
178 pkt->writeDataToBlock(blk->data, blkSize);
179 }
180 // Always mark the line as dirty (and thus transition to the
181 // Modified state) even if we are a failed StoreCond so we
182 // supply data to any snoops that have appended themselves to
183 // this cache before knowing the store will fail.
184 blk->status |= BlkDirty;
185 DPRINTF(CacheVerbose, "%s for %s (write)\n", __func__, pkt->print());
186 } else if (pkt->isRead()) {
187 if (pkt->isLLSC()) {
188 blk->trackLoadLocked(pkt);
189 }
190
191 // all read responses have a data payload
192 assert(pkt->hasRespData());
193 pkt->setDataFromBlock(blk->data, blkSize);
194
86 if (pkt->isRead()) {
195 // determine if this read is from a (coherent) cache or not
196 if (pkt->fromCache()) {
197 assert(pkt->getSize() == blkSize);
198 // special handling for coherent block requests from
199 // upper-level caches
200 if (pkt->needsWritable()) {
201 // sanity check
202 assert(pkt->cmd == MemCmd::ReadExReq ||
203 pkt->cmd == MemCmd::SCUpgradeFailReq);
204 assert(!pkt->hasSharers());
205
206 // if we have a dirty copy, make sure the recipient
207 // keeps it marked dirty (in the modified state)
208 if (blk->isDirty()) {
209 pkt->setCacheResponding();
210 blk->status &= ~BlkDirty;
211 }
212 } else if (blk->isWritable() && !pending_downgrade &&
213 !pkt->hasSharers() &&
214 pkt->cmd != MemCmd::ReadCleanReq) {
215 // we can give the requester a writable copy on a read
216 // request if:
217 // - we have a writable copy at this level (& below)
218 // - we don't have a pending snoop from below
219 // signaling another read request
220 // - no other cache above has a copy (otherwise it
221 // would have set hasSharers flag when
222 // snooping the packet)
223 // - the read has explicitly asked for a clean
224 // copy of the line
225 if (blk->isDirty()) {
226 // special considerations if we're owner:
227 if (!deferred_response) {
228 // respond with the line in Modified state
229 // (cacheResponding set, hasSharers not set)
230 pkt->setCacheResponding();
231
232 // if this cache is mostly inclusive, we
233 // keep the block in the Exclusive state,
234 // and pass it upwards as Modified
235 // (writable and dirty), hence we have
236 // multiple caches, all on the same path
237 // towards memory, all considering the
238 // same block writable, but only one
239 // considering it Modified
240
241 // we get away with multiple caches (on
242 // the same path to memory) considering
243 // the block writeable as we always enter
244 // the cache hierarchy through a cache,
245 // and first snoop upwards in all other
246 // branches
247 blk->status &= ~BlkDirty;
248 } else {
249 // if we're responding after our own miss,
250 // there's a window where the recipient didn't
251 // know it was getting ownership and may not
252 // have responded to snoops correctly, so we
253 // have to respond with a shared line
254 pkt->setHasSharers();
255 }
256 }
257 } else {
258 // otherwise only respond with a shared copy
259 pkt->setHasSharers();
260 }
261 }
87 // determine if this read is from a (coherent) cache or not
88 if (pkt->fromCache()) {
89 assert(pkt->getSize() == blkSize);
90 // special handling for coherent block requests from
91 // upper-level caches
92 if (pkt->needsWritable()) {
93 // sanity check
94 assert(pkt->cmd == MemCmd::ReadExReq ||
95 pkt->cmd == MemCmd::SCUpgradeFailReq);
96 assert(!pkt->hasSharers());
97
98 // if we have a dirty copy, make sure the recipient
99 // keeps it marked dirty (in the modified state)
100 if (blk->isDirty()) {
101 pkt->setCacheResponding();
102 blk->status &= ~BlkDirty;
103 }
104 } else if (blk->isWritable() && !pending_downgrade &&
105 !pkt->hasSharers() &&
106 pkt->cmd != MemCmd::ReadCleanReq) {
107 // we can give the requester a writable copy on a read
108 // request if:
109 // - we have a writable copy at this level (& below)
110 // - we don't have a pending snoop from below
111 // signaling another read request
112 // - no other cache above has a copy (otherwise it
113 // would have set hasSharers flag when
114 // snooping the packet)
115 // - the read has explicitly asked for a clean
116 // copy of the line
117 if (blk->isDirty()) {
118 // special considerations if we're owner:
119 if (!deferred_response) {
120 // respond with the line in Modified state
121 // (cacheResponding set, hasSharers not set)
122 pkt->setCacheResponding();
123
124 // if this cache is mostly inclusive, we
125 // keep the block in the Exclusive state,
126 // and pass it upwards as Modified
127 // (writable and dirty), hence we have
128 // multiple caches, all on the same path
129 // towards memory, all considering the
130 // same block writable, but only one
131 // considering it Modified
132
133 // we get away with multiple caches (on
134 // the same path to memory) considering
135 // the block writeable as we always enter
136 // the cache hierarchy through a cache,
137 // and first snoop upwards in all other
138 // branches
139 blk->status &= ~BlkDirty;
140 } else {
141 // if we're responding after our own miss,
142 // there's a window where the recipient didn't
143 // know it was getting ownership and may not
144 // have responded to snoops correctly, so we
145 // have to respond with a shared line
146 pkt->setHasSharers();
147 }
148 }
149 } else {
150 // otherwise only respond with a shared copy
151 pkt->setHasSharers();
152 }
153 }
262 } else if (pkt->isUpgrade()) {
263 // sanity check
264 assert(!pkt->hasSharers());
265
266 if (blk->isDirty()) {
267 // we were in the Owned state, and a cache above us that
268 // has the line in Shared state needs to be made aware
269 // that the data it already has is in fact dirty
270 pkt->setCacheResponding();
271 blk->status &= ~BlkDirty;
272 }
273 } else {
274 assert(pkt->isInvalidate());
275 invalidateBlock(blk);
276 DPRINTF(CacheVerbose, "%s for %s (invalidation)\n", __func__,
277 pkt->print());
278 }
279}
280
281/////////////////////////////////////////////////////
282//
283// Access path: requests coming in from the CPU side
284//
285/////////////////////////////////////////////////////
286
287bool
288Cache::access(PacketPtr pkt, CacheBlk *&blk, Cycles &lat,
289 PacketList &writebacks)
290{
154 }
155}
156
157/////////////////////////////////////////////////////
158//
159// Access path: requests coming in from the CPU side
160//
161/////////////////////////////////////////////////////
162
163bool
164Cache::access(PacketPtr pkt, CacheBlk *&blk, Cycles &lat,
165 PacketList &writebacks)
166{
291 // sanity check
292 assert(pkt->isRequest());
293
167
294 chatty_assert(!(isReadOnly && pkt->isWrite()),
295 "Should never see a write in a read-only cache %s\n",
296 name());
168 if (pkt->req->isUncacheable()) {
169 assert(pkt->isRequest());
297
170
298 DPRINTF(CacheVerbose, "%s for %s\n", __func__, pkt->print());
171 chatty_assert(!(isReadOnly && pkt->isWrite()),
172 "Should never see a write in a read-only cache %s\n",
173 name());
299
174
300 if (pkt->req->isUncacheable()) {
301 DPRINTF(Cache, "uncacheable: %s\n", pkt->print());
175 DPRINTF(Cache, "%s for %s\n", __func__, pkt->print());
302
303 // flush and invalidate any existing block
304 CacheBlk *old_blk(tags->findBlock(pkt->getAddr(), pkt->isSecure()));
305 if (old_blk && old_blk->isValid()) {
306 evictBlock(old_blk, writebacks);
307 }
308
309 blk = nullptr;
310 // lookupLatency is the latency in case the request is uncacheable.
311 lat = lookupLatency;
312 return false;
313 }
314
176
177 // flush and invalidate any existing block
178 CacheBlk *old_blk(tags->findBlock(pkt->getAddr(), pkt->isSecure()));
179 if (old_blk && old_blk->isValid()) {
180 evictBlock(old_blk, writebacks);
181 }
182
183 blk = nullptr;
184 // lookupLatency is the latency in case the request is uncacheable.
185 lat = lookupLatency;
186 return false;
187 }
188
315 // Here lat is the value passed as parameter to accessBlock() function
316 // that can modify its value.
317 blk = tags->accessBlock(pkt->getAddr(), pkt->isSecure(), lat);
318
319 DPRINTF(Cache, "%s %s\n", pkt->print(),
320 blk ? "hit " + blk->print() : "miss");
321
322 if (pkt->req->isCacheMaintenance()) {
323 // A cache maintenance operation is always forwarded to the
324 // memory below even if the block is found in dirty state.
325
326 // We defer any changes to the state of the block until we
327 // create and mark as in service the mshr for the downstream
328 // packet.
329 return false;
330 }
331
332 if (pkt->isEviction()) {
333 // We check for presence of block in above caches before issuing
334 // Writeback or CleanEvict to write buffer. Therefore the only
335 // possible cases can be of a CleanEvict packet coming from above
336 // encountering a Writeback generated in this cache peer cache and
337 // waiting in the write buffer. Cases of upper level peer caches
338 // generating CleanEvict and Writeback or simply CleanEvict and
339 // CleanEvict almost simultaneously will be caught by snoops sent out
340 // by crossbar.
341 WriteQueueEntry *wb_entry = writeBuffer.findMatch(pkt->getAddr(),
342 pkt->isSecure());
343 if (wb_entry) {
344 assert(wb_entry->getNumTargets() == 1);
345 PacketPtr wbPkt = wb_entry->getTarget()->pkt;
346 assert(wbPkt->isWriteback());
347
348 if (pkt->isCleanEviction()) {
349 // The CleanEvict and WritebackClean snoops into other
350 // peer caches of the same level while traversing the
351 // crossbar. If a copy of the block is found, the
352 // packet is deleted in the crossbar. Hence, none of
353 // the other upper level caches connected to this
354 // cache have the block, so we can clear the
355 // BLOCK_CACHED flag in the Writeback if set and
356 // discard the CleanEvict by returning true.
357 wbPkt->clearBlockCached();
358 return true;
359 } else {
360 assert(pkt->cmd == MemCmd::WritebackDirty);
361 // Dirty writeback from above trumps our clean
362 // writeback... discard here
363 // Note: markInService will remove entry from writeback buffer.
364 markInService(wb_entry);
365 delete wbPkt;
366 }
367 }
368 }
369
370 // Writeback handling is special case. We can write the block into
371 // the cache without having a writeable copy (or any copy at all).
372 if (pkt->isWriteback()) {
373 assert(blkSize == pkt->getSize());
374
375 // we could get a clean writeback while we are having
376 // outstanding accesses to a block, do the simple thing for
377 // now and drop the clean writeback so that we do not upset
378 // any ordering/decisions about ownership already taken
379 if (pkt->cmd == MemCmd::WritebackClean &&
380 mshrQueue.findMatch(pkt->getAddr(), pkt->isSecure())) {
381 DPRINTF(Cache, "Clean writeback %#llx to block with MSHR, "
382 "dropping\n", pkt->getAddr());
383 return true;
384 }
385
386 if (blk == nullptr) {
387 // need to do a replacement
388 blk = allocateBlock(pkt->getAddr(), pkt->isSecure(), writebacks);
389 if (blk == nullptr) {
390 // no replaceable block available: give up, fwd to next level.
391 incMissCount(pkt);
392 return false;
393 }
394 tags->insertBlock(pkt, blk);
395
396 blk->status |= (BlkValid | BlkReadable);
397 }
398 // only mark the block dirty if we got a writeback command,
399 // and leave it as is for a clean writeback
400 if (pkt->cmd == MemCmd::WritebackDirty) {
401 assert(!blk->isDirty());
402 blk->status |= BlkDirty;
403 }
404 // if the packet does not have sharers, it is passing
405 // writable, and we got the writeback in Modified or Exclusive
406 // state, if not we are in the Owned or Shared state
407 if (!pkt->hasSharers()) {
408 blk->status |= BlkWritable;
409 }
410 // nothing else to do; writeback doesn't expect response
411 assert(!pkt->needsResponse());
412 pkt->writeDataToBlock(blk->data, blkSize);
413 DPRINTF(Cache, "%s new state is %s\n", __func__, blk->print());
414 incHitCount(pkt);
415 // populate the time when the block will be ready to access.
416 blk->whenReady = clockEdge(fillLatency) + pkt->headerDelay +
417 pkt->payloadDelay;
418 return true;
419 } else if (pkt->cmd == MemCmd::CleanEvict) {
420 if (blk != nullptr) {
421 // Found the block in the tags, need to stop CleanEvict from
422 // propagating further down the hierarchy. Returning true will
423 // treat the CleanEvict like a satisfied write request and delete
424 // it.
425 return true;
426 }
427 // We didn't find the block here, propagate the CleanEvict further
428 // down the memory hierarchy. Returning false will treat the CleanEvict
429 // like a Writeback which could not find a replaceable block so has to
430 // go to next level.
431 return false;
432 } else if (pkt->cmd == MemCmd::WriteClean) {
433 // WriteClean handling is a special case. We can allocate a
434 // block directly if it doesn't exist and we can update the
435 // block immediately. The WriteClean transfers the ownership
436 // of the block as well.
437 assert(blkSize == pkt->getSize());
438
439 if (!blk) {
440 if (pkt->writeThrough()) {
441 // if this is a write through packet, we don't try to
442 // allocate if the block is not present
443 return false;
444 } else {
445 // a writeback that misses needs to allocate a new block
446 blk = allocateBlock(pkt->getAddr(), pkt->isSecure(),
447 writebacks);
448 if (!blk) {
449 // no replaceable block available: give up, fwd to
450 // next level.
451 incMissCount(pkt);
452 return false;
453 }
454 tags->insertBlock(pkt, blk);
455
456 blk->status |= (BlkValid | BlkReadable);
457 }
458 }
459
460 // at this point either this is a writeback or a write-through
461 // write clean operation and the block is already in this
462 // cache, we need to update the data and the block flags
463 assert(blk);
464 assert(!blk->isDirty());
465 if (!pkt->writeThrough()) {
466 blk->status |= BlkDirty;
467 }
468 // nothing else to do; writeback doesn't expect response
469 assert(!pkt->needsResponse());
470 pkt->writeDataToBlock(blk->data, blkSize);
471 DPRINTF(Cache, "%s new state is %s\n", __func__, blk->print());
472
473 incHitCount(pkt);
474 // populate the time when the block will be ready to access.
475 blk->whenReady = clockEdge(fillLatency) + pkt->headerDelay +
476 pkt->payloadDelay;
477 // if this a write-through packet it will be sent to cache
478 // below
479 return !pkt->writeThrough();
480 } else if (blk && (pkt->needsWritable() ? blk->isWritable() :
481 blk->isReadable())) {
482 // OK to satisfy access
483 incHitCount(pkt);
484 satisfyRequest(pkt, blk);
485 maintainClusivity(pkt->fromCache(), blk);
486
487 return true;
488 }
489
490 // Can't satisfy access normally... either no block (blk == nullptr)
491 // or have block but need writable
492
493 incMissCount(pkt);
494
495 if (blk == nullptr && pkt->isLLSC() && pkt->isWrite()) {
496 // complete miss on store conditional... just give up now
497 pkt->req->setExtraData(0);
498 return true;
499 }
500
501 return false;
189 return BaseCache::access(pkt, blk, lat, writebacks);
502}
503
504void
190}
191
192void
505Cache::maintainClusivity(bool from_cache, CacheBlk *blk)
506{
507 if (from_cache && blk && blk->isValid() && !blk->isDirty() &&
508 clusivity == Enums::mostly_excl) {
509 // if we have responded to a cache, and our block is still
510 // valid, but not dirty, and this cache is mostly exclusive
511 // with respect to the cache above, drop the block
512 invalidateBlock(blk);
513 }
514}
515
516void
517Cache::doWritebacks(PacketList& writebacks, Tick forward_time)
518{
519 while (!writebacks.empty()) {
520 PacketPtr wbPkt = writebacks.front();
521 // We use forwardLatency here because we are copying writebacks to
522 // write buffer.
523
524 // Call isCachedAbove for Writebacks, CleanEvicts and
525 // WriteCleans to discover if the block is cached above.
526 if (isCachedAbove(wbPkt)) {
527 if (wbPkt->cmd == MemCmd::CleanEvict) {
528 // Delete CleanEvict because cached copies exist above. The
529 // packet destructor will delete the request object because
530 // this is a non-snoop request packet which does not require a
531 // response.
532 delete wbPkt;
533 } else if (wbPkt->cmd == MemCmd::WritebackClean) {
534 // clean writeback, do not send since the block is
535 // still cached above
536 assert(writebackClean);
537 delete wbPkt;
538 } else {
539 assert(wbPkt->cmd == MemCmd::WritebackDirty ||
540 wbPkt->cmd == MemCmd::WriteClean);
541 // Set BLOCK_CACHED flag in Writeback and send below, so that
542 // the Writeback does not reset the bit corresponding to this
543 // address in the snoop filter below.
544 wbPkt->setBlockCached();
545 allocateWriteBuffer(wbPkt, forward_time);
546 }
547 } else {
548 // If the block is not cached above, send packet below. Both
549 // CleanEvict and Writeback with BLOCK_CACHED flag cleared will
550 // reset the bit corresponding to this address in the snoop filter
551 // below.
552 allocateWriteBuffer(wbPkt, forward_time);
553 }
554 writebacks.pop_front();
555 }
556}
557
558void
559Cache::doWritebacksAtomic(PacketList& writebacks)
560{
561 while (!writebacks.empty()) {
562 PacketPtr wbPkt = writebacks.front();
563 // Call isCachedAbove for both Writebacks and CleanEvicts. If
564 // isCachedAbove returns true we set BLOCK_CACHED flag in Writebacks
565 // and discard CleanEvicts.
566 if (isCachedAbove(wbPkt, false)) {
567 if (wbPkt->cmd == MemCmd::WritebackDirty ||
568 wbPkt->cmd == MemCmd::WriteClean) {
569 // Set BLOCK_CACHED flag in Writeback and send below,
570 // so that the Writeback does not reset the bit
571 // corresponding to this address in the snoop filter
572 // below. We can discard CleanEvicts because cached
573 // copies exist above. Atomic mode isCachedAbove
574 // modifies packet to set BLOCK_CACHED flag
193Cache::doWritebacks(PacketList& writebacks, Tick forward_time)
194{
195 while (!writebacks.empty()) {
196 PacketPtr wbPkt = writebacks.front();
197 // We use forwardLatency here because we are copying writebacks to
198 // write buffer.
199
200 // Call isCachedAbove for Writebacks, CleanEvicts and
201 // WriteCleans to discover if the block is cached above.
202 if (isCachedAbove(wbPkt)) {
203 if (wbPkt->cmd == MemCmd::CleanEvict) {
204 // Delete CleanEvict because cached copies exist above. The
205 // packet destructor will delete the request object because
206 // this is a non-snoop request packet which does not require a
207 // response.
208 delete wbPkt;
209 } else if (wbPkt->cmd == MemCmd::WritebackClean) {
210 // clean writeback, do not send since the block is
211 // still cached above
212 assert(writebackClean);
213 delete wbPkt;
214 } else {
215 assert(wbPkt->cmd == MemCmd::WritebackDirty ||
216 wbPkt->cmd == MemCmd::WriteClean);
217 // Set BLOCK_CACHED flag in Writeback and send below, so that
218 // the Writeback does not reset the bit corresponding to this
219 // address in the snoop filter below.
220 wbPkt->setBlockCached();
221 allocateWriteBuffer(wbPkt, forward_time);
222 }
223 } else {
224 // If the block is not cached above, send packet below. Both
225 // CleanEvict and Writeback with BLOCK_CACHED flag cleared will
226 // reset the bit corresponding to this address in the snoop filter
227 // below.
228 allocateWriteBuffer(wbPkt, forward_time);
229 }
230 writebacks.pop_front();
231 }
232}
233
234void
235Cache::doWritebacksAtomic(PacketList& writebacks)
236{
237 while (!writebacks.empty()) {
238 PacketPtr wbPkt = writebacks.front();
239 // Call isCachedAbove for both Writebacks and CleanEvicts. If
240 // isCachedAbove returns true we set BLOCK_CACHED flag in Writebacks
241 // and discard CleanEvicts.
242 if (isCachedAbove(wbPkt, false)) {
243 if (wbPkt->cmd == MemCmd::WritebackDirty ||
244 wbPkt->cmd == MemCmd::WriteClean) {
245 // Set BLOCK_CACHED flag in Writeback and send below,
246 // so that the Writeback does not reset the bit
247 // corresponding to this address in the snoop filter
248 // below. We can discard CleanEvicts because cached
249 // copies exist above. Atomic mode isCachedAbove
250 // modifies packet to set BLOCK_CACHED flag
575 memSidePort->sendAtomic(wbPkt);
251 memSidePort.sendAtomic(wbPkt);
576 }
577 } else {
578 // If the block is not cached above, send packet below. Both
579 // CleanEvict and Writeback with BLOCK_CACHED flag cleared will
580 // reset the bit corresponding to this address in the snoop filter
581 // below.
252 }
253 } else {
254 // If the block is not cached above, send packet below. Both
255 // CleanEvict and Writeback with BLOCK_CACHED flag cleared will
256 // reset the bit corresponding to this address in the snoop filter
257 // below.
582 memSidePort->sendAtomic(wbPkt);
258 memSidePort.sendAtomic(wbPkt);
583 }
584 writebacks.pop_front();
585 // In case of CleanEvicts, the packet destructor will delete the
586 // request object because this is a non-snoop request packet which
587 // does not require a response.
588 delete wbPkt;
589 }
590}
591
592
593void
594Cache::recvTimingSnoopResp(PacketPtr pkt)
595{
596 DPRINTF(Cache, "%s for %s\n", __func__, pkt->print());
597
598 assert(pkt->isResponse());
599 assert(!system->bypassCaches());
600
601 // determine if the response is from a snoop request we created
602 // (in which case it should be in the outstandingSnoop), or if we
603 // merely forwarded someone else's snoop request
604 const bool forwardAsSnoop = outstandingSnoop.find(pkt->req) ==
605 outstandingSnoop.end();
606
607 if (!forwardAsSnoop) {
608 // the packet came from this cache, so sink it here and do not
609 // forward it
610 assert(pkt->cmd == MemCmd::HardPFResp);
611
612 outstandingSnoop.erase(pkt->req);
613
614 DPRINTF(Cache, "Got prefetch response from above for addr "
615 "%#llx (%s)\n", pkt->getAddr(), pkt->isSecure() ? "s" : "ns");
616 recvTimingResp(pkt);
617 return;
618 }
619
620 // forwardLatency is set here because there is a response from an
621 // upper level cache.
622 // To pay the delay that occurs if the packet comes from the bus,
623 // we charge also headerDelay.
624 Tick snoop_resp_time = clockEdge(forwardLatency) + pkt->headerDelay;
625 // Reset the timing of the packet.
626 pkt->headerDelay = pkt->payloadDelay = 0;
259 }
260 writebacks.pop_front();
261 // In case of CleanEvicts, the packet destructor will delete the
262 // request object because this is a non-snoop request packet which
263 // does not require a response.
264 delete wbPkt;
265 }
266}
267
268
269void
270Cache::recvTimingSnoopResp(PacketPtr pkt)
271{
272 DPRINTF(Cache, "%s for %s\n", __func__, pkt->print());
273
274 assert(pkt->isResponse());
275 assert(!system->bypassCaches());
276
277 // determine if the response is from a snoop request we created
278 // (in which case it should be in the outstandingSnoop), or if we
279 // merely forwarded someone else's snoop request
280 const bool forwardAsSnoop = outstandingSnoop.find(pkt->req) ==
281 outstandingSnoop.end();
282
283 if (!forwardAsSnoop) {
284 // the packet came from this cache, so sink it here and do not
285 // forward it
286 assert(pkt->cmd == MemCmd::HardPFResp);
287
288 outstandingSnoop.erase(pkt->req);
289
290 DPRINTF(Cache, "Got prefetch response from above for addr "
291 "%#llx (%s)\n", pkt->getAddr(), pkt->isSecure() ? "s" : "ns");
292 recvTimingResp(pkt);
293 return;
294 }
295
296 // forwardLatency is set here because there is a response from an
297 // upper level cache.
298 // To pay the delay that occurs if the packet comes from the bus,
299 // we charge also headerDelay.
300 Tick snoop_resp_time = clockEdge(forwardLatency) + pkt->headerDelay;
301 // Reset the timing of the packet.
302 pkt->headerDelay = pkt->payloadDelay = 0;
627 memSidePort->schedTimingSnoopResp(pkt, snoop_resp_time);
303 memSidePort.schedTimingSnoopResp(pkt, snoop_resp_time);
628}
629
630void
631Cache::promoteWholeLineWrites(PacketPtr pkt)
632{
633 // Cache line clearing instructions
634 if (doFastWrites && (pkt->cmd == MemCmd::WriteReq) &&
635 (pkt->getSize() == blkSize) && (pkt->getOffset(blkSize) == 0)) {
636 pkt->cmd = MemCmd::WriteLineReq;
637 DPRINTF(Cache, "packet promoted from Write to WriteLineReq\n");
638 }
639}
640
641void
642Cache::handleTimingReqHit(PacketPtr pkt, CacheBlk *blk, Tick request_time)
643{
644 // should never be satisfying an uncacheable access as we
645 // flush and invalidate any existing block as part of the
646 // lookup
647 assert(!pkt->req->isUncacheable());
648
304}
305
306void
307Cache::promoteWholeLineWrites(PacketPtr pkt)
308{
309 // Cache line clearing instructions
310 if (doFastWrites && (pkt->cmd == MemCmd::WriteReq) &&
311 (pkt->getSize() == blkSize) && (pkt->getOffset(blkSize) == 0)) {
312 pkt->cmd = MemCmd::WriteLineReq;
313 DPRINTF(Cache, "packet promoted from Write to WriteLineReq\n");
314 }
315}
316
317void
318Cache::handleTimingReqHit(PacketPtr pkt, CacheBlk *blk, Tick request_time)
319{
320 // should never be satisfying an uncacheable access as we
321 // flush and invalidate any existing block as part of the
322 // lookup
323 assert(!pkt->req->isUncacheable());
324
649 if (pkt->needsResponse()) {
650 pkt->makeTimingResponse();
651 // @todo: Make someone pay for this
652 pkt->headerDelay = pkt->payloadDelay = 0;
653
654 // In this case we are considering request_time that takes
655 // into account the delay of the xbar, if any, and just
656 // lat, neglecting responseLatency, modelling hit latency
657 // just as lookupLatency or or the value of lat overriden
658 // by access(), that calls accessBlock() function.
659 cpuSidePort->schedTimingResp(pkt, request_time, true);
660 } else {
661 DPRINTF(Cache, "%s satisfied %s, no response needed\n", __func__,
662 pkt->print());
663
664 // queue the packet for deletion, as the sending cache is
665 // still relying on it; if the block is found in access(),
666 // CleanEvict and Writeback messages will be deleted
667 // here as well
668 pendingDelete.reset(pkt);
669 }
325 BaseCache::handleTimingReqHit(pkt, blk, request_time);
670}
671
672void
673Cache::handleTimingReqMiss(PacketPtr pkt, CacheBlk *blk, Tick forward_time,
674 Tick request_time)
675{
326}
327
328void
329Cache::handleTimingReqMiss(PacketPtr pkt, CacheBlk *blk, Tick forward_time,
330 Tick request_time)
331{
332 if (pkt->req->isUncacheable()) {
333 // ignore any existing MSHR if we are dealing with an
334 // uncacheable request
335
336 // should have flushed and have no valid block
337 assert(!blk || !blk->isValid());
338
339 mshr_uncacheable[pkt->cmdToIndex()][pkt->req->masterId()]++;
340
341 if (pkt->isWrite()) {
342 allocateWriteBuffer(pkt, forward_time);
343 } else {
344 assert(pkt->isRead());
345
346 // uncacheable accesses always allocate a new MSHR
347
348 // Here we are using forward_time, modelling the latency of
349 // a miss (outbound) just as forwardLatency, neglecting the
350 // lookupLatency component.
351 allocateMissBuffer(pkt, forward_time);
352 }
353
354 return;
355 }
356
676 Addr blk_addr = pkt->getBlockAddr(blkSize);
677
357 Addr blk_addr = pkt->getBlockAddr(blkSize);
358
678 // ignore any existing MSHR if we are dealing with an
679 // uncacheable request
680 MSHR *mshr = pkt->req->isUncacheable() ? nullptr :
681 mshrQueue.findMatch(blk_addr, pkt->isSecure());
359 MSHR *mshr = mshrQueue.findMatch(blk_addr, pkt->isSecure());
682
683 // Software prefetch handling:
684 // To keep the core from waiting on data it won't look at
685 // anyway, send back a response with dummy data. Miss handling
686 // will continue asynchronously. Unfortunately, the core will
687 // insist upon freeing original Packet/Request, so we have to
688 // create a new pair with a different lifecycle. Note that this
689 // processing happens before any MSHR munging on the behalf of
690 // this request because this new Request will be the one stored
691 // into the MSHRs, not the original.
692 if (pkt->cmd.isSWPrefetch()) {
693 assert(pkt->needsResponse());
694 assert(pkt->req->hasPaddr());
695 assert(!pkt->req->isUncacheable());
696
697 // There's no reason to add a prefetch as an additional target
698 // to an existing MSHR. If an outstanding request is already
699 // in progress, there is nothing for the prefetch to do.
700 // If this is the case, we don't even create a request at all.
701 PacketPtr pf = nullptr;
702
703 if (!mshr) {
704 // copy the request and create a new SoftPFReq packet
705 RequestPtr req = new Request(pkt->req->getPaddr(),
706 pkt->req->getSize(),
707 pkt->req->getFlags(),
708 pkt->req->masterId());
709 pf = new Packet(req, pkt->cmd);
710 pf->allocate();
711 assert(pf->getAddr() == pkt->getAddr());
712 assert(pf->getSize() == pkt->getSize());
713 }
714
715 pkt->makeTimingResponse();
716
717 // request_time is used here, taking into account lat and the delay
718 // charged if the packet comes from the xbar.
360
361 // Software prefetch handling:
362 // To keep the core from waiting on data it won't look at
363 // anyway, send back a response with dummy data. Miss handling
364 // will continue asynchronously. Unfortunately, the core will
365 // insist upon freeing original Packet/Request, so we have to
366 // create a new pair with a different lifecycle. Note that this
367 // processing happens before any MSHR munging on the behalf of
368 // this request because this new Request will be the one stored
369 // into the MSHRs, not the original.
370 if (pkt->cmd.isSWPrefetch()) {
371 assert(pkt->needsResponse());
372 assert(pkt->req->hasPaddr());
373 assert(!pkt->req->isUncacheable());
374
375 // There's no reason to add a prefetch as an additional target
376 // to an existing MSHR. If an outstanding request is already
377 // in progress, there is nothing for the prefetch to do.
378 // If this is the case, we don't even create a request at all.
379 PacketPtr pf = nullptr;
380
381 if (!mshr) {
382 // copy the request and create a new SoftPFReq packet
383 RequestPtr req = new Request(pkt->req->getPaddr(),
384 pkt->req->getSize(),
385 pkt->req->getFlags(),
386 pkt->req->masterId());
387 pf = new Packet(req, pkt->cmd);
388 pf->allocate();
389 assert(pf->getAddr() == pkt->getAddr());
390 assert(pf->getSize() == pkt->getSize());
391 }
392
393 pkt->makeTimingResponse();
394
395 // request_time is used here, taking into account lat and the delay
396 // charged if the packet comes from the xbar.
719 cpuSidePort->schedTimingResp(pkt, request_time, true);
397 cpuSidePort.schedTimingResp(pkt, request_time, true);
720
721 // If an outstanding request is in progress (we found an
722 // MSHR) this is set to null
723 pkt = pf;
724 }
725
398
399 // If an outstanding request is in progress (we found an
400 // MSHR) this is set to null
401 pkt = pf;
402 }
403
726 if (mshr) {
727 /// MSHR hit
728 /// @note writebacks will be checked in getNextMSHR()
729 /// for any conflicting requests to the same block
730
731 //@todo remove hw_pf here
732
733 // Coalesce unless it was a software prefetch (see above).
734 if (pkt) {
735 assert(!pkt->isWriteback());
736 // CleanEvicts corresponding to blocks which have
737 // outstanding requests in MSHRs are simply sunk here
738 if (pkt->cmd == MemCmd::CleanEvict) {
739 pendingDelete.reset(pkt);
740 } else if (pkt->cmd == MemCmd::WriteClean) {
741 // A WriteClean should never coalesce with any
742 // outstanding cache maintenance requests.
743
744 // We use forward_time here because there is an
745 // uncached memory write, forwarded to WriteBuffer.
746 allocateWriteBuffer(pkt, forward_time);
747 } else {
748 DPRINTF(Cache, "%s coalescing MSHR for %s\n", __func__,
749 pkt->print());
750
751 assert(pkt->req->masterId() < system->maxMasters());
752 mshr_hits[pkt->cmdToIndex()][pkt->req->masterId()]++;
753
754 // uncacheable accesses always allocate a new
755 // MSHR, and cacheable accesses ignore any
756 // uncacheable MSHRs, thus we should never have
757 // targets addded if originally allocated
758 // uncacheable
759 assert(!mshr->isUncacheable());
760
761 // We use forward_time here because it is the same
762 // considering new targets. We have multiple
763 // requests for the same address here. It
764 // specifies the latency to allocate an internal
765 // buffer and to schedule an event to the queued
766 // port and also takes into account the additional
767 // delay of the xbar.
768 mshr->allocateTarget(pkt, forward_time, order++,
769 allocOnFill(pkt->cmd));
770 if (mshr->getNumTargets() == numTarget) {
771 noTargetMSHR = mshr;
772 setBlocked(Blocked_NoTargets);
773 // need to be careful with this... if this mshr isn't
774 // ready yet (i.e. time > curTick()), we don't want to
775 // move it ahead of mshrs that are ready
776 // mshrQueue.moveToFront(mshr);
777 }
778 }
779 }
780 } else {
781 // no MSHR
782 assert(pkt->req->masterId() < system->maxMasters());
783 if (pkt->req->isUncacheable()) {
784 mshr_uncacheable[pkt->cmdToIndex()][pkt->req->masterId()]++;
785 } else {
786 mshr_misses[pkt->cmdToIndex()][pkt->req->masterId()]++;
787 }
788
789 if (pkt->isEviction() || pkt->cmd == MemCmd::WriteClean ||
790 (pkt->req->isUncacheable() && pkt->isWrite())) {
791 // We use forward_time here because there is an
792 // uncached memory write, forwarded to WriteBuffer.
793 allocateWriteBuffer(pkt, forward_time);
794 } else {
795 if (blk && blk->isValid()) {
796 // should have flushed and have no valid block
797 assert(!pkt->req->isUncacheable());
798
799 // If we have a write miss to a valid block, we
800 // need to mark the block non-readable. Otherwise
801 // if we allow reads while there's an outstanding
802 // write miss, the read could return stale data
803 // out of the cache block... a more aggressive
804 // system could detect the overlap (if any) and
805 // forward data out of the MSHRs, but we don't do
806 // that yet. Note that we do need to leave the
807 // block valid so that it stays in the cache, in
808 // case we get an upgrade response (and hence no
809 // new data) when the write miss completes.
810 // As long as CPUs do proper store/load forwarding
811 // internally, and have a sufficiently weak memory
812 // model, this is probably unnecessary, but at some
813 // point it must have seemed like we needed it...
814 assert((pkt->needsWritable() && !blk->isWritable()) ||
815 pkt->req->isCacheMaintenance());
816 blk->status &= ~BlkReadable;
817 }
818 // Here we are using forward_time, modelling the latency of
819 // a miss (outbound) just as forwardLatency, neglecting the
820 // lookupLatency component.
821 allocateMissBuffer(pkt, forward_time);
822 }
823 }
404 BaseCache::handleTimingReqMiss(pkt, mshr, blk, forward_time, request_time);
824}
825
826void
827Cache::recvTimingReq(PacketPtr pkt)
828{
829 DPRINTF(CacheTags, "%s tags:\n%s\n", __func__, tags->print());
830
831 assert(pkt->isRequest());
832
833 // Just forward the packet if caches are disabled.
834 if (system->bypassCaches()) {
835 // @todo This should really enqueue the packet rather
405}
406
407void
408Cache::recvTimingReq(PacketPtr pkt)
409{
410 DPRINTF(CacheTags, "%s tags:\n%s\n", __func__, tags->print());
411
412 assert(pkt->isRequest());
413
414 // Just forward the packet if caches are disabled.
415 if (system->bypassCaches()) {
416 // @todo This should really enqueue the packet rather
836 bool M5_VAR_USED success = memSidePort->sendTimingReq(pkt);
417 bool M5_VAR_USED success = memSidePort.sendTimingReq(pkt);
837 assert(success);
838 return;
839 }
840
841 promoteWholeLineWrites(pkt);
842
418 assert(success);
419 return;
420 }
421
422 promoteWholeLineWrites(pkt);
423
843 // Cache maintenance operations have to visit all the caches down
844 // to the specified xbar (PoC, PoU, etc.). Even if a cache above
845 // is responding we forward the packet to the memory below rather
846 // than creating an express snoop.
847 if (pkt->cacheResponding()) {
848 // a cache above us (but not where the packet came from) is
849 // responding to the request, in other words it has the line
850 // in Modified or Owned state
851 DPRINTF(Cache, "Cache above responding to %s: not responding\n",
852 pkt->print());
853
854 // if the packet needs the block to be writable, and the cache
855 // that has promised to respond (setting the cache responding
856 // flag) is not providing writable (it is in Owned rather than
857 // the Modified state), we know that there may be other Shared
858 // copies in the system; go out and invalidate them all
859 assert(pkt->needsWritable() && !pkt->responderHadWritable());
860
861 // an upstream cache that had the line in Owned state
862 // (dirty, but not writable), is responding and thus
863 // transferring the dirty line from one branch of the
864 // cache hierarchy to another
865
866 // send out an express snoop and invalidate all other
867 // copies (snooping a packet that needs writable is the
868 // same as an invalidation), thus turning the Owned line
869 // into a Modified line, note that we don't invalidate the
870 // block in the current cache or any other cache on the
871 // path to memory
872
873 // create a downstream express snoop with cleared packet
874 // flags, there is no need to allocate any data as the
875 // packet is merely used to co-ordinate state transitions
876 Packet *snoop_pkt = new Packet(pkt, true, false);
877
878 // also reset the bus time that the original packet has
879 // not yet paid for
880 snoop_pkt->headerDelay = snoop_pkt->payloadDelay = 0;
881
882 // make this an instantaneous express snoop, and let the
883 // other caches in the system know that the another cache
884 // is responding, because we have found the authorative
885 // copy (Modified or Owned) that will supply the right
886 // data
887 snoop_pkt->setExpressSnoop();
888 snoop_pkt->setCacheResponding();
889
890 // this express snoop travels towards the memory, and at
891 // every crossbar it is snooped upwards thus reaching
892 // every cache in the system
424 if (pkt->cacheResponding()) {
425 // a cache above us (but not where the packet came from) is
426 // responding to the request, in other words it has the line
427 // in Modified or Owned state
428 DPRINTF(Cache, "Cache above responding to %s: not responding\n",
429 pkt->print());
430
431 // if the packet needs the block to be writable, and the cache
432 // that has promised to respond (setting the cache responding
433 // flag) is not providing writable (it is in Owned rather than
434 // the Modified state), we know that there may be other Shared
435 // copies in the system; go out and invalidate them all
436 assert(pkt->needsWritable() && !pkt->responderHadWritable());
437
438 // an upstream cache that had the line in Owned state
439 // (dirty, but not writable), is responding and thus
440 // transferring the dirty line from one branch of the
441 // cache hierarchy to another
442
443 // send out an express snoop and invalidate all other
444 // copies (snooping a packet that needs writable is the
445 // same as an invalidation), thus turning the Owned line
446 // into a Modified line, note that we don't invalidate the
447 // block in the current cache or any other cache on the
448 // path to memory
449
450 // create a downstream express snoop with cleared packet
451 // flags, there is no need to allocate any data as the
452 // packet is merely used to co-ordinate state transitions
453 Packet *snoop_pkt = new Packet(pkt, true, false);
454
455 // also reset the bus time that the original packet has
456 // not yet paid for
457 snoop_pkt->headerDelay = snoop_pkt->payloadDelay = 0;
458
459 // make this an instantaneous express snoop, and let the
460 // other caches in the system know that the another cache
461 // is responding, because we have found the authorative
462 // copy (Modified or Owned) that will supply the right
463 // data
464 snoop_pkt->setExpressSnoop();
465 snoop_pkt->setCacheResponding();
466
467 // this express snoop travels towards the memory, and at
468 // every crossbar it is snooped upwards thus reaching
469 // every cache in the system
893 bool M5_VAR_USED success = memSidePort->sendTimingReq(snoop_pkt);
470 bool M5_VAR_USED success = memSidePort.sendTimingReq(snoop_pkt);
894 // express snoops always succeed
895 assert(success);
896
897 // main memory will delete the snoop packet
898
899 // queue for deletion, as opposed to immediate deletion, as
900 // the sending cache is still relying on the packet
901 pendingDelete.reset(pkt);
902
903 // no need to take any further action in this particular cache
904 // as an upstram cache has already committed to responding,
905 // and we have already sent out any express snoops in the
906 // section above to ensure all other copies in the system are
907 // invalidated
908 return;
909 }
910
471 // express snoops always succeed
472 assert(success);
473
474 // main memory will delete the snoop packet
475
476 // queue for deletion, as opposed to immediate deletion, as
477 // the sending cache is still relying on the packet
478 pendingDelete.reset(pkt);
479
480 // no need to take any further action in this particular cache
481 // as an upstram cache has already committed to responding,
482 // and we have already sent out any express snoops in the
483 // section above to ensure all other copies in the system are
484 // invalidated
485 return;
486 }
487
911 // anything that is merely forwarded pays for the forward latency and
912 // the delay provided by the crossbar
913 Tick forward_time = clockEdge(forwardLatency) + pkt->headerDelay;
914
915 // We use lookupLatency here because it is used to specify the latency
916 // to access.
917 Cycles lat = lookupLatency;
918 CacheBlk *blk = nullptr;
919 bool satisfied = false;
920 {
921 PacketList writebacks;
922 // Note that lat is passed by reference here. The function
923 // access() calls accessBlock() which can modify lat value.
924 satisfied = access(pkt, blk, lat, writebacks);
925
926 // copy writebacks to write buffer here to ensure they logically
927 // proceed anything happening below
928 doWritebacks(writebacks, forward_time);
929 }
930
931 // Here we charge the headerDelay that takes into account the latencies
932 // of the bus, if the packet comes from it.
933 // The latency charged it is just lat that is the value of lookupLatency
934 // modified by access() function, or if not just lookupLatency.
935 // In case of a hit we are neglecting response latency.
936 // In case of a miss we are neglecting forward latency.
937 Tick request_time = clockEdge(lat) + pkt->headerDelay;
938 // Here we reset the timing of the packet.
939 pkt->headerDelay = pkt->payloadDelay = 0;
940
941 // track time of availability of next prefetch, if any
942 Tick next_pf_time = MaxTick;
943
944 if (satisfied) {
945 // if need to notify the prefetcher we need to do it anything
946 // else, handleTimingReqHit might turn the packet into a
947 // response
948 if (prefetcher &&
949 (prefetchOnAccess || (blk && blk->wasPrefetched()))) {
950 if (blk)
951 blk->status &= ~BlkHWPrefetched;
952
953 // Don't notify on SWPrefetch
954 if (!pkt->cmd.isSWPrefetch()) {
955 assert(!pkt->req->isCacheMaintenance());
956 next_pf_time = prefetcher->notify(pkt);
957 }
958 }
959
960 handleTimingReqHit(pkt, blk, request_time);
961 } else {
962 handleTimingReqMiss(pkt, blk, forward_time, request_time);
963
964 // We should call the prefetcher reguardless if the request is
965 // satisfied or not, reguardless if the request is in the MSHR
966 // or not. The request could be a ReadReq hit, but still not
967 // satisfied (potentially because of a prior write to the same
968 // cache line. So, even when not satisfied, there is an MSHR
969 // already allocated for this, we need to let the prefetcher
970 // know about the request
971 if (prefetcher && pkt &&
972 !pkt->cmd.isSWPrefetch() &&
973 !pkt->req->isCacheMaintenance()) {
974 next_pf_time = prefetcher->notify(pkt);
975 }
976 }
977
978 if (next_pf_time != MaxTick)
979 schedMemSideSendEvent(next_pf_time);
488 BaseCache::recvTimingReq(pkt);
980}
981
982PacketPtr
983Cache::createMissPacket(PacketPtr cpu_pkt, CacheBlk *blk,
984 bool needsWritable) const
985{
986 // should never see evictions here
987 assert(!cpu_pkt->isEviction());
988
989 bool blkValid = blk && blk->isValid();
990
991 if (cpu_pkt->req->isUncacheable() ||
992 (!blkValid && cpu_pkt->isUpgrade()) ||
993 cpu_pkt->cmd == MemCmd::InvalidateReq || cpu_pkt->isClean()) {
994 // uncacheable requests and upgrades from upper-level caches
995 // that missed completely just go through as is
996 return nullptr;
997 }
998
999 assert(cpu_pkt->needsResponse());
1000
1001 MemCmd cmd;
1002 // @TODO make useUpgrades a parameter.
1003 // Note that ownership protocols require upgrade, otherwise a
1004 // write miss on a shared owned block will generate a ReadExcl,
1005 // which will clobber the owned copy.
1006 const bool useUpgrades = true;
1007 if (cpu_pkt->cmd == MemCmd::WriteLineReq) {
1008 assert(!blkValid || !blk->isWritable());
1009 // forward as invalidate to all other caches, this gives us
1010 // the line in Exclusive state, and invalidates all other
1011 // copies
1012 cmd = MemCmd::InvalidateReq;
1013 } else if (blkValid && useUpgrades) {
1014 // only reason to be here is that blk is read only and we need
1015 // it to be writable
1016 assert(needsWritable);
1017 assert(!blk->isWritable());
1018 cmd = cpu_pkt->isLLSC() ? MemCmd::SCUpgradeReq : MemCmd::UpgradeReq;
1019 } else if (cpu_pkt->cmd == MemCmd::SCUpgradeFailReq ||
1020 cpu_pkt->cmd == MemCmd::StoreCondFailReq) {
1021 // Even though this SC will fail, we still need to send out the
1022 // request and get the data to supply it to other snoopers in the case
1023 // where the determination the StoreCond fails is delayed due to
1024 // all caches not being on the same local bus.
1025 cmd = MemCmd::SCUpgradeFailReq;
1026 } else {
1027 // block is invalid
1028
1029 // If the request does not need a writable there are two cases
1030 // where we need to ensure the response will not fetch the
1031 // block in dirty state:
1032 // * this cache is read only and it does not perform
1033 // writebacks,
1034 // * this cache is mostly exclusive and will not fill (since
1035 // it does not fill it will have to writeback the dirty data
1036 // immediately which generates uneccesary writebacks).
1037 bool force_clean_rsp = isReadOnly || clusivity == Enums::mostly_excl;
1038 cmd = needsWritable ? MemCmd::ReadExReq :
1039 (force_clean_rsp ? MemCmd::ReadCleanReq : MemCmd::ReadSharedReq);
1040 }
1041 PacketPtr pkt = new Packet(cpu_pkt->req, cmd, blkSize);
1042
1043 // if there are upstream caches that have already marked the
1044 // packet as having sharers (not passing writable), pass that info
1045 // downstream
1046 if (cpu_pkt->hasSharers() && !needsWritable) {
1047 // note that cpu_pkt may have spent a considerable time in the
1048 // MSHR queue and that the information could possibly be out
1049 // of date, however, there is no harm in conservatively
1050 // assuming the block has sharers
1051 pkt->setHasSharers();
1052 DPRINTF(Cache, "%s: passing hasSharers from %s to %s\n",
1053 __func__, cpu_pkt->print(), pkt->print());
1054 }
1055
1056 // the packet should be block aligned
1057 assert(pkt->getAddr() == pkt->getBlockAddr(blkSize));
1058
1059 pkt->allocate();
1060 DPRINTF(Cache, "%s: created %s from %s\n", __func__, pkt->print(),
1061 cpu_pkt->print());
1062 return pkt;
1063}
1064
1065
1066Cycles
1067Cache::handleAtomicReqMiss(PacketPtr pkt, CacheBlk *blk,
1068 PacketList &writebacks)
1069{
1070 // deal with the packets that go through the write path of
1071 // the cache, i.e. any evictions and writes
1072 if (pkt->isEviction() || pkt->cmd == MemCmd::WriteClean ||
1073 (pkt->req->isUncacheable() && pkt->isWrite())) {
489}
490
491PacketPtr
492Cache::createMissPacket(PacketPtr cpu_pkt, CacheBlk *blk,
493 bool needsWritable) const
494{
495 // should never see evictions here
496 assert(!cpu_pkt->isEviction());
497
498 bool blkValid = blk && blk->isValid();
499
500 if (cpu_pkt->req->isUncacheable() ||
501 (!blkValid && cpu_pkt->isUpgrade()) ||
502 cpu_pkt->cmd == MemCmd::InvalidateReq || cpu_pkt->isClean()) {
503 // uncacheable requests and upgrades from upper-level caches
504 // that missed completely just go through as is
505 return nullptr;
506 }
507
508 assert(cpu_pkt->needsResponse());
509
510 MemCmd cmd;
511 // @TODO make useUpgrades a parameter.
512 // Note that ownership protocols require upgrade, otherwise a
513 // write miss on a shared owned block will generate a ReadExcl,
514 // which will clobber the owned copy.
515 const bool useUpgrades = true;
516 if (cpu_pkt->cmd == MemCmd::WriteLineReq) {
517 assert(!blkValid || !blk->isWritable());
518 // forward as invalidate to all other caches, this gives us
519 // the line in Exclusive state, and invalidates all other
520 // copies
521 cmd = MemCmd::InvalidateReq;
522 } else if (blkValid && useUpgrades) {
523 // only reason to be here is that blk is read only and we need
524 // it to be writable
525 assert(needsWritable);
526 assert(!blk->isWritable());
527 cmd = cpu_pkt->isLLSC() ? MemCmd::SCUpgradeReq : MemCmd::UpgradeReq;
528 } else if (cpu_pkt->cmd == MemCmd::SCUpgradeFailReq ||
529 cpu_pkt->cmd == MemCmd::StoreCondFailReq) {
530 // Even though this SC will fail, we still need to send out the
531 // request and get the data to supply it to other snoopers in the case
532 // where the determination the StoreCond fails is delayed due to
533 // all caches not being on the same local bus.
534 cmd = MemCmd::SCUpgradeFailReq;
535 } else {
536 // block is invalid
537
538 // If the request does not need a writable there are two cases
539 // where we need to ensure the response will not fetch the
540 // block in dirty state:
541 // * this cache is read only and it does not perform
542 // writebacks,
543 // * this cache is mostly exclusive and will not fill (since
544 // it does not fill it will have to writeback the dirty data
545 // immediately which generates uneccesary writebacks).
546 bool force_clean_rsp = isReadOnly || clusivity == Enums::mostly_excl;
547 cmd = needsWritable ? MemCmd::ReadExReq :
548 (force_clean_rsp ? MemCmd::ReadCleanReq : MemCmd::ReadSharedReq);
549 }
550 PacketPtr pkt = new Packet(cpu_pkt->req, cmd, blkSize);
551
552 // if there are upstream caches that have already marked the
553 // packet as having sharers (not passing writable), pass that info
554 // downstream
555 if (cpu_pkt->hasSharers() && !needsWritable) {
556 // note that cpu_pkt may have spent a considerable time in the
557 // MSHR queue and that the information could possibly be out
558 // of date, however, there is no harm in conservatively
559 // assuming the block has sharers
560 pkt->setHasSharers();
561 DPRINTF(Cache, "%s: passing hasSharers from %s to %s\n",
562 __func__, cpu_pkt->print(), pkt->print());
563 }
564
565 // the packet should be block aligned
566 assert(pkt->getAddr() == pkt->getBlockAddr(blkSize));
567
568 pkt->allocate();
569 DPRINTF(Cache, "%s: created %s from %s\n", __func__, pkt->print(),
570 cpu_pkt->print());
571 return pkt;
572}
573
574
575Cycles
576Cache::handleAtomicReqMiss(PacketPtr pkt, CacheBlk *blk,
577 PacketList &writebacks)
578{
579 // deal with the packets that go through the write path of
580 // the cache, i.e. any evictions and writes
581 if (pkt->isEviction() || pkt->cmd == MemCmd::WriteClean ||
582 (pkt->req->isUncacheable() && pkt->isWrite())) {
1074 Cycles latency = ticksToCycles(memSidePort->sendAtomic(pkt));
583 Cycles latency = ticksToCycles(memSidePort.sendAtomic(pkt));
1075
1076 // at this point, if the request was an uncacheable write
1077 // request, it has been satisfied by a memory below and the
1078 // packet carries the response back
1079 assert(!(pkt->req->isUncacheable() && pkt->isWrite()) ||
1080 pkt->isResponse());
1081
1082 return latency;
1083 }
1084
1085 // only misses left
1086
1087 PacketPtr bus_pkt = createMissPacket(pkt, blk, pkt->needsWritable());
1088
1089 bool is_forward = (bus_pkt == nullptr);
1090
1091 if (is_forward) {
1092 // just forwarding the same request to the next level
1093 // no local cache operation involved
1094 bus_pkt = pkt;
1095 }
1096
1097 DPRINTF(Cache, "%s: Sending an atomic %s\n", __func__,
1098 bus_pkt->print());
1099
1100#if TRACING_ON
1101 CacheBlk::State old_state = blk ? blk->status : 0;
1102#endif
1103
584
585 // at this point, if the request was an uncacheable write
586 // request, it has been satisfied by a memory below and the
587 // packet carries the response back
588 assert(!(pkt->req->isUncacheable() && pkt->isWrite()) ||
589 pkt->isResponse());
590
591 return latency;
592 }
593
594 // only misses left
595
596 PacketPtr bus_pkt = createMissPacket(pkt, blk, pkt->needsWritable());
597
598 bool is_forward = (bus_pkt == nullptr);
599
600 if (is_forward) {
601 // just forwarding the same request to the next level
602 // no local cache operation involved
603 bus_pkt = pkt;
604 }
605
606 DPRINTF(Cache, "%s: Sending an atomic %s\n", __func__,
607 bus_pkt->print());
608
609#if TRACING_ON
610 CacheBlk::State old_state = blk ? blk->status : 0;
611#endif
612
1104 Cycles latency = ticksToCycles(memSidePort->sendAtomic(bus_pkt));
613 Cycles latency = ticksToCycles(memSidePort.sendAtomic(bus_pkt));
1105
1106 bool is_invalidate = bus_pkt->isInvalidate();
1107
1108 // We are now dealing with the response handling
1109 DPRINTF(Cache, "%s: Receive response: %s in state %i\n", __func__,
1110 bus_pkt->print(), old_state);
1111
1112 // If packet was a forward, the response (if any) is already
1113 // in place in the bus_pkt == pkt structure, so we don't need
1114 // to do anything. Otherwise, use the separate bus_pkt to
1115 // generate response to pkt and then delete it.
1116 if (!is_forward) {
1117 if (pkt->needsResponse()) {
1118 assert(bus_pkt->isResponse());
1119 if (bus_pkt->isError()) {
1120 pkt->makeAtomicResponse();
1121 pkt->copyError(bus_pkt);
1122 } else if (pkt->cmd == MemCmd::WriteLineReq) {
1123 // note the use of pkt, not bus_pkt here.
1124
1125 // write-line request to the cache that promoted
1126 // the write to a whole line
1127 blk = handleFill(pkt, blk, writebacks,
1128 allocOnFill(pkt->cmd));
1129 assert(blk != NULL);
1130 is_invalidate = false;
1131 satisfyRequest(pkt, blk);
1132 } else if (bus_pkt->isRead() ||
1133 bus_pkt->cmd == MemCmd::UpgradeResp) {
1134 // we're updating cache state to allow us to
1135 // satisfy the upstream request from the cache
1136 blk = handleFill(bus_pkt, blk, writebacks,
1137 allocOnFill(pkt->cmd));
1138 satisfyRequest(pkt, blk);
1139 maintainClusivity(pkt->fromCache(), blk);
1140 } else {
1141 // we're satisfying the upstream request without
1142 // modifying cache state, e.g., a write-through
1143 pkt->makeAtomicResponse();
1144 }
1145 }
1146 delete bus_pkt;
1147 }
1148
1149 if (is_invalidate && blk && blk->isValid()) {
1150 invalidateBlock(blk);
1151 }
1152
1153 return latency;
1154}
1155
1156Tick
1157Cache::recvAtomic(PacketPtr pkt)
1158{
614
615 bool is_invalidate = bus_pkt->isInvalidate();
616
617 // We are now dealing with the response handling
618 DPRINTF(Cache, "%s: Receive response: %s in state %i\n", __func__,
619 bus_pkt->print(), old_state);
620
621 // If packet was a forward, the response (if any) is already
622 // in place in the bus_pkt == pkt structure, so we don't need
623 // to do anything. Otherwise, use the separate bus_pkt to
624 // generate response to pkt and then delete it.
625 if (!is_forward) {
626 if (pkt->needsResponse()) {
627 assert(bus_pkt->isResponse());
628 if (bus_pkt->isError()) {
629 pkt->makeAtomicResponse();
630 pkt->copyError(bus_pkt);
631 } else if (pkt->cmd == MemCmd::WriteLineReq) {
632 // note the use of pkt, not bus_pkt here.
633
634 // write-line request to the cache that promoted
635 // the write to a whole line
636 blk = handleFill(pkt, blk, writebacks,
637 allocOnFill(pkt->cmd));
638 assert(blk != NULL);
639 is_invalidate = false;
640 satisfyRequest(pkt, blk);
641 } else if (bus_pkt->isRead() ||
642 bus_pkt->cmd == MemCmd::UpgradeResp) {
643 // we're updating cache state to allow us to
644 // satisfy the upstream request from the cache
645 blk = handleFill(bus_pkt, blk, writebacks,
646 allocOnFill(pkt->cmd));
647 satisfyRequest(pkt, blk);
648 maintainClusivity(pkt->fromCache(), blk);
649 } else {
650 // we're satisfying the upstream request without
651 // modifying cache state, e.g., a write-through
652 pkt->makeAtomicResponse();
653 }
654 }
655 delete bus_pkt;
656 }
657
658 if (is_invalidate && blk && blk->isValid()) {
659 invalidateBlock(blk);
660 }
661
662 return latency;
663}
664
665Tick
666Cache::recvAtomic(PacketPtr pkt)
667{
1159 // We are in atomic mode so we pay just for lookupLatency here.
1160 Cycles lat = lookupLatency;
1161
1162 // Forward the request if the system is in cache bypass mode.
1163 if (system->bypassCaches())
668 // Forward the request if the system is in cache bypass mode.
669 if (system->bypassCaches())
1164 return ticksToCycles(memSidePort->sendAtomic(pkt));
670 return ticksToCycles(memSidePort.sendAtomic(pkt));
1165
1166 promoteWholeLineWrites(pkt);
1167
671
672 promoteWholeLineWrites(pkt);
673
1168 // follow the same flow as in recvTimingReq, and check if a cache
1169 // above us is responding
1170 if (pkt->cacheResponding() && !pkt->isClean()) {
1171 assert(!pkt->req->isCacheInvalidate());
1172 DPRINTF(Cache, "Cache above responding to %s: not responding\n",
1173 pkt->print());
1174
1175 // if a cache is responding, and it had the line in Owned
1176 // rather than Modified state, we need to invalidate any
1177 // copies that are not on the same path to memory
1178 assert(pkt->needsWritable() && !pkt->responderHadWritable());
1179 lat += ticksToCycles(memSidePort->sendAtomic(pkt));
1180
1181 return lat * clockPeriod();
1182 }
1183
1184 // should assert here that there are no outstanding MSHRs or
1185 // writebacks... that would mean that someone used an atomic
1186 // access in timing mode
1187
1188 CacheBlk *blk = nullptr;
1189 PacketList writebacks;
1190 bool satisfied = access(pkt, blk, lat, writebacks);
1191
1192 if (pkt->isClean() && blk && blk->isDirty()) {
1193 // A cache clean opearation is looking for a dirty
1194 // block. If a dirty block is encountered a WriteClean
1195 // will update any copies to the path to the memory
1196 // until the point of reference.
1197 DPRINTF(CacheVerbose, "%s: packet %s found block: %s\n",
1198 __func__, pkt->print(), blk->print());
1199 PacketPtr wb_pkt = writecleanBlk(blk, pkt->req->getDest(), pkt->id);
1200 writebacks.push_back(wb_pkt);
1201 pkt->setSatisfied();
1202 }
1203
1204 // handle writebacks resulting from the access here to ensure they
1205 // logically proceed anything happening below
1206 doWritebacksAtomic(writebacks);
1207 assert(writebacks.empty());
1208
1209 if (!satisfied) {
1210 lat += handleAtomicReqMiss(pkt, blk, writebacks);
1211 }
1212
1213 // Note that we don't invoke the prefetcher at all in atomic mode.
1214 // It's not clear how to do it properly, particularly for
1215 // prefetchers that aggressively generate prefetch candidates and
1216 // rely on bandwidth contention to throttle them; these will tend
1217 // to pollute the cache in atomic mode since there is no bandwidth
1218 // contention. If we ever do want to enable prefetching in atomic
1219 // mode, though, this is the place to do it... see timingAccess()
1220 // for an example (though we'd want to issue the prefetch(es)
1221 // immediately rather than calling requestMemSideBus() as we do
1222 // there).
1223
1224 // do any writebacks resulting from the response handling
1225 doWritebacksAtomic(writebacks);
1226
1227 // if we used temp block, check to see if its valid and if so
1228 // clear it out, but only do so after the call to recvAtomic is
1229 // finished so that any downstream observers (such as a snoop
1230 // filter), first see the fill, and only then see the eviction
1231 if (blk == tempBlock && tempBlock->isValid()) {
1232 // the atomic CPU calls recvAtomic for fetch and load/store
1233 // sequentuially, and we may already have a tempBlock
1234 // writeback from the fetch that we have not yet sent
1235 if (tempBlockWriteback) {
1236 // if that is the case, write the prevoius one back, and
1237 // do not schedule any new event
1238 writebackTempBlockAtomic();
1239 } else {
1240 // the writeback/clean eviction happens after the call to
1241 // recvAtomic has finished (but before any successive
1242 // calls), so that the response handling from the fill is
1243 // allowed to happen first
1244 schedule(writebackTempBlockAtomicEvent, curTick());
1245 }
1246
1247 tempBlockWriteback = evictBlock(blk);
1248 }
1249
1250 if (pkt->needsResponse()) {
1251 pkt->makeAtomicResponse();
1252 }
1253
1254 return lat * clockPeriod();
674 return BaseCache::recvAtomic(pkt);
1255}
1256
1257
675}
676
677
1258void
1259Cache::functionalAccess(PacketPtr pkt, bool fromCpuSide)
1260{
1261 if (system->bypassCaches()) {
1262 // Packets from the memory side are snoop request and
1263 // shouldn't happen in bypass mode.
1264 assert(fromCpuSide);
1265
1266 // The cache should be flushed if we are in cache bypass mode,
1267 // so we don't need to check if we need to update anything.
1268 memSidePort->sendFunctional(pkt);
1269 return;
1270 }
1271
1272 Addr blk_addr = pkt->getBlockAddr(blkSize);
1273 bool is_secure = pkt->isSecure();
1274 CacheBlk *blk = tags->findBlock(pkt->getAddr(), is_secure);
1275 MSHR *mshr = mshrQueue.findMatch(blk_addr, is_secure);
1276
1277 pkt->pushLabel(name());
1278
1279 CacheBlkPrintWrapper cbpw(blk);
1280
1281 // Note that just because an L2/L3 has valid data doesn't mean an
1282 // L1 doesn't have a more up-to-date modified copy that still
1283 // needs to be found. As a result we always update the request if
1284 // we have it, but only declare it satisfied if we are the owner.
1285
1286 // see if we have data at all (owned or otherwise)
1287 bool have_data = blk && blk->isValid()
1288 && pkt->checkFunctional(&cbpw, blk_addr, is_secure, blkSize,
1289 blk->data);
1290
1291 // data we have is dirty if marked as such or if we have an
1292 // in-service MSHR that is pending a modified line
1293 bool have_dirty =
1294 have_data && (blk->isDirty() ||
1295 (mshr && mshr->inService && mshr->isPendingModified()));
1296
1297 bool done = have_dirty
1298 || cpuSidePort->checkFunctional(pkt)
1299 || mshrQueue.checkFunctional(pkt, blk_addr)
1300 || writeBuffer.checkFunctional(pkt, blk_addr)
1301 || memSidePort->checkFunctional(pkt);
1302
1303 DPRINTF(CacheVerbose, "%s: %s %s%s%s\n", __func__, pkt->print(),
1304 (blk && blk->isValid()) ? "valid " : "",
1305 have_data ? "data " : "", done ? "done " : "");
1306
1307 // We're leaving the cache, so pop cache->name() label
1308 pkt->popLabel();
1309
1310 if (done) {
1311 pkt->makeResponse();
1312 } else {
1313 // if it came as a request from the CPU side then make sure it
1314 // continues towards the memory side
1315 if (fromCpuSide) {
1316 memSidePort->sendFunctional(pkt);
1317 } else if (cpuSidePort->isSnooping()) {
1318 // if it came from the memory side, it must be a snoop request
1319 // and we should only forward it if we are forwarding snoops
1320 cpuSidePort->sendFunctionalSnoop(pkt);
1321 }
1322 }
1323}
1324
1325
1326/////////////////////////////////////////////////////
1327//
1328// Response handling: responses from the memory side
1329//
1330/////////////////////////////////////////////////////
1331
1332
1333void
678/////////////////////////////////////////////////////
679//
680// Response handling: responses from the memory side
681//
682/////////////////////////////////////////////////////
683
684
685void
1334Cache::handleUncacheableWriteResp(PacketPtr pkt)
1335{
1336 Tick completion_time = clockEdge(responseLatency) +
1337 pkt->headerDelay + pkt->payloadDelay;
1338
1339 // Reset the bus additional time as it is now accounted for
1340 pkt->headerDelay = pkt->payloadDelay = 0;
1341
1342 cpuSidePort->schedTimingResp(pkt, completion_time, true);
1343}
1344
1345void
1346Cache::serviceMSHRTargets(MSHR *mshr, const PacketPtr pkt, CacheBlk *blk,
1347 PacketList &writebacks)
1348{
1349 MSHR::Target *initial_tgt = mshr->getTarget();
1350 // First offset for critical word first calculations
1351 const int initial_offset = initial_tgt->pkt->getOffset(blkSize);
1352
1353 const bool is_error = pkt->isError();
1354 bool is_fill = !mshr->isForward &&
1355 (pkt->isRead() || pkt->cmd == MemCmd::UpgradeResp);
1356 // allow invalidation responses originating from write-line
1357 // requests to be discarded
1358 bool is_invalidate = pkt->isInvalidate();
1359
1360 MSHR::TargetList targets = mshr->extractServiceableTargets(pkt);
1361 for (auto &target: targets) {
1362 Packet *tgt_pkt = target.pkt;
1363 switch (target.source) {
1364 case MSHR::Target::FromCPU:
1365 Tick completion_time;
1366 // Here we charge on completion_time the delay of the xbar if the
1367 // packet comes from it, charged on headerDelay.
1368 completion_time = pkt->headerDelay;
1369
1370 // Software prefetch handling for cache closest to core
1371 if (tgt_pkt->cmd.isSWPrefetch()) {
1372 // a software prefetch would have already been ack'd
1373 // immediately with dummy data so the core would be able to
1374 // retire it. This request completes right here, so we
1375 // deallocate it.
1376 delete tgt_pkt->req;
1377 delete tgt_pkt;
1378 break; // skip response
1379 }
1380
1381 // unlike the other packet flows, where data is found in other
1382 // caches or memory and brought back, write-line requests always
1383 // have the data right away, so the above check for "is fill?"
1384 // cannot actually be determined until examining the stored MSHR
1385 // state. We "catch up" with that logic here, which is duplicated
1386 // from above.
1387 if (tgt_pkt->cmd == MemCmd::WriteLineReq) {
1388 assert(!is_error);
1389 // we got the block in a writable state, so promote
1390 // any deferred targets if possible
1391 mshr->promoteWritable();
1392 // NB: we use the original packet here and not the response!
1393 blk = handleFill(tgt_pkt, blk, writebacks,
1394 targets.allocOnFill);
1395 assert(blk);
1396
1397 // treat as a fill, and discard the invalidation
1398 // response
1399 is_fill = true;
1400 is_invalidate = false;
1401 }
1402
1403 if (is_fill) {
1404 satisfyRequest(tgt_pkt, blk, true, mshr->hasPostDowngrade());
1405
1406 // How many bytes past the first request is this one
1407 int transfer_offset =
1408 tgt_pkt->getOffset(blkSize) - initial_offset;
1409 if (transfer_offset < 0) {
1410 transfer_offset += blkSize;
1411 }
1412
1413 // If not critical word (offset) return payloadDelay.
1414 // responseLatency is the latency of the return path
1415 // from lower level caches/memory to an upper level cache or
1416 // the core.
1417 completion_time += clockEdge(responseLatency) +
1418 (transfer_offset ? pkt->payloadDelay : 0);
1419
1420 assert(!tgt_pkt->req->isUncacheable());
1421
1422 assert(tgt_pkt->req->masterId() < system->maxMasters());
1423 missLatency[tgt_pkt->cmdToIndex()][tgt_pkt->req->masterId()] +=
1424 completion_time - target.recvTime;
1425 } else if (pkt->cmd == MemCmd::UpgradeFailResp) {
1426 // failed StoreCond upgrade
1427 assert(tgt_pkt->cmd == MemCmd::StoreCondReq ||
1428 tgt_pkt->cmd == MemCmd::StoreCondFailReq ||
1429 tgt_pkt->cmd == MemCmd::SCUpgradeFailReq);
1430 // responseLatency is the latency of the return path
1431 // from lower level caches/memory to an upper level cache or
1432 // the core.
1433 completion_time += clockEdge(responseLatency) +
1434 pkt->payloadDelay;
1435 tgt_pkt->req->setExtraData(0);
1436 } else {
1437 // We are about to send a response to a cache above
1438 // that asked for an invalidation; we need to
1439 // invalidate our copy immediately as the most
1440 // up-to-date copy of the block will now be in the
1441 // cache above. It will also prevent this cache from
1442 // responding (if the block was previously dirty) to
1443 // snoops as they should snoop the caches above where
1444 // they will get the response from.
1445 if (is_invalidate && blk && blk->isValid()) {
1446 invalidateBlock(blk);
1447 }
1448 // not a cache fill, just forwarding response
1449 // responseLatency is the latency of the return path
1450 // from lower level cahces/memory to the core.
1451 completion_time += clockEdge(responseLatency) +
1452 pkt->payloadDelay;
1453 if (pkt->isRead() && !is_error) {
1454 // sanity check
1455 assert(pkt->getAddr() == tgt_pkt->getAddr());
1456 assert(pkt->getSize() >= tgt_pkt->getSize());
1457
1458 tgt_pkt->setData(pkt->getConstPtr<uint8_t>());
1459 }
1460 }
1461 tgt_pkt->makeTimingResponse();
1462 // if this packet is an error copy that to the new packet
1463 if (is_error)
1464 tgt_pkt->copyError(pkt);
1465 if (tgt_pkt->cmd == MemCmd::ReadResp &&
1466 (is_invalidate || mshr->hasPostInvalidate())) {
1467 // If intermediate cache got ReadRespWithInvalidate,
1468 // propagate that. Response should not have
1469 // isInvalidate() set otherwise.
1470 tgt_pkt->cmd = MemCmd::ReadRespWithInvalidate;
1471 DPRINTF(Cache, "%s: updated cmd to %s\n", __func__,
1472 tgt_pkt->print());
1473 }
1474 // Reset the bus additional time as it is now accounted for
1475 tgt_pkt->headerDelay = tgt_pkt->payloadDelay = 0;
686Cache::serviceMSHRTargets(MSHR *mshr, const PacketPtr pkt, CacheBlk *blk,
687 PacketList &writebacks)
688{
689 MSHR::Target *initial_tgt = mshr->getTarget();
690 // First offset for critical word first calculations
691 const int initial_offset = initial_tgt->pkt->getOffset(blkSize);
692
693 const bool is_error = pkt->isError();
694 bool is_fill = !mshr->isForward &&
695 (pkt->isRead() || pkt->cmd == MemCmd::UpgradeResp);
696 // allow invalidation responses originating from write-line
697 // requests to be discarded
698 bool is_invalidate = pkt->isInvalidate();
699
700 MSHR::TargetList targets = mshr->extractServiceableTargets(pkt);
701 for (auto &target: targets) {
702 Packet *tgt_pkt = target.pkt;
703 switch (target.source) {
704 case MSHR::Target::FromCPU:
705 Tick completion_time;
706 // Here we charge on completion_time the delay of the xbar if the
707 // packet comes from it, charged on headerDelay.
708 completion_time = pkt->headerDelay;
709
710 // Software prefetch handling for cache closest to core
711 if (tgt_pkt->cmd.isSWPrefetch()) {
712 // a software prefetch would have already been ack'd
713 // immediately with dummy data so the core would be able to
714 // retire it. This request completes right here, so we
715 // deallocate it.
716 delete tgt_pkt->req;
717 delete tgt_pkt;
718 break; // skip response
719 }
720
721 // unlike the other packet flows, where data is found in other
722 // caches or memory and brought back, write-line requests always
723 // have the data right away, so the above check for "is fill?"
724 // cannot actually be determined until examining the stored MSHR
725 // state. We "catch up" with that logic here, which is duplicated
726 // from above.
727 if (tgt_pkt->cmd == MemCmd::WriteLineReq) {
728 assert(!is_error);
729 // we got the block in a writable state, so promote
730 // any deferred targets if possible
731 mshr->promoteWritable();
732 // NB: we use the original packet here and not the response!
733 blk = handleFill(tgt_pkt, blk, writebacks,
734 targets.allocOnFill);
735 assert(blk);
736
737 // treat as a fill, and discard the invalidation
738 // response
739 is_fill = true;
740 is_invalidate = false;
741 }
742
743 if (is_fill) {
744 satisfyRequest(tgt_pkt, blk, true, mshr->hasPostDowngrade());
745
746 // How many bytes past the first request is this one
747 int transfer_offset =
748 tgt_pkt->getOffset(blkSize) - initial_offset;
749 if (transfer_offset < 0) {
750 transfer_offset += blkSize;
751 }
752
753 // If not critical word (offset) return payloadDelay.
754 // responseLatency is the latency of the return path
755 // from lower level caches/memory to an upper level cache or
756 // the core.
757 completion_time += clockEdge(responseLatency) +
758 (transfer_offset ? pkt->payloadDelay : 0);
759
760 assert(!tgt_pkt->req->isUncacheable());
761
762 assert(tgt_pkt->req->masterId() < system->maxMasters());
763 missLatency[tgt_pkt->cmdToIndex()][tgt_pkt->req->masterId()] +=
764 completion_time - target.recvTime;
765 } else if (pkt->cmd == MemCmd::UpgradeFailResp) {
766 // failed StoreCond upgrade
767 assert(tgt_pkt->cmd == MemCmd::StoreCondReq ||
768 tgt_pkt->cmd == MemCmd::StoreCondFailReq ||
769 tgt_pkt->cmd == MemCmd::SCUpgradeFailReq);
770 // responseLatency is the latency of the return path
771 // from lower level caches/memory to an upper level cache or
772 // the core.
773 completion_time += clockEdge(responseLatency) +
774 pkt->payloadDelay;
775 tgt_pkt->req->setExtraData(0);
776 } else {
777 // We are about to send a response to a cache above
778 // that asked for an invalidation; we need to
779 // invalidate our copy immediately as the most
780 // up-to-date copy of the block will now be in the
781 // cache above. It will also prevent this cache from
782 // responding (if the block was previously dirty) to
783 // snoops as they should snoop the caches above where
784 // they will get the response from.
785 if (is_invalidate && blk && blk->isValid()) {
786 invalidateBlock(blk);
787 }
788 // not a cache fill, just forwarding response
789 // responseLatency is the latency of the return path
790 // from lower level cahces/memory to the core.
791 completion_time += clockEdge(responseLatency) +
792 pkt->payloadDelay;
793 if (pkt->isRead() && !is_error) {
794 // sanity check
795 assert(pkt->getAddr() == tgt_pkt->getAddr());
796 assert(pkt->getSize() >= tgt_pkt->getSize());
797
798 tgt_pkt->setData(pkt->getConstPtr<uint8_t>());
799 }
800 }
801 tgt_pkt->makeTimingResponse();
802 // if this packet is an error copy that to the new packet
803 if (is_error)
804 tgt_pkt->copyError(pkt);
805 if (tgt_pkt->cmd == MemCmd::ReadResp &&
806 (is_invalidate || mshr->hasPostInvalidate())) {
807 // If intermediate cache got ReadRespWithInvalidate,
808 // propagate that. Response should not have
809 // isInvalidate() set otherwise.
810 tgt_pkt->cmd = MemCmd::ReadRespWithInvalidate;
811 DPRINTF(Cache, "%s: updated cmd to %s\n", __func__,
812 tgt_pkt->print());
813 }
814 // Reset the bus additional time as it is now accounted for
815 tgt_pkt->headerDelay = tgt_pkt->payloadDelay = 0;
1476 cpuSidePort->schedTimingResp(tgt_pkt, completion_time, true);
816 cpuSidePort.schedTimingResp(tgt_pkt, completion_time, true);
1477 break;
1478
1479 case MSHR::Target::FromPrefetcher:
1480 assert(tgt_pkt->cmd == MemCmd::HardPFReq);
1481 if (blk)
1482 blk->status |= BlkHWPrefetched;
1483 delete tgt_pkt->req;
1484 delete tgt_pkt;
1485 break;
1486
1487 case MSHR::Target::FromSnoop:
1488 // I don't believe that a snoop can be in an error state
1489 assert(!is_error);
1490 // response to snoop request
1491 DPRINTF(Cache, "processing deferred snoop...\n");
1492 // If the response is invalidating, a snooping target can
1493 // be satisfied if it is also invalidating. If the reponse is, not
1494 // only invalidating, but more specifically an InvalidateResp and
1495 // the MSHR was created due to an InvalidateReq then a cache above
1496 // is waiting to satisfy a WriteLineReq. In this case even an
1497 // non-invalidating snoop is added as a target here since this is
1498 // the ordering point. When the InvalidateResp reaches this cache,
1499 // the snooping target will snoop further the cache above with the
1500 // WriteLineReq.
1501 assert(!is_invalidate || pkt->cmd == MemCmd::InvalidateResp ||
1502 pkt->req->isCacheMaintenance() ||
1503 mshr->hasPostInvalidate());
1504 handleSnoop(tgt_pkt, blk, true, true, mshr->hasPostInvalidate());
1505 break;
1506
1507 default:
1508 panic("Illegal target->source enum %d\n", target.source);
1509 }
1510 }
1511
1512 maintainClusivity(targets.hasFromCache, blk);
1513
1514 if (blk && blk->isValid()) {
1515 // an invalidate response stemming from a write line request
1516 // should not invalidate the block, so check if the
1517 // invalidation should be discarded
1518 if (is_invalidate || mshr->hasPostInvalidate()) {
1519 invalidateBlock(blk);
1520 } else if (mshr->hasPostDowngrade()) {
1521 blk->status &= ~BlkWritable;
1522 }
1523 }
1524}
1525
817 break;
818
819 case MSHR::Target::FromPrefetcher:
820 assert(tgt_pkt->cmd == MemCmd::HardPFReq);
821 if (blk)
822 blk->status |= BlkHWPrefetched;
823 delete tgt_pkt->req;
824 delete tgt_pkt;
825 break;
826
827 case MSHR::Target::FromSnoop:
828 // I don't believe that a snoop can be in an error state
829 assert(!is_error);
830 // response to snoop request
831 DPRINTF(Cache, "processing deferred snoop...\n");
832 // If the response is invalidating, a snooping target can
833 // be satisfied if it is also invalidating. If the reponse is, not
834 // only invalidating, but more specifically an InvalidateResp and
835 // the MSHR was created due to an InvalidateReq then a cache above
836 // is waiting to satisfy a WriteLineReq. In this case even an
837 // non-invalidating snoop is added as a target here since this is
838 // the ordering point. When the InvalidateResp reaches this cache,
839 // the snooping target will snoop further the cache above with the
840 // WriteLineReq.
841 assert(!is_invalidate || pkt->cmd == MemCmd::InvalidateResp ||
842 pkt->req->isCacheMaintenance() ||
843 mshr->hasPostInvalidate());
844 handleSnoop(tgt_pkt, blk, true, true, mshr->hasPostInvalidate());
845 break;
846
847 default:
848 panic("Illegal target->source enum %d\n", target.source);
849 }
850 }
851
852 maintainClusivity(targets.hasFromCache, blk);
853
854 if (blk && blk->isValid()) {
855 // an invalidate response stemming from a write line request
856 // should not invalidate the block, so check if the
857 // invalidation should be discarded
858 if (is_invalidate || mshr->hasPostInvalidate()) {
859 invalidateBlock(blk);
860 } else if (mshr->hasPostDowngrade()) {
861 blk->status &= ~BlkWritable;
862 }
863 }
864}
865
1526void
1527Cache::recvTimingResp(PacketPtr pkt)
1528{
1529 assert(pkt->isResponse());
1530
1531 // all header delay should be paid for by the crossbar, unless
1532 // this is a prefetch response from above
1533 panic_if(pkt->headerDelay != 0 && pkt->cmd != MemCmd::HardPFResp,
1534 "%s saw a non-zero packet delay\n", name());
1535
1536 const bool is_error = pkt->isError();
1537
1538 if (is_error) {
1539 DPRINTF(Cache, "%s: Cache received %s with error\n", __func__,
1540 pkt->print());
1541 }
1542
1543 DPRINTF(Cache, "%s: Handling response %s\n", __func__,
1544 pkt->print());
1545
1546 // if this is a write, we should be looking at an uncacheable
1547 // write
1548 if (pkt->isWrite()) {
1549 assert(pkt->req->isUncacheable());
1550 handleUncacheableWriteResp(pkt);
1551 return;
1552 }
1553
1554 // we have dealt with any (uncacheable) writes above, from here on
1555 // we know we are dealing with an MSHR due to a miss or a prefetch
1556 MSHR *mshr = dynamic_cast<MSHR*>(pkt->popSenderState());
1557 assert(mshr);
1558
1559 if (mshr == noTargetMSHR) {
1560 // we always clear at least one target
1561 clearBlocked(Blocked_NoTargets);
1562 noTargetMSHR = nullptr;
1563 }
1564
1565 // Initial target is used just for stats
1566 MSHR::Target *initial_tgt = mshr->getTarget();
1567 int stats_cmd_idx = initial_tgt->pkt->cmdToIndex();
1568 Tick miss_latency = curTick() - initial_tgt->recvTime;
1569
1570 if (pkt->req->isUncacheable()) {
1571 assert(pkt->req->masterId() < system->maxMasters());
1572 mshr_uncacheable_lat[stats_cmd_idx][pkt->req->masterId()] +=
1573 miss_latency;
1574 } else {
1575 assert(pkt->req->masterId() < system->maxMasters());
1576 mshr_miss_latency[stats_cmd_idx][pkt->req->masterId()] +=
1577 miss_latency;
1578 }
1579
1580 PacketList writebacks;
1581
1582 bool is_fill = !mshr->isForward &&
1583 (pkt->isRead() || pkt->cmd == MemCmd::UpgradeResp);
1584
1585 CacheBlk *blk = tags->findBlock(pkt->getAddr(), pkt->isSecure());
1586
1587 if (is_fill && !is_error) {
1588 DPRINTF(Cache, "Block for addr %#llx being updated in Cache\n",
1589 pkt->getAddr());
1590
1591 blk = handleFill(pkt, blk, writebacks, mshr->allocOnFill());
1592 assert(blk != nullptr);
1593 }
1594
1595 if (blk && blk->isValid() && pkt->isClean() && !pkt->isInvalidate()) {
1596 // The block was marked not readable while there was a pending
1597 // cache maintenance operation, restore its flag.
1598 blk->status |= BlkReadable;
1599 }
1600
1601 if (blk && blk->isWritable() && !pkt->req->isCacheInvalidate()) {
1602 // If at this point the referenced block is writable and the
1603 // response is not a cache invalidate, we promote targets that
1604 // were deferred as we couldn't guarrantee a writable copy
1605 mshr->promoteWritable();
1606 }
1607
1608 serviceMSHRTargets(mshr, pkt, blk, writebacks);
1609
1610 if (mshr->promoteDeferredTargets()) {
1611 // avoid later read getting stale data while write miss is
1612 // outstanding.. see comment in timingAccess()
1613 if (blk) {
1614 blk->status &= ~BlkReadable;
1615 }
1616 mshrQueue.markPending(mshr);
1617 schedMemSideSendEvent(clockEdge() + pkt->payloadDelay);
1618 } else {
1619 // while we deallocate an mshr from the queue we still have to
1620 // check the isFull condition before and after as we might
1621 // have been using the reserved entries already
1622 const bool was_full = mshrQueue.isFull();
1623 mshrQueue.deallocate(mshr);
1624 if (was_full && !mshrQueue.isFull()) {
1625 clearBlocked(Blocked_NoMSHRs);
1626 }
1627
1628 // Request the bus for a prefetch if this deallocation freed enough
1629 // MSHRs for a prefetch to take place
1630 if (prefetcher && mshrQueue.canPrefetch()) {
1631 Tick next_pf_time = std::max(prefetcher->nextPrefetchReadyTime(),
1632 clockEdge());
1633 if (next_pf_time != MaxTick)
1634 schedMemSideSendEvent(next_pf_time);
1635 }
1636 }
1637
1638 // if we used temp block, check to see if its valid and then clear it out
1639 if (blk == tempBlock && tempBlock->isValid()) {
1640 evictBlock(blk, writebacks);
1641 }
1642
1643 const Tick forward_time = clockEdge(forwardLatency) + pkt->headerDelay;
1644 // copy writebacks to write buffer
1645 doWritebacks(writebacks, forward_time);
1646
1647 DPRINTF(CacheVerbose, "%s: Leaving with %s\n", __func__, pkt->print());
1648 delete pkt;
1649}
1650
1651PacketPtr
1652Cache::evictBlock(CacheBlk *blk)
1653{
1654 PacketPtr pkt = (blk->isDirty() || writebackClean) ?
1655 writebackBlk(blk) : cleanEvictBlk(blk);
1656
1657 invalidateBlock(blk);
1658
1659 return pkt;
1660}
1661
1662void
1663Cache::evictBlock(CacheBlk *blk, PacketList &writebacks)
1664{
1665 PacketPtr pkt = evictBlock(blk);
1666 if (pkt) {
1667 writebacks.push_back(pkt);
1668 }
1669}
1670
1671PacketPtr
866PacketPtr
867Cache::evictBlock(CacheBlk *blk)
868{
869 PacketPtr pkt = (blk->isDirty() || writebackClean) ?
870 writebackBlk(blk) : cleanEvictBlk(blk);
871
872 invalidateBlock(blk);
873
874 return pkt;
875}
876
877void
878Cache::evictBlock(CacheBlk *blk, PacketList &writebacks)
879{
880 PacketPtr pkt = evictBlock(blk);
881 if (pkt) {
882 writebacks.push_back(pkt);
883 }
884}
885
886PacketPtr
1672Cache::writebackBlk(CacheBlk *blk)
1673{
1674 chatty_assert(!isReadOnly || writebackClean,
1675 "Writeback from read-only cache");
1676 assert(blk && blk->isValid() && (blk->isDirty() || writebackClean));
1677
1678 writebacks[Request::wbMasterId]++;
1679
1680 Request *req = new Request(tags->regenerateBlkAddr(blk), blkSize, 0,
1681 Request::wbMasterId);
1682 if (blk->isSecure())
1683 req->setFlags(Request::SECURE);
1684
1685 req->taskId(blk->task_id);
1686
1687 PacketPtr pkt =
1688 new Packet(req, blk->isDirty() ?
1689 MemCmd::WritebackDirty : MemCmd::WritebackClean);
1690
1691 DPRINTF(Cache, "Create Writeback %s writable: %d, dirty: %d\n",
1692 pkt->print(), blk->isWritable(), blk->isDirty());
1693
1694 if (blk->isWritable()) {
1695 // not asserting shared means we pass the block in modified
1696 // state, mark our own block non-writeable
1697 blk->status &= ~BlkWritable;
1698 } else {
1699 // we are in the Owned state, tell the receiver
1700 pkt->setHasSharers();
1701 }
1702
1703 // make sure the block is not marked dirty
1704 blk->status &= ~BlkDirty;
1705
1706 pkt->allocate();
1707 pkt->setDataFromBlock(blk->data, blkSize);
1708
1709 return pkt;
1710}
1711
1712PacketPtr
1713Cache::writecleanBlk(CacheBlk *blk, Request::Flags dest, PacketId id)
1714{
1715 Request *req = new Request(tags->regenerateBlkAddr(blk), blkSize, 0,
1716 Request::wbMasterId);
1717 if (blk->isSecure()) {
1718 req->setFlags(Request::SECURE);
1719 }
1720 req->taskId(blk->task_id);
1721
1722 PacketPtr pkt = new Packet(req, MemCmd::WriteClean, blkSize, id);
1723
1724 if (dest) {
1725 req->setFlags(dest);
1726 pkt->setWriteThrough();
1727 }
1728
1729 DPRINTF(Cache, "Create %s writable: %d, dirty: %d\n", pkt->print(),
1730 blk->isWritable(), blk->isDirty());
1731
1732 if (blk->isWritable()) {
1733 // not asserting shared means we pass the block in modified
1734 // state, mark our own block non-writeable
1735 blk->status &= ~BlkWritable;
1736 } else {
1737 // we are in the Owned state, tell the receiver
1738 pkt->setHasSharers();
1739 }
1740
1741 // make sure the block is not marked dirty
1742 blk->status &= ~BlkDirty;
1743
1744 pkt->allocate();
1745 pkt->setDataFromBlock(blk->data, blkSize);
1746
1747 return pkt;
1748}
1749
1750
1751PacketPtr
1752Cache::cleanEvictBlk(CacheBlk *blk)
1753{
1754 assert(!writebackClean);
1755 assert(blk && blk->isValid() && !blk->isDirty());
1756 // Creating a zero sized write, a message to the snoop filter
1757 Request *req =
1758 new Request(tags->regenerateBlkAddr(blk), blkSize, 0,
1759 Request::wbMasterId);
1760 if (blk->isSecure())
1761 req->setFlags(Request::SECURE);
1762
1763 req->taskId(blk->task_id);
1764
1765 PacketPtr pkt = new Packet(req, MemCmd::CleanEvict);
1766 pkt->allocate();
1767 DPRINTF(Cache, "Create CleanEvict %s\n", pkt->print());
1768
1769 return pkt;
1770}
1771
887Cache::cleanEvictBlk(CacheBlk *blk)
888{
889 assert(!writebackClean);
890 assert(blk && blk->isValid() && !blk->isDirty());
891 // Creating a zero sized write, a message to the snoop filter
892 Request *req =
893 new Request(tags->regenerateBlkAddr(blk), blkSize, 0,
894 Request::wbMasterId);
895 if (blk->isSecure())
896 req->setFlags(Request::SECURE);
897
898 req->taskId(blk->task_id);
899
900 PacketPtr pkt = new Packet(req, MemCmd::CleanEvict);
901 pkt->allocate();
902 DPRINTF(Cache, "Create CleanEvict %s\n", pkt->print());
903
904 return pkt;
905}
906
1772void
1773Cache::memWriteback()
1774{
1775 CacheBlkVisitorWrapper visitor(*this, &Cache::writebackVisitor);
1776 tags->forEachBlk(visitor);
1777}
1778
907
1779void
1780Cache::memInvalidate()
1781{
1782 CacheBlkVisitorWrapper visitor(*this, &Cache::invalidateVisitor);
1783 tags->forEachBlk(visitor);
1784}
1785
1786bool
1787Cache::isDirty() const
1788{
1789 CacheBlkIsDirtyVisitor visitor;
1790 tags->forEachBlk(visitor);
1791
1792 return visitor.isDirty();
1793}
1794
1795bool
1796Cache::writebackVisitor(CacheBlk &blk)
1797{
1798 if (blk.isDirty()) {
1799 assert(blk.isValid());
1800
1801 Request request(tags->regenerateBlkAddr(&blk), blkSize, 0,
1802 Request::funcMasterId);
1803 request.taskId(blk.task_id);
1804 if (blk.isSecure()) {
1805 request.setFlags(Request::SECURE);
1806 }
1807
1808 Packet packet(&request, MemCmd::WriteReq);
1809 packet.dataStatic(blk.data);
1810
1811 memSidePort->sendFunctional(&packet);
1812
1813 blk.status &= ~BlkDirty;
1814 }
1815
1816 return true;
1817}
1818
1819bool
1820Cache::invalidateVisitor(CacheBlk &blk)
1821{
1822
1823 if (blk.isDirty())
1824 warn_once("Invalidating dirty cache lines. Expect things to break.\n");
1825
1826 if (blk.isValid()) {
1827 assert(!blk.isDirty());
1828 invalidateBlock(&blk);
1829 }
1830
1831 return true;
1832}
1833
1834CacheBlk*
1835Cache::allocateBlock(Addr addr, bool is_secure, PacketList &writebacks)
1836{
1837 // Find replacement victim
1838 CacheBlk *blk = tags->findVictim(addr);
1839
1840 // It is valid to return nullptr if there is no victim
1841 if (!blk)
1842 return nullptr;
1843
1844 if (blk->isValid()) {
1845 Addr repl_addr = tags->regenerateBlkAddr(blk);
1846 MSHR *repl_mshr = mshrQueue.findMatch(repl_addr, blk->isSecure());
1847 if (repl_mshr) {
1848 // must be an outstanding upgrade or clean request
1849 // on a block we're about to replace...
1850 assert((!blk->isWritable() && repl_mshr->needsWritable()) ||
1851 repl_mshr->isCleaning());
1852 // too hard to replace block with transient state
1853 // allocation failed, block not inserted
1854 return nullptr;
1855 } else {
1856 DPRINTF(Cache, "replacement: replacing %#llx (%s) with %#llx "
1857 "(%s): %s\n", repl_addr, blk->isSecure() ? "s" : "ns",
1858 addr, is_secure ? "s" : "ns",
1859 blk->isDirty() ? "writeback" : "clean");
1860
1861 if (blk->wasPrefetched()) {
1862 unusedPrefetches++;
1863 }
1864 evictBlock(blk, writebacks);
1865 replacements++;
1866 }
1867 }
1868
1869 return blk;
1870}
1871
1872void
1873Cache::invalidateBlock(CacheBlk *blk)
1874{
1875 if (blk != tempBlock)
1876 tags->invalidate(blk);
1877 blk->invalidate();
1878}
1879
1880// Note that the reason we return a list of writebacks rather than
1881// inserting them directly in the write buffer is that this function
1882// is called by both atomic and timing-mode accesses, and in atomic
1883// mode we don't mess with the write buffer (we just perform the
1884// writebacks atomically once the original request is complete).
1885CacheBlk*
1886Cache::handleFill(PacketPtr pkt, CacheBlk *blk, PacketList &writebacks,
1887 bool allocate)
1888{
1889 assert(pkt->isResponse() || pkt->cmd == MemCmd::WriteLineReq);
1890 Addr addr = pkt->getAddr();
1891 bool is_secure = pkt->isSecure();
1892#if TRACING_ON
1893 CacheBlk::State old_state = blk ? blk->status : 0;
1894#endif
1895
1896 // When handling a fill, we should have no writes to this line.
1897 assert(addr == pkt->getBlockAddr(blkSize));
1898 assert(!writeBuffer.findMatch(addr, is_secure));
1899
1900 if (blk == nullptr) {
1901 // better have read new data...
1902 assert(pkt->hasData());
1903
1904 // only read responses and write-line requests have data;
1905 // note that we don't write the data here for write-line - that
1906 // happens in the subsequent call to satisfyRequest
1907 assert(pkt->isRead() || pkt->cmd == MemCmd::WriteLineReq);
1908
1909 // need to do a replacement if allocating, otherwise we stick
1910 // with the temporary storage
1911 blk = allocate ? allocateBlock(addr, is_secure, writebacks) : nullptr;
1912
1913 if (blk == nullptr) {
1914 // No replaceable block or a mostly exclusive
1915 // cache... just use temporary storage to complete the
1916 // current request and then get rid of it
1917 assert(!tempBlock->isValid());
1918 blk = tempBlock;
1919 tempBlock->set = tags->extractSet(addr);
1920 tempBlock->tag = tags->extractTag(addr);
1921 if (is_secure) {
1922 tempBlock->status |= BlkSecure;
1923 }
1924 DPRINTF(Cache, "using temp block for %#llx (%s)\n", addr,
1925 is_secure ? "s" : "ns");
1926 } else {
1927 tags->insertBlock(pkt, blk);
1928 }
1929
1930 // we should never be overwriting a valid block
1931 assert(!blk->isValid());
1932 } else {
1933 // existing block... probably an upgrade
1934 assert(blk->tag == tags->extractTag(addr));
1935 // either we're getting new data or the block should already be valid
1936 assert(pkt->hasData() || blk->isValid());
1937 // don't clear block status... if block is already dirty we
1938 // don't want to lose that
1939 }
1940
1941 if (is_secure)
1942 blk->status |= BlkSecure;
1943 blk->status |= BlkValid | BlkReadable;
1944
1945 // sanity check for whole-line writes, which should always be
1946 // marked as writable as part of the fill, and then later marked
1947 // dirty as part of satisfyRequest
1948 if (pkt->cmd == MemCmd::WriteLineReq) {
1949 assert(!pkt->hasSharers());
1950 }
1951
1952 // here we deal with setting the appropriate state of the line,
1953 // and we start by looking at the hasSharers flag, and ignore the
1954 // cacheResponding flag (normally signalling dirty data) if the
1955 // packet has sharers, thus the line is never allocated as Owned
1956 // (dirty but not writable), and always ends up being either
1957 // Shared, Exclusive or Modified, see Packet::setCacheResponding
1958 // for more details
1959 if (!pkt->hasSharers()) {
1960 // we could get a writable line from memory (rather than a
1961 // cache) even in a read-only cache, note that we set this bit
1962 // even for a read-only cache, possibly revisit this decision
1963 blk->status |= BlkWritable;
1964
1965 // check if we got this via cache-to-cache transfer (i.e., from a
1966 // cache that had the block in Modified or Owned state)
1967 if (pkt->cacheResponding()) {
1968 // we got the block in Modified state, and invalidated the
1969 // owners copy
1970 blk->status |= BlkDirty;
1971
1972 chatty_assert(!isReadOnly, "Should never see dirty snoop response "
1973 "in read-only cache %s\n", name());
1974 }
1975 }
1976
1977 DPRINTF(Cache, "Block addr %#llx (%s) moving from state %x to %s\n",
1978 addr, is_secure ? "s" : "ns", old_state, blk->print());
1979
1980 // if we got new data, copy it in (checking for a read response
1981 // and a response that has data is the same in the end)
1982 if (pkt->isRead()) {
1983 // sanity checks
1984 assert(pkt->hasData());
1985 assert(pkt->getSize() == blkSize);
1986
1987 pkt->writeDataToBlock(blk->data, blkSize);
1988 }
1989 // We pay for fillLatency here.
1990 blk->whenReady = clockEdge() + fillLatency * clockPeriod() +
1991 pkt->payloadDelay;
1992
1993 return blk;
1994}
1995
1996
1997/////////////////////////////////////////////////////
1998//
1999// Snoop path: requests coming in from the memory side
2000//
2001/////////////////////////////////////////////////////
2002
2003void
2004Cache::doTimingSupplyResponse(PacketPtr req_pkt, const uint8_t *blk_data,
2005 bool already_copied, bool pending_inval)
2006{
2007 // sanity check
2008 assert(req_pkt->isRequest());
2009 assert(req_pkt->needsResponse());
2010
2011 DPRINTF(Cache, "%s: for %s\n", __func__, req_pkt->print());
2012 // timing-mode snoop responses require a new packet, unless we
2013 // already made a copy...
2014 PacketPtr pkt = req_pkt;
2015 if (!already_copied)
2016 // do not clear flags, and allocate space for data if the
2017 // packet needs it (the only packets that carry data are read
2018 // responses)
2019 pkt = new Packet(req_pkt, false, req_pkt->isRead());
2020
2021 assert(req_pkt->req->isUncacheable() || req_pkt->isInvalidate() ||
2022 pkt->hasSharers());
2023 pkt->makeTimingResponse();
2024 if (pkt->isRead()) {
2025 pkt->setDataFromBlock(blk_data, blkSize);
2026 }
2027 if (pkt->cmd == MemCmd::ReadResp && pending_inval) {
2028 // Assume we defer a response to a read from a far-away cache
2029 // A, then later defer a ReadExcl from a cache B on the same
2030 // bus as us. We'll assert cacheResponding in both cases, but
2031 // in the latter case cacheResponding will keep the
2032 // invalidation from reaching cache A. This special response
2033 // tells cache A that it gets the block to satisfy its read,
2034 // but must immediately invalidate it.
2035 pkt->cmd = MemCmd::ReadRespWithInvalidate;
2036 }
2037 // Here we consider forward_time, paying for just forward latency and
2038 // also charging the delay provided by the xbar.
2039 // forward_time is used as send_time in next allocateWriteBuffer().
2040 Tick forward_time = clockEdge(forwardLatency) + pkt->headerDelay;
2041 // Here we reset the timing of the packet.
2042 pkt->headerDelay = pkt->payloadDelay = 0;
2043 DPRINTF(CacheVerbose, "%s: created response: %s tick: %lu\n", __func__,
2044 pkt->print(), forward_time);
908/////////////////////////////////////////////////////
909//
910// Snoop path: requests coming in from the memory side
911//
912/////////////////////////////////////////////////////
913
914void
915Cache::doTimingSupplyResponse(PacketPtr req_pkt, const uint8_t *blk_data,
916 bool already_copied, bool pending_inval)
917{
918 // sanity check
919 assert(req_pkt->isRequest());
920 assert(req_pkt->needsResponse());
921
922 DPRINTF(Cache, "%s: for %s\n", __func__, req_pkt->print());
923 // timing-mode snoop responses require a new packet, unless we
924 // already made a copy...
925 PacketPtr pkt = req_pkt;
926 if (!already_copied)
927 // do not clear flags, and allocate space for data if the
928 // packet needs it (the only packets that carry data are read
929 // responses)
930 pkt = new Packet(req_pkt, false, req_pkt->isRead());
931
932 assert(req_pkt->req->isUncacheable() || req_pkt->isInvalidate() ||
933 pkt->hasSharers());
934 pkt->makeTimingResponse();
935 if (pkt->isRead()) {
936 pkt->setDataFromBlock(blk_data, blkSize);
937 }
938 if (pkt->cmd == MemCmd::ReadResp && pending_inval) {
939 // Assume we defer a response to a read from a far-away cache
940 // A, then later defer a ReadExcl from a cache B on the same
941 // bus as us. We'll assert cacheResponding in both cases, but
942 // in the latter case cacheResponding will keep the
943 // invalidation from reaching cache A. This special response
944 // tells cache A that it gets the block to satisfy its read,
945 // but must immediately invalidate it.
946 pkt->cmd = MemCmd::ReadRespWithInvalidate;
947 }
948 // Here we consider forward_time, paying for just forward latency and
949 // also charging the delay provided by the xbar.
950 // forward_time is used as send_time in next allocateWriteBuffer().
951 Tick forward_time = clockEdge(forwardLatency) + pkt->headerDelay;
952 // Here we reset the timing of the packet.
953 pkt->headerDelay = pkt->payloadDelay = 0;
954 DPRINTF(CacheVerbose, "%s: created response: %s tick: %lu\n", __func__,
955 pkt->print(), forward_time);
2045 memSidePort->schedTimingSnoopResp(pkt, forward_time, true);
956 memSidePort.schedTimingSnoopResp(pkt, forward_time, true);
2046}
2047
2048uint32_t
2049Cache::handleSnoop(PacketPtr pkt, CacheBlk *blk, bool is_timing,
2050 bool is_deferred, bool pending_inval)
2051{
2052 DPRINTF(CacheVerbose, "%s: for %s\n", __func__, pkt->print());
2053 // deferred snoops can only happen in timing mode
2054 assert(!(is_deferred && !is_timing));
2055 // pending_inval only makes sense on deferred snoops
2056 assert(!(pending_inval && !is_deferred));
2057 assert(pkt->isRequest());
2058
2059 // the packet may get modified if we or a forwarded snooper
2060 // responds in atomic mode, so remember a few things about the
2061 // original packet up front
2062 bool invalidate = pkt->isInvalidate();
2063 bool M5_VAR_USED needs_writable = pkt->needsWritable();
2064
2065 // at the moment we could get an uncacheable write which does not
2066 // have the invalidate flag, and we need a suitable way of dealing
2067 // with this case
2068 panic_if(invalidate && pkt->req->isUncacheable(),
2069 "%s got an invalidating uncacheable snoop request %s",
2070 name(), pkt->print());
2071
2072 uint32_t snoop_delay = 0;
2073
2074 if (forwardSnoops) {
2075 // first propagate snoop upward to see if anyone above us wants to
2076 // handle it. save & restore packet src since it will get
2077 // rewritten to be relative to cpu-side bus (if any)
2078 bool alreadyResponded = pkt->cacheResponding();
2079 if (is_timing) {
2080 // copy the packet so that we can clear any flags before
2081 // forwarding it upwards, we also allocate data (passing
2082 // the pointer along in case of static data), in case
2083 // there is a snoop hit in upper levels
2084 Packet snoopPkt(pkt, true, true);
2085 snoopPkt.setExpressSnoop();
2086 // the snoop packet does not need to wait any additional
2087 // time
2088 snoopPkt.headerDelay = snoopPkt.payloadDelay = 0;
957}
958
959uint32_t
960Cache::handleSnoop(PacketPtr pkt, CacheBlk *blk, bool is_timing,
961 bool is_deferred, bool pending_inval)
962{
963 DPRINTF(CacheVerbose, "%s: for %s\n", __func__, pkt->print());
964 // deferred snoops can only happen in timing mode
965 assert(!(is_deferred && !is_timing));
966 // pending_inval only makes sense on deferred snoops
967 assert(!(pending_inval && !is_deferred));
968 assert(pkt->isRequest());
969
970 // the packet may get modified if we or a forwarded snooper
971 // responds in atomic mode, so remember a few things about the
972 // original packet up front
973 bool invalidate = pkt->isInvalidate();
974 bool M5_VAR_USED needs_writable = pkt->needsWritable();
975
976 // at the moment we could get an uncacheable write which does not
977 // have the invalidate flag, and we need a suitable way of dealing
978 // with this case
979 panic_if(invalidate && pkt->req->isUncacheable(),
980 "%s got an invalidating uncacheable snoop request %s",
981 name(), pkt->print());
982
983 uint32_t snoop_delay = 0;
984
985 if (forwardSnoops) {
986 // first propagate snoop upward to see if anyone above us wants to
987 // handle it. save & restore packet src since it will get
988 // rewritten to be relative to cpu-side bus (if any)
989 bool alreadyResponded = pkt->cacheResponding();
990 if (is_timing) {
991 // copy the packet so that we can clear any flags before
992 // forwarding it upwards, we also allocate data (passing
993 // the pointer along in case of static data), in case
994 // there is a snoop hit in upper levels
995 Packet snoopPkt(pkt, true, true);
996 snoopPkt.setExpressSnoop();
997 // the snoop packet does not need to wait any additional
998 // time
999 snoopPkt.headerDelay = snoopPkt.payloadDelay = 0;
2089 cpuSidePort->sendTimingSnoopReq(&snoopPkt);
1000 cpuSidePort.sendTimingSnoopReq(&snoopPkt);
2090
2091 // add the header delay (including crossbar and snoop
2092 // delays) of the upward snoop to the snoop delay for this
2093 // cache
2094 snoop_delay += snoopPkt.headerDelay;
2095
2096 if (snoopPkt.cacheResponding()) {
2097 // cache-to-cache response from some upper cache
2098 assert(!alreadyResponded);
2099 pkt->setCacheResponding();
2100 }
2101 // upstream cache has the block, or has an outstanding
2102 // MSHR, pass the flag on
2103 if (snoopPkt.hasSharers()) {
2104 pkt->setHasSharers();
2105 }
2106 // If this request is a prefetch or clean evict and an upper level
2107 // signals block present, make sure to propagate the block
2108 // presence to the requester.
2109 if (snoopPkt.isBlockCached()) {
2110 pkt->setBlockCached();
2111 }
2112 // If the request was satisfied by snooping the cache
2113 // above, mark the original packet as satisfied too.
2114 if (snoopPkt.satisfied()) {
2115 pkt->setSatisfied();
2116 }
2117 } else {
1001
1002 // add the header delay (including crossbar and snoop
1003 // delays) of the upward snoop to the snoop delay for this
1004 // cache
1005 snoop_delay += snoopPkt.headerDelay;
1006
1007 if (snoopPkt.cacheResponding()) {
1008 // cache-to-cache response from some upper cache
1009 assert(!alreadyResponded);
1010 pkt->setCacheResponding();
1011 }
1012 // upstream cache has the block, or has an outstanding
1013 // MSHR, pass the flag on
1014 if (snoopPkt.hasSharers()) {
1015 pkt->setHasSharers();
1016 }
1017 // If this request is a prefetch or clean evict and an upper level
1018 // signals block present, make sure to propagate the block
1019 // presence to the requester.
1020 if (snoopPkt.isBlockCached()) {
1021 pkt->setBlockCached();
1022 }
1023 // If the request was satisfied by snooping the cache
1024 // above, mark the original packet as satisfied too.
1025 if (snoopPkt.satisfied()) {
1026 pkt->setSatisfied();
1027 }
1028 } else {
2118 cpuSidePort->sendAtomicSnoop(pkt);
1029 cpuSidePort.sendAtomicSnoop(pkt);
2119 if (!alreadyResponded && pkt->cacheResponding()) {
2120 // cache-to-cache response from some upper cache:
2121 // forward response to original requester
2122 assert(pkt->isResponse());
2123 }
2124 }
2125 }
2126
2127 bool respond = false;
2128 bool blk_valid = blk && blk->isValid();
2129 if (pkt->isClean()) {
2130 if (blk_valid && blk->isDirty()) {
2131 DPRINTF(CacheVerbose, "%s: packet (snoop) %s found block: %s\n",
2132 __func__, pkt->print(), blk->print());
2133 PacketPtr wb_pkt = writecleanBlk(blk, pkt->req->getDest(), pkt->id);
2134 PacketList writebacks;
2135 writebacks.push_back(wb_pkt);
2136
2137 if (is_timing) {
2138 // anything that is merely forwarded pays for the forward
2139 // latency and the delay provided by the crossbar
2140 Tick forward_time = clockEdge(forwardLatency) +
2141 pkt->headerDelay;
2142 doWritebacks(writebacks, forward_time);
2143 } else {
2144 doWritebacksAtomic(writebacks);
2145 }
2146 pkt->setSatisfied();
2147 }
2148 } else if (!blk_valid) {
2149 DPRINTF(CacheVerbose, "%s: snoop miss for %s\n", __func__,
2150 pkt->print());
2151 if (is_deferred) {
2152 // we no longer have the block, and will not respond, but a
2153 // packet was allocated in MSHR::handleSnoop and we have
2154 // to delete it
2155 assert(pkt->needsResponse());
2156
2157 // we have passed the block to a cache upstream, that
2158 // cache should be responding
2159 assert(pkt->cacheResponding());
2160
2161 delete pkt;
2162 }
2163 return snoop_delay;
2164 } else {
2165 DPRINTF(Cache, "%s: snoop hit for %s, old state is %s\n", __func__,
2166 pkt->print(), blk->print());
2167
2168 // We may end up modifying both the block state and the packet (if
2169 // we respond in atomic mode), so just figure out what to do now
2170 // and then do it later. We respond to all snoops that need
2171 // responses provided we have the block in dirty state. The
2172 // invalidation itself is taken care of below. We don't respond to
2173 // cache maintenance operations as this is done by the destination
2174 // xbar.
2175 respond = blk->isDirty() && pkt->needsResponse();
2176
2177 chatty_assert(!(isReadOnly && blk->isDirty()), "Should never have "
2178 "a dirty block in a read-only cache %s\n", name());
2179 }
2180
2181 // Invalidate any prefetch's from below that would strip write permissions
2182 // MemCmd::HardPFReq is only observed by upstream caches. After missing
2183 // above and in it's own cache, a new MemCmd::ReadReq is created that
2184 // downstream caches observe.
2185 if (pkt->mustCheckAbove()) {
2186 DPRINTF(Cache, "Found addr %#llx in upper level cache for snoop %s "
2187 "from lower cache\n", pkt->getAddr(), pkt->print());
2188 pkt->setBlockCached();
2189 return snoop_delay;
2190 }
2191
2192 if (pkt->isRead() && !invalidate) {
2193 // reading without requiring the line in a writable state
2194 assert(!needs_writable);
2195 pkt->setHasSharers();
2196
2197 // if the requesting packet is uncacheable, retain the line in
2198 // the current state, otherwhise unset the writable flag,
2199 // which means we go from Modified to Owned (and will respond
2200 // below), remain in Owned (and will respond below), from
2201 // Exclusive to Shared, or remain in Shared
2202 if (!pkt->req->isUncacheable())
2203 blk->status &= ~BlkWritable;
2204 DPRINTF(Cache, "new state is %s\n", blk->print());
2205 }
2206
2207 if (respond) {
2208 // prevent anyone else from responding, cache as well as
2209 // memory, and also prevent any memory from even seeing the
2210 // request
2211 pkt->setCacheResponding();
2212 if (!pkt->isClean() && blk->isWritable()) {
2213 // inform the cache hierarchy that this cache had the line
2214 // in the Modified state so that we avoid unnecessary
2215 // invalidations (see Packet::setResponderHadWritable)
2216 pkt->setResponderHadWritable();
2217
2218 // in the case of an uncacheable request there is no point
2219 // in setting the responderHadWritable flag, but since the
2220 // recipient does not care there is no harm in doing so
2221 } else {
2222 // if the packet has needsWritable set we invalidate our
2223 // copy below and all other copies will be invalidates
2224 // through express snoops, and if needsWritable is not set
2225 // we already called setHasSharers above
2226 }
2227
2228 // if we are returning a writable and dirty (Modified) line,
2229 // we should be invalidating the line
2230 panic_if(!invalidate && !pkt->hasSharers(),
2231 "%s is passing a Modified line through %s, "
2232 "but keeping the block", name(), pkt->print());
2233
2234 if (is_timing) {
2235 doTimingSupplyResponse(pkt, blk->data, is_deferred, pending_inval);
2236 } else {
2237 pkt->makeAtomicResponse();
2238 // packets such as upgrades do not actually have any data
2239 // payload
2240 if (pkt->hasData())
2241 pkt->setDataFromBlock(blk->data, blkSize);
2242 }
2243 }
2244
2245 if (!respond && is_deferred) {
2246 assert(pkt->needsResponse());
2247
2248 // if we copied the deferred packet with the intention to
2249 // respond, but are not responding, then a cache above us must
2250 // be, and we can use this as the indication of whether this
2251 // is a packet where we created a copy of the request or not
2252 if (!pkt->cacheResponding()) {
2253 delete pkt->req;
2254 }
2255
2256 delete pkt;
2257 }
2258
2259 // Do this last in case it deallocates block data or something
2260 // like that
2261 if (blk_valid && invalidate) {
2262 invalidateBlock(blk);
2263 DPRINTF(Cache, "new state is %s\n", blk->print());
2264 }
2265
2266 return snoop_delay;
2267}
2268
2269
2270void
2271Cache::recvTimingSnoopReq(PacketPtr pkt)
2272{
2273 DPRINTF(CacheVerbose, "%s: for %s\n", __func__, pkt->print());
2274
2275 // Snoops shouldn't happen when bypassing caches
2276 assert(!system->bypassCaches());
2277
2278 // no need to snoop requests that are not in range
2279 if (!inRange(pkt->getAddr())) {
2280 return;
2281 }
2282
2283 bool is_secure = pkt->isSecure();
2284 CacheBlk *blk = tags->findBlock(pkt->getAddr(), is_secure);
2285
2286 Addr blk_addr = pkt->getBlockAddr(blkSize);
2287 MSHR *mshr = mshrQueue.findMatch(blk_addr, is_secure);
2288
2289 // Update the latency cost of the snoop so that the crossbar can
2290 // account for it. Do not overwrite what other neighbouring caches
2291 // have already done, rather take the maximum. The update is
2292 // tentative, for cases where we return before an upward snoop
2293 // happens below.
2294 pkt->snoopDelay = std::max<uint32_t>(pkt->snoopDelay,
2295 lookupLatency * clockPeriod());
2296
2297 // Inform request(Prefetch, CleanEvict or Writeback) from below of
2298 // MSHR hit, set setBlockCached.
2299 if (mshr && pkt->mustCheckAbove()) {
2300 DPRINTF(Cache, "Setting block cached for %s from lower cache on "
2301 "mshr hit\n", pkt->print());
2302 pkt->setBlockCached();
2303 return;
2304 }
2305
2306 // Bypass any existing cache maintenance requests if the request
2307 // has been satisfied already (i.e., the dirty block has been
2308 // found).
2309 if (mshr && pkt->req->isCacheMaintenance() && pkt->satisfied()) {
2310 return;
2311 }
2312
2313 // Let the MSHR itself track the snoop and decide whether we want
2314 // to go ahead and do the regular cache snoop
2315 if (mshr && mshr->handleSnoop(pkt, order++)) {
2316 DPRINTF(Cache, "Deferring snoop on in-service MSHR to blk %#llx (%s)."
2317 "mshrs: %s\n", blk_addr, is_secure ? "s" : "ns",
2318 mshr->print());
2319
2320 if (mshr->getNumTargets() > numTarget)
2321 warn("allocating bonus target for snoop"); //handle later
2322 return;
2323 }
2324
2325 //We also need to check the writeback buffers and handle those
2326 WriteQueueEntry *wb_entry = writeBuffer.findMatch(blk_addr, is_secure);
2327 if (wb_entry) {
2328 DPRINTF(Cache, "Snoop hit in writeback to addr %#llx (%s)\n",
2329 pkt->getAddr(), is_secure ? "s" : "ns");
2330 // Expect to see only Writebacks and/or CleanEvicts here, both of
2331 // which should not be generated for uncacheable data.
2332 assert(!wb_entry->isUncacheable());
2333 // There should only be a single request responsible for generating
2334 // Writebacks/CleanEvicts.
2335 assert(wb_entry->getNumTargets() == 1);
2336 PacketPtr wb_pkt = wb_entry->getTarget()->pkt;
2337 assert(wb_pkt->isEviction() || wb_pkt->cmd == MemCmd::WriteClean);
2338
2339 if (pkt->isEviction()) {
2340 // if the block is found in the write queue, set the BLOCK_CACHED
2341 // flag for Writeback/CleanEvict snoop. On return the snoop will
2342 // propagate the BLOCK_CACHED flag in Writeback packets and prevent
2343 // any CleanEvicts from travelling down the memory hierarchy.
2344 pkt->setBlockCached();
2345 DPRINTF(Cache, "%s: Squashing %s from lower cache on writequeue "
2346 "hit\n", __func__, pkt->print());
2347 return;
2348 }
2349
2350 // conceptually writebacks are no different to other blocks in
2351 // this cache, so the behaviour is modelled after handleSnoop,
2352 // the difference being that instead of querying the block
2353 // state to determine if it is dirty and writable, we use the
2354 // command and fields of the writeback packet
2355 bool respond = wb_pkt->cmd == MemCmd::WritebackDirty &&
2356 pkt->needsResponse();
2357 bool have_writable = !wb_pkt->hasSharers();
2358 bool invalidate = pkt->isInvalidate();
2359
2360 if (!pkt->req->isUncacheable() && pkt->isRead() && !invalidate) {
2361 assert(!pkt->needsWritable());
2362 pkt->setHasSharers();
2363 wb_pkt->setHasSharers();
2364 }
2365
2366 if (respond) {
2367 pkt->setCacheResponding();
2368
2369 if (have_writable) {
2370 pkt->setResponderHadWritable();
2371 }
2372
2373 doTimingSupplyResponse(pkt, wb_pkt->getConstPtr<uint8_t>(),
2374 false, false);
2375 }
2376
2377 if (invalidate && wb_pkt->cmd != MemCmd::WriteClean) {
2378 // Invalidation trumps our writeback... discard here
2379 // Note: markInService will remove entry from writeback buffer.
2380 markInService(wb_entry);
2381 delete wb_pkt;
2382 }
2383 }
2384
2385 // If this was a shared writeback, there may still be
2386 // other shared copies above that require invalidation.
2387 // We could be more selective and return here if the
2388 // request is non-exclusive or if the writeback is
2389 // exclusive.
2390 uint32_t snoop_delay = handleSnoop(pkt, blk, true, false, false);
2391
2392 // Override what we did when we first saw the snoop, as we now
2393 // also have the cost of the upwards snoops to account for
2394 pkt->snoopDelay = std::max<uint32_t>(pkt->snoopDelay, snoop_delay +
2395 lookupLatency * clockPeriod());
2396}
2397
1030 if (!alreadyResponded && pkt->cacheResponding()) {
1031 // cache-to-cache response from some upper cache:
1032 // forward response to original requester
1033 assert(pkt->isResponse());
1034 }
1035 }
1036 }
1037
1038 bool respond = false;
1039 bool blk_valid = blk && blk->isValid();
1040 if (pkt->isClean()) {
1041 if (blk_valid && blk->isDirty()) {
1042 DPRINTF(CacheVerbose, "%s: packet (snoop) %s found block: %s\n",
1043 __func__, pkt->print(), blk->print());
1044 PacketPtr wb_pkt = writecleanBlk(blk, pkt->req->getDest(), pkt->id);
1045 PacketList writebacks;
1046 writebacks.push_back(wb_pkt);
1047
1048 if (is_timing) {
1049 // anything that is merely forwarded pays for the forward
1050 // latency and the delay provided by the crossbar
1051 Tick forward_time = clockEdge(forwardLatency) +
1052 pkt->headerDelay;
1053 doWritebacks(writebacks, forward_time);
1054 } else {
1055 doWritebacksAtomic(writebacks);
1056 }
1057 pkt->setSatisfied();
1058 }
1059 } else if (!blk_valid) {
1060 DPRINTF(CacheVerbose, "%s: snoop miss for %s\n", __func__,
1061 pkt->print());
1062 if (is_deferred) {
1063 // we no longer have the block, and will not respond, but a
1064 // packet was allocated in MSHR::handleSnoop and we have
1065 // to delete it
1066 assert(pkt->needsResponse());
1067
1068 // we have passed the block to a cache upstream, that
1069 // cache should be responding
1070 assert(pkt->cacheResponding());
1071
1072 delete pkt;
1073 }
1074 return snoop_delay;
1075 } else {
1076 DPRINTF(Cache, "%s: snoop hit for %s, old state is %s\n", __func__,
1077 pkt->print(), blk->print());
1078
1079 // We may end up modifying both the block state and the packet (if
1080 // we respond in atomic mode), so just figure out what to do now
1081 // and then do it later. We respond to all snoops that need
1082 // responses provided we have the block in dirty state. The
1083 // invalidation itself is taken care of below. We don't respond to
1084 // cache maintenance operations as this is done by the destination
1085 // xbar.
1086 respond = blk->isDirty() && pkt->needsResponse();
1087
1088 chatty_assert(!(isReadOnly && blk->isDirty()), "Should never have "
1089 "a dirty block in a read-only cache %s\n", name());
1090 }
1091
1092 // Invalidate any prefetch's from below that would strip write permissions
1093 // MemCmd::HardPFReq is only observed by upstream caches. After missing
1094 // above and in it's own cache, a new MemCmd::ReadReq is created that
1095 // downstream caches observe.
1096 if (pkt->mustCheckAbove()) {
1097 DPRINTF(Cache, "Found addr %#llx in upper level cache for snoop %s "
1098 "from lower cache\n", pkt->getAddr(), pkt->print());
1099 pkt->setBlockCached();
1100 return snoop_delay;
1101 }
1102
1103 if (pkt->isRead() && !invalidate) {
1104 // reading without requiring the line in a writable state
1105 assert(!needs_writable);
1106 pkt->setHasSharers();
1107
1108 // if the requesting packet is uncacheable, retain the line in
1109 // the current state, otherwhise unset the writable flag,
1110 // which means we go from Modified to Owned (and will respond
1111 // below), remain in Owned (and will respond below), from
1112 // Exclusive to Shared, or remain in Shared
1113 if (!pkt->req->isUncacheable())
1114 blk->status &= ~BlkWritable;
1115 DPRINTF(Cache, "new state is %s\n", blk->print());
1116 }
1117
1118 if (respond) {
1119 // prevent anyone else from responding, cache as well as
1120 // memory, and also prevent any memory from even seeing the
1121 // request
1122 pkt->setCacheResponding();
1123 if (!pkt->isClean() && blk->isWritable()) {
1124 // inform the cache hierarchy that this cache had the line
1125 // in the Modified state so that we avoid unnecessary
1126 // invalidations (see Packet::setResponderHadWritable)
1127 pkt->setResponderHadWritable();
1128
1129 // in the case of an uncacheable request there is no point
1130 // in setting the responderHadWritable flag, but since the
1131 // recipient does not care there is no harm in doing so
1132 } else {
1133 // if the packet has needsWritable set we invalidate our
1134 // copy below and all other copies will be invalidates
1135 // through express snoops, and if needsWritable is not set
1136 // we already called setHasSharers above
1137 }
1138
1139 // if we are returning a writable and dirty (Modified) line,
1140 // we should be invalidating the line
1141 panic_if(!invalidate && !pkt->hasSharers(),
1142 "%s is passing a Modified line through %s, "
1143 "but keeping the block", name(), pkt->print());
1144
1145 if (is_timing) {
1146 doTimingSupplyResponse(pkt, blk->data, is_deferred, pending_inval);
1147 } else {
1148 pkt->makeAtomicResponse();
1149 // packets such as upgrades do not actually have any data
1150 // payload
1151 if (pkt->hasData())
1152 pkt->setDataFromBlock(blk->data, blkSize);
1153 }
1154 }
1155
1156 if (!respond && is_deferred) {
1157 assert(pkt->needsResponse());
1158
1159 // if we copied the deferred packet with the intention to
1160 // respond, but are not responding, then a cache above us must
1161 // be, and we can use this as the indication of whether this
1162 // is a packet where we created a copy of the request or not
1163 if (!pkt->cacheResponding()) {
1164 delete pkt->req;
1165 }
1166
1167 delete pkt;
1168 }
1169
1170 // Do this last in case it deallocates block data or something
1171 // like that
1172 if (blk_valid && invalidate) {
1173 invalidateBlock(blk);
1174 DPRINTF(Cache, "new state is %s\n", blk->print());
1175 }
1176
1177 return snoop_delay;
1178}
1179
1180
1181void
1182Cache::recvTimingSnoopReq(PacketPtr pkt)
1183{
1184 DPRINTF(CacheVerbose, "%s: for %s\n", __func__, pkt->print());
1185
1186 // Snoops shouldn't happen when bypassing caches
1187 assert(!system->bypassCaches());
1188
1189 // no need to snoop requests that are not in range
1190 if (!inRange(pkt->getAddr())) {
1191 return;
1192 }
1193
1194 bool is_secure = pkt->isSecure();
1195 CacheBlk *blk = tags->findBlock(pkt->getAddr(), is_secure);
1196
1197 Addr blk_addr = pkt->getBlockAddr(blkSize);
1198 MSHR *mshr = mshrQueue.findMatch(blk_addr, is_secure);
1199
1200 // Update the latency cost of the snoop so that the crossbar can
1201 // account for it. Do not overwrite what other neighbouring caches
1202 // have already done, rather take the maximum. The update is
1203 // tentative, for cases where we return before an upward snoop
1204 // happens below.
1205 pkt->snoopDelay = std::max<uint32_t>(pkt->snoopDelay,
1206 lookupLatency * clockPeriod());
1207
1208 // Inform request(Prefetch, CleanEvict or Writeback) from below of
1209 // MSHR hit, set setBlockCached.
1210 if (mshr && pkt->mustCheckAbove()) {
1211 DPRINTF(Cache, "Setting block cached for %s from lower cache on "
1212 "mshr hit\n", pkt->print());
1213 pkt->setBlockCached();
1214 return;
1215 }
1216
1217 // Bypass any existing cache maintenance requests if the request
1218 // has been satisfied already (i.e., the dirty block has been
1219 // found).
1220 if (mshr && pkt->req->isCacheMaintenance() && pkt->satisfied()) {
1221 return;
1222 }
1223
1224 // Let the MSHR itself track the snoop and decide whether we want
1225 // to go ahead and do the regular cache snoop
1226 if (mshr && mshr->handleSnoop(pkt, order++)) {
1227 DPRINTF(Cache, "Deferring snoop on in-service MSHR to blk %#llx (%s)."
1228 "mshrs: %s\n", blk_addr, is_secure ? "s" : "ns",
1229 mshr->print());
1230
1231 if (mshr->getNumTargets() > numTarget)
1232 warn("allocating bonus target for snoop"); //handle later
1233 return;
1234 }
1235
1236 //We also need to check the writeback buffers and handle those
1237 WriteQueueEntry *wb_entry = writeBuffer.findMatch(blk_addr, is_secure);
1238 if (wb_entry) {
1239 DPRINTF(Cache, "Snoop hit in writeback to addr %#llx (%s)\n",
1240 pkt->getAddr(), is_secure ? "s" : "ns");
1241 // Expect to see only Writebacks and/or CleanEvicts here, both of
1242 // which should not be generated for uncacheable data.
1243 assert(!wb_entry->isUncacheable());
1244 // There should only be a single request responsible for generating
1245 // Writebacks/CleanEvicts.
1246 assert(wb_entry->getNumTargets() == 1);
1247 PacketPtr wb_pkt = wb_entry->getTarget()->pkt;
1248 assert(wb_pkt->isEviction() || wb_pkt->cmd == MemCmd::WriteClean);
1249
1250 if (pkt->isEviction()) {
1251 // if the block is found in the write queue, set the BLOCK_CACHED
1252 // flag for Writeback/CleanEvict snoop. On return the snoop will
1253 // propagate the BLOCK_CACHED flag in Writeback packets and prevent
1254 // any CleanEvicts from travelling down the memory hierarchy.
1255 pkt->setBlockCached();
1256 DPRINTF(Cache, "%s: Squashing %s from lower cache on writequeue "
1257 "hit\n", __func__, pkt->print());
1258 return;
1259 }
1260
1261 // conceptually writebacks are no different to other blocks in
1262 // this cache, so the behaviour is modelled after handleSnoop,
1263 // the difference being that instead of querying the block
1264 // state to determine if it is dirty and writable, we use the
1265 // command and fields of the writeback packet
1266 bool respond = wb_pkt->cmd == MemCmd::WritebackDirty &&
1267 pkt->needsResponse();
1268 bool have_writable = !wb_pkt->hasSharers();
1269 bool invalidate = pkt->isInvalidate();
1270
1271 if (!pkt->req->isUncacheable() && pkt->isRead() && !invalidate) {
1272 assert(!pkt->needsWritable());
1273 pkt->setHasSharers();
1274 wb_pkt->setHasSharers();
1275 }
1276
1277 if (respond) {
1278 pkt->setCacheResponding();
1279
1280 if (have_writable) {
1281 pkt->setResponderHadWritable();
1282 }
1283
1284 doTimingSupplyResponse(pkt, wb_pkt->getConstPtr<uint8_t>(),
1285 false, false);
1286 }
1287
1288 if (invalidate && wb_pkt->cmd != MemCmd::WriteClean) {
1289 // Invalidation trumps our writeback... discard here
1290 // Note: markInService will remove entry from writeback buffer.
1291 markInService(wb_entry);
1292 delete wb_pkt;
1293 }
1294 }
1295
1296 // If this was a shared writeback, there may still be
1297 // other shared copies above that require invalidation.
1298 // We could be more selective and return here if the
1299 // request is non-exclusive or if the writeback is
1300 // exclusive.
1301 uint32_t snoop_delay = handleSnoop(pkt, blk, true, false, false);
1302
1303 // Override what we did when we first saw the snoop, as we now
1304 // also have the cost of the upwards snoops to account for
1305 pkt->snoopDelay = std::max<uint32_t>(pkt->snoopDelay, snoop_delay +
1306 lookupLatency * clockPeriod());
1307}
1308
2398bool
2399Cache::CpuSidePort::recvTimingSnoopResp(PacketPtr pkt)
2400{
2401 // Express snoop responses from master to slave, e.g., from L1 to L2
2402 cache->recvTimingSnoopResp(pkt);
2403 return true;
2404}
2405
2406Tick
2407Cache::recvAtomicSnoop(PacketPtr pkt)
2408{
2409 // Snoops shouldn't happen when bypassing caches
2410 assert(!system->bypassCaches());
2411
2412 // no need to snoop requests that are not in range.
2413 if (!inRange(pkt->getAddr())) {
2414 return 0;
2415 }
2416
2417 CacheBlk *blk = tags->findBlock(pkt->getAddr(), pkt->isSecure());
2418 uint32_t snoop_delay = handleSnoop(pkt, blk, false, false, false);
2419 return snoop_delay + lookupLatency * clockPeriod();
2420}
2421
1309Tick
1310Cache::recvAtomicSnoop(PacketPtr pkt)
1311{
1312 // Snoops shouldn't happen when bypassing caches
1313 assert(!system->bypassCaches());
1314
1315 // no need to snoop requests that are not in range.
1316 if (!inRange(pkt->getAddr())) {
1317 return 0;
1318 }
1319
1320 CacheBlk *blk = tags->findBlock(pkt->getAddr(), pkt->isSecure());
1321 uint32_t snoop_delay = handleSnoop(pkt, blk, false, false, false);
1322 return snoop_delay + lookupLatency * clockPeriod();
1323}
1324
2422
2423QueueEntry*
2424Cache::getNextQueueEntry()
2425{
2426 // Check both MSHR queue and write buffer for potential requests,
2427 // note that null does not mean there is no request, it could
2428 // simply be that it is not ready
2429 MSHR *miss_mshr = mshrQueue.getNext();
2430 WriteQueueEntry *wq_entry = writeBuffer.getNext();
2431
2432 // If we got a write buffer request ready, first priority is a
2433 // full write buffer, otherwise we favour the miss requests
2434 if (wq_entry && (writeBuffer.isFull() || !miss_mshr)) {
2435 // need to search MSHR queue for conflicting earlier miss.
2436 MSHR *conflict_mshr =
2437 mshrQueue.findPending(wq_entry->blkAddr,
2438 wq_entry->isSecure);
2439
2440 if (conflict_mshr && conflict_mshr->order < wq_entry->order) {
2441 // Service misses in order until conflict is cleared.
2442 return conflict_mshr;
2443
2444 // @todo Note that we ignore the ready time of the conflict here
2445 }
2446
2447 // No conflicts; issue write
2448 return wq_entry;
2449 } else if (miss_mshr) {
2450 // need to check for conflicting earlier writeback
2451 WriteQueueEntry *conflict_mshr =
2452 writeBuffer.findPending(miss_mshr->blkAddr,
2453 miss_mshr->isSecure);
2454 if (conflict_mshr) {
2455 // not sure why we don't check order here... it was in the
2456 // original code but commented out.
2457
2458 // The only way this happens is if we are
2459 // doing a write and we didn't have permissions
2460 // then subsequently saw a writeback (owned got evicted)
2461 // We need to make sure to perform the writeback first
2462 // To preserve the dirty data, then we can issue the write
2463
2464 // should we return wq_entry here instead? I.e. do we
2465 // have to flush writes in order? I don't think so... not
2466 // for Alpha anyway. Maybe for x86?
2467 return conflict_mshr;
2468
2469 // @todo Note that we ignore the ready time of the conflict here
2470 }
2471
2472 // No conflicts; issue read
2473 return miss_mshr;
2474 }
2475
2476 // fall through... no pending requests. Try a prefetch.
2477 assert(!miss_mshr && !wq_entry);
2478 if (prefetcher && mshrQueue.canPrefetch()) {
2479 // If we have a miss queue slot, we can try a prefetch
2480 PacketPtr pkt = prefetcher->getPacket();
2481 if (pkt) {
2482 Addr pf_addr = pkt->getBlockAddr(blkSize);
2483 if (!tags->findBlock(pf_addr, pkt->isSecure()) &&
2484 !mshrQueue.findMatch(pf_addr, pkt->isSecure()) &&
2485 !writeBuffer.findMatch(pf_addr, pkt->isSecure())) {
2486 // Update statistic on number of prefetches issued
2487 // (hwpf_mshr_misses)
2488 assert(pkt->req->masterId() < system->maxMasters());
2489 mshr_misses[pkt->cmdToIndex()][pkt->req->masterId()]++;
2490
2491 // allocate an MSHR and return it, note
2492 // that we send the packet straight away, so do not
2493 // schedule the send
2494 return allocateMissBuffer(pkt, curTick(), false);
2495 } else {
2496 // free the request and packet
2497 delete pkt->req;
2498 delete pkt;
2499 }
2500 }
2501 }
2502
2503 return nullptr;
2504}
2505
2506bool
1325bool
2507Cache::isCachedAbove(PacketPtr pkt, bool is_timing) const
1326Cache::isCachedAbove(PacketPtr pkt, bool is_timing)
2508{
2509 if (!forwardSnoops)
2510 return false;
2511 // Mirroring the flow of HardPFReqs, the cache sends CleanEvict and
2512 // Writeback snoops into upper level caches to check for copies of the
2513 // same block. Using the BLOCK_CACHED flag with the Writeback/CleanEvict
2514 // packet, the cache can inform the crossbar below of presence or absence
2515 // of the block.
2516 if (is_timing) {
2517 Packet snoop_pkt(pkt, true, false);
2518 snoop_pkt.setExpressSnoop();
2519 // Assert that packet is either Writeback or CleanEvict and not a
2520 // prefetch request because prefetch requests need an MSHR and may
2521 // generate a snoop response.
2522 assert(pkt->isEviction() || pkt->cmd == MemCmd::WriteClean);
2523 snoop_pkt.senderState = nullptr;
1327{
1328 if (!forwardSnoops)
1329 return false;
1330 // Mirroring the flow of HardPFReqs, the cache sends CleanEvict and
1331 // Writeback snoops into upper level caches to check for copies of the
1332 // same block. Using the BLOCK_CACHED flag with the Writeback/CleanEvict
1333 // packet, the cache can inform the crossbar below of presence or absence
1334 // of the block.
1335 if (is_timing) {
1336 Packet snoop_pkt(pkt, true, false);
1337 snoop_pkt.setExpressSnoop();
1338 // Assert that packet is either Writeback or CleanEvict and not a
1339 // prefetch request because prefetch requests need an MSHR and may
1340 // generate a snoop response.
1341 assert(pkt->isEviction() || pkt->cmd == MemCmd::WriteClean);
1342 snoop_pkt.senderState = nullptr;
2524 cpuSidePort->sendTimingSnoopReq(&snoop_pkt);
1343 cpuSidePort.sendTimingSnoopReq(&snoop_pkt);
2525 // Writeback/CleanEvict snoops do not generate a snoop response.
2526 assert(!(snoop_pkt.cacheResponding()));
2527 return snoop_pkt.isBlockCached();
2528 } else {
1344 // Writeback/CleanEvict snoops do not generate a snoop response.
1345 assert(!(snoop_pkt.cacheResponding()));
1346 return snoop_pkt.isBlockCached();
1347 } else {
2529 cpuSidePort->sendAtomicSnoop(pkt);
1348 cpuSidePort.sendAtomicSnoop(pkt);
2530 return pkt->isBlockCached();
2531 }
2532}
2533
1349 return pkt->isBlockCached();
1350 }
1351}
1352
2534Tick
2535Cache::nextQueueReadyTime() const
2536{
2537 Tick nextReady = std::min(mshrQueue.nextReadyTime(),
2538 writeBuffer.nextReadyTime());
2539
2540 // Don't signal prefetch ready time if no MSHRs available
2541 // Will signal once enoguh MSHRs are deallocated
2542 if (prefetcher && mshrQueue.canPrefetch()) {
2543 nextReady = std::min(nextReady,
2544 prefetcher->nextPrefetchReadyTime());
2545 }
2546
2547 return nextReady;
2548}
2549
2550bool
2551Cache::sendMSHRQueuePacket(MSHR* mshr)
2552{
2553 assert(mshr);
2554
2555 // use request from 1st target
2556 PacketPtr tgt_pkt = mshr->getTarget()->pkt;
2557
1353bool
1354Cache::sendMSHRQueuePacket(MSHR* mshr)
1355{
1356 assert(mshr);
1357
1358 // use request from 1st target
1359 PacketPtr tgt_pkt = mshr->getTarget()->pkt;
1360
2558 DPRINTF(Cache, "%s: MSHR %s\n", __func__, tgt_pkt->print());
2559
2560 CacheBlk *blk = tags->findBlock(mshr->blkAddr, mshr->isSecure);
2561
2562 if (tgt_pkt->cmd == MemCmd::HardPFReq && forwardSnoops) {
1361 if (tgt_pkt->cmd == MemCmd::HardPFReq && forwardSnoops) {
1362 DPRINTF(Cache, "%s: MSHR %s\n", __func__, tgt_pkt->print());
1363
2563 // we should never have hardware prefetches to allocated
2564 // blocks
1364 // we should never have hardware prefetches to allocated
1365 // blocks
2565 assert(blk == nullptr);
1366 assert(!tags->findBlock(mshr->blkAddr, mshr->isSecure));
2566
2567 // We need to check the caches above us to verify that
2568 // they don't have a copy of this block in the dirty state
2569 // at the moment. Without this check we could get a stale
2570 // copy from memory that might get used in place of the
2571 // dirty one.
2572 Packet snoop_pkt(tgt_pkt, true, false);
2573 snoop_pkt.setExpressSnoop();
2574 // We are sending this packet upwards, but if it hits we will
2575 // get a snoop response that we end up treating just like a
2576 // normal response, hence it needs the MSHR as its sender
2577 // state
2578 snoop_pkt.senderState = mshr;
1367
1368 // We need to check the caches above us to verify that
1369 // they don't have a copy of this block in the dirty state
1370 // at the moment. Without this check we could get a stale
1371 // copy from memory that might get used in place of the
1372 // dirty one.
1373 Packet snoop_pkt(tgt_pkt, true, false);
1374 snoop_pkt.setExpressSnoop();
1375 // We are sending this packet upwards, but if it hits we will
1376 // get a snoop response that we end up treating just like a
1377 // normal response, hence it needs the MSHR as its sender
1378 // state
1379 snoop_pkt.senderState = mshr;
2579 cpuSidePort->sendTimingSnoopReq(&snoop_pkt);
1380 cpuSidePort.sendTimingSnoopReq(&snoop_pkt);
2580
2581 // Check to see if the prefetch was squashed by an upper cache (to
2582 // prevent us from grabbing the line) or if a Check to see if a
2583 // writeback arrived between the time the prefetch was placed in
2584 // the MSHRs and when it was selected to be sent or if the
2585 // prefetch was squashed by an upper cache.
2586
2587 // It is important to check cacheResponding before
2588 // prefetchSquashed. If another cache has committed to
2589 // responding, it will be sending a dirty response which will
2590 // arrive at the MSHR allocated for this request. Checking the
2591 // prefetchSquash first may result in the MSHR being
2592 // prematurely deallocated.
2593 if (snoop_pkt.cacheResponding()) {
2594 auto M5_VAR_USED r = outstandingSnoop.insert(snoop_pkt.req);
2595 assert(r.second);
2596
2597 // if we are getting a snoop response with no sharers it
2598 // will be allocated as Modified
2599 bool pending_modified_resp = !snoop_pkt.hasSharers();
2600 markInService(mshr, pending_modified_resp);
2601
2602 DPRINTF(Cache, "Upward snoop of prefetch for addr"
2603 " %#x (%s) hit\n",
2604 tgt_pkt->getAddr(), tgt_pkt->isSecure()? "s": "ns");
2605 return false;
2606 }
2607
2608 if (snoop_pkt.isBlockCached()) {
2609 DPRINTF(Cache, "Block present, prefetch squashed by cache. "
2610 "Deallocating mshr target %#x.\n",
2611 mshr->blkAddr);
2612
2613 // Deallocate the mshr target
2614 if (mshrQueue.forceDeallocateTarget(mshr)) {
2615 // Clear block if this deallocation resulted freed an
2616 // mshr when all had previously been utilized
2617 clearBlocked(Blocked_NoMSHRs);
2618 }
2619
2620 // given that no response is expected, delete Request and Packet
2621 delete tgt_pkt->req;
2622 delete tgt_pkt;
2623
2624 return false;
2625 }
2626 }
2627
1381
1382 // Check to see if the prefetch was squashed by an upper cache (to
1383 // prevent us from grabbing the line) or if a Check to see if a
1384 // writeback arrived between the time the prefetch was placed in
1385 // the MSHRs and when it was selected to be sent or if the
1386 // prefetch was squashed by an upper cache.
1387
1388 // It is important to check cacheResponding before
1389 // prefetchSquashed. If another cache has committed to
1390 // responding, it will be sending a dirty response which will
1391 // arrive at the MSHR allocated for this request. Checking the
1392 // prefetchSquash first may result in the MSHR being
1393 // prematurely deallocated.
1394 if (snoop_pkt.cacheResponding()) {
1395 auto M5_VAR_USED r = outstandingSnoop.insert(snoop_pkt.req);
1396 assert(r.second);
1397
1398 // if we are getting a snoop response with no sharers it
1399 // will be allocated as Modified
1400 bool pending_modified_resp = !snoop_pkt.hasSharers();
1401 markInService(mshr, pending_modified_resp);
1402
1403 DPRINTF(Cache, "Upward snoop of prefetch for addr"
1404 " %#x (%s) hit\n",
1405 tgt_pkt->getAddr(), tgt_pkt->isSecure()? "s": "ns");
1406 return false;
1407 }
1408
1409 if (snoop_pkt.isBlockCached()) {
1410 DPRINTF(Cache, "Block present, prefetch squashed by cache. "
1411 "Deallocating mshr target %#x.\n",
1412 mshr->blkAddr);
1413
1414 // Deallocate the mshr target
1415 if (mshrQueue.forceDeallocateTarget(mshr)) {
1416 // Clear block if this deallocation resulted freed an
1417 // mshr when all had previously been utilized
1418 clearBlocked(Blocked_NoMSHRs);
1419 }
1420
1421 // given that no response is expected, delete Request and Packet
1422 delete tgt_pkt->req;
1423 delete tgt_pkt;
1424
1425 return false;
1426 }
1427 }
1428
2628 // either a prefetch that is not present upstream, or a normal
2629 // MSHR request, proceed to get the packet to send downstream
2630 PacketPtr pkt = createMissPacket(tgt_pkt, blk, mshr->needsWritable());
2631
2632 mshr->isForward = (pkt == nullptr);
2633
2634 if (mshr->isForward) {
2635 // not a cache block request, but a response is expected
2636 // make copy of current packet to forward, keep current
2637 // copy for response handling
2638 pkt = new Packet(tgt_pkt, false, true);
2639 assert(!pkt->isWrite());
2640 }
2641
2642 // play it safe and append (rather than set) the sender state,
2643 // as forwarded packets may already have existing state
2644 pkt->pushSenderState(mshr);
2645
2646 if (pkt->isClean() && blk && blk->isDirty()) {
2647 // A cache clean opearation is looking for a dirty block. Mark
2648 // the packet so that the destination xbar can determine that
2649 // there will be a follow-up write packet as well.
2650 pkt->setSatisfied();
2651 }
2652
2653 if (!memSidePort->sendTimingReq(pkt)) {
2654 // we are awaiting a retry, but we
2655 // delete the packet and will be creating a new packet
2656 // when we get the opportunity
2657 delete pkt;
2658
2659 // note that we have now masked any requestBus and
2660 // schedSendEvent (we will wait for a retry before
2661 // doing anything), and this is so even if we do not
2662 // care about this packet and might override it before
2663 // it gets retried
2664 return true;
2665 } else {
2666 // As part of the call to sendTimingReq the packet is
2667 // forwarded to all neighbouring caches (and any caches
2668 // above them) as a snoop. Thus at this point we know if
2669 // any of the neighbouring caches are responding, and if
2670 // so, we know it is dirty, and we can determine if it is
2671 // being passed as Modified, making our MSHR the ordering
2672 // point
2673 bool pending_modified_resp = !pkt->hasSharers() &&
2674 pkt->cacheResponding();
2675 markInService(mshr, pending_modified_resp);
2676 if (pkt->isClean() && blk && blk->isDirty()) {
2677 // A cache clean opearation is looking for a dirty
2678 // block. If a dirty block is encountered a WriteClean
2679 // will update any copies to the path to the memory
2680 // until the point of reference.
2681 DPRINTF(CacheVerbose, "%s: packet %s found block: %s\n",
2682 __func__, pkt->print(), blk->print());
2683 PacketPtr wb_pkt = writecleanBlk(blk, pkt->req->getDest(),
2684 pkt->id);
2685 PacketList writebacks;
2686 writebacks.push_back(wb_pkt);
2687 doWritebacks(writebacks, 0);
2688 }
2689
2690 return false;
2691 }
1429 return BaseCache::sendMSHRQueuePacket(mshr);
2692}
2693
1430}
1431
2694bool
2695Cache::sendWriteQueuePacket(WriteQueueEntry* wq_entry)
2696{
2697 assert(wq_entry);
2698
2699 // always a single target for write queue entries
2700 PacketPtr tgt_pkt = wq_entry->getTarget()->pkt;
2701
2702 DPRINTF(Cache, "%s: write %s\n", __func__, tgt_pkt->print());
2703
2704 // forward as is, both for evictions and uncacheable writes
2705 if (!memSidePort->sendTimingReq(tgt_pkt)) {
2706 // note that we have now masked any requestBus and
2707 // schedSendEvent (we will wait for a retry before
2708 // doing anything), and this is so even if we do not
2709 // care about this packet and might override it before
2710 // it gets retried
2711 return true;
2712 } else {
2713 markInService(wq_entry);
2714 return false;
2715 }
2716}
2717
2718void
2719Cache::serialize(CheckpointOut &cp) const
2720{
2721 bool dirty(isDirty());
2722
2723 if (dirty) {
2724 warn("*** The cache still contains dirty data. ***\n");
2725 warn(" Make sure to drain the system using the correct flags.\n");
2726 warn(" This checkpoint will not restore correctly and dirty data "
2727 " in the cache will be lost!\n");
2728 }
2729
2730 // Since we don't checkpoint the data in the cache, any dirty data
2731 // will be lost when restoring from a checkpoint of a system that
2732 // wasn't drained properly. Flag the checkpoint as invalid if the
2733 // cache contains dirty data.
2734 bool bad_checkpoint(dirty);
2735 SERIALIZE_SCALAR(bad_checkpoint);
2736}
2737
2738void
2739Cache::unserialize(CheckpointIn &cp)
2740{
2741 bool bad_checkpoint;
2742 UNSERIALIZE_SCALAR(bad_checkpoint);
2743 if (bad_checkpoint) {
2744 fatal("Restoring from checkpoints with dirty caches is not supported "
2745 "in the classic memory system. Please remove any caches or "
2746 " drain them properly before taking checkpoints.\n");
2747 }
2748}
2749
2750///////////////
2751//
2752// CpuSidePort
2753//
2754///////////////
2755
2756AddrRangeList
2757Cache::CpuSidePort::getAddrRanges() const
2758{
2759 return cache->getAddrRanges();
2760}
2761
2762bool
2763Cache::CpuSidePort::tryTiming(PacketPtr pkt)
2764{
2765 assert(!cache->system->bypassCaches());
2766
2767 // always let express snoop packets through if even if blocked
2768 if (pkt->isExpressSnoop()) {
2769 return true;
2770 } else if (isBlocked() || mustSendRetry) {
2771 // either already committed to send a retry, or blocked
2772 mustSendRetry = true;
2773 return false;
2774 }
2775 mustSendRetry = false;
2776 return true;
2777}
2778
2779bool
2780Cache::CpuSidePort::recvTimingReq(PacketPtr pkt)
2781{
2782 assert(!cache->system->bypassCaches());
2783
2784 // always let express snoop packets through if even if blocked
2785 if (pkt->isExpressSnoop() || tryTiming(pkt)) {
2786 cache->recvTimingReq(pkt);
2787 return true;
2788 }
2789 return false;
2790}
2791
2792Tick
2793Cache::CpuSidePort::recvAtomic(PacketPtr pkt)
2794{
2795 return cache->recvAtomic(pkt);
2796}
2797
2798void
2799Cache::CpuSidePort::recvFunctional(PacketPtr pkt)
2800{
2801 // functional request
2802 cache->functionalAccess(pkt, true);
2803}
2804
2805Cache::
2806CpuSidePort::CpuSidePort(const std::string &_name, Cache *_cache,
2807 const std::string &_label)
2808 : BaseCache::CacheSlavePort(_name, _cache, _label), cache(_cache)
2809{
2810}
2811
2812Cache*
2813CacheParams::create()
2814{
2815 assert(tags);
2816 assert(replacement_policy);
2817
2818 return new Cache(this);
2819}
1432Cache*
1433CacheParams::create()
1434{
1435 assert(tags);
1436 assert(replacement_policy);
1437
1438 return new Cache(this);
1439}
2820///////////////
2821//
2822// MemSidePort
2823//
2824///////////////
2825
2826bool
2827Cache::MemSidePort::recvTimingResp(PacketPtr pkt)
2828{
2829 cache->recvTimingResp(pkt);
2830 return true;
2831}
2832
2833// Express snooping requests to memside port
2834void
2835Cache::MemSidePort::recvTimingSnoopReq(PacketPtr pkt)
2836{
2837 // handle snooping requests
2838 cache->recvTimingSnoopReq(pkt);
2839}
2840
2841Tick
2842Cache::MemSidePort::recvAtomicSnoop(PacketPtr pkt)
2843{
2844 return cache->recvAtomicSnoop(pkt);
2845}
2846
2847void
2848Cache::MemSidePort::recvFunctionalSnoop(PacketPtr pkt)
2849{
2850 // functional snoop (note that in contrast to atomic we don't have
2851 // a specific functionalSnoop method, as they have the same
2852 // behaviour regardless)
2853 cache->functionalAccess(pkt, false);
2854}
2855
2856void
2857Cache::CacheReqPacketQueue::sendDeferredPacket()
2858{
2859 // sanity check
2860 assert(!waitingOnRetry);
2861
2862 // there should never be any deferred request packets in the
2863 // queue, instead we resly on the cache to provide the packets
2864 // from the MSHR queue or write queue
2865 assert(deferredPacketReadyTime() == MaxTick);
2866
2867 // check for request packets (requests & writebacks)
2868 QueueEntry* entry = cache.getNextQueueEntry();
2869
2870 if (!entry) {
2871 // can happen if e.g. we attempt a writeback and fail, but
2872 // before the retry, the writeback is eliminated because
2873 // we snoop another cache's ReadEx.
2874 } else {
2875 // let our snoop responses go first if there are responses to
2876 // the same addresses
2877 if (checkConflictingSnoop(entry->blkAddr)) {
2878 return;
2879 }
2880 waitingOnRetry = entry->sendPacket(cache);
2881 }
2882
2883 // if we succeeded and are not waiting for a retry, schedule the
2884 // next send considering when the next queue is ready, note that
2885 // snoop responses have their own packet queue and thus schedule
2886 // their own events
2887 if (!waitingOnRetry) {
2888 schedSendEvent(cache.nextQueueReadyTime());
2889 }
2890}
2891
2892Cache::
2893MemSidePort::MemSidePort(const std::string &_name, Cache *_cache,
2894 const std::string &_label)
2895 : BaseCache::CacheMasterPort(_name, _cache, _reqQueue, _snoopRespQueue),
2896 _reqQueue(*_cache, *this, _snoopRespQueue, _label),
2897 _snoopRespQueue(*_cache, *this, _label), cache(_cache)
2898{
2899}