cache.cc revision 11136
18999Suri.wiener@arm.com/*
28999Suri.wiener@arm.com * Copyright (c) 2010-2015 ARM Limited
38999Suri.wiener@arm.com * All rights reserved.
48999Suri.wiener@arm.com *
58999Suri.wiener@arm.com * The license below extends only to copyright in the software and shall
68999Suri.wiener@arm.com * not be construed as granting a license to any other intellectual
78999Suri.wiener@arm.com * property including but not limited to intellectual property relating
88999Suri.wiener@arm.com * to a hardware implementation of the functionality of the software
98999Suri.wiener@arm.com * licensed hereunder.  You may use the software subject to the license
108999Suri.wiener@arm.com * terms below provided that you ensure that this notice is replicated
118999Suri.wiener@arm.com * unmodified and in its entirety in all distributions of the software,
128999Suri.wiener@arm.com * modified or unmodified, in source code or in binary form.
134762Snate@binkert.org *
147534Ssteve.reinhardt@amd.com * Copyright (c) 2002-2005 The Regents of The University of Michigan
154762Snate@binkert.org * Copyright (c) 2010,2015 Advanced Micro Devices, Inc.
164762Snate@binkert.org * All rights reserved.
174762Snate@binkert.org *
184762Snate@binkert.org * Redistribution and use in source and binary forms, with or without
194762Snate@binkert.org * modification, are permitted provided that the following conditions are
204762Snate@binkert.org * met: redistributions of source code must retain the above copyright
214762Snate@binkert.org * notice, this list of conditions and the following disclaimer;
224762Snate@binkert.org * redistributions in binary form must reproduce the above copyright
234762Snate@binkert.org * notice, this list of conditions and the following disclaimer in the
244762Snate@binkert.org * documentation and/or other materials provided with the distribution;
254762Snate@binkert.org * neither the name of the copyright holders nor the names of its
264762Snate@binkert.org * contributors may be used to endorse or promote products derived from
274762Snate@binkert.org * this software without specific prior written permission.
284762Snate@binkert.org *
294762Snate@binkert.org * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
304762Snate@binkert.org * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
314762Snate@binkert.org * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
324762Snate@binkert.org * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
334762Snate@binkert.org * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
344762Snate@binkert.org * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
354762Snate@binkert.org * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
364762Snate@binkert.org * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
374762Snate@binkert.org * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
384762Snate@binkert.org * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
394762Snate@binkert.org * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
404762Snate@binkert.org *
414762Snate@binkert.org * Authors: Erik Hallnor
424762Snate@binkert.org *          Dave Greene
434762Snate@binkert.org *          Nathan Binkert
444762Snate@binkert.org *          Steve Reinhardt
454762Snate@binkert.org *          Ron Dreslinski
464762Snate@binkert.org *          Andreas Sandberg
474762Snate@binkert.org */
484762Snate@binkert.org
496001Snate@binkert.org/**
506001Snate@binkert.org * @file
514762Snate@binkert.org * Cache definitions.
524762Snate@binkert.org */
534851Snate@binkert.org
548999Suri.wiener@arm.com#include "mem/cache/cache.hh"
558999Suri.wiener@arm.com
567525Ssteve.reinhardt@amd.com#include "base/misc.hh"
578664SAli.Saidi@ARM.com#include "base/types.hh"
584762Snate@binkert.org#include "debug/Cache.hh"
596654Snate@binkert.org#include "debug/CachePort.hh"
606654Snate@binkert.org#include "debug/CacheTags.hh"
616654Snate@binkert.org#include "mem/cache/blk.hh"
624762Snate@binkert.org#include "mem/cache/mshr.hh"
634762Snate@binkert.org#include "mem/cache/prefetch/base.hh"
647531Ssteve.reinhardt@amd.com#include "sim/sim_exit.hh"
658245Snate@binkert.org
668234Snate@binkert.orgCache::Cache(const CacheParams *p)
677525Ssteve.reinhardt@amd.com    : BaseCache(p, p->system->cacheLineSize()),
687525Ssteve.reinhardt@amd.com      tags(p->tags),
697525Ssteve.reinhardt@amd.com      prefetcher(p->prefetcher),
707525Ssteve.reinhardt@amd.com      doFastWrites(true),
717525Ssteve.reinhardt@amd.com      prefetchOnAccess(p->prefetch_on_access)
724762Snate@binkert.org{
734762Snate@binkert.org    tempBlock = new CacheBlk();
744762Snate@binkert.org    tempBlock->data = new uint8_t[blkSize];
757528Ssteve.reinhardt@amd.com
767528Ssteve.reinhardt@amd.com    cpuSidePort = new CpuSidePort(p->name + ".cpu_side", this,
777528Ssteve.reinhardt@amd.com                                  "CpuSidePort");
787528Ssteve.reinhardt@amd.com    memSidePort = new MemSidePort(p->name + ".mem_side", this,
797527Ssteve.reinhardt@amd.com                                  "MemSidePort");
807527Ssteve.reinhardt@amd.com
815037Smilesck@eecs.umich.edu    tags->setCache(this);
825773Snate@binkert.org    if (prefetcher)
835773Snate@binkert.org        prefetcher->setCache(this);
847527Ssteve.reinhardt@amd.com}
857527Ssteve.reinhardt@amd.com
867527Ssteve.reinhardt@amd.comCache::~Cache()
875773Snate@binkert.org{
884762Snate@binkert.org    delete [] tempBlock->data;
898664SAli.Saidi@ARM.com    delete tempBlock;
908675SAli.Saidi@ARM.com
918675SAli.Saidi@ARM.com    delete cpuSidePort;
928675SAli.Saidi@ARM.com    delete memSidePort;
938675SAli.Saidi@ARM.com}
948675SAli.Saidi@ARM.com
958675SAli.Saidi@ARM.comvoid
968675SAli.Saidi@ARM.comCache::regStats()
978675SAli.Saidi@ARM.com{
988664SAli.Saidi@ARM.com    BaseCache::regStats();
998999Suri.wiener@arm.com}
1008664SAli.Saidi@ARM.com
1014762Snate@binkert.orgvoid
1026001Snate@binkert.orgCache::cmpAndSwap(CacheBlk *blk, PacketPtr pkt)
1034762Snate@binkert.org{
1044762Snate@binkert.org    assert(pkt->isRequest());
1057527Ssteve.reinhardt@amd.com
1067527Ssteve.reinhardt@amd.com    uint64_t overwrite_val;
1074762Snate@binkert.org    bool overwrite_mem;
1084762Snate@binkert.org    uint64_t condition_val64;
1097527Ssteve.reinhardt@amd.com    uint32_t condition_val32;
1104762Snate@binkert.org
1114762Snate@binkert.org    int offset = tags->extractBlkOffset(pkt->getAddr());
1127527Ssteve.reinhardt@amd.com    uint8_t *blk_data = blk->data + offset;
1134762Snate@binkert.org
1146001Snate@binkert.org    assert(sizeof(uint64_t) >= pkt->getSize());
1156001Snate@binkert.org
1164762Snate@binkert.org    overwrite_mem = true;
1177531Ssteve.reinhardt@amd.com    // keep a copy of our possible write value, and copy what is at the
1187531Ssteve.reinhardt@amd.com    // memory address into the packet
1197532Ssteve.reinhardt@amd.com    pkt->writeData((uint8_t *)&overwrite_val);
1207532Ssteve.reinhardt@amd.com    pkt->setData(blk_data);
1217532Ssteve.reinhardt@amd.com
1227531Ssteve.reinhardt@amd.com    if (pkt->req->isCondSwap()) {
1237532Ssteve.reinhardt@amd.com        if (pkt->getSize() == sizeof(uint64_t)) {
1247532Ssteve.reinhardt@amd.com            condition_val64 = pkt->req->getExtraData();
1257531Ssteve.reinhardt@amd.com            overwrite_mem = !std::memcmp(&condition_val64, blk_data,
1264762Snate@binkert.org                                         sizeof(uint64_t));
1276001Snate@binkert.org        } else if (pkt->getSize() == sizeof(uint32_t)) {
1284762Snate@binkert.org            condition_val32 = (uint32_t)pkt->req->getExtraData();
1294762Snate@binkert.org            overwrite_mem = !std::memcmp(&condition_val32, blk_data,
1304762Snate@binkert.org                                         sizeof(uint32_t));
1314762Snate@binkert.org        } else
1324762Snate@binkert.org            panic("Invalid size for conditional read/write\n");
1334762Snate@binkert.org    }
1344762Snate@binkert.org
1357527Ssteve.reinhardt@amd.com    if (overwrite_mem) {
1367527Ssteve.reinhardt@amd.com        std::memcpy(blk_data, &overwrite_val, pkt->getSize());
1374762Snate@binkert.org        blk->status |= BlkDirty;
1384762Snate@binkert.org    }
1394762Snate@binkert.org}
1404762Snate@binkert.org
1414762Snate@binkert.org
1424762Snate@binkert.orgvoid
1434762Snate@binkert.orgCache::satisfyCpuSideRequest(PacketPtr pkt, CacheBlk *blk,
1444762Snate@binkert.org                             bool deferred_response, bool pending_downgrade)
1454762Snate@binkert.org{
1464762Snate@binkert.org    assert(pkt->isRequest());
1477823Ssteve.reinhardt@amd.com
1484762Snate@binkert.org    assert(blk && blk->isValid());
1494762Snate@binkert.org    // Occasionally this is not true... if we are a lower-level cache
1508296Snate@binkert.org    // satisfying a string of Read and ReadEx requests from
1514762Snate@binkert.org    // upper-level caches, a Read will mark the block as shared but we
1524762Snate@binkert.org    // can satisfy a following ReadEx anyway since we can rely on the
1534762Snate@binkert.org    // Read requester(s) to have buffered the ReadEx snoop and to
1544762Snate@binkert.org    // invalidate their blocks after receiving them.
1554762Snate@binkert.org    // assert(!pkt->needsExclusive() || blk->isWritable());
1564762Snate@binkert.org    assert(pkt->getOffset(blkSize) + pkt->getSize() <= blkSize);
1574762Snate@binkert.org
1584762Snate@binkert.org    // Check RMW operations first since both isRead() and
1594762Snate@binkert.org    // isWrite() will be true for them
1604762Snate@binkert.org    if (pkt->cmd == MemCmd::SwapReq) {
1614762Snate@binkert.org        cmpAndSwap(blk, pkt);
1624762Snate@binkert.org    } else if (pkt->isWrite()) {
1634762Snate@binkert.org        assert(blk->isWritable());
1644762Snate@binkert.org        // Write or WriteLine at the first cache with block in Exclusive
1654762Snate@binkert.org        if (blk->checkWrite(pkt)) {
1664762Snate@binkert.org            pkt->writeDataToBlock(blk->data, blkSize);
1674762Snate@binkert.org        }
1687527Ssteve.reinhardt@amd.com        // Always mark the line as dirty even if we are a failed
1694762Snate@binkert.org        // StoreCond so we supply data to any snoops that have
1707527Ssteve.reinhardt@amd.com        // appended themselves to this cache before knowing the store
1717527Ssteve.reinhardt@amd.com        // will fail.
1724762Snate@binkert.org        blk->status |= BlkDirty;
1734762Snate@binkert.org        DPRINTF(Cache, "%s for %s addr %#llx size %d (write)\n", __func__,
1744762Snate@binkert.org                pkt->cmdString(), pkt->getAddr(), pkt->getSize());
1754762Snate@binkert.org    } else if (pkt->isRead()) {
1764762Snate@binkert.org        if (pkt->isLLSC()) {
1774762Snate@binkert.org            blk->trackLoadLocked(pkt);
1784762Snate@binkert.org        }
1797527Ssteve.reinhardt@amd.com        pkt->setDataFromBlock(blk->data, blkSize);
1804762Snate@binkert.org        // determine if this read is from a (coherent) cache, or not
1817525Ssteve.reinhardt@amd.com        // by looking at the command type; we could potentially add a
1827525Ssteve.reinhardt@amd.com        // packet attribute such as 'FromCache' to make this check a
1834762Snate@binkert.org        // bit cleaner
1844762Snate@binkert.org        if (pkt->cmd == MemCmd::ReadExReq ||
1854762Snate@binkert.org            pkt->cmd == MemCmd::ReadSharedReq ||
1864762Snate@binkert.org            pkt->cmd == MemCmd::ReadCleanReq ||
1874859Snate@binkert.org            pkt->cmd == MemCmd::SCUpgradeFailReq) {
1884762Snate@binkert.org            assert(pkt->getSize() == blkSize);
1894762Snate@binkert.org            // special handling for coherent block requests from
1904762Snate@binkert.org            // upper-level caches
1914762Snate@binkert.org            if (pkt->needsExclusive()) {
1924762Snate@binkert.org                // sanity check
1934762Snate@binkert.org                assert(pkt->cmd == MemCmd::ReadExReq ||
1944945Snate@binkert.org                       pkt->cmd == MemCmd::SCUpgradeFailReq);
1954762Snate@binkert.org
1964762Snate@binkert.org                // if we have a dirty copy, make sure the recipient
1979253SAndreas.Sandberg@arm.com                // keeps it marked dirty
1984762Snate@binkert.org                if (blk->isDirty()) {
1994762Snate@binkert.org                    pkt->assertMemInhibit();
2004762Snate@binkert.org                }
2014762Snate@binkert.org                // on ReadExReq we give up our copy unconditionally
2024762Snate@binkert.org                if (blk != tempBlock)
2034762Snate@binkert.org                    tags->invalidate(blk);
2044945Snate@binkert.org                blk->invalidate();
2054762Snate@binkert.org            } else if (blk->isWritable() && !pending_downgrade &&
2069253SAndreas.Sandberg@arm.com                       !pkt->sharedAsserted() &&
2074762Snate@binkert.org                       pkt->cmd != MemCmd::ReadCleanReq) {
2084762Snate@binkert.org                // we can give the requester an exclusive copy (by not
2094762Snate@binkert.org                // asserting shared line) on a read request if:
2104762Snate@binkert.org                // - we have an exclusive copy at this level (& below)
2114762Snate@binkert.org                // - we don't have a pending snoop from below
2124946Snate@binkert.org                //   signaling another read request
2134946Snate@binkert.org                // - no other cache above has a copy (otherwise it
2144762Snate@binkert.org                //   would have asseretd shared line on request)
2154762Snate@binkert.org                // - we are not satisfying an instruction fetch (this
2164946Snate@binkert.org                //   prevents dirty data in the i-cache)
2174946Snate@binkert.org
2184946Snate@binkert.org                if (blk->isDirty()) {
2194946Snate@binkert.org                    // special considerations if we're owner:
2204946Snate@binkert.org                    if (!deferred_response) {
2214762Snate@binkert.org                        // if we are responding immediately and can
2224946Snate@binkert.org                        // signal that we're transferring ownership
2234946Snate@binkert.org                        // along with exclusivity, do so
2249254SAndreas.Sandberg@arm.com                        pkt->assertMemInhibit();
2254762Snate@binkert.org                        blk->status &= ~BlkDirty;
2264946Snate@binkert.org                    } else {
2274946Snate@binkert.org                        // if we're responding after our own miss,
2285523Snate@binkert.org                        // there's a window where the recipient didn't
2295523Snate@binkert.org                        // know it was getting ownership and may not
230                        // have responded to snoops correctly, so we
231                        // can't pass off ownership *or* exclusivity
232                        pkt->assertShared();
233                    }
234                }
235            } else {
236                // otherwise only respond with a shared copy
237                pkt->assertShared();
238            }
239        }
240    } else {
241        // Upgrade or Invalidate, since we have it Exclusively (E or
242        // M), we ack then invalidate.
243        assert(pkt->isUpgrade() || pkt->isInvalidate());
244        assert(blk != tempBlock);
245        tags->invalidate(blk);
246        blk->invalidate();
247        DPRINTF(Cache, "%s for %s addr %#llx size %d (invalidation)\n",
248                __func__, pkt->cmdString(), pkt->getAddr(), pkt->getSize());
249    }
250}
251
252
253/////////////////////////////////////////////////////
254//
255// MSHR helper functions
256//
257/////////////////////////////////////////////////////
258
259
260void
261Cache::markInService(MSHR *mshr, bool pending_dirty_resp)
262{
263    markInServiceInternal(mshr, pending_dirty_resp);
264}
265
266/////////////////////////////////////////////////////
267//
268// Access path: requests coming in from the CPU side
269//
270/////////////////////////////////////////////////////
271
272bool
273Cache::access(PacketPtr pkt, CacheBlk *&blk, Cycles &lat,
274              PacketList &writebacks)
275{
276    // sanity check
277    assert(pkt->isRequest());
278
279    chatty_assert(!(isReadOnly && pkt->isWrite()),
280                  "Should never see a write in a read-only cache %s\n",
281                  name());
282
283    DPRINTF(Cache, "%s for %s addr %#llx size %d\n", __func__,
284            pkt->cmdString(), pkt->getAddr(), pkt->getSize());
285
286    if (pkt->req->isUncacheable()) {
287        DPRINTF(Cache, "%s%s addr %#llx uncacheable\n", pkt->cmdString(),
288                pkt->req->isInstFetch() ? " (ifetch)" : "",
289                pkt->getAddr());
290
291        // flush and invalidate any existing block
292        CacheBlk *old_blk(tags->findBlock(pkt->getAddr(), pkt->isSecure()));
293        if (old_blk && old_blk->isValid()) {
294            if (old_blk->isDirty())
295                writebacks.push_back(writebackBlk(old_blk));
296            else
297                writebacks.push_back(cleanEvictBlk(old_blk));
298            tags->invalidate(old_blk);
299            old_blk->invalidate();
300        }
301
302        blk = NULL;
303        // lookupLatency is the latency in case the request is uncacheable.
304        lat = lookupLatency;
305        return false;
306    }
307
308    ContextID id = pkt->req->hasContextId() ?
309        pkt->req->contextId() : InvalidContextID;
310    // Here lat is the value passed as parameter to accessBlock() function
311    // that can modify its value.
312    blk = tags->accessBlock(pkt->getAddr(), pkt->isSecure(), lat, id);
313
314    DPRINTF(Cache, "%s%s addr %#llx size %d (%s) %s\n", pkt->cmdString(),
315            pkt->req->isInstFetch() ? " (ifetch)" : "",
316            pkt->getAddr(), pkt->getSize(), pkt->isSecure() ? "s" : "ns",
317            blk ? "hit " + blk->print() : "miss");
318
319
320    if (pkt->evictingBlock()) {
321        // We check for presence of block in above caches before issuing
322        // Writeback or CleanEvict to write buffer. Therefore the only
323        // possible cases can be of a CleanEvict packet coming from above
324        // encountering a Writeback generated in this cache peer cache and
325        // waiting in the write buffer. Cases of upper level peer caches
326        // generating CleanEvict and Writeback or simply CleanEvict and
327        // CleanEvict almost simultaneously will be caught by snoops sent out
328        // by crossbar.
329        std::vector<MSHR *> outgoing;
330        if (writeBuffer.findMatches(pkt->getAddr(), pkt->isSecure(),
331                                   outgoing)) {
332            assert(outgoing.size() == 1);
333            PacketPtr wbPkt = outgoing[0]->getTarget()->pkt;
334            assert(pkt->cmd == MemCmd::CleanEvict &&
335                   wbPkt->cmd == MemCmd::Writeback);
336            // As the CleanEvict is coming from above, it would have snooped
337            // into other peer caches of the same level while traversing the
338            // crossbar. If a copy of the block had been found, the CleanEvict
339            // would have been deleted in the crossbar. Now that the
340            // CleanEvict is here we can be sure none of the other upper level
341            // caches connected to this cache have the block, so we can clear
342            // the BLOCK_CACHED flag in the Writeback if set and discard the
343            // CleanEvict by returning true.
344            wbPkt->clearBlockCached();
345            return true;
346        }
347    }
348
349    // Writeback handling is special case.  We can write the block into
350    // the cache without having a writeable copy (or any copy at all).
351    if (pkt->cmd == MemCmd::Writeback) {
352        assert(blkSize == pkt->getSize());
353        if (blk == NULL) {
354            // need to do a replacement
355            blk = allocateBlock(pkt->getAddr(), pkt->isSecure(), writebacks);
356            if (blk == NULL) {
357                // no replaceable block available: give up, fwd to next level.
358                incMissCount(pkt);
359                return false;
360            }
361            tags->insertBlock(pkt, blk);
362
363            blk->status = (BlkValid | BlkReadable);
364            if (pkt->isSecure()) {
365                blk->status |= BlkSecure;
366            }
367        }
368        blk->status |= BlkDirty;
369        // if shared is not asserted we got the writeback in modified
370        // state, if it is asserted we are in the owned state
371        if (!pkt->sharedAsserted()) {
372            blk->status |= BlkWritable;
373        }
374        // nothing else to do; writeback doesn't expect response
375        assert(!pkt->needsResponse());
376        std::memcpy(blk->data, pkt->getConstPtr<uint8_t>(), blkSize);
377        DPRINTF(Cache, "%s new state is %s\n", __func__, blk->print());
378        incHitCount(pkt);
379        return true;
380    } else if (pkt->cmd == MemCmd::CleanEvict) {
381        if (blk != NULL) {
382            // Found the block in the tags, need to stop CleanEvict from
383            // propagating further down the hierarchy. Returning true will
384            // treat the CleanEvict like a satisfied write request and delete
385            // it.
386            return true;
387        }
388        // We didn't find the block here, propagate the CleanEvict further
389        // down the memory hierarchy. Returning false will treat the CleanEvict
390        // like a Writeback which could not find a replaceable block so has to
391        // go to next level.
392        return false;
393    } else if ((blk != NULL) &&
394               (pkt->needsExclusive() ? blk->isWritable()
395                                      : blk->isReadable())) {
396        // OK to satisfy access
397        incHitCount(pkt);
398        satisfyCpuSideRequest(pkt, blk);
399        return true;
400    }
401
402    // Can't satisfy access normally... either no block (blk == NULL)
403    // or have block but need exclusive & only have shared.
404
405    incMissCount(pkt);
406
407    if (blk == NULL && pkt->isLLSC() && pkt->isWrite()) {
408        // complete miss on store conditional... just give up now
409        pkt->req->setExtraData(0);
410        return true;
411    }
412
413    return false;
414}
415
416
417class ForwardResponseRecord : public Packet::SenderState
418{
419  public:
420
421    ForwardResponseRecord() {}
422};
423
424void
425Cache::doWritebacks(PacketList& writebacks, Tick forward_time)
426{
427    while (!writebacks.empty()) {
428        PacketPtr wbPkt = writebacks.front();
429        // We use forwardLatency here because we are copying writebacks to
430        // write buffer.  Call isCachedAbove for both Writebacks and
431        // CleanEvicts. If isCachedAbove returns true we set BLOCK_CACHED flag
432        // in Writebacks and discard CleanEvicts.
433        if (isCachedAbove(wbPkt)) {
434            if (wbPkt->cmd == MemCmd::CleanEvict) {
435                // Delete CleanEvict because cached copies exist above. The
436                // packet destructor will delete the request object because
437                // this is a non-snoop request packet which does not require a
438                // response.
439                delete wbPkt;
440            } else {
441                // Set BLOCK_CACHED flag in Writeback and send below, so that
442                // the Writeback does not reset the bit corresponding to this
443                // address in the snoop filter below.
444                wbPkt->setBlockCached();
445                allocateWriteBuffer(wbPkt, forward_time);
446            }
447        } else {
448            // If the block is not cached above, send packet below. Both
449            // CleanEvict and Writeback with BLOCK_CACHED flag cleared will
450            // reset the bit corresponding to this address in the snoop filter
451            // below.
452            allocateWriteBuffer(wbPkt, forward_time);
453        }
454        writebacks.pop_front();
455    }
456}
457
458void
459Cache::doWritebacksAtomic(PacketList& writebacks)
460{
461    while (!writebacks.empty()) {
462        PacketPtr wbPkt = writebacks.front();
463        // Call isCachedAbove for both Writebacks and CleanEvicts. If
464        // isCachedAbove returns true we set BLOCK_CACHED flag in Writebacks
465        // and discard CleanEvicts.
466        if (isCachedAbove(wbPkt, false)) {
467            if (wbPkt->cmd == MemCmd::Writeback) {
468                // Set BLOCK_CACHED flag in Writeback and send below,
469                // so that the Writeback does not reset the bit
470                // corresponding to this address in the snoop filter
471                // below. We can discard CleanEvicts because cached
472                // copies exist above. Atomic mode isCachedAbove
473                // modifies packet to set BLOCK_CACHED flag
474                memSidePort->sendAtomic(wbPkt);
475            }
476        } else {
477            // If the block is not cached above, send packet below. Both
478            // CleanEvict and Writeback with BLOCK_CACHED flag cleared will
479            // reset the bit corresponding to this address in the snoop filter
480            // below.
481            memSidePort->sendAtomic(wbPkt);
482        }
483        writebacks.pop_front();
484        // In case of CleanEvicts, the packet destructor will delete the
485        // request object because this is a non-snoop request packet which
486        // does not require a response.
487        delete wbPkt;
488    }
489}
490
491
492void
493Cache::recvTimingSnoopResp(PacketPtr pkt)
494{
495    DPRINTF(Cache, "%s for %s addr %#llx size %d\n", __func__,
496            pkt->cmdString(), pkt->getAddr(), pkt->getSize());
497
498    assert(pkt->isResponse());
499
500    // must be cache-to-cache response from upper to lower level
501    ForwardResponseRecord *rec =
502        dynamic_cast<ForwardResponseRecord *>(pkt->senderState);
503    assert(!system->bypassCaches());
504
505    if (rec == NULL) {
506        // @todo What guarantee do we have that this HardPFResp is
507        // actually for this cache, and not a cache closer to the
508        // memory?
509        assert(pkt->cmd == MemCmd::HardPFResp);
510        // Check if it's a prefetch response and handle it. We shouldn't
511        // get any other kinds of responses without FRRs.
512        DPRINTF(Cache, "Got prefetch response from above for addr %#llx (%s)\n",
513                pkt->getAddr(), pkt->isSecure() ? "s" : "ns");
514        recvTimingResp(pkt);
515        return;
516    }
517
518    pkt->popSenderState();
519    delete rec;
520    // forwardLatency is set here because there is a response from an
521    // upper level cache.
522    // To pay the delay that occurs if the packet comes from the bus,
523    // we charge also headerDelay.
524    Tick snoop_resp_time = clockEdge(forwardLatency) + pkt->headerDelay;
525    // Reset the timing of the packet.
526    pkt->headerDelay = pkt->payloadDelay = 0;
527    memSidePort->schedTimingSnoopResp(pkt, snoop_resp_time);
528}
529
530void
531Cache::promoteWholeLineWrites(PacketPtr pkt)
532{
533    // Cache line clearing instructions
534    if (doFastWrites && (pkt->cmd == MemCmd::WriteReq) &&
535        (pkt->getSize() == blkSize) && (pkt->getOffset(blkSize) == 0)) {
536        pkt->cmd = MemCmd::WriteLineReq;
537        DPRINTF(Cache, "packet promoted from Write to WriteLineReq\n");
538    }
539}
540
541bool
542Cache::recvTimingReq(PacketPtr pkt)
543{
544    DPRINTF(CacheTags, "%s tags: %s\n", __func__, tags->print());
545//@todo Add back in MemDebug Calls
546//    MemDebug::cacheAccess(pkt);
547
548
549    /// @todo temporary hack to deal with memory corruption issue until
550    /// 4-phase transactions are complete
551    for (int x = 0; x < pendingDelete.size(); x++)
552        delete pendingDelete[x];
553    pendingDelete.clear();
554
555    assert(pkt->isRequest());
556
557    // Just forward the packet if caches are disabled.
558    if (system->bypassCaches()) {
559        // @todo This should really enqueue the packet rather
560        bool M5_VAR_USED success = memSidePort->sendTimingReq(pkt);
561        assert(success);
562        return true;
563    }
564
565    promoteWholeLineWrites(pkt);
566
567    if (pkt->memInhibitAsserted()) {
568        // a cache above us (but not where the packet came from) is
569        // responding to the request
570        DPRINTF(Cache, "mem inhibited on addr %#llx (%s): not responding\n",
571                pkt->getAddr(), pkt->isSecure() ? "s" : "ns");
572
573        // if the packet needs exclusive, and the cache that has
574        // promised to respond (setting the inhibit flag) is not
575        // providing exclusive (it is in O vs M state), we know that
576        // there may be other shared copies in the system; go out and
577        // invalidate them all
578        if (pkt->needsExclusive() && !pkt->isSupplyExclusive()) {
579            // create a downstream express snoop with cleared packet
580            // flags, there is no need to allocate any data as the
581            // packet is merely used to co-ordinate state transitions
582            Packet *snoop_pkt = new Packet(pkt, true, false);
583
584            // also reset the bus time that the original packet has
585            // not yet paid for
586            snoop_pkt->headerDelay = snoop_pkt->payloadDelay = 0;
587
588            // make this an instantaneous express snoop, and let the
589            // other caches in the system know that the packet is
590            // inhibited, because we have found the authorative copy
591            // (O) that will supply the right data
592            snoop_pkt->setExpressSnoop();
593            snoop_pkt->assertMemInhibit();
594
595            // this express snoop travels towards the memory, and at
596            // every crossbar it is snooped upwards thus reaching
597            // every cache in the system
598            bool M5_VAR_USED success = memSidePort->sendTimingReq(snoop_pkt);
599            // express snoops always succeed
600            assert(success);
601
602            // main memory will delete the packet
603        }
604
605        /// @todo nominally we should just delete the packet here,
606        /// however, until 4-phase stuff we can't because sending
607        /// cache is still relying on it.
608        pendingDelete.push_back(pkt);
609
610        // no need to take any action in this particular cache as the
611        // caches along the path to memory are allowed to keep lines
612        // in a shared state, and a cache above us already committed
613        // to responding
614        return true;
615    }
616
617    // anything that is merely forwarded pays for the forward latency and
618    // the delay provided by the crossbar
619    Tick forward_time = clockEdge(forwardLatency) + pkt->headerDelay;
620
621    // We use lookupLatency here because it is used to specify the latency
622    // to access.
623    Cycles lat = lookupLatency;
624    CacheBlk *blk = NULL;
625    bool satisfied = false;
626    {
627        PacketList writebacks;
628        // Note that lat is passed by reference here. The function
629        // access() calls accessBlock() which can modify lat value.
630        satisfied = access(pkt, blk, lat, writebacks);
631
632        // copy writebacks to write buffer here to ensure they logically
633        // proceed anything happening below
634        doWritebacks(writebacks, forward_time);
635    }
636
637    // Here we charge the headerDelay that takes into account the latencies
638    // of the bus, if the packet comes from it.
639    // The latency charged it is just lat that is the value of lookupLatency
640    // modified by access() function, or if not just lookupLatency.
641    // In case of a hit we are neglecting response latency.
642    // In case of a miss we are neglecting forward latency.
643    Tick request_time = clockEdge(lat) + pkt->headerDelay;
644    // Here we reset the timing of the packet.
645    pkt->headerDelay = pkt->payloadDelay = 0;
646
647    // track time of availability of next prefetch, if any
648    Tick next_pf_time = MaxTick;
649
650    bool needsResponse = pkt->needsResponse();
651
652    if (satisfied) {
653        // should never be satisfying an uncacheable access as we
654        // flush and invalidate any existing block as part of the
655        // lookup
656        assert(!pkt->req->isUncacheable());
657
658        // hit (for all other request types)
659
660        if (prefetcher && (prefetchOnAccess || (blk && blk->wasPrefetched()))) {
661            if (blk)
662                blk->status &= ~BlkHWPrefetched;
663
664            // Don't notify on SWPrefetch
665            if (!pkt->cmd.isSWPrefetch())
666                next_pf_time = prefetcher->notify(pkt);
667        }
668
669        if (needsResponse) {
670            pkt->makeTimingResponse();
671            // @todo: Make someone pay for this
672            pkt->headerDelay = pkt->payloadDelay = 0;
673
674            // In this case we are considering request_time that takes
675            // into account the delay of the xbar, if any, and just
676            // lat, neglecting responseLatency, modelling hit latency
677            // just as lookupLatency or or the value of lat overriden
678            // by access(), that calls accessBlock() function.
679            cpuSidePort->schedTimingResp(pkt, request_time);
680        } else {
681            /// @todo nominally we should just delete the packet here,
682            /// however, until 4-phase stuff we can't because sending cache is
683            /// still relying on it. If the block is found in access(),
684            /// CleanEvict and Writeback messages will be deleted here as
685            /// well.
686            pendingDelete.push_back(pkt);
687        }
688    } else {
689        // miss
690
691        Addr blk_addr = blockAlign(pkt->getAddr());
692
693        // ignore any existing MSHR if we are dealing with an
694        // uncacheable request
695        MSHR *mshr = pkt->req->isUncacheable() ? nullptr :
696            mshrQueue.findMatch(blk_addr, pkt->isSecure());
697
698        // Software prefetch handling:
699        // To keep the core from waiting on data it won't look at
700        // anyway, send back a response with dummy data. Miss handling
701        // will continue asynchronously. Unfortunately, the core will
702        // insist upon freeing original Packet/Request, so we have to
703        // create a new pair with a different lifecycle. Note that this
704        // processing happens before any MSHR munging on the behalf of
705        // this request because this new Request will be the one stored
706        // into the MSHRs, not the original.
707        if (pkt->cmd.isSWPrefetch()) {
708            assert(needsResponse);
709            assert(pkt->req->hasPaddr());
710            assert(!pkt->req->isUncacheable());
711
712            // There's no reason to add a prefetch as an additional target
713            // to an existing MSHR. If an outstanding request is already
714            // in progress, there is nothing for the prefetch to do.
715            // If this is the case, we don't even create a request at all.
716            PacketPtr pf = nullptr;
717
718            if (!mshr) {
719                // copy the request and create a new SoftPFReq packet
720                RequestPtr req = new Request(pkt->req->getPaddr(),
721                                             pkt->req->getSize(),
722                                             pkt->req->getFlags(),
723                                             pkt->req->masterId());
724                pf = new Packet(req, pkt->cmd);
725                pf->allocate();
726                assert(pf->getAddr() == pkt->getAddr());
727                assert(pf->getSize() == pkt->getSize());
728            }
729
730            pkt->makeTimingResponse();
731            // for debugging, set all the bits in the response data
732            // (also keeps valgrind from complaining when debugging settings
733            //  print out instruction results)
734            std::memset(pkt->getPtr<uint8_t>(), 0xFF, pkt->getSize());
735            // request_time is used here, taking into account lat and the delay
736            // charged if the packet comes from the xbar.
737            cpuSidePort->schedTimingResp(pkt, request_time);
738
739            // If an outstanding request is in progress (we found an
740            // MSHR) this is set to null
741            pkt = pf;
742        }
743
744        if (mshr) {
745            /// MSHR hit
746            /// @note writebacks will be checked in getNextMSHR()
747            /// for any conflicting requests to the same block
748
749            //@todo remove hw_pf here
750
751            // Coalesce unless it was a software prefetch (see above).
752            if (pkt) {
753                assert(pkt->cmd != MemCmd::Writeback);
754                // CleanEvicts corresponding to blocks which have outstanding
755                // requests in MSHRs can be deleted here.
756                if (pkt->cmd == MemCmd::CleanEvict) {
757                    pendingDelete.push_back(pkt);
758                } else {
759                    DPRINTF(Cache, "%s coalescing MSHR for %s addr %#llx size %d\n",
760                            __func__, pkt->cmdString(), pkt->getAddr(),
761                            pkt->getSize());
762
763                    assert(pkt->req->masterId() < system->maxMasters());
764                    mshr_hits[pkt->cmdToIndex()][pkt->req->masterId()]++;
765                    if (mshr->threadNum != 0/*pkt->req->threadId()*/) {
766                        mshr->threadNum = -1;
767                    }
768                    // We use forward_time here because it is the same
769                    // considering new targets. We have multiple
770                    // requests for the same address here. It
771                    // specifies the latency to allocate an internal
772                    // buffer and to schedule an event to the queued
773                    // port and also takes into account the additional
774                    // delay of the xbar.
775                    mshr->allocateTarget(pkt, forward_time, order++);
776                    if (mshr->getNumTargets() == numTarget) {
777                        noTargetMSHR = mshr;
778                        setBlocked(Blocked_NoTargets);
779                        // need to be careful with this... if this mshr isn't
780                        // ready yet (i.e. time > curTick()), we don't want to
781                        // move it ahead of mshrs that are ready
782                        // mshrQueue.moveToFront(mshr);
783                    }
784                }
785                // We should call the prefetcher reguardless if the request is
786                // satisfied or not, reguardless if the request is in the MSHR or
787                // not.  The request could be a ReadReq hit, but still not
788                // satisfied (potentially because of a prior write to the same
789                // cache line.  So, even when not satisfied, tehre is an MSHR
790                // already allocated for this, we need to let the prefetcher know
791                // about the request
792                if (prefetcher) {
793                    // Don't notify on SWPrefetch
794                    if (!pkt->cmd.isSWPrefetch())
795                        next_pf_time = prefetcher->notify(pkt);
796                }
797            }
798        } else {
799            // no MSHR
800            assert(pkt->req->masterId() < system->maxMasters());
801            if (pkt->req->isUncacheable()) {
802                mshr_uncacheable[pkt->cmdToIndex()][pkt->req->masterId()]++;
803            } else {
804                mshr_misses[pkt->cmdToIndex()][pkt->req->masterId()]++;
805            }
806
807            if (pkt->evictingBlock() ||
808                (pkt->req->isUncacheable() && pkt->isWrite())) {
809                // We use forward_time here because there is an
810                // uncached memory write, forwarded to WriteBuffer.
811                allocateWriteBuffer(pkt, forward_time);
812            } else {
813                if (blk && blk->isValid()) {
814                    // should have flushed and have no valid block
815                    assert(!pkt->req->isUncacheable());
816
817                    // If we have a write miss to a valid block, we
818                    // need to mark the block non-readable.  Otherwise
819                    // if we allow reads while there's an outstanding
820                    // write miss, the read could return stale data
821                    // out of the cache block... a more aggressive
822                    // system could detect the overlap (if any) and
823                    // forward data out of the MSHRs, but we don't do
824                    // that yet.  Note that we do need to leave the
825                    // block valid so that it stays in the cache, in
826                    // case we get an upgrade response (and hence no
827                    // new data) when the write miss completes.
828                    // As long as CPUs do proper store/load forwarding
829                    // internally, and have a sufficiently weak memory
830                    // model, this is probably unnecessary, but at some
831                    // point it must have seemed like we needed it...
832                    assert(pkt->needsExclusive());
833                    assert(!blk->isWritable());
834                    blk->status &= ~BlkReadable;
835                }
836                // Here we are using forward_time, modelling the latency of
837                // a miss (outbound) just as forwardLatency, neglecting the
838                // lookupLatency component.
839                allocateMissBuffer(pkt, forward_time);
840            }
841
842            if (prefetcher) {
843                // Don't notify on SWPrefetch
844                if (!pkt->cmd.isSWPrefetch())
845                    next_pf_time = prefetcher->notify(pkt);
846            }
847        }
848    }
849
850    if (next_pf_time != MaxTick)
851        schedMemSideSendEvent(next_pf_time);
852
853    return true;
854}
855
856
857// See comment in cache.hh.
858PacketPtr
859Cache::getBusPacket(PacketPtr cpu_pkt, CacheBlk *blk,
860                    bool needsExclusive) const
861{
862    bool blkValid = blk && blk->isValid();
863
864    if (cpu_pkt->req->isUncacheable()) {
865        // note that at the point we see the uncacheable request we
866        // flush any block, but there could be an outstanding MSHR,
867        // and the cache could have filled again before we actually
868        // send out the forwarded uncacheable request (blk could thus
869        // be non-null)
870        return NULL;
871    }
872
873    if (!blkValid &&
874        (cpu_pkt->isUpgrade() ||
875         cpu_pkt->evictingBlock())) {
876        // Writebacks that weren't allocated in access() and upgrades
877        // from upper-level caches that missed completely just go
878        // through.
879        return NULL;
880    }
881
882    assert(cpu_pkt->needsResponse());
883
884    MemCmd cmd;
885    // @TODO make useUpgrades a parameter.
886    // Note that ownership protocols require upgrade, otherwise a
887    // write miss on a shared owned block will generate a ReadExcl,
888    // which will clobber the owned copy.
889    const bool useUpgrades = true;
890    if (blkValid && useUpgrades) {
891        // only reason to be here is that blk is shared
892        // (read-only) and we need exclusive
893        assert(needsExclusive);
894        assert(!blk->isWritable());
895        cmd = cpu_pkt->isLLSC() ? MemCmd::SCUpgradeReq : MemCmd::UpgradeReq;
896    } else if (cpu_pkt->cmd == MemCmd::SCUpgradeFailReq ||
897               cpu_pkt->cmd == MemCmd::StoreCondFailReq) {
898        // Even though this SC will fail, we still need to send out the
899        // request and get the data to supply it to other snoopers in the case
900        // where the determination the StoreCond fails is delayed due to
901        // all caches not being on the same local bus.
902        cmd = MemCmd::SCUpgradeFailReq;
903    } else if (cpu_pkt->cmd == MemCmd::WriteLineReq) {
904        // forward as invalidate to all other caches, this gives us
905        // the line in exclusive state, and invalidates all other
906        // copies
907        cmd = MemCmd::InvalidateReq;
908    } else {
909        // block is invalid
910        cmd = needsExclusive ? MemCmd::ReadExReq :
911            (isReadOnly ? MemCmd::ReadCleanReq : MemCmd::ReadSharedReq);
912    }
913    PacketPtr pkt = new Packet(cpu_pkt->req, cmd, blkSize);
914
915    // if there are sharers in the upper levels, pass that info downstream
916    if (cpu_pkt->sharedAsserted()) {
917        // note that cpu_pkt may have spent a considerable time in the
918        // MSHR queue and that the information could possibly be out
919        // of date, however, there is no harm in conservatively
920        // assuming the block is shared
921        pkt->assertShared();
922        DPRINTF(Cache, "%s passing shared from %s to %s addr %#llx size %d\n",
923                __func__, cpu_pkt->cmdString(), pkt->cmdString(),
924                pkt->getAddr(), pkt->getSize());
925    }
926
927    // the packet should be block aligned
928    assert(pkt->getAddr() == blockAlign(pkt->getAddr()));
929
930    pkt->allocate();
931    DPRINTF(Cache, "%s created %s from %s for  addr %#llx size %d\n",
932            __func__, pkt->cmdString(), cpu_pkt->cmdString(), pkt->getAddr(),
933            pkt->getSize());
934    return pkt;
935}
936
937
938Tick
939Cache::recvAtomic(PacketPtr pkt)
940{
941    // We are in atomic mode so we pay just for lookupLatency here.
942    Cycles lat = lookupLatency;
943    // @TODO: make this a parameter
944    bool last_level_cache = false;
945
946    // Forward the request if the system is in cache bypass mode.
947    if (system->bypassCaches())
948        return ticksToCycles(memSidePort->sendAtomic(pkt));
949
950    promoteWholeLineWrites(pkt);
951
952    if (pkt->memInhibitAsserted()) {
953        // have to invalidate ourselves and any lower caches even if
954        // upper cache will be responding
955        if (pkt->isInvalidate()) {
956            CacheBlk *blk = tags->findBlock(pkt->getAddr(), pkt->isSecure());
957            if (blk && blk->isValid()) {
958                tags->invalidate(blk);
959                blk->invalidate();
960                DPRINTF(Cache, "rcvd mem-inhibited %s on %#llx (%s):"
961                        " invalidating\n",
962                        pkt->cmdString(), pkt->getAddr(),
963                        pkt->isSecure() ? "s" : "ns");
964            }
965            if (!last_level_cache) {
966                DPRINTF(Cache, "forwarding mem-inhibited %s on %#llx (%s)\n",
967                        pkt->cmdString(), pkt->getAddr(),
968                        pkt->isSecure() ? "s" : "ns");
969                lat += ticksToCycles(memSidePort->sendAtomic(pkt));
970            }
971        } else {
972            DPRINTF(Cache, "rcvd mem-inhibited %s on %#llx: not responding\n",
973                    pkt->cmdString(), pkt->getAddr());
974        }
975
976        return lat * clockPeriod();
977    }
978
979    // should assert here that there are no outstanding MSHRs or
980    // writebacks... that would mean that someone used an atomic
981    // access in timing mode
982
983    CacheBlk *blk = NULL;
984    PacketList writebacks;
985    bool satisfied = access(pkt, blk, lat, writebacks);
986
987    // handle writebacks resulting from the access here to ensure they
988    // logically proceed anything happening below
989    doWritebacksAtomic(writebacks);
990
991    if (!satisfied) {
992        // MISS
993
994        PacketPtr bus_pkt = getBusPacket(pkt, blk, pkt->needsExclusive());
995
996        bool is_forward = (bus_pkt == NULL);
997
998        if (is_forward) {
999            // just forwarding the same request to the next level
1000            // no local cache operation involved
1001            bus_pkt = pkt;
1002        }
1003
1004        DPRINTF(Cache, "Sending an atomic %s for %#llx (%s)\n",
1005                bus_pkt->cmdString(), bus_pkt->getAddr(),
1006                bus_pkt->isSecure() ? "s" : "ns");
1007
1008#if TRACING_ON
1009        CacheBlk::State old_state = blk ? blk->status : 0;
1010#endif
1011
1012        lat += ticksToCycles(memSidePort->sendAtomic(bus_pkt));
1013
1014        // We are now dealing with the response handling
1015        DPRINTF(Cache, "Receive response: %s for addr %#llx (%s) in state %i\n",
1016                bus_pkt->cmdString(), bus_pkt->getAddr(),
1017                bus_pkt->isSecure() ? "s" : "ns",
1018                old_state);
1019
1020        // If packet was a forward, the response (if any) is already
1021        // in place in the bus_pkt == pkt structure, so we don't need
1022        // to do anything.  Otherwise, use the separate bus_pkt to
1023        // generate response to pkt and then delete it.
1024        if (!is_forward) {
1025            if (pkt->needsResponse()) {
1026                assert(bus_pkt->isResponse());
1027                if (bus_pkt->isError()) {
1028                    pkt->makeAtomicResponse();
1029                    pkt->copyError(bus_pkt);
1030                } else if (pkt->cmd == MemCmd::InvalidateReq) {
1031                    if (blk) {
1032                        // invalidate response to a cache that received
1033                        // an invalidate request
1034                        satisfyCpuSideRequest(pkt, blk);
1035                    }
1036                } else if (pkt->cmd == MemCmd::WriteLineReq) {
1037                    // note the use of pkt, not bus_pkt here.
1038
1039                    // write-line request to the cache that promoted
1040                    // the write to a whole line
1041                    blk = handleFill(pkt, blk, writebacks);
1042                    satisfyCpuSideRequest(pkt, blk);
1043                } else if (bus_pkt->isRead() ||
1044                           bus_pkt->cmd == MemCmd::UpgradeResp) {
1045                    // we're updating cache state to allow us to
1046                    // satisfy the upstream request from the cache
1047                    blk = handleFill(bus_pkt, blk, writebacks);
1048                    satisfyCpuSideRequest(pkt, blk);
1049                } else {
1050                    // we're satisfying the upstream request without
1051                    // modifying cache state, e.g., a write-through
1052                    pkt->makeAtomicResponse();
1053                }
1054            }
1055            delete bus_pkt;
1056        }
1057    }
1058
1059    // Note that we don't invoke the prefetcher at all in atomic mode.
1060    // It's not clear how to do it properly, particularly for
1061    // prefetchers that aggressively generate prefetch candidates and
1062    // rely on bandwidth contention to throttle them; these will tend
1063    // to pollute the cache in atomic mode since there is no bandwidth
1064    // contention.  If we ever do want to enable prefetching in atomic
1065    // mode, though, this is the place to do it... see timingAccess()
1066    // for an example (though we'd want to issue the prefetch(es)
1067    // immediately rather than calling requestMemSideBus() as we do
1068    // there).
1069
1070    // Handle writebacks (from the response handling) if needed
1071    doWritebacksAtomic(writebacks);
1072
1073    if (pkt->needsResponse()) {
1074        pkt->makeAtomicResponse();
1075    }
1076
1077    return lat * clockPeriod();
1078}
1079
1080
1081void
1082Cache::functionalAccess(PacketPtr pkt, bool fromCpuSide)
1083{
1084    if (system->bypassCaches()) {
1085        // Packets from the memory side are snoop request and
1086        // shouldn't happen in bypass mode.
1087        assert(fromCpuSide);
1088
1089        // The cache should be flushed if we are in cache bypass mode,
1090        // so we don't need to check if we need to update anything.
1091        memSidePort->sendFunctional(pkt);
1092        return;
1093    }
1094
1095    Addr blk_addr = blockAlign(pkt->getAddr());
1096    bool is_secure = pkt->isSecure();
1097    CacheBlk *blk = tags->findBlock(pkt->getAddr(), is_secure);
1098    MSHR *mshr = mshrQueue.findMatch(blk_addr, is_secure);
1099
1100    pkt->pushLabel(name());
1101
1102    CacheBlkPrintWrapper cbpw(blk);
1103
1104    // Note that just because an L2/L3 has valid data doesn't mean an
1105    // L1 doesn't have a more up-to-date modified copy that still
1106    // needs to be found.  As a result we always update the request if
1107    // we have it, but only declare it satisfied if we are the owner.
1108
1109    // see if we have data at all (owned or otherwise)
1110    bool have_data = blk && blk->isValid()
1111        && pkt->checkFunctional(&cbpw, blk_addr, is_secure, blkSize,
1112                                blk->data);
1113
1114    // data we have is dirty if marked as such or if valid & ownership
1115    // pending due to outstanding UpgradeReq
1116    bool have_dirty =
1117        have_data && (blk->isDirty() ||
1118                      (mshr && mshr->inService && mshr->isPendingDirty()));
1119
1120    bool done = have_dirty
1121        || cpuSidePort->checkFunctional(pkt)
1122        || mshrQueue.checkFunctional(pkt, blk_addr)
1123        || writeBuffer.checkFunctional(pkt, blk_addr)
1124        || memSidePort->checkFunctional(pkt);
1125
1126    DPRINTF(Cache, "functional %s %#llx (%s) %s%s%s\n",
1127            pkt->cmdString(), pkt->getAddr(), is_secure ? "s" : "ns",
1128            (blk && blk->isValid()) ? "valid " : "",
1129            have_data ? "data " : "", done ? "done " : "");
1130
1131    // We're leaving the cache, so pop cache->name() label
1132    pkt->popLabel();
1133
1134    if (done) {
1135        pkt->makeResponse();
1136    } else {
1137        // if it came as a request from the CPU side then make sure it
1138        // continues towards the memory side
1139        if (fromCpuSide) {
1140            memSidePort->sendFunctional(pkt);
1141        } else if (forwardSnoops && cpuSidePort->isSnooping()) {
1142            // if it came from the memory side, it must be a snoop request
1143            // and we should only forward it if we are forwarding snoops
1144            cpuSidePort->sendFunctionalSnoop(pkt);
1145        }
1146    }
1147}
1148
1149
1150/////////////////////////////////////////////////////
1151//
1152// Response handling: responses from the memory side
1153//
1154/////////////////////////////////////////////////////
1155
1156
1157void
1158Cache::recvTimingResp(PacketPtr pkt)
1159{
1160    assert(pkt->isResponse());
1161
1162    // all header delay should be paid for by the crossbar, unless
1163    // this is a prefetch response from above
1164    panic_if(pkt->headerDelay != 0 && pkt->cmd != MemCmd::HardPFResp,
1165             "%s saw a non-zero packet delay\n", name());
1166
1167    MSHR *mshr = dynamic_cast<MSHR*>(pkt->senderState);
1168    bool is_error = pkt->isError();
1169
1170    assert(mshr);
1171
1172    if (is_error) {
1173        DPRINTF(Cache, "Cache received packet with error for addr %#llx (%s), "
1174                "cmd: %s\n", pkt->getAddr(), pkt->isSecure() ? "s" : "ns",
1175                pkt->cmdString());
1176    }
1177
1178    DPRINTF(Cache, "Handling response %s for addr %#llx size %d (%s)\n",
1179            pkt->cmdString(), pkt->getAddr(), pkt->getSize(),
1180            pkt->isSecure() ? "s" : "ns");
1181
1182    MSHRQueue *mq = mshr->queue;
1183    bool wasFull = mq->isFull();
1184
1185    if (mshr == noTargetMSHR) {
1186        // we always clear at least one target
1187        clearBlocked(Blocked_NoTargets);
1188        noTargetMSHR = NULL;
1189    }
1190
1191    // Initial target is used just for stats
1192    MSHR::Target *initial_tgt = mshr->getTarget();
1193    CacheBlk *blk = tags->findBlock(pkt->getAddr(), pkt->isSecure());
1194    int stats_cmd_idx = initial_tgt->pkt->cmdToIndex();
1195    Tick miss_latency = curTick() - initial_tgt->recvTime;
1196    PacketList writebacks;
1197    // We need forward_time here because we have a call of
1198    // allocateWriteBuffer() that need this parameter to specify the
1199    // time to request the bus.  In this case we use forward latency
1200    // because there is a writeback.  We pay also here for headerDelay
1201    // that is charged of bus latencies if the packet comes from the
1202    // bus.
1203    Tick forward_time = clockEdge(forwardLatency) + pkt->headerDelay;
1204
1205    if (pkt->req->isUncacheable()) {
1206        assert(pkt->req->masterId() < system->maxMasters());
1207        mshr_uncacheable_lat[stats_cmd_idx][pkt->req->masterId()] +=
1208            miss_latency;
1209    } else {
1210        assert(pkt->req->masterId() < system->maxMasters());
1211        mshr_miss_latency[stats_cmd_idx][pkt->req->masterId()] +=
1212            miss_latency;
1213    }
1214
1215    bool is_fill = !mshr->isForward &&
1216        (pkt->isRead() || pkt->cmd == MemCmd::UpgradeResp);
1217
1218    if (is_fill && !is_error) {
1219        DPRINTF(Cache, "Block for addr %#llx being updated in Cache\n",
1220                pkt->getAddr());
1221
1222        // give mshr a chance to do some dirty work
1223        mshr->handleFill(pkt, blk);
1224
1225        blk = handleFill(pkt, blk, writebacks);
1226        assert(blk != NULL);
1227    }
1228
1229    // allow invalidation responses originating from write-line
1230    // requests to be discarded
1231    bool is_invalidate = pkt->isInvalidate();
1232
1233    // First offset for critical word first calculations
1234    int initial_offset = initial_tgt->pkt->getOffset(blkSize);
1235
1236    while (mshr->hasTargets()) {
1237        MSHR::Target *target = mshr->getTarget();
1238        Packet *tgt_pkt = target->pkt;
1239
1240        switch (target->source) {
1241          case MSHR::Target::FromCPU:
1242            Tick completion_time;
1243            // Here we charge on completion_time the delay of the xbar if the
1244            // packet comes from it, charged on headerDelay.
1245            completion_time = pkt->headerDelay;
1246
1247            // Software prefetch handling for cache closest to core
1248            if (tgt_pkt->cmd.isSWPrefetch()) {
1249                // a software prefetch would have already been ack'd immediately
1250                // with dummy data so the core would be able to retire it.
1251                // this request completes right here, so we deallocate it.
1252                delete tgt_pkt->req;
1253                delete tgt_pkt;
1254                break; // skip response
1255            }
1256
1257            // unlike the other packet flows, where data is found in other
1258            // caches or memory and brought back, write-line requests always
1259            // have the data right away, so the above check for "is fill?"
1260            // cannot actually be determined until examining the stored MSHR
1261            // state. We "catch up" with that logic here, which is duplicated
1262            // from above.
1263            if (tgt_pkt->cmd == MemCmd::WriteLineReq) {
1264                assert(!is_error);
1265
1266                // NB: we use the original packet here and not the response!
1267                mshr->handleFill(tgt_pkt, blk);
1268                blk = handleFill(tgt_pkt, blk, writebacks);
1269                assert(blk != NULL);
1270
1271                // treat as a fill, and discard the invalidation
1272                // response
1273                is_fill = true;
1274                is_invalidate = false;
1275            }
1276
1277            if (is_fill) {
1278                satisfyCpuSideRequest(tgt_pkt, blk,
1279                                      true, mshr->hasPostDowngrade());
1280
1281                // How many bytes past the first request is this one
1282                int transfer_offset =
1283                    tgt_pkt->getOffset(blkSize) - initial_offset;
1284                if (transfer_offset < 0) {
1285                    transfer_offset += blkSize;
1286                }
1287
1288                // If not critical word (offset) return payloadDelay.
1289                // responseLatency is the latency of the return path
1290                // from lower level caches/memory to an upper level cache or
1291                // the core.
1292                completion_time += clockEdge(responseLatency) +
1293                    (transfer_offset ? pkt->payloadDelay : 0);
1294
1295                assert(!tgt_pkt->req->isUncacheable());
1296
1297                assert(tgt_pkt->req->masterId() < system->maxMasters());
1298                missLatency[tgt_pkt->cmdToIndex()][tgt_pkt->req->masterId()] +=
1299                    completion_time - target->recvTime;
1300            } else if (pkt->cmd == MemCmd::UpgradeFailResp) {
1301                // failed StoreCond upgrade
1302                assert(tgt_pkt->cmd == MemCmd::StoreCondReq ||
1303                       tgt_pkt->cmd == MemCmd::StoreCondFailReq ||
1304                       tgt_pkt->cmd == MemCmd::SCUpgradeFailReq);
1305                // responseLatency is the latency of the return path
1306                // from lower level caches/memory to an upper level cache or
1307                // the core.
1308                completion_time += clockEdge(responseLatency) +
1309                    pkt->payloadDelay;
1310                tgt_pkt->req->setExtraData(0);
1311            } else {
1312                // not a cache fill, just forwarding response
1313                // responseLatency is the latency of the return path
1314                // from lower level cahces/memory to the core.
1315                completion_time += clockEdge(responseLatency) +
1316                    pkt->payloadDelay;
1317                if (pkt->isRead() && !is_error) {
1318                    // sanity check
1319                    assert(pkt->getAddr() == tgt_pkt->getAddr());
1320                    assert(pkt->getSize() >= tgt_pkt->getSize());
1321
1322                    tgt_pkt->setData(pkt->getConstPtr<uint8_t>());
1323                }
1324            }
1325            tgt_pkt->makeTimingResponse();
1326            // if this packet is an error copy that to the new packet
1327            if (is_error)
1328                tgt_pkt->copyError(pkt);
1329            if (tgt_pkt->cmd == MemCmd::ReadResp &&
1330                (is_invalidate || mshr->hasPostInvalidate())) {
1331                // If intermediate cache got ReadRespWithInvalidate,
1332                // propagate that.  Response should not have
1333                // isInvalidate() set otherwise.
1334                tgt_pkt->cmd = MemCmd::ReadRespWithInvalidate;
1335                DPRINTF(Cache, "%s updated cmd to %s for addr %#llx\n",
1336                        __func__, tgt_pkt->cmdString(), tgt_pkt->getAddr());
1337            }
1338            // Reset the bus additional time as it is now accounted for
1339            tgt_pkt->headerDelay = tgt_pkt->payloadDelay = 0;
1340            cpuSidePort->schedTimingResp(tgt_pkt, completion_time);
1341            break;
1342
1343          case MSHR::Target::FromPrefetcher:
1344            assert(tgt_pkt->cmd == MemCmd::HardPFReq);
1345            if (blk)
1346                blk->status |= BlkHWPrefetched;
1347            delete tgt_pkt->req;
1348            delete tgt_pkt;
1349            break;
1350
1351          case MSHR::Target::FromSnoop:
1352            // I don't believe that a snoop can be in an error state
1353            assert(!is_error);
1354            // response to snoop request
1355            DPRINTF(Cache, "processing deferred snoop...\n");
1356            assert(!(is_invalidate && !mshr->hasPostInvalidate()));
1357            handleSnoop(tgt_pkt, blk, true, true, mshr->hasPostInvalidate());
1358            break;
1359
1360          default:
1361            panic("Illegal target->source enum %d\n", target->source);
1362        }
1363
1364        mshr->popTarget();
1365    }
1366
1367    if (blk && blk->isValid()) {
1368        // an invalidate response stemming from a write line request
1369        // should not invalidate the block, so check if the
1370        // invalidation should be discarded
1371        if (is_invalidate || mshr->hasPostInvalidate()) {
1372            assert(blk != tempBlock);
1373            tags->invalidate(blk);
1374            blk->invalidate();
1375        } else if (mshr->hasPostDowngrade()) {
1376            blk->status &= ~BlkWritable;
1377        }
1378    }
1379
1380    if (mshr->promoteDeferredTargets()) {
1381        // avoid later read getting stale data while write miss is
1382        // outstanding.. see comment in timingAccess()
1383        if (blk) {
1384            blk->status &= ~BlkReadable;
1385        }
1386        mq = mshr->queue;
1387        mq->markPending(mshr);
1388        schedMemSideSendEvent(clockEdge() + pkt->payloadDelay);
1389    } else {
1390        mq->deallocate(mshr);
1391        if (wasFull && !mq->isFull()) {
1392            clearBlocked((BlockedCause)mq->index);
1393        }
1394
1395        // Request the bus for a prefetch if this deallocation freed enough
1396        // MSHRs for a prefetch to take place
1397        if (prefetcher && mq == &mshrQueue && mshrQueue.canPrefetch()) {
1398            Tick next_pf_time = std::max(prefetcher->nextPrefetchReadyTime(),
1399                                         clockEdge());
1400            if (next_pf_time != MaxTick)
1401                schedMemSideSendEvent(next_pf_time);
1402        }
1403    }
1404    // reset the xbar additional timinig  as it is now accounted for
1405    pkt->headerDelay = pkt->payloadDelay = 0;
1406
1407    // copy writebacks to write buffer
1408    doWritebacks(writebacks, forward_time);
1409
1410    // if we used temp block, check to see if its valid and then clear it out
1411    if (blk == tempBlock && tempBlock->isValid()) {
1412        // We use forwardLatency here because we are copying
1413        // Writebacks/CleanEvicts to write buffer. It specifies the latency to
1414        // allocate an internal buffer and to schedule an event to the
1415        // queued port.
1416        if (blk->isDirty()) {
1417            PacketPtr wbPkt = writebackBlk(blk);
1418            allocateWriteBuffer(wbPkt, forward_time);
1419            // Set BLOCK_CACHED flag if cached above.
1420            if (isCachedAbove(wbPkt))
1421                wbPkt->setBlockCached();
1422        } else {
1423            PacketPtr wcPkt = cleanEvictBlk(blk);
1424            // Check to see if block is cached above. If not allocate
1425            // write buffer
1426            if (isCachedAbove(wcPkt))
1427                delete wcPkt;
1428            else
1429                allocateWriteBuffer(wcPkt, forward_time);
1430        }
1431        blk->invalidate();
1432    }
1433
1434    DPRINTF(Cache, "Leaving %s with %s for addr %#llx\n", __func__,
1435            pkt->cmdString(), pkt->getAddr());
1436    delete pkt;
1437}
1438
1439PacketPtr
1440Cache::writebackBlk(CacheBlk *blk)
1441{
1442    chatty_assert(!isReadOnly, "Writeback from read-only cache");
1443    assert(blk && blk->isValid() && blk->isDirty());
1444
1445    writebacks[Request::wbMasterId]++;
1446
1447    Request *writebackReq =
1448        new Request(tags->regenerateBlkAddr(blk->tag, blk->set), blkSize, 0,
1449                Request::wbMasterId);
1450    if (blk->isSecure())
1451        writebackReq->setFlags(Request::SECURE);
1452
1453    writebackReq->taskId(blk->task_id);
1454    blk->task_id= ContextSwitchTaskId::Unknown;
1455    blk->tickInserted = curTick();
1456
1457    PacketPtr writeback = new Packet(writebackReq, MemCmd::Writeback);
1458    if (blk->isWritable()) {
1459        // not asserting shared means we pass the block in modified
1460        // state, mark our own block non-writeable
1461        blk->status &= ~BlkWritable;
1462    } else {
1463        // we are in the owned state, tell the receiver
1464        writeback->assertShared();
1465    }
1466
1467    writeback->allocate();
1468    std::memcpy(writeback->getPtr<uint8_t>(), blk->data, blkSize);
1469
1470    blk->status &= ~BlkDirty;
1471    return writeback;
1472}
1473
1474PacketPtr
1475Cache::cleanEvictBlk(CacheBlk *blk)
1476{
1477    assert(blk && blk->isValid() && !blk->isDirty());
1478    // Creating a zero sized write, a message to the snoop filter
1479    Request *req =
1480        new Request(tags->regenerateBlkAddr(blk->tag, blk->set), blkSize, 0,
1481                    Request::wbMasterId);
1482    if (blk->isSecure())
1483        req->setFlags(Request::SECURE);
1484
1485    req->taskId(blk->task_id);
1486    blk->task_id = ContextSwitchTaskId::Unknown;
1487    blk->tickInserted = curTick();
1488
1489    PacketPtr pkt = new Packet(req, MemCmd::CleanEvict);
1490    pkt->allocate();
1491    DPRINTF(Cache, "%s%s %x Create CleanEvict\n", pkt->cmdString(),
1492            pkt->req->isInstFetch() ? " (ifetch)" : "",
1493            pkt->getAddr());
1494
1495    return pkt;
1496}
1497
1498void
1499Cache::memWriteback()
1500{
1501    CacheBlkVisitorWrapper visitor(*this, &Cache::writebackVisitor);
1502    tags->forEachBlk(visitor);
1503}
1504
1505void
1506Cache::memInvalidate()
1507{
1508    CacheBlkVisitorWrapper visitor(*this, &Cache::invalidateVisitor);
1509    tags->forEachBlk(visitor);
1510}
1511
1512bool
1513Cache::isDirty() const
1514{
1515    CacheBlkIsDirtyVisitor visitor;
1516    tags->forEachBlk(visitor);
1517
1518    return visitor.isDirty();
1519}
1520
1521bool
1522Cache::writebackVisitor(CacheBlk &blk)
1523{
1524    if (blk.isDirty()) {
1525        assert(blk.isValid());
1526
1527        Request request(tags->regenerateBlkAddr(blk.tag, blk.set),
1528                        blkSize, 0, Request::funcMasterId);
1529        request.taskId(blk.task_id);
1530
1531        Packet packet(&request, MemCmd::WriteReq);
1532        packet.dataStatic(blk.data);
1533
1534        memSidePort->sendFunctional(&packet);
1535
1536        blk.status &= ~BlkDirty;
1537    }
1538
1539    return true;
1540}
1541
1542bool
1543Cache::invalidateVisitor(CacheBlk &blk)
1544{
1545
1546    if (blk.isDirty())
1547        warn_once("Invalidating dirty cache lines. Expect things to break.\n");
1548
1549    if (blk.isValid()) {
1550        assert(!blk.isDirty());
1551        tags->invalidate(&blk);
1552        blk.invalidate();
1553    }
1554
1555    return true;
1556}
1557
1558CacheBlk*
1559Cache::allocateBlock(Addr addr, bool is_secure, PacketList &writebacks)
1560{
1561    CacheBlk *blk = tags->findVictim(addr);
1562
1563    // It is valid to return NULL if there is no victim
1564    if (!blk)
1565        return nullptr;
1566
1567    if (blk->isValid()) {
1568        Addr repl_addr = tags->regenerateBlkAddr(blk->tag, blk->set);
1569        MSHR *repl_mshr = mshrQueue.findMatch(repl_addr, blk->isSecure());
1570        if (repl_mshr) {
1571            // must be an outstanding upgrade request
1572            // on a block we're about to replace...
1573            assert(!blk->isWritable() || blk->isDirty());
1574            assert(repl_mshr->needsExclusive());
1575            // too hard to replace block with transient state
1576            // allocation failed, block not inserted
1577            return NULL;
1578        } else {
1579            DPRINTF(Cache, "replacement: replacing %#llx (%s) with %#llx (%s): %s\n",
1580                    repl_addr, blk->isSecure() ? "s" : "ns",
1581                    addr, is_secure ? "s" : "ns",
1582                    blk->isDirty() ? "writeback" : "clean");
1583
1584            // Will send up Writeback/CleanEvict snoops via isCachedAbove
1585            // when pushing this writeback list into the write buffer.
1586            if (blk->isDirty()) {
1587                // Save writeback packet for handling by caller
1588                writebacks.push_back(writebackBlk(blk));
1589            } else {
1590                writebacks.push_back(cleanEvictBlk(blk));
1591            }
1592        }
1593    }
1594
1595    return blk;
1596}
1597
1598
1599// Note that the reason we return a list of writebacks rather than
1600// inserting them directly in the write buffer is that this function
1601// is called by both atomic and timing-mode accesses, and in atomic
1602// mode we don't mess with the write buffer (we just perform the
1603// writebacks atomically once the original request is complete).
1604CacheBlk*
1605Cache::handleFill(PacketPtr pkt, CacheBlk *blk, PacketList &writebacks)
1606{
1607    assert(pkt->isResponse() || pkt->cmd == MemCmd::WriteLineReq);
1608    Addr addr = pkt->getAddr();
1609    bool is_secure = pkt->isSecure();
1610#if TRACING_ON
1611    CacheBlk::State old_state = blk ? blk->status : 0;
1612#endif
1613
1614    // When handling a fill, discard any CleanEvicts for the
1615    // same address in write buffer.
1616    Addr M5_VAR_USED blk_addr = blockAlign(pkt->getAddr());
1617    std::vector<MSHR *> M5_VAR_USED wbs;
1618    assert (!writeBuffer.findMatches(blk_addr, is_secure, wbs));
1619
1620    if (blk == NULL) {
1621        // better have read new data...
1622        assert(pkt->hasData());
1623
1624        // only read responses and write-line requests have data;
1625        // note that we don't write the data here for write-line - that
1626        // happens in the subsequent satisfyCpuSideRequest.
1627        assert(pkt->isRead() || pkt->cmd == MemCmd::WriteLineReq);
1628
1629        // need to do a replacement
1630        blk = allocateBlock(addr, is_secure, writebacks);
1631        if (blk == NULL) {
1632            // No replaceable block... just use temporary storage to
1633            // complete the current request and then get rid of it
1634            assert(!tempBlock->isValid());
1635            blk = tempBlock;
1636            tempBlock->set = tags->extractSet(addr);
1637            tempBlock->tag = tags->extractTag(addr);
1638            // @todo: set security state as well...
1639            DPRINTF(Cache, "using temp block for %#llx (%s)\n", addr,
1640                    is_secure ? "s" : "ns");
1641        } else {
1642            tags->insertBlock(pkt, blk);
1643        }
1644
1645        // we should never be overwriting a valid block
1646        assert(!blk->isValid());
1647    } else {
1648        // existing block... probably an upgrade
1649        assert(blk->tag == tags->extractTag(addr));
1650        // either we're getting new data or the block should already be valid
1651        assert(pkt->hasData() || blk->isValid());
1652        // don't clear block status... if block is already dirty we
1653        // don't want to lose that
1654    }
1655
1656    if (is_secure)
1657        blk->status |= BlkSecure;
1658    blk->status |= BlkValid | BlkReadable;
1659
1660    if (!pkt->sharedAsserted()) {
1661        // we could get non-shared responses from memory (rather than
1662        // a cache) even in a read-only cache, note that we set this
1663        // bit even for a read-only cache as we use it to represent
1664        // the exclusive state
1665        blk->status |= BlkWritable;
1666
1667        // If we got this via cache-to-cache transfer (i.e., from a
1668        // cache that was an owner) and took away that owner's copy,
1669        // then we need to write it back.  Normally this happens
1670        // anyway as a side effect of getting a copy to write it, but
1671        // there are cases (such as failed store conditionals or
1672        // compare-and-swaps) where we'll demand an exclusive copy but
1673        // end up not writing it.
1674        if (pkt->memInhibitAsserted()) {
1675            blk->status |= BlkDirty;
1676
1677            chatty_assert(!isReadOnly, "Should never see dirty snoop response "
1678                          "in read-only cache %s\n", name());
1679        }
1680    }
1681
1682    DPRINTF(Cache, "Block addr %#llx (%s) moving from state %x to %s\n",
1683            addr, is_secure ? "s" : "ns", old_state, blk->print());
1684
1685    // if we got new data, copy it in (checking for a read response
1686    // and a response that has data is the same in the end)
1687    if (pkt->isRead()) {
1688        // sanity checks
1689        assert(pkt->hasData());
1690        assert(pkt->getSize() == blkSize);
1691
1692        std::memcpy(blk->data, pkt->getConstPtr<uint8_t>(), blkSize);
1693    }
1694    // We pay for fillLatency here.
1695    blk->whenReady = clockEdge() + fillLatency * clockPeriod() +
1696        pkt->payloadDelay;
1697
1698    return blk;
1699}
1700
1701
1702/////////////////////////////////////////////////////
1703//
1704// Snoop path: requests coming in from the memory side
1705//
1706/////////////////////////////////////////////////////
1707
1708void
1709Cache::doTimingSupplyResponse(PacketPtr req_pkt, const uint8_t *blk_data,
1710                              bool already_copied, bool pending_inval)
1711{
1712    // sanity check
1713    assert(req_pkt->isRequest());
1714    assert(req_pkt->needsResponse());
1715
1716    DPRINTF(Cache, "%s for %s addr %#llx size %d\n", __func__,
1717            req_pkt->cmdString(), req_pkt->getAddr(), req_pkt->getSize());
1718    // timing-mode snoop responses require a new packet, unless we
1719    // already made a copy...
1720    PacketPtr pkt = req_pkt;
1721    if (!already_copied)
1722        // do not clear flags, and allocate space for data if the
1723        // packet needs it (the only packets that carry data are read
1724        // responses)
1725        pkt = new Packet(req_pkt, false, req_pkt->isRead());
1726
1727    assert(req_pkt->req->isUncacheable() || req_pkt->isInvalidate() ||
1728           pkt->sharedAsserted());
1729    pkt->makeTimingResponse();
1730    if (pkt->isRead()) {
1731        pkt->setDataFromBlock(blk_data, blkSize);
1732    }
1733    if (pkt->cmd == MemCmd::ReadResp && pending_inval) {
1734        // Assume we defer a response to a read from a far-away cache
1735        // A, then later defer a ReadExcl from a cache B on the same
1736        // bus as us.  We'll assert MemInhibit in both cases, but in
1737        // the latter case MemInhibit will keep the invalidation from
1738        // reaching cache A.  This special response tells cache A that
1739        // it gets the block to satisfy its read, but must immediately
1740        // invalidate it.
1741        pkt->cmd = MemCmd::ReadRespWithInvalidate;
1742    }
1743    // Here we consider forward_time, paying for just forward latency and
1744    // also charging the delay provided by the xbar.
1745    // forward_time is used as send_time in next allocateWriteBuffer().
1746    Tick forward_time = clockEdge(forwardLatency) + pkt->headerDelay;
1747    // Here we reset the timing of the packet.
1748    pkt->headerDelay = pkt->payloadDelay = 0;
1749    DPRINTF(Cache, "%s created response: %s addr %#llx size %d tick: %lu\n",
1750            __func__, pkt->cmdString(), pkt->getAddr(), pkt->getSize(),
1751            forward_time);
1752    memSidePort->schedTimingSnoopResp(pkt, forward_time, true);
1753}
1754
1755uint32_t
1756Cache::handleSnoop(PacketPtr pkt, CacheBlk *blk, bool is_timing,
1757                   bool is_deferred, bool pending_inval)
1758{
1759    DPRINTF(Cache, "%s for %s addr %#llx size %d\n", __func__,
1760            pkt->cmdString(), pkt->getAddr(), pkt->getSize());
1761    // deferred snoops can only happen in timing mode
1762    assert(!(is_deferred && !is_timing));
1763    // pending_inval only makes sense on deferred snoops
1764    assert(!(pending_inval && !is_deferred));
1765    assert(pkt->isRequest());
1766
1767    // the packet may get modified if we or a forwarded snooper
1768    // responds in atomic mode, so remember a few things about the
1769    // original packet up front
1770    bool invalidate = pkt->isInvalidate();
1771    bool M5_VAR_USED needs_exclusive = pkt->needsExclusive();
1772
1773    uint32_t snoop_delay = 0;
1774
1775    if (forwardSnoops) {
1776        // first propagate snoop upward to see if anyone above us wants to
1777        // handle it.  save & restore packet src since it will get
1778        // rewritten to be relative to cpu-side bus (if any)
1779        bool alreadyResponded = pkt->memInhibitAsserted();
1780        if (is_timing) {
1781            // copy the packet so that we can clear any flags before
1782            // forwarding it upwards, we also allocate data (passing
1783            // the pointer along in case of static data), in case
1784            // there is a snoop hit in upper levels
1785            Packet snoopPkt(pkt, true, true);
1786            snoopPkt.setExpressSnoop();
1787            snoopPkt.pushSenderState(new ForwardResponseRecord());
1788            // the snoop packet does not need to wait any additional
1789            // time
1790            snoopPkt.headerDelay = snoopPkt.payloadDelay = 0;
1791            cpuSidePort->sendTimingSnoopReq(&snoopPkt);
1792
1793            // add the header delay (including crossbar and snoop
1794            // delays) of the upward snoop to the snoop delay for this
1795            // cache
1796            snoop_delay += snoopPkt.headerDelay;
1797
1798            if (snoopPkt.memInhibitAsserted()) {
1799                // cache-to-cache response from some upper cache
1800                assert(!alreadyResponded);
1801                pkt->assertMemInhibit();
1802            } else {
1803                // no cache (or anyone else for that matter) will
1804                // respond, so delete the ForwardResponseRecord here
1805                delete snoopPkt.popSenderState();
1806            }
1807            if (snoopPkt.sharedAsserted()) {
1808                pkt->assertShared();
1809            }
1810            // If this request is a prefetch or clean evict and an upper level
1811            // signals block present, make sure to propagate the block
1812            // presence to the requester.
1813            if (snoopPkt.isBlockCached()) {
1814                pkt->setBlockCached();
1815            }
1816        } else {
1817            cpuSidePort->sendAtomicSnoop(pkt);
1818            if (!alreadyResponded && pkt->memInhibitAsserted()) {
1819                // cache-to-cache response from some upper cache:
1820                // forward response to original requester
1821                assert(pkt->isResponse());
1822            }
1823        }
1824    }
1825
1826    if (!blk || !blk->isValid()) {
1827        DPRINTF(Cache, "%s snoop miss for %s addr %#llx size %d\n",
1828                __func__, pkt->cmdString(), pkt->getAddr(), pkt->getSize());
1829        return snoop_delay;
1830    } else {
1831       DPRINTF(Cache, "%s snoop hit for %s for addr %#llx size %d, "
1832               "old state is %s\n", __func__, pkt->cmdString(),
1833               pkt->getAddr(), pkt->getSize(), blk->print());
1834    }
1835
1836    chatty_assert(!(isReadOnly && blk->isDirty()),
1837                  "Should never have a dirty block in a read-only cache %s\n",
1838                  name());
1839
1840    // We may end up modifying both the block state and the packet (if
1841    // we respond in atomic mode), so just figure out what to do now
1842    // and then do it later. If we find dirty data while snooping for
1843    // an invalidate, we don't need to send a response. The
1844    // invalidation itself is taken care of below.
1845    bool respond = blk->isDirty() && pkt->needsResponse() &&
1846        pkt->cmd != MemCmd::InvalidateReq;
1847    bool have_exclusive = blk->isWritable();
1848
1849    // Invalidate any prefetch's from below that would strip write permissions
1850    // MemCmd::HardPFReq is only observed by upstream caches.  After missing
1851    // above and in it's own cache, a new MemCmd::ReadReq is created that
1852    // downstream caches observe.
1853    if (pkt->mustCheckAbove()) {
1854        DPRINTF(Cache, "Found addr %#llx in upper level cache for snoop %s from"
1855                " lower cache\n", pkt->getAddr(), pkt->cmdString());
1856        pkt->setBlockCached();
1857        return snoop_delay;
1858    }
1859
1860    if (!pkt->req->isUncacheable() && pkt->isRead() && !invalidate) {
1861        // reading non-exclusive shared data, note that we retain
1862        // the block in owned state if it is dirty, with the response
1863        // taken care of below, and otherwhise simply downgrade to
1864        // shared
1865        assert(!needs_exclusive);
1866        pkt->assertShared();
1867        blk->status &= ~BlkWritable;
1868    }
1869
1870    if (respond) {
1871        // prevent anyone else from responding, cache as well as
1872        // memory, and also prevent any memory from even seeing the
1873        // request (with current inhibited semantics), note that this
1874        // applies both to reads and writes and that for writes it
1875        // works thanks to the fact that we still have dirty data and
1876        // will write it back at a later point
1877        pkt->assertMemInhibit();
1878        if (have_exclusive) {
1879            // in the case of an uncacheable request there is no point
1880            // in setting the exclusive flag, but since the recipient
1881            // does not care there is no harm in doing so, in any case
1882            // it is just a hint
1883            pkt->setSupplyExclusive();
1884        }
1885        if (is_timing) {
1886            doTimingSupplyResponse(pkt, blk->data, is_deferred, pending_inval);
1887        } else {
1888            pkt->makeAtomicResponse();
1889            pkt->setDataFromBlock(blk->data, blkSize);
1890        }
1891    }
1892
1893    if (!respond && is_timing && is_deferred) {
1894        // if it's a deferred timing snoop then we've made a copy of
1895        // both the request and the packet, and so if we're not using
1896        // those copies to respond and delete them here
1897        DPRINTF(Cache, "Deleting pkt %p and request %p for cmd %s addr: %p\n",
1898                pkt, pkt->req, pkt->cmdString(), pkt->getAddr());
1899
1900        // the packets needs a response (just not from us), so we also
1901        // need to delete the request and not rely on the packet
1902        // destructor
1903        assert(pkt->needsResponse());
1904        delete pkt->req;
1905        delete pkt;
1906    }
1907
1908    // Do this last in case it deallocates block data or something
1909    // like that
1910    if (invalidate) {
1911        if (blk != tempBlock)
1912            tags->invalidate(blk);
1913        blk->invalidate();
1914    }
1915
1916    DPRINTF(Cache, "new state is %s\n", blk->print());
1917
1918    return snoop_delay;
1919}
1920
1921
1922void
1923Cache::recvTimingSnoopReq(PacketPtr pkt)
1924{
1925    DPRINTF(Cache, "%s for %s addr %#llx size %d\n", __func__,
1926            pkt->cmdString(), pkt->getAddr(), pkt->getSize());
1927
1928    // Snoops shouldn't happen when bypassing caches
1929    assert(!system->bypassCaches());
1930
1931    // no need to snoop requests that are not in range
1932    if (!inRange(pkt->getAddr())) {
1933        return;
1934    }
1935
1936    bool is_secure = pkt->isSecure();
1937    CacheBlk *blk = tags->findBlock(pkt->getAddr(), is_secure);
1938
1939    Addr blk_addr = blockAlign(pkt->getAddr());
1940    MSHR *mshr = mshrQueue.findMatch(blk_addr, is_secure);
1941
1942    // Update the latency cost of the snoop so that the crossbar can
1943    // account for it. Do not overwrite what other neighbouring caches
1944    // have already done, rather take the maximum. The update is
1945    // tentative, for cases where we return before an upward snoop
1946    // happens below.
1947    pkt->snoopDelay = std::max<uint32_t>(pkt->snoopDelay,
1948                                         lookupLatency * clockPeriod());
1949
1950    // Inform request(Prefetch, CleanEvict or Writeback) from below of
1951    // MSHR hit, set setBlockCached.
1952    if (mshr && pkt->mustCheckAbove()) {
1953        DPRINTF(Cache, "Setting block cached for %s from"
1954                "lower cache on mshr hit %#x\n",
1955                pkt->cmdString(), pkt->getAddr());
1956        pkt->setBlockCached();
1957        return;
1958    }
1959
1960    // Let the MSHR itself track the snoop and decide whether we want
1961    // to go ahead and do the regular cache snoop
1962    if (mshr && mshr->handleSnoop(pkt, order++)) {
1963        DPRINTF(Cache, "Deferring snoop on in-service MSHR to blk %#llx (%s)."
1964                "mshrs: %s\n", blk_addr, is_secure ? "s" : "ns",
1965                mshr->print());
1966
1967        if (mshr->getNumTargets() > numTarget)
1968            warn("allocating bonus target for snoop"); //handle later
1969        return;
1970    }
1971
1972    //We also need to check the writeback buffers and handle those
1973    std::vector<MSHR *> writebacks;
1974    if (writeBuffer.findMatches(blk_addr, is_secure, writebacks)) {
1975        DPRINTF(Cache, "Snoop hit in writeback to addr %#llx (%s)\n",
1976                pkt->getAddr(), is_secure ? "s" : "ns");
1977
1978        // Look through writebacks for any cachable writes.
1979        // We should only ever find a single match
1980        assert(writebacks.size() == 1);
1981        MSHR *wb_entry = writebacks[0];
1982        // Expect to see only Writebacks and/or CleanEvicts here, both of
1983        // which should not be generated for uncacheable data.
1984        assert(!wb_entry->isUncacheable());
1985        // There should only be a single request responsible for generating
1986        // Writebacks/CleanEvicts.
1987        assert(wb_entry->getNumTargets() == 1);
1988        PacketPtr wb_pkt = wb_entry->getTarget()->pkt;
1989        assert(wb_pkt->evictingBlock());
1990
1991        if (pkt->evictingBlock()) {
1992            // if the block is found in the write queue, set the BLOCK_CACHED
1993            // flag for Writeback/CleanEvict snoop. On return the snoop will
1994            // propagate the BLOCK_CACHED flag in Writeback packets and prevent
1995            // any CleanEvicts from travelling down the memory hierarchy.
1996            pkt->setBlockCached();
1997            DPRINTF(Cache, "Squashing %s from lower cache on writequeue hit"
1998                    " %#x\n", pkt->cmdString(), pkt->getAddr());
1999            return;
2000        }
2001
2002        if (wb_pkt->cmd == MemCmd::Writeback) {
2003            assert(!pkt->memInhibitAsserted());
2004            pkt->assertMemInhibit();
2005            if (!pkt->needsExclusive()) {
2006                pkt->assertShared();
2007                // the writeback is no longer passing exclusivity (the
2008                // receiving cache should consider the block owned
2009                // rather than modified)
2010                wb_pkt->assertShared();
2011            } else {
2012                // if we're not asserting the shared line, we need to
2013                // invalidate our copy.  we'll do that below as long as
2014                // the packet's invalidate flag is set...
2015                assert(pkt->isInvalidate());
2016            }
2017            doTimingSupplyResponse(pkt, wb_pkt->getConstPtr<uint8_t>(),
2018                                   false, false);
2019        } else {
2020            assert(wb_pkt->cmd == MemCmd::CleanEvict);
2021            // The cache technically holds the block until the
2022            // corresponding CleanEvict message reaches the crossbar
2023            // below. Therefore when a snoop encounters a CleanEvict
2024            // message we must set assertShared (just like when it
2025            // encounters a Writeback) to avoid the snoop filter
2026            // prematurely clearing the holder bit in the crossbar
2027            // below
2028            if (!pkt->needsExclusive())
2029                pkt->assertShared();
2030            else
2031                assert(pkt->isInvalidate());
2032        }
2033
2034        if (pkt->isInvalidate()) {
2035            // Invalidation trumps our writeback... discard here
2036            // Note: markInService will remove entry from writeback buffer.
2037            markInService(wb_entry, false);
2038            delete wb_pkt;
2039        }
2040    }
2041
2042    // If this was a shared writeback, there may still be
2043    // other shared copies above that require invalidation.
2044    // We could be more selective and return here if the
2045    // request is non-exclusive or if the writeback is
2046    // exclusive.
2047    uint32_t snoop_delay = handleSnoop(pkt, blk, true, false, false);
2048
2049    // Override what we did when we first saw the snoop, as we now
2050    // also have the cost of the upwards snoops to account for
2051    pkt->snoopDelay = std::max<uint32_t>(pkt->snoopDelay, snoop_delay +
2052                                         lookupLatency * clockPeriod());
2053}
2054
2055bool
2056Cache::CpuSidePort::recvTimingSnoopResp(PacketPtr pkt)
2057{
2058    // Express snoop responses from master to slave, e.g., from L1 to L2
2059    cache->recvTimingSnoopResp(pkt);
2060    return true;
2061}
2062
2063Tick
2064Cache::recvAtomicSnoop(PacketPtr pkt)
2065{
2066    // Snoops shouldn't happen when bypassing caches
2067    assert(!system->bypassCaches());
2068
2069    // no need to snoop requests that are not in range.
2070    if (!inRange(pkt->getAddr())) {
2071        return 0;
2072    }
2073
2074    CacheBlk *blk = tags->findBlock(pkt->getAddr(), pkt->isSecure());
2075    uint32_t snoop_delay = handleSnoop(pkt, blk, false, false, false);
2076    return snoop_delay + lookupLatency * clockPeriod();
2077}
2078
2079
2080MSHR *
2081Cache::getNextMSHR()
2082{
2083    // Check both MSHR queue and write buffer for potential requests,
2084    // note that null does not mean there is no request, it could
2085    // simply be that it is not ready
2086    MSHR *miss_mshr  = mshrQueue.getNextMSHR();
2087    MSHR *write_mshr = writeBuffer.getNextMSHR();
2088
2089    // If we got a write buffer request ready, first priority is a
2090    // full write buffer, otherwhise we favour the miss requests
2091    if (write_mshr &&
2092        ((writeBuffer.isFull() && writeBuffer.inServiceEntries == 0) ||
2093         !miss_mshr)) {
2094        // need to search MSHR queue for conflicting earlier miss.
2095        MSHR *conflict_mshr =
2096            mshrQueue.findPending(write_mshr->blkAddr,
2097                                  write_mshr->isSecure);
2098
2099        if (conflict_mshr && conflict_mshr->order < write_mshr->order) {
2100            // Service misses in order until conflict is cleared.
2101            return conflict_mshr;
2102
2103            // @todo Note that we ignore the ready time of the conflict here
2104        }
2105
2106        // No conflicts; issue write
2107        return write_mshr;
2108    } else if (miss_mshr) {
2109        // need to check for conflicting earlier writeback
2110        MSHR *conflict_mshr =
2111            writeBuffer.findPending(miss_mshr->blkAddr,
2112                                    miss_mshr->isSecure);
2113        if (conflict_mshr) {
2114            // not sure why we don't check order here... it was in the
2115            // original code but commented out.
2116
2117            // The only way this happens is if we are
2118            // doing a write and we didn't have permissions
2119            // then subsequently saw a writeback (owned got evicted)
2120            // We need to make sure to perform the writeback first
2121            // To preserve the dirty data, then we can issue the write
2122
2123            // should we return write_mshr here instead?  I.e. do we
2124            // have to flush writes in order?  I don't think so... not
2125            // for Alpha anyway.  Maybe for x86?
2126            return conflict_mshr;
2127
2128            // @todo Note that we ignore the ready time of the conflict here
2129        }
2130
2131        // No conflicts; issue read
2132        return miss_mshr;
2133    }
2134
2135    // fall through... no pending requests.  Try a prefetch.
2136    assert(!miss_mshr && !write_mshr);
2137    if (prefetcher && mshrQueue.canPrefetch()) {
2138        // If we have a miss queue slot, we can try a prefetch
2139        PacketPtr pkt = prefetcher->getPacket();
2140        if (pkt) {
2141            Addr pf_addr = blockAlign(pkt->getAddr());
2142            if (!tags->findBlock(pf_addr, pkt->isSecure()) &&
2143                !mshrQueue.findMatch(pf_addr, pkt->isSecure()) &&
2144                !writeBuffer.findMatch(pf_addr, pkt->isSecure())) {
2145                // Update statistic on number of prefetches issued
2146                // (hwpf_mshr_misses)
2147                assert(pkt->req->masterId() < system->maxMasters());
2148                mshr_misses[pkt->cmdToIndex()][pkt->req->masterId()]++;
2149
2150                // allocate an MSHR and return it, note
2151                // that we send the packet straight away, so do not
2152                // schedule the send
2153                return allocateMissBuffer(pkt, curTick(), false);
2154            } else {
2155                // free the request and packet
2156                delete pkt->req;
2157                delete pkt;
2158            }
2159        }
2160    }
2161
2162    return NULL;
2163}
2164
2165bool
2166Cache::isCachedAbove(PacketPtr pkt, bool is_timing) const
2167{
2168    if (!forwardSnoops)
2169        return false;
2170    // Mirroring the flow of HardPFReqs, the cache sends CleanEvict and
2171    // Writeback snoops into upper level caches to check for copies of the
2172    // same block. Using the BLOCK_CACHED flag with the Writeback/CleanEvict
2173    // packet, the cache can inform the crossbar below of presence or absence
2174    // of the block.
2175    if (is_timing) {
2176        Packet snoop_pkt(pkt, true, false);
2177        snoop_pkt.setExpressSnoop();
2178        // Assert that packet is either Writeback or CleanEvict and not a
2179        // prefetch request because prefetch requests need an MSHR and may
2180        // generate a snoop response.
2181        assert(pkt->evictingBlock());
2182        snoop_pkt.senderState = NULL;
2183        cpuSidePort->sendTimingSnoopReq(&snoop_pkt);
2184        // Writeback/CleanEvict snoops do not generate a snoop response.
2185        assert(!(snoop_pkt.memInhibitAsserted()));
2186        return snoop_pkt.isBlockCached();
2187    } else {
2188        cpuSidePort->sendAtomicSnoop(pkt);
2189        return pkt->isBlockCached();
2190    }
2191}
2192
2193PacketPtr
2194Cache::getTimingPacket()
2195{
2196    MSHR *mshr = getNextMSHR();
2197
2198    if (mshr == NULL) {
2199        return NULL;
2200    }
2201
2202    // use request from 1st target
2203    PacketPtr tgt_pkt = mshr->getTarget()->pkt;
2204    PacketPtr pkt = NULL;
2205
2206    DPRINTF(CachePort, "%s %s for addr %#llx size %d\n", __func__,
2207            tgt_pkt->cmdString(), tgt_pkt->getAddr(), tgt_pkt->getSize());
2208
2209    CacheBlk *blk = tags->findBlock(mshr->blkAddr, mshr->isSecure);
2210
2211    if (tgt_pkt->cmd == MemCmd::HardPFReq && forwardSnoops) {
2212        // We need to check the caches above us to verify that
2213        // they don't have a copy of this block in the dirty state
2214        // at the moment. Without this check we could get a stale
2215        // copy from memory that might get used in place of the
2216        // dirty one.
2217        Packet snoop_pkt(tgt_pkt, true, false);
2218        snoop_pkt.setExpressSnoop();
2219        snoop_pkt.senderState = mshr;
2220        cpuSidePort->sendTimingSnoopReq(&snoop_pkt);
2221
2222        // Check to see if the prefetch was squashed by an upper cache (to
2223        // prevent us from grabbing the line) or if a Check to see if a
2224        // writeback arrived between the time the prefetch was placed in
2225        // the MSHRs and when it was selected to be sent or if the
2226        // prefetch was squashed by an upper cache.
2227
2228        // It is important to check memInhibitAsserted before
2229        // prefetchSquashed. If another cache has asserted MEM_INGIBIT, it
2230        // will be sending a response which will arrive at the MSHR
2231        // allocated ofr this request. Checking the prefetchSquash first
2232        // may result in the MSHR being prematurely deallocated.
2233
2234        if (snoop_pkt.memInhibitAsserted()) {
2235            // If we are getting a non-shared response it is dirty
2236            bool pending_dirty_resp = !snoop_pkt.sharedAsserted();
2237            markInService(mshr, pending_dirty_resp);
2238            DPRINTF(Cache, "Upward snoop of prefetch for addr"
2239                    " %#x (%s) hit\n",
2240                    tgt_pkt->getAddr(), tgt_pkt->isSecure()? "s": "ns");
2241            return NULL;
2242        }
2243
2244        if (snoop_pkt.isBlockCached() || blk != NULL) {
2245            DPRINTF(Cache, "Block present, prefetch squashed by cache.  "
2246                    "Deallocating mshr target %#x.\n",
2247                    mshr->blkAddr);
2248
2249            // Deallocate the mshr target
2250            if (tgt_pkt->cmd != MemCmd::Writeback) {
2251                if (mshr->queue->forceDeallocateTarget(mshr)) {
2252                    // Clear block if this deallocation resulted freed an
2253                    // mshr when all had previously been utilized
2254                    clearBlocked((BlockedCause)(mshr->queue->index));
2255                }
2256                return NULL;
2257            } else {
2258                // If this is a Writeback, and the snoops indicate that the blk
2259                // is cached above, set the BLOCK_CACHED flag in the Writeback
2260                // packet, so that it does not reset the bits corresponding to
2261                // this block in the snoop filter below.
2262                tgt_pkt->setBlockCached();
2263            }
2264        }
2265    }
2266
2267    if (mshr->isForwardNoResponse()) {
2268        // no response expected, just forward packet as it is
2269        assert(tags->findBlock(mshr->blkAddr, mshr->isSecure) == NULL);
2270        pkt = tgt_pkt;
2271    } else {
2272        pkt = getBusPacket(tgt_pkt, blk, mshr->needsExclusive());
2273
2274        mshr->isForward = (pkt == NULL);
2275
2276        if (mshr->isForward) {
2277            // not a cache block request, but a response is expected
2278            // make copy of current packet to forward, keep current
2279            // copy for response handling
2280            pkt = new Packet(tgt_pkt, false, true);
2281            if (pkt->isWrite()) {
2282                pkt->setData(tgt_pkt->getConstPtr<uint8_t>());
2283            }
2284        }
2285    }
2286
2287    assert(pkt != NULL);
2288    pkt->senderState = mshr;
2289    return pkt;
2290}
2291
2292
2293Tick
2294Cache::nextMSHRReadyTime() const
2295{
2296    Tick nextReady = std::min(mshrQueue.nextMSHRReadyTime(),
2297                              writeBuffer.nextMSHRReadyTime());
2298
2299    // Don't signal prefetch ready time if no MSHRs available
2300    // Will signal once enoguh MSHRs are deallocated
2301    if (prefetcher && mshrQueue.canPrefetch()) {
2302        nextReady = std::min(nextReady,
2303                             prefetcher->nextPrefetchReadyTime());
2304    }
2305
2306    return nextReady;
2307}
2308
2309void
2310Cache::serialize(CheckpointOut &cp) const
2311{
2312    bool dirty(isDirty());
2313
2314    if (dirty) {
2315        warn("*** The cache still contains dirty data. ***\n");
2316        warn("    Make sure to drain the system using the correct flags.\n");
2317        warn("    This checkpoint will not restore correctly and dirty data in "
2318             "the cache will be lost!\n");
2319    }
2320
2321    // Since we don't checkpoint the data in the cache, any dirty data
2322    // will be lost when restoring from a checkpoint of a system that
2323    // wasn't drained properly. Flag the checkpoint as invalid if the
2324    // cache contains dirty data.
2325    bool bad_checkpoint(dirty);
2326    SERIALIZE_SCALAR(bad_checkpoint);
2327}
2328
2329void
2330Cache::unserialize(CheckpointIn &cp)
2331{
2332    bool bad_checkpoint;
2333    UNSERIALIZE_SCALAR(bad_checkpoint);
2334    if (bad_checkpoint) {
2335        fatal("Restoring from checkpoints with dirty caches is not supported "
2336              "in the classic memory system. Please remove any caches or "
2337              " drain them properly before taking checkpoints.\n");
2338    }
2339}
2340
2341///////////////
2342//
2343// CpuSidePort
2344//
2345///////////////
2346
2347AddrRangeList
2348Cache::CpuSidePort::getAddrRanges() const
2349{
2350    return cache->getAddrRanges();
2351}
2352
2353bool
2354Cache::CpuSidePort::recvTimingReq(PacketPtr pkt)
2355{
2356    assert(!cache->system->bypassCaches());
2357
2358    bool success = false;
2359
2360    // always let inhibited requests through, even if blocked,
2361    // ultimately we should check if this is an express snoop, but at
2362    // the moment that flag is only set in the cache itself
2363    if (pkt->memInhibitAsserted()) {
2364        // do not change the current retry state
2365        bool M5_VAR_USED bypass_success = cache->recvTimingReq(pkt);
2366        assert(bypass_success);
2367        return true;
2368    } else if (blocked || mustSendRetry) {
2369        // either already committed to send a retry, or blocked
2370        success = false;
2371    } else {
2372        // pass it on to the cache, and let the cache decide if we
2373        // have to retry or not
2374        success = cache->recvTimingReq(pkt);
2375    }
2376
2377    // remember if we have to retry
2378    mustSendRetry = !success;
2379    return success;
2380}
2381
2382Tick
2383Cache::CpuSidePort::recvAtomic(PacketPtr pkt)
2384{
2385    return cache->recvAtomic(pkt);
2386}
2387
2388void
2389Cache::CpuSidePort::recvFunctional(PacketPtr pkt)
2390{
2391    // functional request
2392    cache->functionalAccess(pkt, true);
2393}
2394
2395Cache::
2396CpuSidePort::CpuSidePort(const std::string &_name, Cache *_cache,
2397                         const std::string &_label)
2398    : BaseCache::CacheSlavePort(_name, _cache, _label), cache(_cache)
2399{
2400}
2401
2402Cache*
2403CacheParams::create()
2404{
2405    assert(tags);
2406
2407    return new Cache(this);
2408}
2409///////////////
2410//
2411// MemSidePort
2412//
2413///////////////
2414
2415bool
2416Cache::MemSidePort::recvTimingResp(PacketPtr pkt)
2417{
2418    cache->recvTimingResp(pkt);
2419    return true;
2420}
2421
2422// Express snooping requests to memside port
2423void
2424Cache::MemSidePort::recvTimingSnoopReq(PacketPtr pkt)
2425{
2426    // handle snooping requests
2427    cache->recvTimingSnoopReq(pkt);
2428}
2429
2430Tick
2431Cache::MemSidePort::recvAtomicSnoop(PacketPtr pkt)
2432{
2433    return cache->recvAtomicSnoop(pkt);
2434}
2435
2436void
2437Cache::MemSidePort::recvFunctionalSnoop(PacketPtr pkt)
2438{
2439    // functional snoop (note that in contrast to atomic we don't have
2440    // a specific functionalSnoop method, as they have the same
2441    // behaviour regardless)
2442    cache->functionalAccess(pkt, false);
2443}
2444
2445void
2446Cache::CacheReqPacketQueue::sendDeferredPacket()
2447{
2448    // sanity check
2449    assert(!waitingOnRetry);
2450
2451    // there should never be any deferred request packets in the
2452    // queue, instead we resly on the cache to provide the packets
2453    // from the MSHR queue or write queue
2454    assert(deferredPacketReadyTime() == MaxTick);
2455
2456    // check for request packets (requests & writebacks)
2457    PacketPtr pkt = cache.getTimingPacket();
2458    if (pkt == NULL) {
2459        // can happen if e.g. we attempt a writeback and fail, but
2460        // before the retry, the writeback is eliminated because
2461        // we snoop another cache's ReadEx.
2462    } else {
2463        MSHR *mshr = dynamic_cast<MSHR*>(pkt->senderState);
2464        // in most cases getTimingPacket allocates a new packet, and
2465        // we must delete it unless it is successfully sent
2466        bool delete_pkt = !mshr->isForwardNoResponse();
2467
2468        // let our snoop responses go first if there are responses to
2469        // the same addresses we are about to writeback, note that
2470        // this creates a dependency between requests and snoop
2471        // responses, but that should not be a problem since there is
2472        // a chain already and the key is that the snoop responses can
2473        // sink unconditionally
2474        if (snoopRespQueue.hasAddr(pkt->getAddr())) {
2475            DPRINTF(CachePort, "Waiting for snoop response to be sent\n");
2476            Tick when = snoopRespQueue.deferredPacketReadyTime();
2477            schedSendEvent(when);
2478
2479            if (delete_pkt)
2480                delete pkt;
2481
2482            return;
2483        }
2484
2485
2486        waitingOnRetry = !masterPort.sendTimingReq(pkt);
2487
2488        if (waitingOnRetry) {
2489            DPRINTF(CachePort, "now waiting on a retry\n");
2490            if (delete_pkt) {
2491                // we are awaiting a retry, but we
2492                // delete the packet and will be creating a new packet
2493                // when we get the opportunity
2494                delete pkt;
2495            }
2496            // note that we have now masked any requestBus and
2497            // schedSendEvent (we will wait for a retry before
2498            // doing anything), and this is so even if we do not
2499            // care about this packet and might override it before
2500            // it gets retried
2501        } else {
2502            // As part of the call to sendTimingReq the packet is
2503            // forwarded to all neighbouring caches (and any
2504            // caches above them) as a snoop. The packet is also
2505            // sent to any potential cache below as the
2506            // interconnect is not allowed to buffer the
2507            // packet. Thus at this point we know if any of the
2508            // neighbouring, or the downstream cache is
2509            // responding, and if so, if it is with a dirty line
2510            // or not.
2511            bool pending_dirty_resp = !pkt->sharedAsserted() &&
2512                pkt->memInhibitAsserted();
2513
2514            cache.markInService(mshr, pending_dirty_resp);
2515        }
2516    }
2517
2518    // if we succeeded and are not waiting for a retry, schedule the
2519    // next send considering when the next MSHR is ready, note that
2520    // snoop responses have their own packet queue and thus schedule
2521    // their own events
2522    if (!waitingOnRetry) {
2523        schedSendEvent(cache.nextMSHRReadyTime());
2524    }
2525}
2526
2527Cache::
2528MemSidePort::MemSidePort(const std::string &_name, Cache *_cache,
2529                         const std::string &_label)
2530    : BaseCache::CacheMasterPort(_name, _cache, _reqQueue, _snoopRespQueue),
2531      _reqQueue(*_cache, *this, _snoopRespQueue, _label),
2532      _snoopRespQueue(*_cache, *this, _label), cache(_cache)
2533{
2534}
2535