lsq_unit_impl.hh revision 3772:71cccab4eff8
1/*
2 * Copyright (c) 2004-2005 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#include "arch/locked_mem.hh"
33#include "config/use_checker.hh"
34
35#include "cpu/o3/lsq.hh"
36#include "cpu/o3/lsq_unit.hh"
37#include "base/str.hh"
38#include "mem/packet.hh"
39#include "mem/request.hh"
40
41#if USE_CHECKER
42#include "cpu/checker/cpu.hh"
43#endif
44
45template<class Impl>
46LSQUnit<Impl>::WritebackEvent::WritebackEvent(DynInstPtr &_inst, PacketPtr _pkt,
47                                              LSQUnit *lsq_ptr)
48    : Event(&mainEventQueue), inst(_inst), pkt(_pkt), lsqPtr(lsq_ptr)
49{
50    this->setFlags(Event::AutoDelete);
51}
52
53template<class Impl>
54void
55LSQUnit<Impl>::WritebackEvent::process()
56{
57    if (!lsqPtr->isSwitchedOut()) {
58        lsqPtr->writeback(inst, pkt);
59    }
60    delete pkt;
61}
62
63template<class Impl>
64const char *
65LSQUnit<Impl>::WritebackEvent::description()
66{
67    return "Store writeback event";
68}
69
70template<class Impl>
71void
72LSQUnit<Impl>::completeDataAccess(PacketPtr pkt)
73{
74    LSQSenderState *state = dynamic_cast<LSQSenderState *>(pkt->senderState);
75    DynInstPtr inst = state->inst;
76    DPRINTF(IEW, "Writeback event [sn:%lli]\n", inst->seqNum);
77    DPRINTF(Activity, "Activity: Writeback event [sn:%lli]\n", inst->seqNum);
78
79    //iewStage->ldstQueue.removeMSHR(inst->threadNumber,inst->seqNum);
80
81    if (isSwitchedOut() || inst->isSquashed()) {
82        iewStage->decrWb(inst->seqNum);
83        delete state;
84        delete pkt;
85        return;
86    } else {
87        if (!state->noWB) {
88            writeback(inst, pkt);
89        }
90
91        if (inst->isStore()) {
92            completeStore(state->idx);
93        }
94    }
95
96    delete state;
97    delete pkt;
98}
99
100template <class Impl>
101LSQUnit<Impl>::LSQUnit()
102    : loads(0), stores(0), storesToWB(0), stalled(false),
103      isStoreBlocked(false), isLoadBlocked(false),
104      loadBlockedHandled(false)
105{
106}
107
108template<class Impl>
109void
110LSQUnit<Impl>::init(Params *params, LSQ *lsq_ptr, unsigned maxLQEntries,
111                    unsigned maxSQEntries, unsigned id)
112{
113    DPRINTF(LSQUnit, "Creating LSQUnit%i object.\n",id);
114
115    switchedOut = false;
116
117    lsq = lsq_ptr;
118
119    lsqID = id;
120
121    // Add 1 for the sentinel entry (they are circular queues).
122    LQEntries = maxLQEntries + 1;
123    SQEntries = maxSQEntries + 1;
124
125    loadQueue.resize(LQEntries);
126    storeQueue.resize(SQEntries);
127
128    loadHead = loadTail = 0;
129
130    storeHead = storeWBIdx = storeTail = 0;
131
132    usedPorts = 0;
133    cachePorts = params->cachePorts;
134
135    retryPkt = NULL;
136    memDepViolator = NULL;
137
138    blockedLoadSeqNum = 0;
139}
140
141template<class Impl>
142void
143LSQUnit<Impl>::setCPU(O3CPU *cpu_ptr)
144{
145    cpu = cpu_ptr;
146
147#if USE_CHECKER
148    if (cpu->checker) {
149        cpu->checker->setDcachePort(dcachePort);
150    }
151#endif
152}
153
154template<class Impl>
155std::string
156LSQUnit<Impl>::name() const
157{
158    if (Impl::MaxThreads == 1) {
159        return iewStage->name() + ".lsq";
160    } else {
161        return iewStage->name() + ".lsq.thread." + to_string(lsqID);
162    }
163}
164
165template<class Impl>
166void
167LSQUnit<Impl>::regStats()
168{
169    lsqForwLoads
170        .name(name() + ".forwLoads")
171        .desc("Number of loads that had data forwarded from stores");
172
173    invAddrLoads
174        .name(name() + ".invAddrLoads")
175        .desc("Number of loads ignored due to an invalid address");
176
177    lsqSquashedLoads
178        .name(name() + ".squashedLoads")
179        .desc("Number of loads squashed");
180
181    lsqIgnoredResponses
182        .name(name() + ".ignoredResponses")
183        .desc("Number of memory responses ignored because the instruction is squashed");
184
185    lsqMemOrderViolation
186        .name(name() + ".memOrderViolation")
187        .desc("Number of memory ordering violations");
188
189    lsqSquashedStores
190        .name(name() + ".squashedStores")
191        .desc("Number of stores squashed");
192
193    invAddrSwpfs
194        .name(name() + ".invAddrSwpfs")
195        .desc("Number of software prefetches ignored due to an invalid address");
196
197    lsqBlockedLoads
198        .name(name() + ".blockedLoads")
199        .desc("Number of blocked loads due to partial load-store forwarding");
200
201    lsqRescheduledLoads
202        .name(name() + ".rescheduledLoads")
203        .desc("Number of loads that were rescheduled");
204
205    lsqCacheBlocked
206        .name(name() + ".cacheBlocked")
207        .desc("Number of times an access to memory failed due to the cache being blocked");
208}
209
210template<class Impl>
211void
212LSQUnit<Impl>::clearLQ()
213{
214    loadQueue.clear();
215}
216
217template<class Impl>
218void
219LSQUnit<Impl>::clearSQ()
220{
221    storeQueue.clear();
222}
223
224template<class Impl>
225void
226LSQUnit<Impl>::switchOut()
227{
228    switchedOut = true;
229    for (int i = 0; i < loadQueue.size(); ++i) {
230        assert(!loadQueue[i]);
231        loadQueue[i] = NULL;
232    }
233
234    assert(storesToWB == 0);
235}
236
237template<class Impl>
238void
239LSQUnit<Impl>::takeOverFrom()
240{
241    switchedOut = false;
242    loads = stores = storesToWB = 0;
243
244    loadHead = loadTail = 0;
245
246    storeHead = storeWBIdx = storeTail = 0;
247
248    usedPorts = 0;
249
250    memDepViolator = NULL;
251
252    blockedLoadSeqNum = 0;
253
254    stalled = false;
255    isLoadBlocked = false;
256    loadBlockedHandled = false;
257}
258
259template<class Impl>
260void
261LSQUnit<Impl>::resizeLQ(unsigned size)
262{
263    unsigned size_plus_sentinel = size + 1;
264    assert(size_plus_sentinel >= LQEntries);
265
266    if (size_plus_sentinel > LQEntries) {
267        while (size_plus_sentinel > loadQueue.size()) {
268            DynInstPtr dummy;
269            loadQueue.push_back(dummy);
270            LQEntries++;
271        }
272    } else {
273        LQEntries = size_plus_sentinel;
274    }
275
276}
277
278template<class Impl>
279void
280LSQUnit<Impl>::resizeSQ(unsigned size)
281{
282    unsigned size_plus_sentinel = size + 1;
283    if (size_plus_sentinel > SQEntries) {
284        while (size_plus_sentinel > storeQueue.size()) {
285            SQEntry dummy;
286            storeQueue.push_back(dummy);
287            SQEntries++;
288        }
289    } else {
290        SQEntries = size_plus_sentinel;
291    }
292}
293
294template <class Impl>
295void
296LSQUnit<Impl>::insert(DynInstPtr &inst)
297{
298    assert(inst->isMemRef());
299
300    assert(inst->isLoad() || inst->isStore());
301
302    if (inst->isLoad()) {
303        insertLoad(inst);
304    } else {
305        insertStore(inst);
306    }
307
308    inst->setInLSQ();
309}
310
311template <class Impl>
312void
313LSQUnit<Impl>::insertLoad(DynInstPtr &load_inst)
314{
315    assert((loadTail + 1) % LQEntries != loadHead);
316    assert(loads < LQEntries);
317
318    DPRINTF(LSQUnit, "Inserting load PC %#x, idx:%i [sn:%lli]\n",
319            load_inst->readPC(), loadTail, load_inst->seqNum);
320
321    load_inst->lqIdx = loadTail;
322
323    if (stores == 0) {
324        load_inst->sqIdx = -1;
325    } else {
326        load_inst->sqIdx = storeTail;
327    }
328
329    loadQueue[loadTail] = load_inst;
330
331    incrLdIdx(loadTail);
332
333    ++loads;
334}
335
336template <class Impl>
337void
338LSQUnit<Impl>::insertStore(DynInstPtr &store_inst)
339{
340    // Make sure it is not full before inserting an instruction.
341    assert((storeTail + 1) % SQEntries != storeHead);
342    assert(stores < SQEntries);
343
344    DPRINTF(LSQUnit, "Inserting store PC %#x, idx:%i [sn:%lli]\n",
345            store_inst->readPC(), storeTail, store_inst->seqNum);
346
347    store_inst->sqIdx = storeTail;
348    store_inst->lqIdx = loadTail;
349
350    storeQueue[storeTail] = SQEntry(store_inst);
351
352    incrStIdx(storeTail);
353
354    ++stores;
355}
356
357template <class Impl>
358typename Impl::DynInstPtr
359LSQUnit<Impl>::getMemDepViolator()
360{
361    DynInstPtr temp = memDepViolator;
362
363    memDepViolator = NULL;
364
365    return temp;
366}
367
368template <class Impl>
369unsigned
370LSQUnit<Impl>::numFreeEntries()
371{
372    unsigned free_lq_entries = LQEntries - loads;
373    unsigned free_sq_entries = SQEntries - stores;
374
375    // Both the LQ and SQ entries have an extra dummy entry to differentiate
376    // empty/full conditions.  Subtract 1 from the free entries.
377    if (free_lq_entries < free_sq_entries) {
378        return free_lq_entries - 1;
379    } else {
380        return free_sq_entries - 1;
381    }
382}
383
384template <class Impl>
385int
386LSQUnit<Impl>::numLoadsReady()
387{
388    int load_idx = loadHead;
389    int retval = 0;
390
391    while (load_idx != loadTail) {
392        assert(loadQueue[load_idx]);
393
394        if (loadQueue[load_idx]->readyToIssue()) {
395            ++retval;
396        }
397    }
398
399    return retval;
400}
401
402template <class Impl>
403Fault
404LSQUnit<Impl>::executeLoad(DynInstPtr &inst)
405{
406    // Execute a specific load.
407    Fault load_fault = NoFault;
408
409    DPRINTF(LSQUnit, "Executing load PC %#x, [sn:%lli]\n",
410            inst->readPC(),inst->seqNum);
411
412    load_fault = inst->initiateAcc();
413
414    // If the instruction faulted, then we need to send it along to commit
415    // without the instruction completing.
416    if (load_fault != NoFault) {
417        // Send this instruction to commit, also make sure iew stage
418        // realizes there is activity.
419        // Mark it as executed unless it is an uncached load that
420        // needs to hit the head of commit.
421        if (!(inst->req->isUncacheable()) || inst->isAtCommit()) {
422            inst->setExecuted();
423        }
424        iewStage->instToCommit(inst);
425        iewStage->activityThisCycle();
426    }
427
428    return load_fault;
429}
430
431template <class Impl>
432Fault
433LSQUnit<Impl>::executeStore(DynInstPtr &store_inst)
434{
435    using namespace TheISA;
436    // Make sure that a store exists.
437    assert(stores != 0);
438
439    int store_idx = store_inst->sqIdx;
440
441    DPRINTF(LSQUnit, "Executing store PC %#x [sn:%lli]\n",
442            store_inst->readPC(), store_inst->seqNum);
443
444    // Check the recently completed loads to see if any match this store's
445    // address.  If so, then we have a memory ordering violation.
446    int load_idx = store_inst->lqIdx;
447
448    Fault store_fault = store_inst->initiateAcc();
449
450    if (storeQueue[store_idx].size == 0) {
451        DPRINTF(LSQUnit,"Fault on Store PC %#x, [sn:%lli],Size = 0\n",
452                store_inst->readPC(),store_inst->seqNum);
453
454        return store_fault;
455    }
456
457    assert(store_fault == NoFault);
458
459    if (store_inst->isStoreConditional()) {
460        // Store conditionals need to set themselves as able to
461        // writeback if we haven't had a fault by here.
462        storeQueue[store_idx].canWB = true;
463
464        ++storesToWB;
465    }
466
467    if (!memDepViolator) {
468        while (load_idx != loadTail) {
469            // Really only need to check loads that have actually executed
470            // It's safe to check all loads because effAddr is set to
471            // InvalAddr when the dyn inst is created.
472
473            // @todo: For now this is extra conservative, detecting a
474            // violation if the addresses match assuming all accesses
475            // are quad word accesses.
476
477            // @todo: Fix this, magic number being used here
478            if ((loadQueue[load_idx]->effAddr >> 8) ==
479                (store_inst->effAddr >> 8)) {
480                // A load incorrectly passed this store.  Squash and refetch.
481                // For now return a fault to show that it was unsuccessful.
482                memDepViolator = loadQueue[load_idx];
483                ++lsqMemOrderViolation;
484
485                return genMachineCheckFault();
486            }
487
488            incrLdIdx(load_idx);
489        }
490
491        // If we've reached this point, there was no violation.
492        memDepViolator = NULL;
493    }
494
495    return store_fault;
496}
497
498template <class Impl>
499void
500LSQUnit<Impl>::commitLoad()
501{
502    assert(loadQueue[loadHead]);
503
504    DPRINTF(LSQUnit, "Committing head load instruction, PC %#x\n",
505            loadQueue[loadHead]->readPC());
506
507    loadQueue[loadHead] = NULL;
508
509    incrLdIdx(loadHead);
510
511    --loads;
512}
513
514template <class Impl>
515void
516LSQUnit<Impl>::commitLoads(InstSeqNum &youngest_inst)
517{
518    assert(loads == 0 || loadQueue[loadHead]);
519
520    while (loads != 0 && loadQueue[loadHead]->seqNum <= youngest_inst) {
521        commitLoad();
522    }
523}
524
525template <class Impl>
526void
527LSQUnit<Impl>::commitStores(InstSeqNum &youngest_inst)
528{
529    assert(stores == 0 || storeQueue[storeHead].inst);
530
531    int store_idx = storeHead;
532
533    while (store_idx != storeTail) {
534        assert(storeQueue[store_idx].inst);
535        // Mark any stores that are now committed and have not yet
536        // been marked as able to write back.
537        if (!storeQueue[store_idx].canWB) {
538            if (storeQueue[store_idx].inst->seqNum > youngest_inst) {
539                break;
540            }
541            DPRINTF(LSQUnit, "Marking store as able to write back, PC "
542                    "%#x [sn:%lli]\n",
543                    storeQueue[store_idx].inst->readPC(),
544                    storeQueue[store_idx].inst->seqNum);
545
546            storeQueue[store_idx].canWB = true;
547
548            ++storesToWB;
549        }
550
551        incrStIdx(store_idx);
552    }
553}
554
555template <class Impl>
556void
557LSQUnit<Impl>::writebackStores()
558{
559    while (storesToWB > 0 &&
560           storeWBIdx != storeTail &&
561           storeQueue[storeWBIdx].inst &&
562           storeQueue[storeWBIdx].canWB &&
563           usedPorts < cachePorts) {
564
565        if (isStoreBlocked || lsq->cacheBlocked()) {
566            DPRINTF(LSQUnit, "Unable to write back any more stores, cache"
567                    " is blocked!\n");
568            break;
569        }
570
571        // Store didn't write any data so no need to write it back to
572        // memory.
573        if (storeQueue[storeWBIdx].size == 0) {
574            completeStore(storeWBIdx);
575
576            incrStIdx(storeWBIdx);
577
578            continue;
579        }
580
581        ++usedPorts;
582
583        if (storeQueue[storeWBIdx].inst->isDataPrefetch()) {
584            incrStIdx(storeWBIdx);
585
586            continue;
587        }
588
589        assert(storeQueue[storeWBIdx].req);
590        assert(!storeQueue[storeWBIdx].committed);
591
592        DynInstPtr inst = storeQueue[storeWBIdx].inst;
593
594        Request *req = storeQueue[storeWBIdx].req;
595        storeQueue[storeWBIdx].committed = true;
596
597        assert(!inst->memData);
598        inst->memData = new uint8_t[64];
599
600        TheISA::IntReg convertedData =
601            TheISA::htog(storeQueue[storeWBIdx].data);
602
603        memcpy(inst->memData, (uint8_t *)&convertedData,
604               req->getSize());
605
606        PacketPtr data_pkt = new Packet(req, Packet::WriteReq, Packet::Broadcast);
607        data_pkt->dataStatic(inst->memData);
608
609        LSQSenderState *state = new LSQSenderState;
610        state->isLoad = false;
611        state->idx = storeWBIdx;
612        state->inst = inst;
613        data_pkt->senderState = state;
614
615        DPRINTF(LSQUnit, "D-Cache: Writing back store idx:%i PC:%#x "
616                "to Addr:%#x, data:%#x [sn:%lli]\n",
617                storeWBIdx, inst->readPC(),
618                req->getPaddr(), *(inst->memData),
619                inst->seqNum);
620
621        // @todo: Remove this SC hack once the memory system handles it.
622        if (req->isLocked()) {
623            // Disable recording the result temporarily.  Writing to
624            // misc regs normally updates the result, but this is not
625            // the desired behavior when handling store conditionals.
626            inst->recordResult = false;
627            bool success = TheISA::handleLockedWrite(inst.get(), req);
628            inst->recordResult = true;
629
630            if (!success) {
631                // Instantly complete this store.
632                DPRINTF(LSQUnit, "Store conditional [sn:%lli] failed.  "
633                        "Instantly completing it.\n",
634                        inst->seqNum);
635                WritebackEvent *wb = new WritebackEvent(inst, data_pkt, this);
636                wb->schedule(curTick + 1);
637                delete state;
638                completeStore(storeWBIdx);
639                incrStIdx(storeWBIdx);
640                continue;
641            }
642        } else {
643            // Non-store conditionals do not need a writeback.
644            state->noWB = true;
645        }
646
647        if (!dcachePort->sendTiming(data_pkt)) {
648            if (data_pkt->result == Packet::BadAddress) {
649                panic("LSQ sent out a bad address for a completed store!");
650            }
651            // Need to handle becoming blocked on a store.
652            DPRINTF(IEW, "D-Cache became blcoked when writing [sn:%lli], will"
653                    "retry later\n",
654                    inst->seqNum);
655            isStoreBlocked = true;
656            ++lsqCacheBlocked;
657            assert(retryPkt == NULL);
658            retryPkt = data_pkt;
659            lsq->setRetryTid(lsqID);
660        } else {
661            storePostSend(data_pkt);
662        }
663    }
664
665    // Not sure this should set it to 0.
666    usedPorts = 0;
667
668    assert(stores >= 0 && storesToWB >= 0);
669}
670
671/*template <class Impl>
672void
673LSQUnit<Impl>::removeMSHR(InstSeqNum seqNum)
674{
675    list<InstSeqNum>::iterator mshr_it = find(mshrSeqNums.begin(),
676                                              mshrSeqNums.end(),
677                                              seqNum);
678
679    if (mshr_it != mshrSeqNums.end()) {
680        mshrSeqNums.erase(mshr_it);
681        DPRINTF(LSQUnit, "Removing MSHR. count = %i\n",mshrSeqNums.size());
682    }
683}*/
684
685template <class Impl>
686void
687LSQUnit<Impl>::squash(const InstSeqNum &squashed_num)
688{
689    DPRINTF(LSQUnit, "Squashing until [sn:%lli]!"
690            "(Loads:%i Stores:%i)\n", squashed_num, loads, stores);
691
692    int load_idx = loadTail;
693    decrLdIdx(load_idx);
694
695    while (loads != 0 && loadQueue[load_idx]->seqNum > squashed_num) {
696        DPRINTF(LSQUnit,"Load Instruction PC %#x squashed, "
697                "[sn:%lli]\n",
698                loadQueue[load_idx]->readPC(),
699                loadQueue[load_idx]->seqNum);
700
701        if (isStalled() && load_idx == stallingLoadIdx) {
702            stalled = false;
703            stallingStoreIsn = 0;
704            stallingLoadIdx = 0;
705        }
706
707        // Clear the smart pointer to make sure it is decremented.
708        loadQueue[load_idx]->setSquashed();
709        loadQueue[load_idx] = NULL;
710        --loads;
711
712        // Inefficient!
713        loadTail = load_idx;
714
715        decrLdIdx(load_idx);
716        ++lsqSquashedLoads;
717    }
718
719    if (isLoadBlocked) {
720        if (squashed_num < blockedLoadSeqNum) {
721            isLoadBlocked = false;
722            loadBlockedHandled = false;
723            blockedLoadSeqNum = 0;
724        }
725    }
726
727    int store_idx = storeTail;
728    decrStIdx(store_idx);
729
730    while (stores != 0 &&
731           storeQueue[store_idx].inst->seqNum > squashed_num) {
732        // Instructions marked as can WB are already committed.
733        if (storeQueue[store_idx].canWB) {
734            break;
735        }
736
737        DPRINTF(LSQUnit,"Store Instruction PC %#x squashed, "
738                "idx:%i [sn:%lli]\n",
739                storeQueue[store_idx].inst->readPC(),
740                store_idx, storeQueue[store_idx].inst->seqNum);
741
742        // I don't think this can happen.  It should have been cleared
743        // by the stalling load.
744        if (isStalled() &&
745            storeQueue[store_idx].inst->seqNum == stallingStoreIsn) {
746            panic("Is stalled should have been cleared by stalling load!\n");
747            stalled = false;
748            stallingStoreIsn = 0;
749        }
750
751        // Clear the smart pointer to make sure it is decremented.
752        storeQueue[store_idx].inst->setSquashed();
753        storeQueue[store_idx].inst = NULL;
754        storeQueue[store_idx].canWB = 0;
755
756        storeQueue[store_idx].req = NULL;
757        --stores;
758
759        // Inefficient!
760        storeTail = store_idx;
761
762        decrStIdx(store_idx);
763        ++lsqSquashedStores;
764    }
765}
766
767template <class Impl>
768void
769LSQUnit<Impl>::storePostSend(PacketPtr pkt)
770{
771    if (isStalled() &&
772        storeQueue[storeWBIdx].inst->seqNum == stallingStoreIsn) {
773        DPRINTF(LSQUnit, "Unstalling, stalling store [sn:%lli] "
774                "load idx:%i\n",
775                stallingStoreIsn, stallingLoadIdx);
776        stalled = false;
777        stallingStoreIsn = 0;
778        iewStage->replayMemInst(loadQueue[stallingLoadIdx]);
779    }
780
781    if (!storeQueue[storeWBIdx].inst->isStoreConditional()) {
782        // The store is basically completed at this time. This
783        // only works so long as the checker doesn't try to
784        // verify the value in memory for stores.
785        storeQueue[storeWBIdx].inst->setCompleted();
786#if USE_CHECKER
787        if (cpu->checker) {
788            cpu->checker->verify(storeQueue[storeWBIdx].inst);
789        }
790#endif
791    }
792
793    if (pkt->result != Packet::Success) {
794        DPRINTF(LSQUnit,"D-Cache Write Miss on idx:%i!\n",
795                storeWBIdx);
796
797        DPRINTF(Activity, "Active st accessing mem miss [sn:%lli]\n",
798                storeQueue[storeWBIdx].inst->seqNum);
799
800        //mshrSeqNums.push_back(storeQueue[storeWBIdx].inst->seqNum);
801
802        //DPRINTF(LSQUnit, "Added MSHR. count = %i\n",mshrSeqNums.size());
803
804        // @todo: Increment stat here.
805    } else {
806        DPRINTF(LSQUnit,"D-Cache: Write Hit on idx:%i !\n",
807                storeWBIdx);
808
809        DPRINTF(Activity, "Active st accessing mem hit [sn:%lli]\n",
810                storeQueue[storeWBIdx].inst->seqNum);
811    }
812
813    incrStIdx(storeWBIdx);
814}
815
816template <class Impl>
817void
818LSQUnit<Impl>::writeback(DynInstPtr &inst, PacketPtr pkt)
819{
820    iewStage->wakeCPU();
821
822    // Squashed instructions do not need to complete their access.
823    if (inst->isSquashed()) {
824        iewStage->decrWb(inst->seqNum);
825        assert(!inst->isStore());
826        ++lsqIgnoredResponses;
827        return;
828    }
829
830    if (!inst->isExecuted()) {
831        inst->setExecuted();
832
833        // Complete access to copy data to proper place.
834        inst->completeAcc(pkt);
835    }
836
837    // Need to insert instruction into queue to commit
838    iewStage->instToCommit(inst);
839
840    iewStage->activityThisCycle();
841}
842
843template <class Impl>
844void
845LSQUnit<Impl>::completeStore(int store_idx)
846{
847    assert(storeQueue[store_idx].inst);
848    storeQueue[store_idx].completed = true;
849    --storesToWB;
850    // A bit conservative because a store completion may not free up entries,
851    // but hopefully avoids two store completions in one cycle from making
852    // the CPU tick twice.
853    cpu->wakeCPU();
854    cpu->activityThisCycle();
855
856    if (store_idx == storeHead) {
857        do {
858            incrStIdx(storeHead);
859
860            --stores;
861        } while (storeQueue[storeHead].completed &&
862                 storeHead != storeTail);
863
864        iewStage->updateLSQNextCycle = true;
865    }
866
867    DPRINTF(LSQUnit, "Completing store [sn:%lli], idx:%i, store head "
868            "idx:%i\n",
869            storeQueue[store_idx].inst->seqNum, store_idx, storeHead);
870
871    if (isStalled() &&
872        storeQueue[store_idx].inst->seqNum == stallingStoreIsn) {
873        DPRINTF(LSQUnit, "Unstalling, stalling store [sn:%lli] "
874                "load idx:%i\n",
875                stallingStoreIsn, stallingLoadIdx);
876        stalled = false;
877        stallingStoreIsn = 0;
878        iewStage->replayMemInst(loadQueue[stallingLoadIdx]);
879    }
880
881    storeQueue[store_idx].inst->setCompleted();
882
883    // Tell the checker we've completed this instruction.  Some stores
884    // may get reported twice to the checker, but the checker can
885    // handle that case.
886#if USE_CHECKER
887    if (cpu->checker) {
888        cpu->checker->verify(storeQueue[store_idx].inst);
889    }
890#endif
891}
892
893template <class Impl>
894void
895LSQUnit<Impl>::recvRetry()
896{
897    if (isStoreBlocked) {
898        assert(retryPkt != NULL);
899
900        if (dcachePort->sendTiming(retryPkt)) {
901            if (retryPkt->result == Packet::BadAddress) {
902                panic("LSQ sent out a bad address for a completed store!");
903            }
904            storePostSend(retryPkt);
905            retryPkt = NULL;
906            isStoreBlocked = false;
907            lsq->setRetryTid(-1);
908        } else {
909            // Still blocked!
910            ++lsqCacheBlocked;
911            lsq->setRetryTid(lsqID);
912        }
913    } else if (isLoadBlocked) {
914        DPRINTF(LSQUnit, "Loads squash themselves and all younger insts, "
915                "no need to resend packet.\n");
916    } else {
917        DPRINTF(LSQUnit, "Retry received but LSQ is no longer blocked.\n");
918    }
919}
920
921template <class Impl>
922inline void
923LSQUnit<Impl>::incrStIdx(int &store_idx)
924{
925    if (++store_idx >= SQEntries)
926        store_idx = 0;
927}
928
929template <class Impl>
930inline void
931LSQUnit<Impl>::decrStIdx(int &store_idx)
932{
933    if (--store_idx < 0)
934        store_idx += SQEntries;
935}
936
937template <class Impl>
938inline void
939LSQUnit<Impl>::incrLdIdx(int &load_idx)
940{
941    if (++load_idx >= LQEntries)
942        load_idx = 0;
943}
944
945template <class Impl>
946inline void
947LSQUnit<Impl>::decrLdIdx(int &load_idx)
948{
949    if (--load_idx < 0)
950        load_idx += LQEntries;
951}
952
953template <class Impl>
954void
955LSQUnit<Impl>::dumpInsts()
956{
957    cprintf("Load store queue: Dumping instructions.\n");
958    cprintf("Load queue size: %i\n", loads);
959    cprintf("Load queue: ");
960
961    int load_idx = loadHead;
962
963    while (load_idx != loadTail && loadQueue[load_idx]) {
964        cprintf("%#x ", loadQueue[load_idx]->readPC());
965
966        incrLdIdx(load_idx);
967    }
968
969    cprintf("Store queue size: %i\n", stores);
970    cprintf("Store queue: ");
971
972    int store_idx = storeHead;
973
974    while (store_idx != storeTail && storeQueue[store_idx].inst) {
975        cprintf("%#x ", storeQueue[store_idx].inst->readPC());
976
977        incrStIdx(store_idx);
978    }
979
980    cprintf("\n");
981}
982