lsq_unit.hh revision 9444
12817Sksewell@umich.edu/*
29426SAndreas.Sandberg@ARM.com * Copyright (c) 2012 ARM Limited
39920Syasuko.eckert@amd.com * All rights reserved
48733Sgeoffrey.blake@arm.com *
58733Sgeoffrey.blake@arm.com * The license below extends only to copyright in the software and shall
68733Sgeoffrey.blake@arm.com * not be construed as granting a license to any other intellectual
78733Sgeoffrey.blake@arm.com * property including but not limited to intellectual property relating
88733Sgeoffrey.blake@arm.com * to a hardware implementation of the functionality of the software
98733Sgeoffrey.blake@arm.com * licensed hereunder.  You may use the software subject to the license
108733Sgeoffrey.blake@arm.com * terms below provided that you ensure that this notice is replicated
118733Sgeoffrey.blake@arm.com * unmodified and in its entirety in all distributions of the software,
128733Sgeoffrey.blake@arm.com * modified or unmodified, in source code or in binary form.
138733Sgeoffrey.blake@arm.com *
148733Sgeoffrey.blake@arm.com * Copyright (c) 2004-2006 The Regents of The University of Michigan
152817Sksewell@umich.edu * All rights reserved.
162817Sksewell@umich.edu *
172817Sksewell@umich.edu * Redistribution and use in source and binary forms, with or without
182817Sksewell@umich.edu * modification, are permitted provided that the following conditions are
192817Sksewell@umich.edu * met: redistributions of source code must retain the above copyright
202817Sksewell@umich.edu * notice, this list of conditions and the following disclaimer;
212817Sksewell@umich.edu * redistributions in binary form must reproduce the above copyright
222817Sksewell@umich.edu * notice, this list of conditions and the following disclaimer in the
232817Sksewell@umich.edu * documentation and/or other materials provided with the distribution;
242817Sksewell@umich.edu * neither the name of the copyright holders nor the names of its
252817Sksewell@umich.edu * contributors may be used to endorse or promote products derived from
262817Sksewell@umich.edu * this software without specific prior written permission.
272817Sksewell@umich.edu *
282817Sksewell@umich.edu * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
292817Sksewell@umich.edu * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
302817Sksewell@umich.edu * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
312817Sksewell@umich.edu * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
322817Sksewell@umich.edu * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
332817Sksewell@umich.edu * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
342817Sksewell@umich.edu * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
352817Sksewell@umich.edu * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
362817Sksewell@umich.edu * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
372817Sksewell@umich.edu * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
382817Sksewell@umich.edu * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
392817Sksewell@umich.edu *
402817Sksewell@umich.edu * Authors: Kevin Lim
412817Sksewell@umich.edu *          Korey Sewell
422817Sksewell@umich.edu */
432817Sksewell@umich.edu
442817Sksewell@umich.edu#ifndef __CPU_O3_LSQ_UNIT_HH__
452817Sksewell@umich.edu#define __CPU_O3_LSQ_UNIT_HH__
462817Sksewell@umich.edu
476658Snate@binkert.org#include <algorithm>
488229Snate@binkert.org#include <cstring>
492935Sksewell@umich.edu#include <map>
502817Sksewell@umich.edu#include <queue>
512834Sksewell@umich.edu
522834Sksewell@umich.edu#include "arch/generic/debugfaults.hh"
532834Sksewell@umich.edu#include "arch/isa_traits.hh"
548902Sandreas.hansson@arm.com#include "arch/locked_mem.hh"
552834Sksewell@umich.edu#include "arch/mmapped_ipr.hh"
562817Sksewell@umich.edu#include "base/hashmap.hh"
572817Sksewell@umich.edu#include "config/the_isa.hh"
582817Sksewell@umich.edu#include "cpu/inst_seq.hh"
592817Sksewell@umich.edu#include "cpu/timebuf.hh"
602817Sksewell@umich.edu#include "debug/LSQUnit.hh"
612817Sksewell@umich.edu#include "mem/packet.hh"
622817Sksewell@umich.edu#include "mem/port.hh"
632817Sksewell@umich.edu#include "sim/fault_fwd.hh"
642817Sksewell@umich.edu
652817Sksewell@umich.edustruct DerivO3CPUParams;
662817Sksewell@umich.edu
672817Sksewell@umich.edu/**
682817Sksewell@umich.edu * Class that implements the actual LQ and SQ for each specific
692817Sksewell@umich.edu * thread.  Both are circular queues; load entries are freed upon
702817Sksewell@umich.edu * committing, while store entries are freed once they writeback. The
712817Sksewell@umich.edu * LSQUnit tracks if there are memory ordering violations, and also
722817Sksewell@umich.edu * detects partial load to store forwarding cases (a store only has
732817Sksewell@umich.edu * part of a load's data) that requires the load to wait until the
742817Sksewell@umich.edu * store writes back. In the former case it holds onto the instruction
752817Sksewell@umich.edu * until the dependence unit looks at it, and in the latter it stalls
762817Sksewell@umich.edu * the LSQ until the store writes back. At that point the load is
772817Sksewell@umich.edu * replayed.
782817Sksewell@umich.edu */
792817Sksewell@umich.edutemplate <class Impl>
802817Sksewell@umich.educlass LSQUnit {
813784Sgblack@eecs.umich.edu  public:
826022Sgblack@eecs.umich.edu    typedef typename Impl::O3CPU O3CPU;
833784Sgblack@eecs.umich.edu    typedef typename Impl::DynInstPtr DynInstPtr;
843784Sgblack@eecs.umich.edu    typedef typename Impl::CPUPol::IEW IEW;
856022Sgblack@eecs.umich.edu    typedef typename Impl::CPUPol::LSQ LSQ;
863784Sgblack@eecs.umich.edu    typedef typename Impl::CPUPol::IssueStruct IssueStruct;
878887Sgeoffrey.blake@arm.com
888733Sgeoffrey.blake@arm.com  public:
899023Sgblack@eecs.umich.edu    /** Constructs an LSQ unit. init() must be called prior to use. */
909023Sgblack@eecs.umich.edu    LSQUnit();
919023Sgblack@eecs.umich.edu
929023Sgblack@eecs.umich.edu    /** Initializes the LSQ unit with the specified number of entries. */
939023Sgblack@eecs.umich.edu    void init(O3CPU *cpu_ptr, IEW *iew_ptr, DerivO3CPUParams *params,
948541Sgblack@eecs.umich.edu            LSQ *lsq_ptr, unsigned maxLQEntries, unsigned maxSQEntries,
952817Sksewell@umich.edu            unsigned id);
962817Sksewell@umich.edu
972817Sksewell@umich.edu    /** Returns the name of the LSQ unit. */
982817Sksewell@umich.edu    std::string name() const;
9910110Sandreas.hansson@arm.com
1002817Sksewell@umich.edu    /** Registers statistics. */
10110190Sakash.bagdia@arm.com    void regStats();
10210190Sakash.bagdia@arm.com
10310190Sakash.bagdia@arm.com    /** Sets the pointer to the dcache port. */
10411005Sandreas.sandberg@arm.com    void setDcachePort(MasterPort *dcache_port);
1055714Shsul@eecs.umich.edu
1065714Shsul@eecs.umich.edu    /** Perform sanity checks after a drain. */
1075714Shsul@eecs.umich.edu    void drainSanityCheck() const;
1085715Shsul@eecs.umich.edu
10910110Sandreas.hansson@arm.com    /** Takes over from another CPU's thread. */
1105715Shsul@eecs.umich.edu    void takeOverFrom();
1115715Shsul@eecs.umich.edu
1122817Sksewell@umich.edu    /** Ticks the LSQ unit, which in this case only resets the number of
1132817Sksewell@umich.edu     * used cache ports.
1142817Sksewell@umich.edu     * @todo: Move the number of used ports up to the LSQ level so it can
1152817Sksewell@umich.edu     * be shared by all LSQ units.
1163548Sgblack@eecs.umich.edu     */
1172817Sksewell@umich.edu    void tick() { usedPorts = 0; }
1182817Sksewell@umich.edu
1198541Sgblack@eecs.umich.edu    /** Inserts an instruction. */
1208541Sgblack@eecs.umich.edu    void insert(DynInstPtr &inst);
1218754Sgblack@eecs.umich.edu    /** Inserts a load instruction. */
1228852Sandreas.hansson@arm.com    void insertLoad(DynInstPtr &load_inst);
1232817Sksewell@umich.edu    /** Inserts a store instruction. */
1248852Sandreas.hansson@arm.com    void insertStore(DynInstPtr &store_inst);
1253675Sktlim@umich.edu
1268706Sandreas.hansson@arm.com    /** Check for ordering violations in the LSQ. For a store squash if we
1278706Sandreas.hansson@arm.com     * ever find a conflicting load. For a load, only squash if we
1288799Sgblack@eecs.umich.edu     * an external snoop invalidate has been seen for that load address
1298852Sandreas.hansson@arm.com     * @param load_idx index to start checking at
1308706Sandreas.hansson@arm.com     * @param inst the instruction to check
1312817Sksewell@umich.edu     */
1322817Sksewell@umich.edu    Fault checkViolations(int load_idx, DynInstPtr &inst);
1332817Sksewell@umich.edu
1342817Sksewell@umich.edu    /** Check if an incoming invalidate hits in the lsq on a load
1352817Sksewell@umich.edu     * that might have issued out of order wrt another load beacuse
1362817Sksewell@umich.edu     * of the intermediate invalidate.
1372817Sksewell@umich.edu     */
1382817Sksewell@umich.edu    void checkSnoop(PacketPtr pkt);
13910407Smitch.hayenga@arm.com
14010407Smitch.hayenga@arm.com    /** Executes a load instruction. */
1412817Sksewell@umich.edu    Fault executeLoad(DynInstPtr &inst);
1422817Sksewell@umich.edu
14310407Smitch.hayenga@arm.com    Fault executeLoad(int lq_idx) { panic("Not implemented"); return NoFault; }
1442817Sksewell@umich.edu    /** Executes a store instruction. */
1452817Sksewell@umich.edu    Fault executeStore(DynInstPtr &inst);
14610407Smitch.hayenga@arm.com
1472817Sksewell@umich.edu    /** Commits the head load. */
1482817Sksewell@umich.edu    void commitLoad();
1492817Sksewell@umich.edu    /** Commits loads older than a specific sequence number. */
1502817Sksewell@umich.edu    void commitLoads(InstSeqNum &youngest_inst);
1512817Sksewell@umich.edu
1528777Sgblack@eecs.umich.edu    /** Commits stores older than a specific sequence number. */
1532817Sksewell@umich.edu    void commitStores(InstSeqNum &youngest_inst);
1542817Sksewell@umich.edu
1552817Sksewell@umich.edu    /** Writes back stores. */
1562817Sksewell@umich.edu    void writebackStores();
1572817Sksewell@umich.edu
1582817Sksewell@umich.edu    /** Completes the data access that has been returned from the
1592817Sksewell@umich.edu     * memory system. */
1602817Sksewell@umich.edu    void completeDataAccess(PacketPtr pkt);
1612817Sksewell@umich.edu
1622817Sksewell@umich.edu    /** Clears all the entries in the LQ. */
1632817Sksewell@umich.edu    void clearLQ();
1642817Sksewell@umich.edu
1652817Sksewell@umich.edu    /** Clears all the entries in the SQ. */
1662817Sksewell@umich.edu    void clearSQ();
1672817Sksewell@umich.edu
1682817Sksewell@umich.edu    /** Resizes the LQ to a given size. */
1692817Sksewell@umich.edu    void resizeLQ(unsigned size);
1702817Sksewell@umich.edu
1712817Sksewell@umich.edu    /** Resizes the SQ to a given size. */
1722817Sksewell@umich.edu    void resizeSQ(unsigned size);
1732817Sksewell@umich.edu
1742817Sksewell@umich.edu    /** Squashes all instructions younger than a specific sequence number. */
1752817Sksewell@umich.edu    void squash(const InstSeqNum &squashed_num);
1769426SAndreas.Sandberg@ARM.com
1779426SAndreas.Sandberg@ARM.com    /** Returns if there is a memory ordering violation. Value is reset upon
1789426SAndreas.Sandberg@ARM.com     * call to getMemDepViolator().
1792817Sksewell@umich.edu     */
1809426SAndreas.Sandberg@ARM.com    bool violation() { return memDepViolator; }
1819426SAndreas.Sandberg@ARM.com
1829426SAndreas.Sandberg@ARM.com    /** Returns the memory ordering violator. */
1832817Sksewell@umich.edu    DynInstPtr getMemDepViolator();
1849426SAndreas.Sandberg@ARM.com
1859426SAndreas.Sandberg@ARM.com    /** Returns if a load became blocked due to the memory system. */
1869426SAndreas.Sandberg@ARM.com    bool loadBlocked()
1872817Sksewell@umich.edu    { return isLoadBlocked; }
1889920Syasuko.eckert@amd.com
1899920Syasuko.eckert@amd.com    /** Clears the signal that a load became blocked. */
1909920Syasuko.eckert@amd.com    void clearLoadBlocked()
1919920Syasuko.eckert@amd.com    { isLoadBlocked = false; }
1922817Sksewell@umich.edu
1939426SAndreas.Sandberg@ARM.com    /** Returns if the blocked load was handled. */
1949426SAndreas.Sandberg@ARM.com    bool isLoadBlockedHandled()
1959426SAndreas.Sandberg@ARM.com    { return loadBlockedHandled; }
1962817Sksewell@umich.edu
1979426SAndreas.Sandberg@ARM.com    /** Records the blocked load as being handled. */
1989426SAndreas.Sandberg@ARM.com    void setLoadBlockedHandled()
1999426SAndreas.Sandberg@ARM.com    { loadBlockedHandled = true; }
2002817Sksewell@umich.edu
2019426SAndreas.Sandberg@ARM.com    /** Returns the number of free entries (min of free LQ and SQ entries). */
2029426SAndreas.Sandberg@ARM.com    unsigned numFreeEntries();
2039426SAndreas.Sandberg@ARM.com
2042817Sksewell@umich.edu    /** Returns the number of loads in the LQ. */
2059920Syasuko.eckert@amd.com    int numLoads() { return loads; }
2069920Syasuko.eckert@amd.com
2079920Syasuko.eckert@amd.com    /** Returns the number of stores in the SQ. */
2089920Syasuko.eckert@amd.com    int numStores() { return stores; }
2097720Sgblack@eecs.umich.edu
2107720Sgblack@eecs.umich.edu    /** Returns if either the LQ or SQ is full. */
2117720Sgblack@eecs.umich.edu    bool isFull() { return lqFull() || sqFull(); }
2127720Sgblack@eecs.umich.edu
2137720Sgblack@eecs.umich.edu    /** Returns if both the LQ and SQ are empty. */
2147720Sgblack@eecs.umich.edu    bool isEmpty() const { return lqEmpty() && sqEmpty(); }
2157720Sgblack@eecs.umich.edu
2168733Sgeoffrey.blake@arm.com    /** Returns if the LQ is full. */
2178733Sgeoffrey.blake@arm.com    bool lqFull() { return loads >= (LQEntries - 1); }
2182817Sksewell@umich.edu
2197720Sgblack@eecs.umich.edu    /** Returns if the SQ is full. */
2207720Sgblack@eecs.umich.edu    bool sqFull() { return stores >= (SQEntries - 1); }
2212817Sksewell@umich.edu
2222817Sksewell@umich.edu    /** Returns if the LQ is empty. */
2237720Sgblack@eecs.umich.edu    bool lqEmpty() const { return loads == 0; }
2247720Sgblack@eecs.umich.edu
2252817Sksewell@umich.edu    /** Returns if the SQ is empty. */
2267720Sgblack@eecs.umich.edu    bool sqEmpty() const { return stores == 0; }
2277720Sgblack@eecs.umich.edu
2287720Sgblack@eecs.umich.edu    /** Returns the number of instructions in the LSQ. */
2295259Sksewell@umich.edu    unsigned getCount() { return loads + stores; }
2302817Sksewell@umich.edu
23110698Sandreas.hansson@arm.com    /** Returns if there are any stores to writeback. */
2325715Shsul@eecs.umich.edu    bool hasStoresToWB() { return storesToWB; }
2334172Ssaidi@eecs.umich.edu
2344172Ssaidi@eecs.umich.edu    /** Returns the number of stores to writeback. */
2354172Ssaidi@eecs.umich.edu    int numStoresToWB() { return storesToWB; }
2362817Sksewell@umich.edu
2375715Shsul@eecs.umich.edu    /** Returns if the LSQ unit will writeback on this cycle. */
2382817Sksewell@umich.edu    bool willWB() { return storeQueue[storeWBIdx].canWB &&
2392817Sksewell@umich.edu                        !storeQueue[storeWBIdx].completed &&
2404172Ssaidi@eecs.umich.edu                        !isStoreBlocked; }
2412817Sksewell@umich.edu
2422817Sksewell@umich.edu    /** Handles doing the retry. */
2432817Sksewell@umich.edu    void recvRetry();
2444172Ssaidi@eecs.umich.edu
2452817Sksewell@umich.edu  private:
2466313Sgblack@eecs.umich.edu    /** Reset the LSQ state */
2476313Sgblack@eecs.umich.edu    void resetState();
2489920Syasuko.eckert@amd.com
24910033SAli.Saidi@ARM.com    /** Writes back the instruction, sending it to IEW. */
2506313Sgblack@eecs.umich.edu    void writeback(DynInstPtr &inst, PacketPtr pkt);
2512817Sksewell@umich.edu
2522817Sksewell@umich.edu    /** Writes back a store that couldn't be completed the previous cycle. */
2532817Sksewell@umich.edu    void writebackPendingStore();
2542817Sksewell@umich.edu
2552817Sksewell@umich.edu    /** Handles completing the send of a store to memory. */
2562817Sksewell@umich.edu    void storePostSend(PacketPtr pkt);
2572817Sksewell@umich.edu
2582817Sksewell@umich.edu    /** Completes the store at the specified index. */
2592817Sksewell@umich.edu    void completeStore(int store_idx);
2602817Sksewell@umich.edu
2612817Sksewell@umich.edu    /** Attempts to send a store to the cache. */
2625715Shsul@eecs.umich.edu    bool sendStore(PacketPtr data_pkt);
2632817Sksewell@umich.edu
2642817Sksewell@umich.edu    /** Increments the given store index (circular queue). */
2652817Sksewell@umich.edu    inline void incrStIdx(int &store_idx) const;
2668777Sgblack@eecs.umich.edu    /** Decrements the given store index (circular queue). */
2675595Sgblack@eecs.umich.edu    inline void decrStIdx(int &store_idx) const;
2685595Sgblack@eecs.umich.edu    /** Increments the given load index (circular queue). */
2695595Sgblack@eecs.umich.edu    inline void incrLdIdx(int &load_idx) const;
2705595Sgblack@eecs.umich.edu    /** Decrements the given load index (circular queue). */
2715595Sgblack@eecs.umich.edu    inline void decrLdIdx(int &load_idx) const;
2729382SAli.Saidi@ARM.com
2739382SAli.Saidi@ARM.com  public:
2749382SAli.Saidi@ARM.com    /** Debugging function to dump instructions in the LSQ. */
2759382SAli.Saidi@ARM.com    void dumpInsts() const;
2769382SAli.Saidi@ARM.com
2779382SAli.Saidi@ARM.com  private:
2789382SAli.Saidi@ARM.com    /** Pointer to the CPU. */
2799382SAli.Saidi@ARM.com    O3CPU *cpu;
2809382SAli.Saidi@ARM.com
2819382SAli.Saidi@ARM.com    /** Pointer to the IEW stage. */
2825595Sgblack@eecs.umich.edu    IEW *iewStage;
2839426SAndreas.Sandberg@ARM.com
2849426SAndreas.Sandberg@ARM.com    /** Pointer to the LSQ. */
2859426SAndreas.Sandberg@ARM.com    LSQ *lsq;
2869426SAndreas.Sandberg@ARM.com
2879426SAndreas.Sandberg@ARM.com    /** Pointer to the dcache port.  Used only for sending. */
2889426SAndreas.Sandberg@ARM.com    MasterPort *dcachePort;
2899426SAndreas.Sandberg@ARM.com
2909426SAndreas.Sandberg@ARM.com    /** Derived class to hold any sender state the LSQ needs. */
2919920Syasuko.eckert@amd.com    class LSQSenderState : public Packet::SenderState
2929920Syasuko.eckert@amd.com    {
2939920Syasuko.eckert@amd.com      public:
2942817Sksewell@umich.edu        /** Default constructor. */
2952817Sksewell@umich.edu        LSQSenderState()
2962817Sksewell@umich.edu            : mainPkt(NULL), pendingPacket(NULL), outstanding(1),
297              noWB(false), isSplit(false), pktToSend(false)
298          { }
299
300        /** Instruction who initiated the access to memory. */
301        DynInstPtr inst;
302        /** The main packet from a split load, used during writeback. */
303        PacketPtr mainPkt;
304        /** A second packet from a split store that needs sending. */
305        PacketPtr pendingPacket;
306        /** The LQ/SQ index of the instruction. */
307        uint8_t idx;
308        /** Number of outstanding packets to complete. */
309        uint8_t outstanding;
310        /** Whether or not it is a load. */
311        bool isLoad;
312        /** Whether or not the instruction will need to writeback. */
313        bool noWB;
314        /** Whether or not this access is split in two. */
315        bool isSplit;
316        /** Whether or not there is a packet that needs sending. */
317        bool pktToSend;
318
319        /** Completes a packet and returns whether the access is finished. */
320        inline bool complete() { return --outstanding == 0; }
321    };
322
323    /** Writeback event, specifically for when stores forward data to loads. */
324    class WritebackEvent : public Event {
325      public:
326        /** Constructs a writeback event. */
327        WritebackEvent(DynInstPtr &_inst, PacketPtr pkt, LSQUnit *lsq_ptr);
328
329        /** Processes the writeback event. */
330        void process();
331
332        /** Returns the description of this event. */
333        const char *description() const;
334
335      private:
336        /** Instruction whose results are being written back. */
337        DynInstPtr inst;
338
339        /** The packet that would have been sent to memory. */
340        PacketPtr pkt;
341
342        /** The pointer to the LSQ unit that issued the store. */
343        LSQUnit<Impl> *lsqPtr;
344    };
345
346  public:
347    struct SQEntry {
348        /** Constructs an empty store queue entry. */
349        SQEntry()
350            : inst(NULL), req(NULL), size(0),
351              canWB(0), committed(0), completed(0)
352        {
353            std::memset(data, 0, sizeof(data));
354        }
355
356        ~SQEntry()
357        {
358            inst = NULL;
359        }
360
361        /** Constructs a store queue entry for a given instruction. */
362        SQEntry(DynInstPtr &_inst)
363            : inst(_inst), req(NULL), sreqLow(NULL), sreqHigh(NULL), size(0),
364              isSplit(0), canWB(0), committed(0), completed(0)
365        {
366            std::memset(data, 0, sizeof(data));
367        }
368        /** The store data. */
369        char data[16];
370        /** The store instruction. */
371        DynInstPtr inst;
372        /** The request for the store. */
373        RequestPtr req;
374        /** The split requests for the store. */
375        RequestPtr sreqLow;
376        RequestPtr sreqHigh;
377        /** The size of the store. */
378        uint8_t size;
379        /** Whether or not the store is split into two requests. */
380        bool isSplit;
381        /** Whether or not the store can writeback. */
382        bool canWB;
383        /** Whether or not the store is committed. */
384        bool committed;
385        /** Whether or not the store is completed. */
386        bool completed;
387    };
388
389  private:
390    /** The LSQUnit thread id. */
391    ThreadID lsqID;
392
393    /** The store queue. */
394    std::vector<SQEntry> storeQueue;
395
396    /** The load queue. */
397    std::vector<DynInstPtr> loadQueue;
398
399    /** The number of LQ entries, plus a sentinel entry (circular queue).
400     *  @todo: Consider having var that records the true number of LQ entries.
401     */
402    unsigned LQEntries;
403    /** The number of SQ entries, plus a sentinel entry (circular queue).
404     *  @todo: Consider having var that records the true number of SQ entries.
405     */
406    unsigned SQEntries;
407
408    /** The number of places to shift addresses in the LSQ before checking
409     * for dependency violations
410     */
411    unsigned depCheckShift;
412
413    /** Should loads be checked for dependency issues */
414    bool checkLoads;
415
416    /** The number of load instructions in the LQ. */
417    int loads;
418    /** The number of store instructions in the SQ. */
419    int stores;
420    /** The number of store instructions in the SQ waiting to writeback. */
421    int storesToWB;
422
423    /** The index of the head instruction in the LQ. */
424    int loadHead;
425    /** The index of the tail instruction in the LQ. */
426    int loadTail;
427
428    /** The index of the head instruction in the SQ. */
429    int storeHead;
430    /** The index of the first instruction that may be ready to be
431     * written back, and has not yet been written back.
432     */
433    int storeWBIdx;
434    /** The index of the tail instruction in the SQ. */
435    int storeTail;
436
437    /// @todo Consider moving to a more advanced model with write vs read ports
438    /** The number of cache ports available each cycle. */
439    int cachePorts;
440
441    /** The number of used cache ports in this cycle. */
442    int usedPorts;
443
444    //list<InstSeqNum> mshrSeqNums;
445
446    /** Address Mask for a cache block (e.g. ~(cache_block_size-1)) */
447    Addr cacheBlockMask;
448
449    /** Wire to read information from the issue stage time queue. */
450    typename TimeBuffer<IssueStruct>::wire fromIssue;
451
452    /** Whether or not the LSQ is stalled. */
453    bool stalled;
454    /** The store that causes the stall due to partial store to load
455     * forwarding.
456     */
457    InstSeqNum stallingStoreIsn;
458    /** The index of the above store. */
459    int stallingLoadIdx;
460
461    /** The packet that needs to be retried. */
462    PacketPtr retryPkt;
463
464    /** Whehter or not a store is blocked due to the memory system. */
465    bool isStoreBlocked;
466
467    /** Whether or not a load is blocked due to the memory system. */
468    bool isLoadBlocked;
469
470    /** Has the blocked load been handled. */
471    bool loadBlockedHandled;
472
473    /** Whether or not a store is in flight. */
474    bool storeInFlight;
475
476    /** The sequence number of the blocked load. */
477    InstSeqNum blockedLoadSeqNum;
478
479    /** The oldest load that caused a memory ordering violation. */
480    DynInstPtr memDepViolator;
481
482    /** Whether or not there is a packet that couldn't be sent because of
483     * a lack of cache ports. */
484    bool hasPendingPkt;
485
486    /** The packet that is pending free cache ports. */
487    PacketPtr pendingPkt;
488
489    /** Flag for memory model. */
490    bool needsTSO;
491
492    // Will also need how many read/write ports the Dcache has.  Or keep track
493    // of that in stage that is one level up, and only call executeLoad/Store
494    // the appropriate number of times.
495    /** Total number of loads forwaded from LSQ stores. */
496    Stats::Scalar lsqForwLoads;
497
498    /** Total number of loads ignored due to invalid addresses. */
499    Stats::Scalar invAddrLoads;
500
501    /** Total number of squashed loads. */
502    Stats::Scalar lsqSquashedLoads;
503
504    /** Total number of responses from the memory system that are
505     * ignored due to the instruction already being squashed. */
506    Stats::Scalar lsqIgnoredResponses;
507
508    /** Tota number of memory ordering violations. */
509    Stats::Scalar lsqMemOrderViolation;
510
511    /** Total number of squashed stores. */
512    Stats::Scalar lsqSquashedStores;
513
514    /** Total number of software prefetches ignored due to invalid addresses. */
515    Stats::Scalar invAddrSwpfs;
516
517    /** Ready loads blocked due to partial store-forwarding. */
518    Stats::Scalar lsqBlockedLoads;
519
520    /** Number of loads that were rescheduled. */
521    Stats::Scalar lsqRescheduledLoads;
522
523    /** Number of times the LSQ is blocked due to the cache. */
524    Stats::Scalar lsqCacheBlocked;
525
526  public:
527    /** Executes the load at the given index. */
528    Fault read(Request *req, Request *sreqLow, Request *sreqHigh,
529               uint8_t *data, int load_idx);
530
531    /** Executes the store at the given index. */
532    Fault write(Request *req, Request *sreqLow, Request *sreqHigh,
533                uint8_t *data, int store_idx);
534
535    /** Returns the index of the head load instruction. */
536    int getLoadHead() { return loadHead; }
537    /** Returns the sequence number of the head load instruction. */
538    InstSeqNum getLoadHeadSeqNum()
539    {
540        if (loadQueue[loadHead]) {
541            return loadQueue[loadHead]->seqNum;
542        } else {
543            return 0;
544        }
545
546    }
547
548    /** Returns the index of the head store instruction. */
549    int getStoreHead() { return storeHead; }
550    /** Returns the sequence number of the head store instruction. */
551    InstSeqNum getStoreHeadSeqNum()
552    {
553        if (storeQueue[storeHead].inst) {
554            return storeQueue[storeHead].inst->seqNum;
555        } else {
556            return 0;
557        }
558
559    }
560
561    /** Returns whether or not the LSQ unit is stalled. */
562    bool isStalled()  { return stalled; }
563};
564
565template <class Impl>
566Fault
567LSQUnit<Impl>::read(Request *req, Request *sreqLow, Request *sreqHigh,
568                    uint8_t *data, int load_idx)
569{
570    DynInstPtr load_inst = loadQueue[load_idx];
571
572    assert(load_inst);
573
574    assert(!load_inst->isExecuted());
575
576    // Make sure this isn't an uncacheable access
577    // A bit of a hackish way to get uncached accesses to work only if they're
578    // at the head of the LSQ and are ready to commit (at the head of the ROB
579    // too).
580    if (req->isUncacheable() &&
581        (load_idx != loadHead || !load_inst->isAtCommit())) {
582        iewStage->rescheduleMemInst(load_inst);
583        ++lsqRescheduledLoads;
584        DPRINTF(LSQUnit, "Uncachable load [sn:%lli] PC %s\n",
585                load_inst->seqNum, load_inst->pcState());
586
587        // Must delete request now that it wasn't handed off to
588        // memory.  This is quite ugly.  @todo: Figure out the proper
589        // place to really handle request deletes.
590        delete req;
591        if (TheISA::HasUnalignedMemAcc && sreqLow) {
592            delete sreqLow;
593            delete sreqHigh;
594        }
595        return new GenericISA::M5PanicFault(
596                "Uncachable load [sn:%llx] PC %s\n",
597                load_inst->seqNum, load_inst->pcState());
598    }
599
600    // Check the SQ for any previous stores that might lead to forwarding
601    int store_idx = load_inst->sqIdx;
602
603    int store_size = 0;
604
605    DPRINTF(LSQUnit, "Read called, load idx: %i, store idx: %i, "
606            "storeHead: %i addr: %#x%s\n",
607            load_idx, store_idx, storeHead, req->getPaddr(),
608            sreqLow ? " split" : "");
609
610    if (req->isLLSC()) {
611        assert(!sreqLow);
612        // Disable recording the result temporarily.  Writing to misc
613        // regs normally updates the result, but this is not the
614        // desired behavior when handling store conditionals.
615        load_inst->recordResult(false);
616        TheISA::handleLockedRead(load_inst.get(), req);
617        load_inst->recordResult(true);
618    }
619
620    if (req->isMmappedIpr()) {
621        assert(!load_inst->memData);
622        load_inst->memData = new uint8_t[64];
623
624        ThreadContext *thread = cpu->tcBase(lsqID);
625        Cycles delay(0);
626        PacketPtr data_pkt = new Packet(req, MemCmd::ReadReq);
627
628        if (!TheISA::HasUnalignedMemAcc || !sreqLow) {
629            data_pkt->dataStatic(load_inst->memData);
630            delay = TheISA::handleIprRead(thread, data_pkt);
631        } else {
632            assert(sreqLow->isMmappedIpr() && sreqHigh->isMmappedIpr());
633            PacketPtr fst_data_pkt = new Packet(sreqLow, MemCmd::ReadReq);
634            PacketPtr snd_data_pkt = new Packet(sreqHigh, MemCmd::ReadReq);
635
636            fst_data_pkt->dataStatic(load_inst->memData);
637            snd_data_pkt->dataStatic(load_inst->memData + sreqLow->getSize());
638
639            delay = TheISA::handleIprRead(thread, fst_data_pkt);
640            Cycles delay2 = TheISA::handleIprRead(thread, snd_data_pkt);
641            if (delay2 > delay)
642                delay = delay2;
643
644            delete sreqLow;
645            delete sreqHigh;
646            delete fst_data_pkt;
647            delete snd_data_pkt;
648        }
649        WritebackEvent *wb = new WritebackEvent(load_inst, data_pkt, this);
650        cpu->schedule(wb, cpu->clockEdge(delay));
651        return NoFault;
652    }
653
654    while (store_idx != -1) {
655        // End once we've reached the top of the LSQ
656        if (store_idx == storeWBIdx) {
657            break;
658        }
659
660        // Move the index to one younger
661        if (--store_idx < 0)
662            store_idx += SQEntries;
663
664        assert(storeQueue[store_idx].inst);
665
666        store_size = storeQueue[store_idx].size;
667
668        if (store_size == 0)
669            continue;
670        else if (storeQueue[store_idx].inst->uncacheable())
671            continue;
672
673        assert(storeQueue[store_idx].inst->effAddrValid());
674
675        // Check if the store data is within the lower and upper bounds of
676        // addresses that the request needs.
677        bool store_has_lower_limit =
678            req->getVaddr() >= storeQueue[store_idx].inst->effAddr;
679        bool store_has_upper_limit =
680            (req->getVaddr() + req->getSize()) <=
681            (storeQueue[store_idx].inst->effAddr + store_size);
682        bool lower_load_has_store_part =
683            req->getVaddr() < (storeQueue[store_idx].inst->effAddr +
684                           store_size);
685        bool upper_load_has_store_part =
686            (req->getVaddr() + req->getSize()) >
687            storeQueue[store_idx].inst->effAddr;
688
689        // If the store's data has all of the data needed, we can forward.
690        if ((store_has_lower_limit && store_has_upper_limit)) {
691            // Get shift amount for offset into the store's data.
692            int shift_amt = req->getVaddr() - storeQueue[store_idx].inst->effAddr;
693
694            memcpy(data, storeQueue[store_idx].data + shift_amt,
695                   req->getSize());
696
697            assert(!load_inst->memData);
698            load_inst->memData = new uint8_t[64];
699
700            memcpy(load_inst->memData,
701                    storeQueue[store_idx].data + shift_amt, req->getSize());
702
703            DPRINTF(LSQUnit, "Forwarding from store idx %i to load to "
704                    "addr %#x, data %#x\n",
705                    store_idx, req->getVaddr(), data);
706
707            PacketPtr data_pkt = new Packet(req, MemCmd::ReadReq);
708            data_pkt->dataStatic(load_inst->memData);
709
710            WritebackEvent *wb = new WritebackEvent(load_inst, data_pkt, this);
711
712            // We'll say this has a 1 cycle load-store forwarding latency
713            // for now.
714            // @todo: Need to make this a parameter.
715            cpu->schedule(wb, curTick());
716
717            // Don't need to do anything special for split loads.
718            if (TheISA::HasUnalignedMemAcc && sreqLow) {
719                delete sreqLow;
720                delete sreqHigh;
721            }
722
723            ++lsqForwLoads;
724            return NoFault;
725        } else if ((store_has_lower_limit && lower_load_has_store_part) ||
726                   (store_has_upper_limit && upper_load_has_store_part) ||
727                   (lower_load_has_store_part && upper_load_has_store_part)) {
728            // This is the partial store-load forwarding case where a store
729            // has only part of the load's data.
730
731            // If it's already been written back, then don't worry about
732            // stalling on it.
733            if (storeQueue[store_idx].completed) {
734                panic("Should not check one of these");
735                continue;
736            }
737
738            // Must stall load and force it to retry, so long as it's the oldest
739            // load that needs to do so.
740            if (!stalled ||
741                (stalled &&
742                 load_inst->seqNum <
743                 loadQueue[stallingLoadIdx]->seqNum)) {
744                stalled = true;
745                stallingStoreIsn = storeQueue[store_idx].inst->seqNum;
746                stallingLoadIdx = load_idx;
747            }
748
749            // Tell IQ/mem dep unit that this instruction will need to be
750            // rescheduled eventually
751            iewStage->rescheduleMemInst(load_inst);
752            iewStage->decrWb(load_inst->seqNum);
753            load_inst->clearIssued();
754            ++lsqRescheduledLoads;
755
756            // Do not generate a writeback event as this instruction is not
757            // complete.
758            DPRINTF(LSQUnit, "Load-store forwarding mis-match. "
759                    "Store idx %i to load addr %#x\n",
760                    store_idx, req->getVaddr());
761
762            // Must delete request now that it wasn't handed off to
763            // memory.  This is quite ugly.  @todo: Figure out the
764            // proper place to really handle request deletes.
765            delete req;
766            if (TheISA::HasUnalignedMemAcc && sreqLow) {
767                delete sreqLow;
768                delete sreqHigh;
769            }
770
771            return NoFault;
772        }
773    }
774
775    // If there's no forwarding case, then go access memory
776    DPRINTF(LSQUnit, "Doing memory access for inst [sn:%lli] PC %s\n",
777            load_inst->seqNum, load_inst->pcState());
778
779    assert(!load_inst->memData);
780    load_inst->memData = new uint8_t[64];
781
782    ++usedPorts;
783
784    // if we the cache is not blocked, do cache access
785    bool completedFirst = false;
786    if (!lsq->cacheBlocked()) {
787        MemCmd command =
788            req->isLLSC() ? MemCmd::LoadLockedReq : MemCmd::ReadReq;
789        PacketPtr data_pkt = new Packet(req, command);
790        PacketPtr fst_data_pkt = NULL;
791        PacketPtr snd_data_pkt = NULL;
792
793        data_pkt->dataStatic(load_inst->memData);
794
795        LSQSenderState *state = new LSQSenderState;
796        state->isLoad = true;
797        state->idx = load_idx;
798        state->inst = load_inst;
799        data_pkt->senderState = state;
800
801        if (!TheISA::HasUnalignedMemAcc || !sreqLow) {
802
803            // Point the first packet at the main data packet.
804            fst_data_pkt = data_pkt;
805        } else {
806
807            // Create the split packets.
808            fst_data_pkt = new Packet(sreqLow, command);
809            snd_data_pkt = new Packet(sreqHigh, command);
810
811            fst_data_pkt->dataStatic(load_inst->memData);
812            snd_data_pkt->dataStatic(load_inst->memData + sreqLow->getSize());
813
814            fst_data_pkt->senderState = state;
815            snd_data_pkt->senderState = state;
816
817            state->isSplit = true;
818            state->outstanding = 2;
819            state->mainPkt = data_pkt;
820        }
821
822        if (!dcachePort->sendTimingReq(fst_data_pkt)) {
823            // Delete state and data packet because a load retry
824            // initiates a pipeline restart; it does not retry.
825            delete state;
826            delete data_pkt->req;
827            delete data_pkt;
828            if (TheISA::HasUnalignedMemAcc && sreqLow) {
829                delete fst_data_pkt->req;
830                delete fst_data_pkt;
831                delete snd_data_pkt->req;
832                delete snd_data_pkt;
833                sreqLow = NULL;
834                sreqHigh = NULL;
835            }
836
837            req = NULL;
838
839            // If the access didn't succeed, tell the LSQ by setting
840            // the retry thread id.
841            lsq->setRetryTid(lsqID);
842        } else if (TheISA::HasUnalignedMemAcc && sreqLow) {
843            completedFirst = true;
844
845            // The first packet was sent without problems, so send this one
846            // too. If there is a problem with this packet then the whole
847            // load will be squashed, so indicate this to the state object.
848            // The first packet will return in completeDataAccess and be
849            // handled there.
850            ++usedPorts;
851            if (!dcachePort->sendTimingReq(snd_data_pkt)) {
852
853                // The main packet will be deleted in completeDataAccess.
854                delete snd_data_pkt->req;
855                delete snd_data_pkt;
856
857                state->complete();
858
859                req = NULL;
860                sreqHigh = NULL;
861
862                lsq->setRetryTid(lsqID);
863            }
864        }
865    }
866
867    // If the cache was blocked, or has become blocked due to the access,
868    // handle it.
869    if (lsq->cacheBlocked()) {
870        if (req)
871            delete req;
872        if (TheISA::HasUnalignedMemAcc && sreqLow && !completedFirst) {
873            delete sreqLow;
874            delete sreqHigh;
875        }
876
877        ++lsqCacheBlocked;
878
879        // If the first part of a split access succeeds, then let the LSQ
880        // handle the decrWb when completeDataAccess is called upon return
881        // of the requested first part of data
882        if (!completedFirst)
883            iewStage->decrWb(load_inst->seqNum);
884
885        // There's an older load that's already going to squash.
886        if (isLoadBlocked && blockedLoadSeqNum < load_inst->seqNum)
887            return NoFault;
888
889        // Record that the load was blocked due to memory.  This
890        // load will squash all instructions after it, be
891        // refetched, and re-executed.
892        isLoadBlocked = true;
893        loadBlockedHandled = false;
894        blockedLoadSeqNum = load_inst->seqNum;
895        // No fault occurred, even though the interface is blocked.
896        return NoFault;
897    }
898
899    return NoFault;
900}
901
902template <class Impl>
903Fault
904LSQUnit<Impl>::write(Request *req, Request *sreqLow, Request *sreqHigh,
905                     uint8_t *data, int store_idx)
906{
907    assert(storeQueue[store_idx].inst);
908
909    DPRINTF(LSQUnit, "Doing write to store idx %i, addr %#x data %#x"
910            " | storeHead:%i [sn:%i]\n",
911            store_idx, req->getPaddr(), data, storeHead,
912            storeQueue[store_idx].inst->seqNum);
913
914    storeQueue[store_idx].req = req;
915    storeQueue[store_idx].sreqLow = sreqLow;
916    storeQueue[store_idx].sreqHigh = sreqHigh;
917    unsigned size = req->getSize();
918    storeQueue[store_idx].size = size;
919    assert(size <= sizeof(storeQueue[store_idx].data));
920
921    // Split stores can only occur in ISAs with unaligned memory accesses.  If
922    // a store request has been split, sreqLow and sreqHigh will be non-null.
923    if (TheISA::HasUnalignedMemAcc && sreqLow) {
924        storeQueue[store_idx].isSplit = true;
925    }
926
927    memcpy(storeQueue[store_idx].data, data, size);
928
929    // This function only writes the data to the store queue, so no fault
930    // can happen here.
931    return NoFault;
932}
933
934#endif // __CPU_O3_LSQ_UNIT_HH__
935