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