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