base.hh revision 12730:6c2ea88bf129
1/*
2 * Copyright (c) 2012-2013, 2015-2016, 2018 ARM Limited
3 * All rights reserved.
4 *
5 * The license below extends only to copyright in the software and shall
6 * not be construed as granting a license to any other intellectual
7 * property including but not limited to intellectual property relating
8 * to a hardware implementation of the functionality of the software
9 * licensed hereunder.  You may use the software subject to the license
10 * terms below provided that you ensure that this notice is replicated
11 * unmodified and in its entirety in all distributions of the software,
12 * modified or unmodified, in source code or in binary form.
13 *
14 * Copyright (c) 2003-2005 The Regents of The University of Michigan
15 * All rights reserved.
16 *
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions are
19 * met: redistributions of source code must retain the above copyright
20 * notice, this list of conditions and the following disclaimer;
21 * redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in the
23 * documentation and/or other materials provided with the distribution;
24 * neither the name of the copyright holders nor the names of its
25 * contributors may be used to endorse or promote products derived from
26 * this software without specific prior written permission.
27 *
28 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
31 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
33 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
34 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
38 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 *
40 * Authors: Erik Hallnor
41 *          Steve Reinhardt
42 *          Ron Dreslinski
43 *          Andreas Hansson
44 *          Nikos Nikoleris
45 */
46
47/**
48 * @file
49 * Declares a basic cache interface BaseCache.
50 */
51
52#ifndef __MEM_CACHE_BASE_HH__
53#define __MEM_CACHE_BASE_HH__
54
55#include <cassert>
56#include <cstdint>
57#include <string>
58
59#include "base/addr_range.hh"
60#include "base/statistics.hh"
61#include "base/trace.hh"
62#include "base/types.hh"
63#include "debug/Cache.hh"
64#include "debug/CachePort.hh"
65#include "enums/Clusivity.hh"
66#include "mem/cache/blk.hh"
67#include "mem/cache/mshr_queue.hh"
68#include "mem/cache/tags/base.hh"
69#include "mem/cache/write_queue.hh"
70#include "mem/cache/write_queue_entry.hh"
71#include "mem/mem_object.hh"
72#include "mem/packet.hh"
73#include "mem/packet_queue.hh"
74#include "mem/qport.hh"
75#include "mem/request.hh"
76#include "sim/eventq.hh"
77#include "sim/serialize.hh"
78#include "sim/sim_exit.hh"
79#include "sim/system.hh"
80
81class BaseMasterPort;
82class BasePrefetcher;
83class BaseSlavePort;
84class MSHR;
85class MasterPort;
86class QueueEntry;
87struct BaseCacheParams;
88
89/**
90 * A basic cache interface. Implements some common functions for speed.
91 */
92class BaseCache : public MemObject
93{
94  protected:
95    /**
96     * Indexes to enumerate the MSHR queues.
97     */
98    enum MSHRQueueIndex {
99        MSHRQueue_MSHRs,
100        MSHRQueue_WriteBuffer
101    };
102
103  public:
104    /**
105     * Reasons for caches to be blocked.
106     */
107    enum BlockedCause {
108        Blocked_NoMSHRs = MSHRQueue_MSHRs,
109        Blocked_NoWBBuffers = MSHRQueue_WriteBuffer,
110        Blocked_NoTargets,
111        NUM_BLOCKED_CAUSES
112    };
113
114  protected:
115
116    /**
117     * A cache master port is used for the memory-side port of the
118     * cache, and in addition to the basic timing port that only sends
119     * response packets through a transmit list, it also offers the
120     * ability to schedule and send request packets (requests &
121     * writebacks). The send event is scheduled through schedSendEvent,
122     * and the sendDeferredPacket of the timing port is modified to
123     * consider both the transmit list and the requests from the MSHR.
124     */
125    class CacheMasterPort : public QueuedMasterPort
126    {
127
128      public:
129
130        /**
131         * Schedule a send of a request packet (from the MSHR). Note
132         * that we could already have a retry outstanding.
133         */
134        void schedSendEvent(Tick time)
135        {
136            DPRINTF(CachePort, "Scheduling send event at %llu\n", time);
137            reqQueue.schedSendEvent(time);
138        }
139
140      protected:
141
142        CacheMasterPort(const std::string &_name, BaseCache *_cache,
143                        ReqPacketQueue &_reqQueue,
144                        SnoopRespPacketQueue &_snoopRespQueue) :
145            QueuedMasterPort(_name, _cache, _reqQueue, _snoopRespQueue)
146        { }
147
148        /**
149         * Memory-side port always snoops.
150         *
151         * @return always true
152         */
153        virtual bool isSnooping() const { return true; }
154    };
155
156    /**
157     * Override the default behaviour of sendDeferredPacket to enable
158     * the memory-side cache port to also send requests based on the
159     * current MSHR status. This queue has a pointer to our specific
160     * cache implementation and is used by the MemSidePort.
161     */
162    class CacheReqPacketQueue : public ReqPacketQueue
163    {
164
165      protected:
166
167        BaseCache &cache;
168        SnoopRespPacketQueue &snoopRespQueue;
169
170      public:
171
172        CacheReqPacketQueue(BaseCache &cache, MasterPort &port,
173                            SnoopRespPacketQueue &snoop_resp_queue,
174                            const std::string &label) :
175            ReqPacketQueue(cache, port, label), cache(cache),
176            snoopRespQueue(snoop_resp_queue) { }
177
178        /**
179         * Override the normal sendDeferredPacket and do not only
180         * consider the transmit list (used for responses), but also
181         * requests.
182         */
183        virtual void sendDeferredPacket();
184
185        /**
186         * Check if there is a conflicting snoop response about to be
187         * send out, and if so simply stall any requests, and schedule
188         * a send event at the same time as the next snoop response is
189         * being sent out.
190         */
191        bool checkConflictingSnoop(Addr addr)
192        {
193            if (snoopRespQueue.hasAddr(addr)) {
194                DPRINTF(CachePort, "Waiting for snoop response to be "
195                        "sent\n");
196                Tick when = snoopRespQueue.deferredPacketReadyTime();
197                schedSendEvent(when);
198                return true;
199            }
200            return false;
201        }
202    };
203
204
205    /**
206     * The memory-side port extends the base cache master port with
207     * access functions for functional, atomic and timing snoops.
208     */
209    class MemSidePort : public CacheMasterPort
210    {
211      private:
212
213        /** The cache-specific queue. */
214        CacheReqPacketQueue _reqQueue;
215
216        SnoopRespPacketQueue _snoopRespQueue;
217
218        // a pointer to our specific cache implementation
219        BaseCache *cache;
220
221      protected:
222
223        virtual void recvTimingSnoopReq(PacketPtr pkt);
224
225        virtual bool recvTimingResp(PacketPtr pkt);
226
227        virtual Tick recvAtomicSnoop(PacketPtr pkt);
228
229        virtual void recvFunctionalSnoop(PacketPtr pkt);
230
231      public:
232
233        MemSidePort(const std::string &_name, BaseCache *_cache,
234                    const std::string &_label);
235    };
236
237    /**
238     * A cache slave port is used for the CPU-side port of the cache,
239     * and it is basically a simple timing port that uses a transmit
240     * list for responses to the CPU (or connected master). In
241     * addition, it has the functionality to block the port for
242     * incoming requests. If blocked, the port will issue a retry once
243     * unblocked.
244     */
245    class CacheSlavePort : public QueuedSlavePort
246    {
247
248      public:
249
250        /** Do not accept any new requests. */
251        void setBlocked();
252
253        /** Return to normal operation and accept new requests. */
254        void clearBlocked();
255
256        bool isBlocked() const { return blocked; }
257
258      protected:
259
260        CacheSlavePort(const std::string &_name, BaseCache *_cache,
261                       const std::string &_label);
262
263        /** A normal packet queue used to store responses. */
264        RespPacketQueue queue;
265
266        bool blocked;
267
268        bool mustSendRetry;
269
270      private:
271
272        void processSendRetry();
273
274        EventFunctionWrapper sendRetryEvent;
275
276    };
277
278    /**
279     * The CPU-side port extends the base cache slave port with access
280     * functions for functional, atomic and timing requests.
281     */
282    class CpuSidePort : public CacheSlavePort
283    {
284      private:
285
286        // a pointer to our specific cache implementation
287        BaseCache *cache;
288
289      protected:
290        virtual bool recvTimingSnoopResp(PacketPtr pkt) override;
291
292        virtual bool tryTiming(PacketPtr pkt) override;
293
294        virtual bool recvTimingReq(PacketPtr pkt) override;
295
296        virtual Tick recvAtomic(PacketPtr pkt) override;
297
298        virtual void recvFunctional(PacketPtr pkt) override;
299
300        virtual AddrRangeList getAddrRanges() const override;
301
302      public:
303
304        CpuSidePort(const std::string &_name, BaseCache *_cache,
305                    const std::string &_label);
306
307    };
308
309    CpuSidePort cpuSidePort;
310    MemSidePort memSidePort;
311
312  protected:
313
314    /** Miss status registers */
315    MSHRQueue mshrQueue;
316
317    /** Write/writeback buffer */
318    WriteQueue writeBuffer;
319
320    /** Tag and data Storage */
321    BaseTags *tags;
322
323    /** Prefetcher */
324    BasePrefetcher *prefetcher;
325
326    /**
327     * Notify the prefetcher on every access, not just misses.
328     */
329    const bool prefetchOnAccess;
330
331    /**
332     * Temporary cache block for occasional transitory use.  We use
333     * the tempBlock to fill when allocation fails (e.g., when there
334     * is an outstanding request that accesses the victim block) or
335     * when we want to avoid allocation (e.g., exclusive caches)
336     */
337    TempCacheBlk *tempBlock;
338
339    /**
340     * Upstream caches need this packet until true is returned, so
341     * hold it for deletion until a subsequent call
342     */
343    std::unique_ptr<Packet> pendingDelete;
344
345    /**
346     * Mark a request as in service (sent downstream in the memory
347     * system), effectively making this MSHR the ordering point.
348     */
349    void markInService(MSHR *mshr, bool pending_modified_resp)
350    {
351        bool wasFull = mshrQueue.isFull();
352        mshrQueue.markInService(mshr, pending_modified_resp);
353
354        if (wasFull && !mshrQueue.isFull()) {
355            clearBlocked(Blocked_NoMSHRs);
356        }
357    }
358
359    void markInService(WriteQueueEntry *entry)
360    {
361        bool wasFull = writeBuffer.isFull();
362        writeBuffer.markInService(entry);
363
364        if (wasFull && !writeBuffer.isFull()) {
365            clearBlocked(Blocked_NoWBBuffers);
366        }
367    }
368
369    /**
370     * Determine whether we should allocate on a fill or not. If this
371     * cache is mostly inclusive with regards to the upstream cache(s)
372     * we always allocate (for any non-forwarded and cacheable
373     * requests). In the case of a mostly exclusive cache, we allocate
374     * on fill if the packet did not come from a cache, thus if we:
375     * are dealing with a whole-line write (the latter behaves much
376     * like a writeback), the original target packet came from a
377     * non-caching source, or if we are performing a prefetch or LLSC.
378     *
379     * @param cmd Command of the incoming requesting packet
380     * @return Whether we should allocate on the fill
381     */
382    inline bool allocOnFill(MemCmd cmd) const
383    {
384        return clusivity == Enums::mostly_incl ||
385            cmd == MemCmd::WriteLineReq ||
386            cmd == MemCmd::ReadReq ||
387            cmd == MemCmd::WriteReq ||
388            cmd.isPrefetch() ||
389            cmd.isLLSC();
390    }
391
392    /**
393     * Regenerate block address using tags.
394     * Block address regeneration depends on whether we're using a temporary
395     * block or not.
396     *
397     * @param blk The block to regenerate address.
398     * @return The block's address.
399     */
400    Addr regenerateBlkAddr(CacheBlk* blk);
401
402    /**
403     * Does all the processing necessary to perform the provided request.
404     * @param pkt The memory request to perform.
405     * @param blk The cache block to be updated.
406     * @param lat The latency of the access.
407     * @param writebacks List for any writebacks that need to be performed.
408     * @return Boolean indicating whether the request was satisfied.
409     */
410    virtual bool access(PacketPtr pkt, CacheBlk *&blk, Cycles &lat,
411                        PacketList &writebacks);
412
413    /*
414     * Handle a timing request that hit in the cache
415     *
416     * @param ptk The request packet
417     * @param blk The referenced block
418     * @param request_time The tick at which the block lookup is compete
419     */
420    virtual void handleTimingReqHit(PacketPtr pkt, CacheBlk *blk,
421                                    Tick request_time);
422
423    /*
424     * Handle a timing request that missed in the cache
425     *
426     * Implementation specific handling for different cache
427     * implementations
428     *
429     * @param ptk The request packet
430     * @param blk The referenced block
431     * @param forward_time The tick at which we can process dependent requests
432     * @param request_time The tick at which the block lookup is compete
433     */
434    virtual void handleTimingReqMiss(PacketPtr pkt, CacheBlk *blk,
435                                     Tick forward_time,
436                                     Tick request_time) = 0;
437
438    /*
439     * Handle a timing request that missed in the cache
440     *
441     * Common functionality across different cache implementations
442     *
443     * @param ptk The request packet
444     * @param blk The referenced block
445     * @param mshr Any existing mshr for the referenced cache block
446     * @param forward_time The tick at which we can process dependent requests
447     * @param request_time The tick at which the block lookup is compete
448     */
449    void handleTimingReqMiss(PacketPtr pkt, MSHR *mshr, CacheBlk *blk,
450                             Tick forward_time, Tick request_time);
451
452    /**
453     * Performs the access specified by the request.
454     * @param pkt The request to perform.
455     */
456    virtual void recvTimingReq(PacketPtr pkt);
457
458    /**
459     * Handling the special case of uncacheable write responses to
460     * make recvTimingResp less cluttered.
461     */
462    void handleUncacheableWriteResp(PacketPtr pkt);
463
464    /**
465     * Service non-deferred MSHR targets using the received response
466     *
467     * Iterates through the list of targets that can be serviced with
468     * the current response. Any writebacks that need to performed
469     * must be appended to the writebacks parameter.
470     *
471     * @param mshr The MSHR that corresponds to the reponse
472     * @param pkt The response packet
473     * @param blk The reference block
474     * @param writebacks List of writebacks that need to be performed
475     */
476    virtual void serviceMSHRTargets(MSHR *mshr, const PacketPtr pkt,
477                                    CacheBlk *blk, PacketList& writebacks) = 0;
478
479    /**
480     * Handles a response (cache line fill/write ack) from the bus.
481     * @param pkt The response packet
482     */
483    virtual void recvTimingResp(PacketPtr pkt);
484
485    /**
486     * Snoops bus transactions to maintain coherence.
487     * @param pkt The current bus transaction.
488     */
489    virtual void recvTimingSnoopReq(PacketPtr pkt) = 0;
490
491    /**
492     * Handle a snoop response.
493     * @param pkt Snoop response packet
494     */
495    virtual void recvTimingSnoopResp(PacketPtr pkt) = 0;
496
497    /**
498     * Handle a request in atomic mode that missed in this cache
499     *
500     * Creates a downstream request, sends it to the memory below and
501     * handles the response. As we are in atomic mode all operations
502     * are performed immediately.
503     *
504     * @param pkt The packet with the requests
505     * @param blk The referenced block
506     * @param writebacks A list with packets for any performed writebacks
507     * @return Cycles for handling the request
508     */
509    virtual Cycles handleAtomicReqMiss(PacketPtr pkt, CacheBlk *blk,
510                                       PacketList &writebacks) = 0;
511
512    /**
513     * Performs the access specified by the request.
514     * @param pkt The request to perform.
515     * @return The number of ticks required for the access.
516     */
517    virtual Tick recvAtomic(PacketPtr pkt);
518
519    /**
520     * Snoop for the provided request in the cache and return the estimated
521     * time taken.
522     * @param pkt The memory request to snoop
523     * @return The number of ticks required for the snoop.
524     */
525    virtual Tick recvAtomicSnoop(PacketPtr pkt) = 0;
526
527    /**
528     * Performs the access specified by the request.
529     *
530     * @param pkt The request to perform.
531     * @param fromCpuSide from the CPU side port or the memory side port
532     */
533    virtual void functionalAccess(PacketPtr pkt, bool from_cpu_side);
534
535    /**
536     * Handle doing the Compare and Swap function for SPARC.
537     */
538    void cmpAndSwap(CacheBlk *blk, PacketPtr pkt);
539
540    /**
541     * Return the next queue entry to service, either a pending miss
542     * from the MSHR queue, a buffered write from the write buffer, or
543     * something from the prefetcher. This function is responsible
544     * for prioritizing among those sources on the fly.
545     */
546    QueueEntry* getNextQueueEntry();
547
548    /**
549     * Insert writebacks into the write buffer
550     */
551    virtual void doWritebacks(PacketList& writebacks, Tick forward_time) = 0;
552
553    /**
554     * Send writebacks down the memory hierarchy in atomic mode
555     */
556    virtual void doWritebacksAtomic(PacketList& writebacks) = 0;
557
558    /**
559     * Create an appropriate downstream bus request packet.
560     *
561     * Creates a new packet with the request to be send to the memory
562     * below, or nullptr if the current request in cpu_pkt should just
563     * be forwarded on.
564     *
565     * @param cpu_pkt The miss packet that needs to be satisfied.
566     * @param blk The referenced block, can be nullptr.
567     * @param needs_writable Indicates that the block must be writable
568     * even if the request in cpu_pkt doesn't indicate that.
569     * @return A packet send to the memory below
570     */
571    virtual PacketPtr createMissPacket(PacketPtr cpu_pkt, CacheBlk *blk,
572                                       bool needs_writable) const = 0;
573
574    /**
575     * Determine if clean lines should be written back or not. In
576     * cases where a downstream cache is mostly inclusive we likely
577     * want it to act as a victim cache also for lines that have not
578     * been modified. Hence, we cannot simply drop the line (or send a
579     * clean evict), but rather need to send the actual data.
580     */
581    const bool writebackClean;
582
583    /**
584     * Writebacks from the tempBlock, resulting on the response path
585     * in atomic mode, must happen after the call to recvAtomic has
586     * finished (for the right ordering of the packets). We therefore
587     * need to hold on to the packets, and have a method and an event
588     * to send them.
589     */
590    PacketPtr tempBlockWriteback;
591
592    /**
593     * Send the outstanding tempBlock writeback. To be called after
594     * recvAtomic finishes in cases where the block we filled is in
595     * fact the tempBlock, and now needs to be written back.
596     */
597    void writebackTempBlockAtomic() {
598        assert(tempBlockWriteback != nullptr);
599        PacketList writebacks{tempBlockWriteback};
600        doWritebacksAtomic(writebacks);
601        tempBlockWriteback = nullptr;
602    }
603
604    /**
605     * An event to writeback the tempBlock after recvAtomic
606     * finishes. To avoid other calls to recvAtomic getting in
607     * between, we create this event with a higher priority.
608     */
609    EventFunctionWrapper writebackTempBlockAtomicEvent;
610
611    /**
612     * Perform any necessary updates to the block and perform any data
613     * exchange between the packet and the block. The flags of the
614     * packet are also set accordingly.
615     *
616     * @param pkt Request packet from upstream that hit a block
617     * @param blk Cache block that the packet hit
618     * @param deferred_response Whether this request originally missed
619     * @param pending_downgrade Whether the writable flag is to be removed
620     */
621    virtual void satisfyRequest(PacketPtr pkt, CacheBlk *blk,
622                                bool deferred_response = false,
623                                bool pending_downgrade = false);
624
625    /**
626     * Maintain the clusivity of this cache by potentially
627     * invalidating a block. This method works in conjunction with
628     * satisfyRequest, but is separate to allow us to handle all MSHR
629     * targets before potentially dropping a block.
630     *
631     * @param from_cache Whether we have dealt with a packet from a cache
632     * @param blk The block that should potentially be dropped
633     */
634    void maintainClusivity(bool from_cache, CacheBlk *blk);
635
636    /**
637     * Handle a fill operation caused by a received packet.
638     *
639     * Populates a cache block and handles all outstanding requests for the
640     * satisfied fill request. This version takes two memory requests. One
641     * contains the fill data, the other is an optional target to satisfy.
642     * Note that the reason we return a list of writebacks rather than
643     * inserting them directly in the write buffer is that this function
644     * is called by both atomic and timing-mode accesses, and in atomic
645     * mode we don't mess with the write buffer (we just perform the
646     * writebacks atomically once the original request is complete).
647     *
648     * @param pkt The memory request with the fill data.
649     * @param blk The cache block if it already exists.
650     * @param writebacks List for any writebacks that need to be performed.
651     * @param allocate Whether to allocate a block or use the temp block
652     * @return Pointer to the new cache block.
653     */
654    CacheBlk *handleFill(PacketPtr pkt, CacheBlk *blk,
655                         PacketList &writebacks, bool allocate);
656
657    /**
658     * Allocate a new block and perform any necessary writebacks
659     *
660     * Find a victim block and if necessary prepare writebacks for any
661     * existing data. May return nullptr if there are no replaceable
662     * blocks.
663     *
664     * @param addr Physical address of the new block
665     * @param is_secure Set if the block should be secure
666     * @param writebacks A list of writeback packets for the evicted blocks
667     * @return the allocated block
668     */
669    CacheBlk *allocateBlock(Addr addr, bool is_secure, PacketList &writebacks);
670    /**
671     * Evict a cache block.
672     *
673     * Performs a writeback if necesssary and invalidates the block
674     *
675     * @param blk Block to invalidate
676     * @return A packet with the writeback, can be nullptr
677     */
678    M5_NODISCARD virtual PacketPtr evictBlock(CacheBlk *blk) = 0;
679
680    /**
681     * Evict a cache block.
682     *
683     * Performs a writeback if necesssary and invalidates the block
684     *
685     * @param blk Block to invalidate
686     * @param writebacks Return a list of packets with writebacks
687     */
688    virtual void evictBlock(CacheBlk *blk, PacketList &writebacks) = 0;
689
690    /**
691     * Invalidate a cache block.
692     *
693     * @param blk Block to invalidate
694     */
695    void invalidateBlock(CacheBlk *blk);
696
697    /**
698     * Create a writeback request for the given block.
699     *
700     * @param blk The block to writeback.
701     * @return The writeback request for the block.
702     */
703    PacketPtr writebackBlk(CacheBlk *blk);
704
705    /**
706     * Create a writeclean request for the given block.
707     *
708     * Creates a request that writes the block to the cache below
709     * without evicting the block from the current cache.
710     *
711     * @param blk The block to write clean.
712     * @param dest The destination of the write clean operation.
713     * @param id Use the given packet id for the write clean operation.
714     * @return The generated write clean packet.
715     */
716    PacketPtr writecleanBlk(CacheBlk *blk, Request::Flags dest, PacketId id);
717
718    /**
719     * Write back dirty blocks in the cache using functional accesses.
720     */
721    virtual void memWriteback() override;
722
723    /**
724     * Invalidates all blocks in the cache.
725     *
726     * @warn Dirty cache lines will not be written back to
727     * memory. Make sure to call functionalWriteback() first if you
728     * want the to write them to memory.
729     */
730    virtual void memInvalidate() override;
731
732    /**
733     * Determine if there are any dirty blocks in the cache.
734     *
735     * @return true if at least one block is dirty, false otherwise.
736     */
737    bool isDirty() const;
738
739    /**
740     * Determine if an address is in the ranges covered by this
741     * cache. This is useful to filter snoops.
742     *
743     * @param addr Address to check against
744     *
745     * @return If the address in question is in range
746     */
747    bool inRange(Addr addr) const;
748
749    /**
750     * Find next request ready time from among possible sources.
751     */
752    Tick nextQueueReadyTime() const;
753
754    /** Block size of this cache */
755    const unsigned blkSize;
756
757    /**
758     * The latency of tag lookup of a cache. It occurs when there is
759     * an access to the cache.
760     */
761    const Cycles lookupLatency;
762
763    /**
764     * The latency of data access of a cache. It occurs when there is
765     * an access to the cache.
766     */
767    const Cycles dataLatency;
768
769    /**
770     * This is the forward latency of the cache. It occurs when there
771     * is a cache miss and a request is forwarded downstream, in
772     * particular an outbound miss.
773     */
774    const Cycles forwardLatency;
775
776    /** The latency to fill a cache block */
777    const Cycles fillLatency;
778
779    /**
780     * The latency of sending reponse to its upper level cache/core on
781     * a linefill. The responseLatency parameter captures this
782     * latency.
783     */
784    const Cycles responseLatency;
785
786    /** The number of targets for each MSHR. */
787    const int numTarget;
788
789    /** Do we forward snoops from mem side port through to cpu side port? */
790    bool forwardSnoops;
791
792    /**
793     * Clusivity with respect to the upstream cache, determining if we
794     * fill into both this cache and the cache above on a miss. Note
795     * that we currently do not support strict clusivity policies.
796     */
797    const Enums::Clusivity clusivity;
798
799    /**
800     * Is this cache read only, for example the instruction cache, or
801     * table-walker cache. A cache that is read only should never see
802     * any writes, and should never get any dirty data (and hence
803     * never have to do any writebacks).
804     */
805    const bool isReadOnly;
806
807    /**
808     * Bit vector of the blocking reasons for the access path.
809     * @sa #BlockedCause
810     */
811    uint8_t blocked;
812
813    /** Increasing order number assigned to each incoming request. */
814    uint64_t order;
815
816    /** Stores time the cache blocked for statistics. */
817    Cycles blockedCycle;
818
819    /** Pointer to the MSHR that has no targets. */
820    MSHR *noTargetMSHR;
821
822    /** The number of misses to trigger an exit event. */
823    Counter missCount;
824
825    /**
826     * The address range to which the cache responds on the CPU side.
827     * Normally this is all possible memory addresses. */
828    const AddrRangeList addrRanges;
829
830  public:
831    /** System we are currently operating in. */
832    System *system;
833
834    // Statistics
835    /**
836     * @addtogroup CacheStatistics
837     * @{
838     */
839
840    /** Number of hits per thread for each type of command.
841        @sa Packet::Command */
842    Stats::Vector hits[MemCmd::NUM_MEM_CMDS];
843    /** Number of hits for demand accesses. */
844    Stats::Formula demandHits;
845    /** Number of hit for all accesses. */
846    Stats::Formula overallHits;
847
848    /** Number of misses per thread for each type of command.
849        @sa Packet::Command */
850    Stats::Vector misses[MemCmd::NUM_MEM_CMDS];
851    /** Number of misses for demand accesses. */
852    Stats::Formula demandMisses;
853    /** Number of misses for all accesses. */
854    Stats::Formula overallMisses;
855
856    /**
857     * Total number of cycles per thread/command spent waiting for a miss.
858     * Used to calculate the average miss latency.
859     */
860    Stats::Vector missLatency[MemCmd::NUM_MEM_CMDS];
861    /** Total number of cycles spent waiting for demand misses. */
862    Stats::Formula demandMissLatency;
863    /** Total number of cycles spent waiting for all misses. */
864    Stats::Formula overallMissLatency;
865
866    /** The number of accesses per command and thread. */
867    Stats::Formula accesses[MemCmd::NUM_MEM_CMDS];
868    /** The number of demand accesses. */
869    Stats::Formula demandAccesses;
870    /** The number of overall accesses. */
871    Stats::Formula overallAccesses;
872
873    /** The miss rate per command and thread. */
874    Stats::Formula missRate[MemCmd::NUM_MEM_CMDS];
875    /** The miss rate of all demand accesses. */
876    Stats::Formula demandMissRate;
877    /** The miss rate for all accesses. */
878    Stats::Formula overallMissRate;
879
880    /** The average miss latency per command and thread. */
881    Stats::Formula avgMissLatency[MemCmd::NUM_MEM_CMDS];
882    /** The average miss latency for demand misses. */
883    Stats::Formula demandAvgMissLatency;
884    /** The average miss latency for all misses. */
885    Stats::Formula overallAvgMissLatency;
886
887    /** The total number of cycles blocked for each blocked cause. */
888    Stats::Vector blocked_cycles;
889    /** The number of times this cache blocked for each blocked cause. */
890    Stats::Vector blocked_causes;
891
892    /** The average number of cycles blocked for each blocked cause. */
893    Stats::Formula avg_blocked;
894
895    /** The number of times a HW-prefetched block is evicted w/o reference. */
896    Stats::Scalar unusedPrefetches;
897
898    /** Number of blocks written back per thread. */
899    Stats::Vector writebacks;
900
901    /** Number of misses that hit in the MSHRs per command and thread. */
902    Stats::Vector mshr_hits[MemCmd::NUM_MEM_CMDS];
903    /** Demand misses that hit in the MSHRs. */
904    Stats::Formula demandMshrHits;
905    /** Total number of misses that hit in the MSHRs. */
906    Stats::Formula overallMshrHits;
907
908    /** Number of misses that miss in the MSHRs, per command and thread. */
909    Stats::Vector mshr_misses[MemCmd::NUM_MEM_CMDS];
910    /** Demand misses that miss in the MSHRs. */
911    Stats::Formula demandMshrMisses;
912    /** Total number of misses that miss in the MSHRs. */
913    Stats::Formula overallMshrMisses;
914
915    /** Number of misses that miss in the MSHRs, per command and thread. */
916    Stats::Vector mshr_uncacheable[MemCmd::NUM_MEM_CMDS];
917    /** Total number of misses that miss in the MSHRs. */
918    Stats::Formula overallMshrUncacheable;
919
920    /** Total cycle latency of each MSHR miss, per command and thread. */
921    Stats::Vector mshr_miss_latency[MemCmd::NUM_MEM_CMDS];
922    /** Total cycle latency of demand MSHR misses. */
923    Stats::Formula demandMshrMissLatency;
924    /** Total cycle latency of overall MSHR misses. */
925    Stats::Formula overallMshrMissLatency;
926
927    /** Total cycle latency of each MSHR miss, per command and thread. */
928    Stats::Vector mshr_uncacheable_lat[MemCmd::NUM_MEM_CMDS];
929    /** Total cycle latency of overall MSHR misses. */
930    Stats::Formula overallMshrUncacheableLatency;
931
932#if 0
933    /** The total number of MSHR accesses per command and thread. */
934    Stats::Formula mshrAccesses[MemCmd::NUM_MEM_CMDS];
935    /** The total number of demand MSHR accesses. */
936    Stats::Formula demandMshrAccesses;
937    /** The total number of MSHR accesses. */
938    Stats::Formula overallMshrAccesses;
939#endif
940
941    /** The miss rate in the MSHRs pre command and thread. */
942    Stats::Formula mshrMissRate[MemCmd::NUM_MEM_CMDS];
943    /** The demand miss rate in the MSHRs. */
944    Stats::Formula demandMshrMissRate;
945    /** The overall miss rate in the MSHRs. */
946    Stats::Formula overallMshrMissRate;
947
948    /** The average latency of an MSHR miss, per command and thread. */
949    Stats::Formula avgMshrMissLatency[MemCmd::NUM_MEM_CMDS];
950    /** The average latency of a demand MSHR miss. */
951    Stats::Formula demandAvgMshrMissLatency;
952    /** The average overall latency of an MSHR miss. */
953    Stats::Formula overallAvgMshrMissLatency;
954
955    /** The average latency of an MSHR miss, per command and thread. */
956    Stats::Formula avgMshrUncacheableLatency[MemCmd::NUM_MEM_CMDS];
957    /** The average overall latency of an MSHR miss. */
958    Stats::Formula overallAvgMshrUncacheableLatency;
959
960    /** Number of replacements of valid blocks. */
961    Stats::Scalar replacements;
962
963    /**
964     * @}
965     */
966
967    /**
968     * Register stats for this object.
969     */
970    void regStats() override;
971
972  public:
973    BaseCache(const BaseCacheParams *p, unsigned blk_size);
974    ~BaseCache();
975
976    void init() override;
977
978    BaseMasterPort &getMasterPort(const std::string &if_name,
979                                  PortID idx = InvalidPortID) override;
980    BaseSlavePort &getSlavePort(const std::string &if_name,
981                                PortID idx = InvalidPortID) override;
982
983    /**
984     * Query block size of a cache.
985     * @return  The block size
986     */
987    unsigned
988    getBlockSize() const
989    {
990        return blkSize;
991    }
992
993    const AddrRangeList &getAddrRanges() const { return addrRanges; }
994
995    MSHR *allocateMissBuffer(PacketPtr pkt, Tick time, bool sched_send = true)
996    {
997        MSHR *mshr = mshrQueue.allocate(pkt->getBlockAddr(blkSize), blkSize,
998                                        pkt, time, order++,
999                                        allocOnFill(pkt->cmd));
1000
1001        if (mshrQueue.isFull()) {
1002            setBlocked((BlockedCause)MSHRQueue_MSHRs);
1003        }
1004
1005        if (sched_send) {
1006            // schedule the send
1007            schedMemSideSendEvent(time);
1008        }
1009
1010        return mshr;
1011    }
1012
1013    void allocateWriteBuffer(PacketPtr pkt, Tick time)
1014    {
1015        // should only see writes or clean evicts here
1016        assert(pkt->isWrite() || pkt->cmd == MemCmd::CleanEvict);
1017
1018        Addr blk_addr = pkt->getBlockAddr(blkSize);
1019
1020        WriteQueueEntry *wq_entry =
1021            writeBuffer.findMatch(blk_addr, pkt->isSecure());
1022        if (wq_entry && !wq_entry->inService) {
1023            DPRINTF(Cache, "Potential to merge writeback %s", pkt->print());
1024        }
1025
1026        writeBuffer.allocate(blk_addr, blkSize, pkt, time, order++);
1027
1028        if (writeBuffer.isFull()) {
1029            setBlocked((BlockedCause)MSHRQueue_WriteBuffer);
1030        }
1031
1032        // schedule the send
1033        schedMemSideSendEvent(time);
1034    }
1035
1036    /**
1037     * Returns true if the cache is blocked for accesses.
1038     */
1039    bool isBlocked() const
1040    {
1041        return blocked != 0;
1042    }
1043
1044    /**
1045     * Marks the access path of the cache as blocked for the given cause. This
1046     * also sets the blocked flag in the slave interface.
1047     * @param cause The reason for the cache blocking.
1048     */
1049    void setBlocked(BlockedCause cause)
1050    {
1051        uint8_t flag = 1 << cause;
1052        if (blocked == 0) {
1053            blocked_causes[cause]++;
1054            blockedCycle = curCycle();
1055            cpuSidePort.setBlocked();
1056        }
1057        blocked |= flag;
1058        DPRINTF(Cache,"Blocking for cause %d, mask=%d\n", cause, blocked);
1059    }
1060
1061    /**
1062     * Marks the cache as unblocked for the given cause. This also clears the
1063     * blocked flags in the appropriate interfaces.
1064     * @param cause The newly unblocked cause.
1065     * @warning Calling this function can cause a blocked request on the bus to
1066     * access the cache. The cache must be in a state to handle that request.
1067     */
1068    void clearBlocked(BlockedCause cause)
1069    {
1070        uint8_t flag = 1 << cause;
1071        blocked &= ~flag;
1072        DPRINTF(Cache,"Unblocking for cause %d, mask=%d\n", cause, blocked);
1073        if (blocked == 0) {
1074            blocked_cycles[cause] += curCycle() - blockedCycle;
1075            cpuSidePort.clearBlocked();
1076        }
1077    }
1078
1079    /**
1080     * Schedule a send event for the memory-side port. If already
1081     * scheduled, this may reschedule the event at an earlier
1082     * time. When the specified time is reached, the port is free to
1083     * send either a response, a request, or a prefetch request.
1084     *
1085     * @param time The time when to attempt sending a packet.
1086     */
1087    void schedMemSideSendEvent(Tick time)
1088    {
1089        memSidePort.schedSendEvent(time);
1090    }
1091
1092    bool inCache(Addr addr, bool is_secure) const {
1093        return tags->findBlock(addr, is_secure);
1094    }
1095
1096    bool inMissQueue(Addr addr, bool is_secure) const {
1097        return mshrQueue.findMatch(addr, is_secure);
1098    }
1099
1100    void incMissCount(PacketPtr pkt)
1101    {
1102        assert(pkt->req->masterId() < system->maxMasters());
1103        misses[pkt->cmdToIndex()][pkt->req->masterId()]++;
1104        pkt->req->incAccessDepth();
1105        if (missCount) {
1106            --missCount;
1107            if (missCount == 0)
1108                exitSimLoop("A cache reached the maximum miss count");
1109        }
1110    }
1111    void incHitCount(PacketPtr pkt)
1112    {
1113        assert(pkt->req->masterId() < system->maxMasters());
1114        hits[pkt->cmdToIndex()][pkt->req->masterId()]++;
1115
1116    }
1117
1118    /**
1119     * Cache block visitor that writes back dirty cache blocks using
1120     * functional writes.
1121     */
1122    void writebackVisitor(CacheBlk &blk);
1123
1124    /**
1125     * Cache block visitor that invalidates all blocks in the cache.
1126     *
1127     * @warn Dirty cache lines will not be written back to memory.
1128     */
1129    void invalidateVisitor(CacheBlk &blk);
1130
1131    /**
1132     * Take an MSHR, turn it into a suitable downstream packet, and
1133     * send it out. This construct allows a queue entry to choose a suitable
1134     * approach based on its type.
1135     *
1136     * @param mshr The MSHR to turn into a packet and send
1137     * @return True if the port is waiting for a retry
1138     */
1139    virtual bool sendMSHRQueuePacket(MSHR* mshr);
1140
1141    /**
1142     * Similar to sendMSHR, but for a write-queue entry
1143     * instead. Create the packet, and send it, and if successful also
1144     * mark the entry in service.
1145     *
1146     * @param wq_entry The write-queue entry to turn into a packet and send
1147     * @return True if the port is waiting for a retry
1148     */
1149    bool sendWriteQueuePacket(WriteQueueEntry* wq_entry);
1150
1151    /**
1152     * Serialize the state of the caches
1153     *
1154     * We currently don't support checkpointing cache state, so this panics.
1155     */
1156    void serialize(CheckpointOut &cp) const override;
1157    void unserialize(CheckpointIn &cp) override;
1158
1159};
1160
1161#endif //__MEM_CACHE_BASE_HH__
1162