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