lsq_unit.hh revision 7520:67c670459d01
12736Sktlim@umich.edu/*
22736Sktlim@umich.edu * Copyright (c) 2004-2006 The Regents of The University of Michigan
32736Sktlim@umich.edu * All rights reserved.
42736Sktlim@umich.edu *
52736Sktlim@umich.edu * Redistribution and use in source and binary forms, with or without
62736Sktlim@umich.edu * modification, are permitted provided that the following conditions are
72736Sktlim@umich.edu * met: redistributions of source code must retain the above copyright
82736Sktlim@umich.edu * notice, this list of conditions and the following disclaimer;
92736Sktlim@umich.edu * redistributions in binary form must reproduce the above copyright
102736Sktlim@umich.edu * notice, this list of conditions and the following disclaimer in the
112736Sktlim@umich.edu * documentation and/or other materials provided with the distribution;
122736Sktlim@umich.edu * neither the name of the copyright holders nor the names of its
132736Sktlim@umich.edu * contributors may be used to endorse or promote products derived from
142736Sktlim@umich.edu * this software without specific prior written permission.
152736Sktlim@umich.edu *
162736Sktlim@umich.edu * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
172736Sktlim@umich.edu * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
182736Sktlim@umich.edu * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
192736Sktlim@umich.edu * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
202736Sktlim@umich.edu * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
212736Sktlim@umich.edu * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
222736Sktlim@umich.edu * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
232736Sktlim@umich.edu * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
242736Sktlim@umich.edu * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
252736Sktlim@umich.edu * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
262736Sktlim@umich.edu * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
272736Sktlim@umich.edu *
282736Sktlim@umich.edu * Authors: Kevin Lim
292736Sktlim@umich.edu *          Korey Sewell
302736Sktlim@umich.edu */
3111793Sbrandon.potter@amd.com
3211793Sbrandon.potter@amd.com#ifndef __CPU_O3_LSQ_UNIT_HH__
332736Sktlim@umich.edu#define __CPU_O3_LSQ_UNIT_HH__
342736Sktlim@umich.edu
352736Sktlim@umich.edu#include <algorithm>
362736Sktlim@umich.edu#include <cstring>
372736Sktlim@umich.edu#include <map>
382736Sktlim@umich.edu#include <queue>
392736Sktlim@umich.edu
402736Sktlim@umich.edu#include "arch/faults.hh"
412736Sktlim@umich.edu#include "arch/locked_mem.hh"
422736Sktlim@umich.edu#include "config/full_system.hh"
432736Sktlim@umich.edu#include "config/the_isa.hh"
442736Sktlim@umich.edu#include "base/fast_alloc.hh"
452736Sktlim@umich.edu#include "base/hashmap.hh"
4610936Sandreas.hansson@arm.com#include "cpu/inst_seq.hh"
4710936Sandreas.hansson@arm.com#include "mem/packet.hh"
482736Sktlim@umich.edu#include "mem/port.hh"
492736Sktlim@umich.edu
502736Sktlim@umich.educlass DerivO3CPUParams;
512736Sktlim@umich.edu
522736Sktlim@umich.edu/**
532736Sktlim@umich.edu * Class that implements the actual LQ and SQ for each specific
542736Sktlim@umich.edu * thread.  Both are circular queues; load entries are freed upon
552736Sktlim@umich.edu * committing, while store entries are freed once they writeback. The
562736Sktlim@umich.edu * LSQUnit tracks if there are memory ordering violations, and also
572736Sktlim@umich.edu * detects partial load to store forwarding cases (a store only has
5810807Snilay@cs.wisc.edu * part of a load's data) that requires the load to wait until the
592736Sktlim@umich.edu * store writes back. In the former case it holds onto the instruction
602736Sktlim@umich.edu * until the dependence unit looks at it, and in the latter it stalls
612736Sktlim@umich.edu * the LSQ until the store writes back. At that point the load is
622736Sktlim@umich.edu * replayed.
632736Sktlim@umich.edu */
642736Sktlim@umich.edutemplate <class Impl>
652736Sktlim@umich.educlass LSQUnit {
6610807Snilay@cs.wisc.edu  protected:
672736Sktlim@umich.edu    typedef TheISA::IntReg IntReg;
6810807Snilay@cs.wisc.edu  public:
692736Sktlim@umich.edu    typedef typename Impl::O3CPU O3CPU;
702736Sktlim@umich.edu    typedef typename Impl::DynInstPtr DynInstPtr;
712736Sktlim@umich.edu    typedef typename Impl::CPUPol::IEW IEW;
722736Sktlim@umich.edu    typedef typename Impl::CPUPol::LSQ LSQ;
732736Sktlim@umich.edu    typedef typename Impl::CPUPol::IssueStruct IssueStruct;
7410807Snilay@cs.wisc.edu
752736Sktlim@umich.edu  public:
762736Sktlim@umich.edu    /** Constructs an LSQ unit. init() must be called prior to use. */
772736Sktlim@umich.edu    LSQUnit();
782736Sktlim@umich.edu
792736Sktlim@umich.edu    /** Initializes the LSQ unit with the specified number of entries. */
802736Sktlim@umich.edu    void init(O3CPU *cpu_ptr, IEW *iew_ptr, DerivO3CPUParams *params,
812736Sktlim@umich.edu            LSQ *lsq_ptr, unsigned maxLQEntries, unsigned maxSQEntries,
822736Sktlim@umich.edu            unsigned id);
832736Sktlim@umich.edu
842736Sktlim@umich.edu    /** Returns the name of the LSQ unit. */
852736Sktlim@umich.edu    std::string name() const;
862736Sktlim@umich.edu
872736Sktlim@umich.edu    /** Registers statistics. */
882736Sktlim@umich.edu    void regStats();
892736Sktlim@umich.edu
902736Sktlim@umich.edu    /** Sets the pointer to the dcache port. */
912736Sktlim@umich.edu    void setDcachePort(Port *dcache_port);
922736Sktlim@umich.edu
932736Sktlim@umich.edu    /** Switches out LSQ unit. */
942736Sktlim@umich.edu    void switchOut();
9510807Snilay@cs.wisc.edu
9610807Snilay@cs.wisc.edu    /** Takes over from another CPU's thread. */
972736Sktlim@umich.edu    void takeOverFrom();
9810807Snilay@cs.wisc.edu
992736Sktlim@umich.edu    /** Returns if the LSQ is switched out. */
1002736Sktlim@umich.edu    bool isSwitchedOut() { return switchedOut; }
1012736Sktlim@umich.edu
1022736Sktlim@umich.edu    /** Ticks the LSQ unit, which in this case only resets the number of
1032736Sktlim@umich.edu     * used cache ports.
1042736Sktlim@umich.edu     * @todo: Move the number of used ports up to the LSQ level so it can
1052736Sktlim@umich.edu     * be shared by all LSQ units.
1062736Sktlim@umich.edu     */
1072736Sktlim@umich.edu    void tick() { usedPorts = 0; }
1082736Sktlim@umich.edu
1092736Sktlim@umich.edu    /** Inserts an instruction. */
1102736Sktlim@umich.edu    void insert(DynInstPtr &inst);
1112736Sktlim@umich.edu    /** Inserts a load instruction. */
1122736Sktlim@umich.edu    void insertLoad(DynInstPtr &load_inst);
1132736Sktlim@umich.edu    /** Inserts a store instruction. */
1142736Sktlim@umich.edu    void insertStore(DynInstPtr &store_inst);
1152736Sktlim@umich.edu
1162736Sktlim@umich.edu    /** Executes a load instruction. */
1172736Sktlim@umich.edu    Fault executeLoad(DynInstPtr &inst);
1182736Sktlim@umich.edu
1192736Sktlim@umich.edu    Fault executeLoad(int lq_idx) { panic("Not implemented"); return NoFault; }
1202736Sktlim@umich.edu    /** Executes a store instruction. */
1214762Snate@binkert.org    Fault executeStore(DynInstPtr &inst);
1224762Snate@binkert.org
1232736Sktlim@umich.edu    /** Commits the head load. */
1245034Smilesck@eecs.umich.edu    void commitLoad();
1252736Sktlim@umich.edu    /** Commits loads older than a specific sequence number. */
1262736Sktlim@umich.edu    void commitLoads(InstSeqNum &youngest_inst);
1272736Sktlim@umich.edu
1282736Sktlim@umich.edu    /** Commits stores older than a specific sequence number. */
1292736Sktlim@umich.edu    void commitStores(InstSeqNum &youngest_inst);
1304762Snate@binkert.org
1314762Snate@binkert.org    /** Writes back stores. */
1322736Sktlim@umich.edu    void writebackStores();
1335034Smilesck@eecs.umich.edu
1342736Sktlim@umich.edu    /** Completes the data access that has been returned from the
135     * memory system. */
136    void completeDataAccess(PacketPtr pkt);
137
138    /** Clears all the entries in the LQ. */
139    void clearLQ();
140
141    /** Clears all the entries in the SQ. */
142    void clearSQ();
143
144    /** Resizes the LQ to a given size. */
145    void resizeLQ(unsigned size);
146
147    /** Resizes the SQ to a given size. */
148    void resizeSQ(unsigned size);
149
150    /** Squashes all instructions younger than a specific sequence number. */
151    void squash(const InstSeqNum &squashed_num);
152
153    /** Returns if there is a memory ordering violation. Value is reset upon
154     * call to getMemDepViolator().
155     */
156    bool violation() { return memDepViolator; }
157
158    /** Returns the memory ordering violator. */
159    DynInstPtr getMemDepViolator();
160
161    /** Returns if a load became blocked due to the memory system. */
162    bool loadBlocked()
163    { return isLoadBlocked; }
164
165    /** Clears the signal that a load became blocked. */
166    void clearLoadBlocked()
167    { isLoadBlocked = false; }
168
169    /** Returns if the blocked load was handled. */
170    bool isLoadBlockedHandled()
171    { return loadBlockedHandled; }
172
173    /** Records the blocked load as being handled. */
174    void setLoadBlockedHandled()
175    { loadBlockedHandled = true; }
176
177    /** Returns the number of free entries (min of free LQ and SQ entries). */
178    unsigned numFreeEntries();
179
180    /** Returns the number of loads ready to execute. */
181    int numLoadsReady();
182
183    /** Returns the number of loads in the LQ. */
184    int numLoads() { return loads; }
185
186    /** Returns the number of stores in the SQ. */
187    int numStores() { return stores; }
188
189    /** Returns if either the LQ or SQ is full. */
190    bool isFull() { return lqFull() || sqFull(); }
191
192    /** Returns if the LQ is full. */
193    bool lqFull() { return loads >= (LQEntries - 1); }
194
195    /** Returns if the SQ is full. */
196    bool sqFull() { return stores >= (SQEntries - 1); }
197
198    /** Returns the number of instructions in the LSQ. */
199    unsigned getCount() { return loads + stores; }
200
201    /** Returns if there are any stores to writeback. */
202    bool hasStoresToWB() { return storesToWB; }
203
204    /** Returns the number of stores to writeback. */
205    int numStoresToWB() { return storesToWB; }
206
207    /** Returns if the LSQ unit will writeback on this cycle. */
208    bool willWB() { return storeQueue[storeWBIdx].canWB &&
209                        !storeQueue[storeWBIdx].completed &&
210                        !isStoreBlocked; }
211
212    /** Handles doing the retry. */
213    void recvRetry();
214
215  private:
216    /** Writes back the instruction, sending it to IEW. */
217    void writeback(DynInstPtr &inst, PacketPtr pkt);
218
219    /** Writes back a store that couldn't be completed the previous cycle. */
220    void writebackPendingStore();
221
222    /** Handles completing the send of a store to memory. */
223    void storePostSend(PacketPtr pkt);
224
225    /** Completes the store at the specified index. */
226    void completeStore(int store_idx);
227
228    /** Attempts to send a store to the cache. */
229    bool sendStore(PacketPtr data_pkt);
230
231    /** Increments the given store index (circular queue). */
232    inline void incrStIdx(int &store_idx);
233    /** Decrements the given store index (circular queue). */
234    inline void decrStIdx(int &store_idx);
235    /** Increments the given load index (circular queue). */
236    inline void incrLdIdx(int &load_idx);
237    /** Decrements the given load index (circular queue). */
238    inline void decrLdIdx(int &load_idx);
239
240  public:
241    /** Debugging function to dump instructions in the LSQ. */
242    void dumpInsts();
243
244  private:
245    /** Pointer to the CPU. */
246    O3CPU *cpu;
247
248    /** Pointer to the IEW stage. */
249    IEW *iewStage;
250
251    /** Pointer to the LSQ. */
252    LSQ *lsq;
253
254    /** Pointer to the dcache port.  Used only for sending. */
255    Port *dcachePort;
256
257    /** Derived class to hold any sender state the LSQ needs. */
258    class LSQSenderState : public Packet::SenderState, public FastAlloc
259    {
260      public:
261        /** Default constructor. */
262        LSQSenderState()
263            : noWB(false), isSplit(false), pktToSend(false), outstanding(1),
264              mainPkt(NULL), pendingPacket(NULL)
265        { }
266
267        /** Instruction who initiated the access to memory. */
268        DynInstPtr inst;
269        /** Whether or not it is a load. */
270        bool isLoad;
271        /** The LQ/SQ index of the instruction. */
272        int idx;
273        /** Whether or not the instruction will need to writeback. */
274        bool noWB;
275        /** Whether or not this access is split in two. */
276        bool isSplit;
277        /** Whether or not there is a packet that needs sending. */
278        bool pktToSend;
279        /** Number of outstanding packets to complete. */
280        int outstanding;
281        /** The main packet from a split load, used during writeback. */
282        PacketPtr mainPkt;
283        /** A second packet from a split store that needs sending. */
284        PacketPtr pendingPacket;
285
286        /** Completes a packet and returns whether the access is finished. */
287        inline bool complete() { return --outstanding == 0; }
288    };
289
290    /** Writeback event, specifically for when stores forward data to loads. */
291    class WritebackEvent : public Event {
292      public:
293        /** Constructs a writeback event. */
294        WritebackEvent(DynInstPtr &_inst, PacketPtr pkt, LSQUnit *lsq_ptr);
295
296        /** Processes the writeback event. */
297        void process();
298
299        /** Returns the description of this event. */
300        const char *description() const;
301
302      private:
303        /** Instruction whose results are being written back. */
304        DynInstPtr inst;
305
306        /** The packet that would have been sent to memory. */
307        PacketPtr pkt;
308
309        /** The pointer to the LSQ unit that issued the store. */
310        LSQUnit<Impl> *lsqPtr;
311    };
312
313  public:
314    struct SQEntry {
315        /** Constructs an empty store queue entry. */
316        SQEntry()
317            : inst(NULL), req(NULL), size(0),
318              canWB(0), committed(0), completed(0)
319        {
320            std::memset(data, 0, sizeof(data));
321        }
322
323        /** Constructs a store queue entry for a given instruction. */
324        SQEntry(DynInstPtr &_inst)
325            : inst(_inst), req(NULL), sreqLow(NULL), sreqHigh(NULL), size(0),
326              isSplit(0), canWB(0), committed(0), completed(0)
327        {
328            std::memset(data, 0, sizeof(data));
329        }
330
331        /** The store instruction. */
332        DynInstPtr inst;
333        /** The request for the store. */
334        RequestPtr req;
335        /** The split requests for the store. */
336        RequestPtr sreqLow;
337        RequestPtr sreqHigh;
338        /** The size of the store. */
339        int size;
340        /** The store data. */
341        char data[sizeof(IntReg)];
342        /** Whether or not the store is split into two requests. */
343        bool isSplit;
344        /** Whether or not the store can writeback. */
345        bool canWB;
346        /** Whether or not the store is committed. */
347        bool committed;
348        /** Whether or not the store is completed. */
349        bool completed;
350    };
351
352  private:
353    /** The LSQUnit thread id. */
354    ThreadID lsqID;
355
356    /** The store queue. */
357    std::vector<SQEntry> storeQueue;
358
359    /** The load queue. */
360    std::vector<DynInstPtr> loadQueue;
361
362    /** The number of LQ entries, plus a sentinel entry (circular queue).
363     *  @todo: Consider having var that records the true number of LQ entries.
364     */
365    unsigned LQEntries;
366    /** The number of SQ entries, plus a sentinel entry (circular queue).
367     *  @todo: Consider having var that records the true number of SQ entries.
368     */
369    unsigned SQEntries;
370
371    /** The number of load instructions in the LQ. */
372    int loads;
373    /** The number of store instructions in the SQ. */
374    int stores;
375    /** The number of store instructions in the SQ waiting to writeback. */
376    int storesToWB;
377
378    /** The index of the head instruction in the LQ. */
379    int loadHead;
380    /** The index of the tail instruction in the LQ. */
381    int loadTail;
382
383    /** The index of the head instruction in the SQ. */
384    int storeHead;
385    /** The index of the first instruction that may be ready to be
386     * written back, and has not yet been written back.
387     */
388    int storeWBIdx;
389    /** The index of the tail instruction in the SQ. */
390    int storeTail;
391
392    /// @todo Consider moving to a more advanced model with write vs read ports
393    /** The number of cache ports available each cycle. */
394    int cachePorts;
395
396    /** The number of used cache ports in this cycle. */
397    int usedPorts;
398
399    /** Is the LSQ switched out. */
400    bool switchedOut;
401
402    //list<InstSeqNum> mshrSeqNums;
403
404    /** Wire to read information from the issue stage time queue. */
405    typename TimeBuffer<IssueStruct>::wire fromIssue;
406
407    /** Whether or not the LSQ is stalled. */
408    bool stalled;
409    /** The store that causes the stall due to partial store to load
410     * forwarding.
411     */
412    InstSeqNum stallingStoreIsn;
413    /** The index of the above store. */
414    int stallingLoadIdx;
415
416    /** The packet that needs to be retried. */
417    PacketPtr retryPkt;
418
419    /** Whehter or not a store is blocked due to the memory system. */
420    bool isStoreBlocked;
421
422    /** Whether or not a load is blocked due to the memory system. */
423    bool isLoadBlocked;
424
425    /** Has the blocked load been handled. */
426    bool loadBlockedHandled;
427
428    /** The sequence number of the blocked load. */
429    InstSeqNum blockedLoadSeqNum;
430
431    /** The oldest load that caused a memory ordering violation. */
432    DynInstPtr memDepViolator;
433
434    /** Whether or not there is a packet that couldn't be sent because of
435     * a lack of cache ports. */
436    bool hasPendingPkt;
437
438    /** The packet that is pending free cache ports. */
439    PacketPtr pendingPkt;
440
441    // Will also need how many read/write ports the Dcache has.  Or keep track
442    // of that in stage that is one level up, and only call executeLoad/Store
443    // the appropriate number of times.
444    /** Total number of loads forwaded from LSQ stores. */
445    Stats::Scalar lsqForwLoads;
446
447    /** Total number of loads ignored due to invalid addresses. */
448    Stats::Scalar invAddrLoads;
449
450    /** Total number of squashed loads. */
451    Stats::Scalar lsqSquashedLoads;
452
453    /** Total number of responses from the memory system that are
454     * ignored due to the instruction already being squashed. */
455    Stats::Scalar lsqIgnoredResponses;
456
457    /** Tota number of memory ordering violations. */
458    Stats::Scalar lsqMemOrderViolation;
459
460    /** Total number of squashed stores. */
461    Stats::Scalar lsqSquashedStores;
462
463    /** Total number of software prefetches ignored due to invalid addresses. */
464    Stats::Scalar invAddrSwpfs;
465
466    /** Ready loads blocked due to partial store-forwarding. */
467    Stats::Scalar lsqBlockedLoads;
468
469    /** Number of loads that were rescheduled. */
470    Stats::Scalar lsqRescheduledLoads;
471
472    /** Number of times the LSQ is blocked due to the cache. */
473    Stats::Scalar lsqCacheBlocked;
474
475  public:
476    /** Executes the load at the given index. */
477    Fault read(Request *req, Request *sreqLow, Request *sreqHigh,
478               uint8_t *data, int load_idx);
479
480    /** Executes the store at the given index. */
481    Fault write(Request *req, Request *sreqLow, Request *sreqHigh,
482                uint8_t *data, int store_idx);
483
484    /** Returns the index of the head load instruction. */
485    int getLoadHead() { return loadHead; }
486    /** Returns the sequence number of the head load instruction. */
487    InstSeqNum getLoadHeadSeqNum()
488    {
489        if (loadQueue[loadHead]) {
490            return loadQueue[loadHead]->seqNum;
491        } else {
492            return 0;
493        }
494
495    }
496
497    /** Returns the index of the head store instruction. */
498    int getStoreHead() { return storeHead; }
499    /** Returns the sequence number of the head store instruction. */
500    InstSeqNum getStoreHeadSeqNum()
501    {
502        if (storeQueue[storeHead].inst) {
503            return storeQueue[storeHead].inst->seqNum;
504        } else {
505            return 0;
506        }
507
508    }
509
510    /** Returns whether or not the LSQ unit is stalled. */
511    bool isStalled()  { return stalled; }
512};
513
514template <class Impl>
515Fault
516LSQUnit<Impl>::read(Request *req, Request *sreqLow, Request *sreqHigh,
517                    uint8_t *data, int load_idx)
518{
519    DynInstPtr load_inst = loadQueue[load_idx];
520
521    assert(load_inst);
522
523    assert(!load_inst->isExecuted());
524
525    // Make sure this isn't an uncacheable access
526    // A bit of a hackish way to get uncached accesses to work only if they're
527    // at the head of the LSQ and are ready to commit (at the head of the ROB
528    // too).
529    if (req->isUncacheable() &&
530        (load_idx != loadHead || !load_inst->isAtCommit())) {
531        iewStage->rescheduleMemInst(load_inst);
532        ++lsqRescheduledLoads;
533
534        // Must delete request now that it wasn't handed off to
535        // memory.  This is quite ugly.  @todo: Figure out the proper
536        // place to really handle request deletes.
537        delete req;
538        if (TheISA::HasUnalignedMemAcc && sreqLow) {
539            delete sreqLow;
540            delete sreqHigh;
541        }
542        return TheISA::genMachineCheckFault();
543    }
544
545    // Check the SQ for any previous stores that might lead to forwarding
546    int store_idx = load_inst->sqIdx;
547
548    int store_size = 0;
549
550    DPRINTF(LSQUnit, "Read called, load idx: %i, store idx: %i, "
551            "storeHead: %i addr: %#x%s\n",
552            load_idx, store_idx, storeHead, req->getPaddr(),
553            sreqLow ? " split" : "");
554
555    if (req->isLLSC()) {
556        assert(!sreqLow);
557        // Disable recording the result temporarily.  Writing to misc
558        // regs normally updates the result, but this is not the
559        // desired behavior when handling store conditionals.
560        load_inst->recordResult = false;
561        TheISA::handleLockedRead(load_inst.get(), req);
562        load_inst->recordResult = true;
563    }
564
565    while (store_idx != -1) {
566        // End once we've reached the top of the LSQ
567        if (store_idx == storeWBIdx) {
568            break;
569        }
570
571        // Move the index to one younger
572        if (--store_idx < 0)
573            store_idx += SQEntries;
574
575        assert(storeQueue[store_idx].inst);
576
577        store_size = storeQueue[store_idx].size;
578
579        if (store_size == 0)
580            continue;
581        else if (storeQueue[store_idx].inst->uncacheable())
582            continue;
583
584        assert(storeQueue[store_idx].inst->effAddrValid);
585
586        // Check if the store data is within the lower and upper bounds of
587        // addresses that the request needs.
588        bool store_has_lower_limit =
589            req->getVaddr() >= storeQueue[store_idx].inst->effAddr;
590        bool store_has_upper_limit =
591            (req->getVaddr() + req->getSize()) <=
592            (storeQueue[store_idx].inst->effAddr + store_size);
593        bool lower_load_has_store_part =
594            req->getVaddr() < (storeQueue[store_idx].inst->effAddr +
595                           store_size);
596        bool upper_load_has_store_part =
597            (req->getVaddr() + req->getSize()) >
598            storeQueue[store_idx].inst->effAddr;
599
600        // If the store's data has all of the data needed, we can forward.
601        if ((store_has_lower_limit && store_has_upper_limit)) {
602            // Get shift amount for offset into the store's data.
603            int shift_amt = req->getVaddr() & (store_size - 1);
604
605            memcpy(data, storeQueue[store_idx].data + shift_amt,
606                   req->getSize());
607
608            assert(!load_inst->memData);
609            load_inst->memData = new uint8_t[64];
610
611            memcpy(load_inst->memData,
612                    storeQueue[store_idx].data + shift_amt, req->getSize());
613
614            DPRINTF(LSQUnit, "Forwarding from store idx %i to load to "
615                    "addr %#x, data %#x\n",
616                    store_idx, req->getVaddr(), data);
617
618            PacketPtr data_pkt = new Packet(req, MemCmd::ReadReq,
619                                            Packet::Broadcast);
620            data_pkt->dataStatic(load_inst->memData);
621
622            WritebackEvent *wb = new WritebackEvent(load_inst, data_pkt, this);
623
624            // We'll say this has a 1 cycle load-store forwarding latency
625            // for now.
626            // @todo: Need to make this a parameter.
627            cpu->schedule(wb, curTick);
628
629            // Don't need to do anything special for split loads.
630            if (TheISA::HasUnalignedMemAcc && sreqLow) {
631                delete sreqLow;
632                delete sreqHigh;
633            }
634
635            ++lsqForwLoads;
636            return NoFault;
637        } else if ((store_has_lower_limit && lower_load_has_store_part) ||
638                   (store_has_upper_limit && upper_load_has_store_part) ||
639                   (lower_load_has_store_part && upper_load_has_store_part)) {
640            // This is the partial store-load forwarding case where a store
641            // has only part of the load's data.
642
643            // If it's already been written back, then don't worry about
644            // stalling on it.
645            if (storeQueue[store_idx].completed) {
646                panic("Should not check one of these");
647                continue;
648            }
649
650            // Must stall load and force it to retry, so long as it's the oldest
651            // load that needs to do so.
652            if (!stalled ||
653                (stalled &&
654                 load_inst->seqNum <
655                 loadQueue[stallingLoadIdx]->seqNum)) {
656                stalled = true;
657                stallingStoreIsn = storeQueue[store_idx].inst->seqNum;
658                stallingLoadIdx = load_idx;
659            }
660
661            // Tell IQ/mem dep unit that this instruction will need to be
662            // rescheduled eventually
663            iewStage->rescheduleMemInst(load_inst);
664            iewStage->decrWb(load_inst->seqNum);
665            load_inst->clearIssued();
666            ++lsqRescheduledLoads;
667
668            // Do not generate a writeback event as this instruction is not
669            // complete.
670            DPRINTF(LSQUnit, "Load-store forwarding mis-match. "
671                    "Store idx %i to load addr %#x\n",
672                    store_idx, req->getVaddr());
673
674            // Must delete request now that it wasn't handed off to
675            // memory.  This is quite ugly.  @todo: Figure out the
676            // proper place to really handle request deletes.
677            delete req;
678            if (TheISA::HasUnalignedMemAcc && sreqLow) {
679                delete sreqLow;
680                delete sreqHigh;
681            }
682
683            return NoFault;
684        }
685    }
686
687    // If there's no forwarding case, then go access memory
688    DPRINTF(LSQUnit, "Doing memory access for inst [sn:%lli] PC %#x\n",
689            load_inst->seqNum, load_inst->readPC());
690
691    assert(!load_inst->memData);
692    load_inst->memData = new uint8_t[64];
693
694    ++usedPorts;
695
696    // if we the cache is not blocked, do cache access
697    bool completedFirst = false;
698    if (!lsq->cacheBlocked()) {
699        MemCmd command =
700            req->isLLSC() ? MemCmd::LoadLockedReq : MemCmd::ReadReq;
701        PacketPtr data_pkt = new Packet(req, command, Packet::Broadcast);
702        PacketPtr fst_data_pkt = NULL;
703        PacketPtr snd_data_pkt = NULL;
704
705        data_pkt->dataStatic(load_inst->memData);
706
707        LSQSenderState *state = new LSQSenderState;
708        state->isLoad = true;
709        state->idx = load_idx;
710        state->inst = load_inst;
711        data_pkt->senderState = state;
712
713        if (!TheISA::HasUnalignedMemAcc || !sreqLow) {
714
715            // Point the first packet at the main data packet.
716            fst_data_pkt = data_pkt;
717        } else {
718
719            // Create the split packets.
720            fst_data_pkt = new Packet(sreqLow, command, Packet::Broadcast);
721            snd_data_pkt = new Packet(sreqHigh, command, Packet::Broadcast);
722
723            fst_data_pkt->dataStatic(load_inst->memData);
724            snd_data_pkt->dataStatic(load_inst->memData + sreqLow->getSize());
725
726            fst_data_pkt->senderState = state;
727            snd_data_pkt->senderState = state;
728
729            state->isSplit = true;
730            state->outstanding = 2;
731            state->mainPkt = data_pkt;
732        }
733
734        if (!dcachePort->sendTiming(fst_data_pkt)) {
735            // Delete state and data packet because a load retry
736            // initiates a pipeline restart; it does not retry.
737            delete state;
738            delete data_pkt->req;
739            delete data_pkt;
740            if (TheISA::HasUnalignedMemAcc && sreqLow) {
741                delete fst_data_pkt->req;
742                delete fst_data_pkt;
743                delete snd_data_pkt->req;
744                delete snd_data_pkt;
745                sreqLow = NULL;
746                sreqHigh = NULL;
747            }
748
749            req = NULL;
750
751            // If the access didn't succeed, tell the LSQ by setting
752            // the retry thread id.
753            lsq->setRetryTid(lsqID);
754        } else if (TheISA::HasUnalignedMemAcc && sreqLow) {
755            completedFirst = true;
756
757            // The first packet was sent without problems, so send this one
758            // too. If there is a problem with this packet then the whole
759            // load will be squashed, so indicate this to the state object.
760            // The first packet will return in completeDataAccess and be
761            // handled there.
762            ++usedPorts;
763            if (!dcachePort->sendTiming(snd_data_pkt)) {
764
765                // The main packet will be deleted in completeDataAccess.
766                delete snd_data_pkt->req;
767                delete snd_data_pkt;
768
769                state->complete();
770
771                req = NULL;
772                sreqHigh = NULL;
773
774                lsq->setRetryTid(lsqID);
775            }
776        }
777    }
778
779    // If the cache was blocked, or has become blocked due to the access,
780    // handle it.
781    if (lsq->cacheBlocked()) {
782        if (req)
783            delete req;
784        if (TheISA::HasUnalignedMemAcc && sreqLow && !completedFirst) {
785            delete sreqLow;
786            delete sreqHigh;
787        }
788
789        ++lsqCacheBlocked;
790
791        iewStage->decrWb(load_inst->seqNum);
792        // There's an older load that's already going to squash.
793        if (isLoadBlocked && blockedLoadSeqNum < load_inst->seqNum)
794            return NoFault;
795
796        // Record that the load was blocked due to memory.  This
797        // load will squash all instructions after it, be
798        // refetched, and re-executed.
799        isLoadBlocked = true;
800        loadBlockedHandled = false;
801        blockedLoadSeqNum = load_inst->seqNum;
802        // No fault occurred, even though the interface is blocked.
803        return NoFault;
804    }
805
806    return NoFault;
807}
808
809template <class Impl>
810Fault
811LSQUnit<Impl>::write(Request *req, Request *sreqLow, Request *sreqHigh,
812                     uint8_t *data, int store_idx)
813{
814    assert(storeQueue[store_idx].inst);
815
816    DPRINTF(LSQUnit, "Doing write to store idx %i, addr %#x data %#x"
817            " | storeHead:%i [sn:%i]\n",
818            store_idx, req->getPaddr(), data, storeHead,
819            storeQueue[store_idx].inst->seqNum);
820
821    storeQueue[store_idx].req = req;
822    storeQueue[store_idx].sreqLow = sreqLow;
823    storeQueue[store_idx].sreqHigh = sreqHigh;
824    unsigned size = req->getSize();
825    storeQueue[store_idx].size = size;
826    assert(size <= sizeof(storeQueue[store_idx].data));
827
828    // Split stores can only occur in ISAs with unaligned memory accesses.  If
829    // a store request has been split, sreqLow and sreqHigh will be non-null.
830    if (TheISA::HasUnalignedMemAcc && sreqLow) {
831        storeQueue[store_idx].isSplit = true;
832    }
833
834    memcpy(storeQueue[store_idx].data, data, size);
835
836    // This function only writes the data to the store queue, so no fault
837    // can happen here.
838    return NoFault;
839}
840
841#endif // __CPU_O3_LSQ_UNIT_HH__
842