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