lsq_unit_impl.hh revision 8481
1/*
2 * Copyright (c) 2010 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-2005 The Regents of The University of Michigan
15 * All rights reserved.
16 *
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions are
19 * met: redistributions of source code must retain the above copyright
20 * notice, this list of conditions and the following disclaimer;
21 * redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in the
23 * documentation and/or other materials provided with the distribution;
24 * neither the name of the copyright holders nor the names of its
25 * contributors may be used to endorse or promote products derived from
26 * this software without specific prior written permission.
27 *
28 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
31 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
33 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
34 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
38 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 *
40 * Authors: Kevin Lim
41 *          Korey Sewell
42 */
43
44#include "arch/locked_mem.hh"
45#include "base/str.hh"
46#include "config/the_isa.hh"
47#include "config/use_checker.hh"
48#include "cpu/o3/lsq.hh"
49#include "cpu/o3/lsq_unit.hh"
50#include "debug/Activity.hh"
51#include "debug/IEW.hh"
52#include "debug/LSQUnit.hh"
53#include "mem/packet.hh"
54#include "mem/request.hh"
55
56#if USE_CHECKER
57#include "cpu/checker/cpu.hh"
58#endif
59
60template<class Impl>
61LSQUnit<Impl>::WritebackEvent::WritebackEvent(DynInstPtr &_inst, PacketPtr _pkt,
62                                              LSQUnit *lsq_ptr)
63    : inst(_inst), pkt(_pkt), lsqPtr(lsq_ptr)
64{
65    this->setFlags(Event::AutoDelete);
66}
67
68template<class Impl>
69void
70LSQUnit<Impl>::WritebackEvent::process()
71{
72    if (!lsqPtr->isSwitchedOut()) {
73        lsqPtr->writeback(inst, pkt);
74    }
75
76    if (pkt->senderState)
77        delete pkt->senderState;
78
79    delete pkt->req;
80    delete pkt;
81}
82
83template<class Impl>
84const char *
85LSQUnit<Impl>::WritebackEvent::description() const
86{
87    return "Store writeback";
88}
89
90template<class Impl>
91void
92LSQUnit<Impl>::completeDataAccess(PacketPtr pkt)
93{
94    LSQSenderState *state = dynamic_cast<LSQSenderState *>(pkt->senderState);
95    DynInstPtr inst = state->inst;
96    DPRINTF(IEW, "Writeback event [sn:%lli].\n", inst->seqNum);
97    DPRINTF(Activity, "Activity: Writeback event [sn:%lli].\n", inst->seqNum);
98
99    //iewStage->ldstQueue.removeMSHR(inst->threadNumber,inst->seqNum);
100
101    assert(!pkt->wasNacked());
102
103    // If this is a split access, wait until all packets are received.
104    if (TheISA::HasUnalignedMemAcc && !state->complete()) {
105        delete pkt->req;
106        delete pkt;
107        return;
108    }
109
110    if (isSwitchedOut() || inst->isSquashed()) {
111        iewStage->decrWb(inst->seqNum);
112    } else {
113        if (!state->noWB) {
114            if (!TheISA::HasUnalignedMemAcc || !state->isSplit ||
115                !state->isLoad) {
116                writeback(inst, pkt);
117            } else {
118                writeback(inst, state->mainPkt);
119            }
120        }
121
122        if (inst->isStore()) {
123            completeStore(state->idx);
124        }
125    }
126
127    if (TheISA::HasUnalignedMemAcc && state->isSplit && state->isLoad) {
128        delete state->mainPkt->req;
129        delete state->mainPkt;
130    }
131    delete state;
132    delete pkt->req;
133    delete pkt;
134}
135
136template <class Impl>
137LSQUnit<Impl>::LSQUnit()
138    : loads(0), stores(0), storesToWB(0), stalled(false),
139      isStoreBlocked(false), isLoadBlocked(false),
140      loadBlockedHandled(false), hasPendingPkt(false)
141{
142}
143
144template<class Impl>
145void
146LSQUnit<Impl>::init(O3CPU *cpu_ptr, IEW *iew_ptr, DerivO3CPUParams *params,
147        LSQ *lsq_ptr, unsigned maxLQEntries, unsigned maxSQEntries,
148        unsigned id)
149{
150    cpu = cpu_ptr;
151    iewStage = iew_ptr;
152
153    DPRINTF(LSQUnit, "Creating LSQUnit%i object.\n",id);
154
155    switchedOut = false;
156
157    lsq = lsq_ptr;
158
159    lsqID = id;
160
161    // Add 1 for the sentinel entry (they are circular queues).
162    LQEntries = maxLQEntries + 1;
163    SQEntries = maxSQEntries + 1;
164
165    loadQueue.resize(LQEntries);
166    storeQueue.resize(SQEntries);
167
168    depCheckShift = params->LSQDepCheckShift;
169    checkLoads = params->LSQCheckLoads;
170
171    loadHead = loadTail = 0;
172
173    storeHead = storeWBIdx = storeTail = 0;
174
175    usedPorts = 0;
176    cachePorts = params->cachePorts;
177
178    retryPkt = NULL;
179    memDepViolator = NULL;
180
181    blockedLoadSeqNum = 0;
182}
183
184template<class Impl>
185std::string
186LSQUnit<Impl>::name() const
187{
188    if (Impl::MaxThreads == 1) {
189        return iewStage->name() + ".lsq";
190    } else {
191        return iewStage->name() + ".lsq.thread" + to_string(lsqID);
192    }
193}
194
195template<class Impl>
196void
197LSQUnit<Impl>::regStats()
198{
199    lsqForwLoads
200        .name(name() + ".forwLoads")
201        .desc("Number of loads that had data forwarded from stores");
202
203    invAddrLoads
204        .name(name() + ".invAddrLoads")
205        .desc("Number of loads ignored due to an invalid address");
206
207    lsqSquashedLoads
208        .name(name() + ".squashedLoads")
209        .desc("Number of loads squashed");
210
211    lsqIgnoredResponses
212        .name(name() + ".ignoredResponses")
213        .desc("Number of memory responses ignored because the instruction is squashed");
214
215    lsqMemOrderViolation
216        .name(name() + ".memOrderViolation")
217        .desc("Number of memory ordering violations");
218
219    lsqSquashedStores
220        .name(name() + ".squashedStores")
221        .desc("Number of stores squashed");
222
223    invAddrSwpfs
224        .name(name() + ".invAddrSwpfs")
225        .desc("Number of software prefetches ignored due to an invalid address");
226
227    lsqBlockedLoads
228        .name(name() + ".blockedLoads")
229        .desc("Number of blocked loads due to partial load-store forwarding");
230
231    lsqRescheduledLoads
232        .name(name() + ".rescheduledLoads")
233        .desc("Number of loads that were rescheduled");
234
235    lsqCacheBlocked
236        .name(name() + ".cacheBlocked")
237        .desc("Number of times an access to memory failed due to the cache being blocked");
238}
239
240template<class Impl>
241void
242LSQUnit<Impl>::setDcachePort(Port *dcache_port)
243{
244    dcachePort = dcache_port;
245
246#if USE_CHECKER
247    if (cpu->checker) {
248        cpu->checker->setDcachePort(dcachePort);
249    }
250#endif
251}
252
253template<class Impl>
254void
255LSQUnit<Impl>::clearLQ()
256{
257    loadQueue.clear();
258}
259
260template<class Impl>
261void
262LSQUnit<Impl>::clearSQ()
263{
264    storeQueue.clear();
265}
266
267template<class Impl>
268void
269LSQUnit<Impl>::switchOut()
270{
271    switchedOut = true;
272    for (int i = 0; i < loadQueue.size(); ++i) {
273        assert(!loadQueue[i]);
274        loadQueue[i] = NULL;
275    }
276
277    assert(storesToWB == 0);
278}
279
280template<class Impl>
281void
282LSQUnit<Impl>::takeOverFrom()
283{
284    switchedOut = false;
285    loads = stores = storesToWB = 0;
286
287    loadHead = loadTail = 0;
288
289    storeHead = storeWBIdx = storeTail = 0;
290
291    usedPorts = 0;
292
293    memDepViolator = NULL;
294
295    blockedLoadSeqNum = 0;
296
297    stalled = false;
298    isLoadBlocked = false;
299    loadBlockedHandled = false;
300}
301
302template<class Impl>
303void
304LSQUnit<Impl>::resizeLQ(unsigned size)
305{
306    unsigned size_plus_sentinel = size + 1;
307    assert(size_plus_sentinel >= LQEntries);
308
309    if (size_plus_sentinel > LQEntries) {
310        while (size_plus_sentinel > loadQueue.size()) {
311            DynInstPtr dummy;
312            loadQueue.push_back(dummy);
313            LQEntries++;
314        }
315    } else {
316        LQEntries = size_plus_sentinel;
317    }
318
319}
320
321template<class Impl>
322void
323LSQUnit<Impl>::resizeSQ(unsigned size)
324{
325    unsigned size_plus_sentinel = size + 1;
326    if (size_plus_sentinel > SQEntries) {
327        while (size_plus_sentinel > storeQueue.size()) {
328            SQEntry dummy;
329            storeQueue.push_back(dummy);
330            SQEntries++;
331        }
332    } else {
333        SQEntries = size_plus_sentinel;
334    }
335}
336
337template <class Impl>
338void
339LSQUnit<Impl>::insert(DynInstPtr &inst)
340{
341    assert(inst->isMemRef());
342
343    assert(inst->isLoad() || inst->isStore());
344
345    if (inst->isLoad()) {
346        insertLoad(inst);
347    } else {
348        insertStore(inst);
349    }
350
351    inst->setInLSQ();
352}
353
354template <class Impl>
355void
356LSQUnit<Impl>::insertLoad(DynInstPtr &load_inst)
357{
358    assert((loadTail + 1) % LQEntries != loadHead);
359    assert(loads < LQEntries);
360
361    DPRINTF(LSQUnit, "Inserting load PC %s, idx:%i [sn:%lli]\n",
362            load_inst->pcState(), loadTail, load_inst->seqNum);
363
364    load_inst->lqIdx = loadTail;
365
366    if (stores == 0) {
367        load_inst->sqIdx = -1;
368    } else {
369        load_inst->sqIdx = storeTail;
370    }
371
372    loadQueue[loadTail] = load_inst;
373
374    incrLdIdx(loadTail);
375
376    ++loads;
377}
378
379template <class Impl>
380void
381LSQUnit<Impl>::insertStore(DynInstPtr &store_inst)
382{
383    // Make sure it is not full before inserting an instruction.
384    assert((storeTail + 1) % SQEntries != storeHead);
385    assert(stores < SQEntries);
386
387    DPRINTF(LSQUnit, "Inserting store PC %s, idx:%i [sn:%lli]\n",
388            store_inst->pcState(), storeTail, store_inst->seqNum);
389
390    store_inst->sqIdx = storeTail;
391    store_inst->lqIdx = loadTail;
392
393    storeQueue[storeTail] = SQEntry(store_inst);
394
395    incrStIdx(storeTail);
396
397    ++stores;
398}
399
400template <class Impl>
401typename Impl::DynInstPtr
402LSQUnit<Impl>::getMemDepViolator()
403{
404    DynInstPtr temp = memDepViolator;
405
406    memDepViolator = NULL;
407
408    return temp;
409}
410
411template <class Impl>
412unsigned
413LSQUnit<Impl>::numFreeEntries()
414{
415    unsigned free_lq_entries = LQEntries - loads;
416    unsigned free_sq_entries = SQEntries - stores;
417
418    // Both the LQ and SQ entries have an extra dummy entry to differentiate
419    // empty/full conditions.  Subtract 1 from the free entries.
420    if (free_lq_entries < free_sq_entries) {
421        return free_lq_entries - 1;
422    } else {
423        return free_sq_entries - 1;
424    }
425}
426
427template <class Impl>
428int
429LSQUnit<Impl>::numLoadsReady()
430{
431    int load_idx = loadHead;
432    int retval = 0;
433
434    while (load_idx != loadTail) {
435        assert(loadQueue[load_idx]);
436
437        if (loadQueue[load_idx]->readyToIssue()) {
438            ++retval;
439        }
440    }
441
442    return retval;
443}
444
445template <class Impl>
446Fault
447LSQUnit<Impl>::checkViolations(int load_idx, DynInstPtr &inst)
448{
449    Addr inst_eff_addr1 = inst->effAddr >> depCheckShift;
450    Addr inst_eff_addr2 = (inst->effAddr + inst->effSize - 1) >> depCheckShift;
451
452    /** @todo in theory you only need to check an instruction that has executed
453     * however, there isn't a good way in the pipeline at the moment to check
454     * all instructions that will execute before the store writes back. Thus,
455     * like the implementation that came before it, we're overly conservative.
456     */
457    while (load_idx != loadTail) {
458        DynInstPtr ld_inst = loadQueue[load_idx];
459        if (!ld_inst->effAddrValid || ld_inst->uncacheable()) {
460            incrLdIdx(load_idx);
461            continue;
462        }
463
464        Addr ld_eff_addr1 = ld_inst->effAddr >> depCheckShift;
465        Addr ld_eff_addr2 =
466            (ld_inst->effAddr + ld_inst->effSize - 1) >> depCheckShift;
467
468        if (inst_eff_addr2 >= ld_eff_addr1 && inst_eff_addr1 <= ld_eff_addr2) {
469            // A load/store incorrectly passed this load/store.
470            // Check if we already have a violator, or if it's newer
471            // squash and refetch.
472            if (memDepViolator && ld_inst->seqNum > memDepViolator->seqNum)
473                break;
474
475            DPRINTF(LSQUnit, "Detected fault with inst [sn:%lli] and [sn:%lli]"
476                    " at address %#x\n", inst->seqNum, ld_inst->seqNum,
477                    ld_eff_addr1);
478            memDepViolator = ld_inst;
479
480            ++lsqMemOrderViolation;
481
482            return TheISA::genMachineCheckFault();
483        }
484
485        incrLdIdx(load_idx);
486    }
487    return NoFault;
488}
489
490
491
492
493template <class Impl>
494Fault
495LSQUnit<Impl>::executeLoad(DynInstPtr &inst)
496{
497    using namespace TheISA;
498    // Execute a specific load.
499    Fault load_fault = NoFault;
500
501    DPRINTF(LSQUnit, "Executing load PC %s, [sn:%lli]\n",
502            inst->pcState(), inst->seqNum);
503
504    assert(!inst->isSquashed());
505
506    load_fault = inst->initiateAcc();
507
508    if (inst->isTranslationDelayed() &&
509        load_fault == NoFault)
510        return load_fault;
511
512    // If the instruction faulted or predicated false, then we need to send it
513    // along to commit without the instruction completing.
514    if (load_fault != NoFault || inst->readPredicate() == false) {
515        // Send this instruction to commit, also make sure iew stage
516        // realizes there is activity.
517        // Mark it as executed unless it is an uncached load that
518        // needs to hit the head of commit.
519        if (inst->readPredicate() == false)
520            inst->forwardOldRegs();
521        DPRINTF(LSQUnit, "Load [sn:%lli] not executed from %s\n",
522                inst->seqNum,
523                (load_fault != NoFault ? "fault" : "predication"));
524        if (!(inst->hasRequest() && inst->uncacheable()) ||
525            inst->isAtCommit()) {
526            inst->setExecuted();
527        }
528        iewStage->instToCommit(inst);
529        iewStage->activityThisCycle();
530    } else if (!loadBlocked()) {
531        assert(inst->effAddrValid);
532        int load_idx = inst->lqIdx;
533        incrLdIdx(load_idx);
534
535        if (checkLoads)
536            return checkViolations(load_idx, inst);
537    }
538
539    return load_fault;
540}
541
542template <class Impl>
543Fault
544LSQUnit<Impl>::executeStore(DynInstPtr &store_inst)
545{
546    using namespace TheISA;
547    // Make sure that a store exists.
548    assert(stores != 0);
549
550    int store_idx = store_inst->sqIdx;
551
552    DPRINTF(LSQUnit, "Executing store PC %s [sn:%lli]\n",
553            store_inst->pcState(), store_inst->seqNum);
554
555    assert(!store_inst->isSquashed());
556
557    // Check the recently completed loads to see if any match this store's
558    // address.  If so, then we have a memory ordering violation.
559    int load_idx = store_inst->lqIdx;
560
561    Fault store_fault = store_inst->initiateAcc();
562
563    if (store_inst->isTranslationDelayed() &&
564        store_fault == NoFault)
565        return store_fault;
566
567    if (store_inst->readPredicate() == false)
568        store_inst->forwardOldRegs();
569
570    if (storeQueue[store_idx].size == 0) {
571        DPRINTF(LSQUnit,"Fault on Store PC %s, [sn:%lli], Size = 0\n",
572                store_inst->pcState(), store_inst->seqNum);
573
574        return store_fault;
575    } else if (store_inst->readPredicate() == false) {
576        DPRINTF(LSQUnit, "Store [sn:%lli] not executed from predication\n",
577                store_inst->seqNum);
578        return store_fault;
579    }
580
581    assert(store_fault == NoFault);
582
583    if (store_inst->isStoreConditional()) {
584        // Store conditionals need to set themselves as able to
585        // writeback if we haven't had a fault by here.
586        storeQueue[store_idx].canWB = true;
587
588        ++storesToWB;
589    }
590
591    return checkViolations(load_idx, store_inst);
592
593}
594
595template <class Impl>
596void
597LSQUnit<Impl>::commitLoad()
598{
599    assert(loadQueue[loadHead]);
600
601    DPRINTF(LSQUnit, "Committing head load instruction, PC %s\n",
602            loadQueue[loadHead]->pcState());
603
604    loadQueue[loadHead] = NULL;
605
606    incrLdIdx(loadHead);
607
608    --loads;
609}
610
611template <class Impl>
612void
613LSQUnit<Impl>::commitLoads(InstSeqNum &youngest_inst)
614{
615    assert(loads == 0 || loadQueue[loadHead]);
616
617    while (loads != 0 && loadQueue[loadHead]->seqNum <= youngest_inst) {
618        commitLoad();
619    }
620}
621
622template <class Impl>
623void
624LSQUnit<Impl>::commitStores(InstSeqNum &youngest_inst)
625{
626    assert(stores == 0 || storeQueue[storeHead].inst);
627
628    int store_idx = storeHead;
629
630    while (store_idx != storeTail) {
631        assert(storeQueue[store_idx].inst);
632        // Mark any stores that are now committed and have not yet
633        // been marked as able to write back.
634        if (!storeQueue[store_idx].canWB) {
635            if (storeQueue[store_idx].inst->seqNum > youngest_inst) {
636                break;
637            }
638            DPRINTF(LSQUnit, "Marking store as able to write back, PC "
639                    "%s [sn:%lli]\n",
640                    storeQueue[store_idx].inst->pcState(),
641                    storeQueue[store_idx].inst->seqNum);
642
643            storeQueue[store_idx].canWB = true;
644
645            ++storesToWB;
646        }
647
648        incrStIdx(store_idx);
649    }
650}
651
652template <class Impl>
653void
654LSQUnit<Impl>::writebackPendingStore()
655{
656    if (hasPendingPkt) {
657        assert(pendingPkt != NULL);
658
659        // If the cache is blocked, this will store the packet for retry.
660        if (sendStore(pendingPkt)) {
661            storePostSend(pendingPkt);
662        }
663        pendingPkt = NULL;
664        hasPendingPkt = false;
665    }
666}
667
668template <class Impl>
669void
670LSQUnit<Impl>::writebackStores()
671{
672    // First writeback the second packet from any split store that didn't
673    // complete last cycle because there weren't enough cache ports available.
674    if (TheISA::HasUnalignedMemAcc) {
675        writebackPendingStore();
676    }
677
678    while (storesToWB > 0 &&
679           storeWBIdx != storeTail &&
680           storeQueue[storeWBIdx].inst &&
681           storeQueue[storeWBIdx].canWB &&
682           usedPorts < cachePorts) {
683
684        if (isStoreBlocked || lsq->cacheBlocked()) {
685            DPRINTF(LSQUnit, "Unable to write back any more stores, cache"
686                    " is blocked!\n");
687            break;
688        }
689
690        // Store didn't write any data so no need to write it back to
691        // memory.
692        if (storeQueue[storeWBIdx].size == 0) {
693            completeStore(storeWBIdx);
694
695            incrStIdx(storeWBIdx);
696
697            continue;
698        }
699
700        ++usedPorts;
701
702        if (storeQueue[storeWBIdx].inst->isDataPrefetch()) {
703            incrStIdx(storeWBIdx);
704
705            continue;
706        }
707
708        assert(storeQueue[storeWBIdx].req);
709        assert(!storeQueue[storeWBIdx].committed);
710
711        if (TheISA::HasUnalignedMemAcc && storeQueue[storeWBIdx].isSplit) {
712            assert(storeQueue[storeWBIdx].sreqLow);
713            assert(storeQueue[storeWBIdx].sreqHigh);
714        }
715
716        DynInstPtr inst = storeQueue[storeWBIdx].inst;
717
718        Request *req = storeQueue[storeWBIdx].req;
719        RequestPtr sreqLow = storeQueue[storeWBIdx].sreqLow;
720        RequestPtr sreqHigh = storeQueue[storeWBIdx].sreqHigh;
721
722        storeQueue[storeWBIdx].committed = true;
723
724        assert(!inst->memData);
725        inst->memData = new uint8_t[64];
726
727        memcpy(inst->memData, storeQueue[storeWBIdx].data, req->getSize());
728
729        MemCmd command =
730            req->isSwap() ? MemCmd::SwapReq :
731            (req->isLLSC() ? MemCmd::StoreCondReq : MemCmd::WriteReq);
732        PacketPtr data_pkt;
733        PacketPtr snd_data_pkt = NULL;
734
735        LSQSenderState *state = new LSQSenderState;
736        state->isLoad = false;
737        state->idx = storeWBIdx;
738        state->inst = inst;
739
740        if (!TheISA::HasUnalignedMemAcc || !storeQueue[storeWBIdx].isSplit) {
741
742            // Build a single data packet if the store isn't split.
743            data_pkt = new Packet(req, command, Packet::Broadcast);
744            data_pkt->dataStatic(inst->memData);
745            data_pkt->senderState = state;
746        } else {
747            // Create two packets if the store is split in two.
748            data_pkt = new Packet(sreqLow, command, Packet::Broadcast);
749            snd_data_pkt = new Packet(sreqHigh, command, Packet::Broadcast);
750
751            data_pkt->dataStatic(inst->memData);
752            snd_data_pkt->dataStatic(inst->memData + sreqLow->getSize());
753
754            data_pkt->senderState = state;
755            snd_data_pkt->senderState = state;
756
757            state->isSplit = true;
758            state->outstanding = 2;
759
760            // Can delete the main request now.
761            delete req;
762            req = sreqLow;
763        }
764
765        DPRINTF(LSQUnit, "D-Cache: Writing back store idx:%i PC:%s "
766                "to Addr:%#x, data:%#x [sn:%lli]\n",
767                storeWBIdx, inst->pcState(),
768                req->getPaddr(), (int)*(inst->memData),
769                inst->seqNum);
770
771        // @todo: Remove this SC hack once the memory system handles it.
772        if (inst->isStoreConditional()) {
773            assert(!storeQueue[storeWBIdx].isSplit);
774            // Disable recording the result temporarily.  Writing to
775            // misc regs normally updates the result, but this is not
776            // the desired behavior when handling store conditionals.
777            inst->recordResult = false;
778            bool success = TheISA::handleLockedWrite(inst.get(), req);
779            inst->recordResult = true;
780
781            if (!success) {
782                // Instantly complete this store.
783                DPRINTF(LSQUnit, "Store conditional [sn:%lli] failed.  "
784                        "Instantly completing it.\n",
785                        inst->seqNum);
786                WritebackEvent *wb = new WritebackEvent(inst, data_pkt, this);
787                cpu->schedule(wb, curTick() + 1);
788                completeStore(storeWBIdx);
789                incrStIdx(storeWBIdx);
790                continue;
791            }
792        } else {
793            // Non-store conditionals do not need a writeback.
794            state->noWB = true;
795        }
796
797        bool split =
798            TheISA::HasUnalignedMemAcc && storeQueue[storeWBIdx].isSplit;
799
800        ThreadContext *thread = cpu->tcBase(lsqID);
801
802        if (req->isMmappedIpr()) {
803            assert(!inst->isStoreConditional());
804            TheISA::handleIprWrite(thread, data_pkt);
805            delete data_pkt;
806            if (split) {
807                assert(snd_data_pkt->req->isMmappedIpr());
808                TheISA::handleIprWrite(thread, snd_data_pkt);
809                delete snd_data_pkt;
810                delete sreqLow;
811                delete sreqHigh;
812            }
813            delete state;
814            delete req;
815            completeStore(storeWBIdx);
816            incrStIdx(storeWBIdx);
817        } else if (!sendStore(data_pkt)) {
818            DPRINTF(IEW, "D-Cache became blocked when writing [sn:%lli], will"
819                    "retry later\n",
820                    inst->seqNum);
821
822            // Need to store the second packet, if split.
823            if (split) {
824                state->pktToSend = true;
825                state->pendingPacket = snd_data_pkt;
826            }
827        } else {
828
829            // If split, try to send the second packet too
830            if (split) {
831                assert(snd_data_pkt);
832
833                // Ensure there are enough ports to use.
834                if (usedPorts < cachePorts) {
835                    ++usedPorts;
836                    if (sendStore(snd_data_pkt)) {
837                        storePostSend(snd_data_pkt);
838                    } else {
839                        DPRINTF(IEW, "D-Cache became blocked when writing"
840                                " [sn:%lli] second packet, will retry later\n",
841                                inst->seqNum);
842                    }
843                } else {
844
845                    // Store the packet for when there's free ports.
846                    assert(pendingPkt == NULL);
847                    pendingPkt = snd_data_pkt;
848                    hasPendingPkt = true;
849                }
850            } else {
851
852                // Not a split store.
853                storePostSend(data_pkt);
854            }
855        }
856    }
857
858    // Not sure this should set it to 0.
859    usedPorts = 0;
860
861    assert(stores >= 0 && storesToWB >= 0);
862}
863
864/*template <class Impl>
865void
866LSQUnit<Impl>::removeMSHR(InstSeqNum seqNum)
867{
868    list<InstSeqNum>::iterator mshr_it = find(mshrSeqNums.begin(),
869                                              mshrSeqNums.end(),
870                                              seqNum);
871
872    if (mshr_it != mshrSeqNums.end()) {
873        mshrSeqNums.erase(mshr_it);
874        DPRINTF(LSQUnit, "Removing MSHR. count = %i\n",mshrSeqNums.size());
875    }
876}*/
877
878template <class Impl>
879void
880LSQUnit<Impl>::squash(const InstSeqNum &squashed_num)
881{
882    DPRINTF(LSQUnit, "Squashing until [sn:%lli]!"
883            "(Loads:%i Stores:%i)\n", squashed_num, loads, stores);
884
885    int load_idx = loadTail;
886    decrLdIdx(load_idx);
887
888    while (loads != 0 && loadQueue[load_idx]->seqNum > squashed_num) {
889        DPRINTF(LSQUnit,"Load Instruction PC %s squashed, "
890                "[sn:%lli]\n",
891                loadQueue[load_idx]->pcState(),
892                loadQueue[load_idx]->seqNum);
893
894        if (isStalled() && load_idx == stallingLoadIdx) {
895            stalled = false;
896            stallingStoreIsn = 0;
897            stallingLoadIdx = 0;
898        }
899
900        // Clear the smart pointer to make sure it is decremented.
901        loadQueue[load_idx]->setSquashed();
902        loadQueue[load_idx] = NULL;
903        --loads;
904
905        // Inefficient!
906        loadTail = load_idx;
907
908        decrLdIdx(load_idx);
909        ++lsqSquashedLoads;
910    }
911
912    if (isLoadBlocked) {
913        if (squashed_num < blockedLoadSeqNum) {
914            isLoadBlocked = false;
915            loadBlockedHandled = false;
916            blockedLoadSeqNum = 0;
917        }
918    }
919
920    if (memDepViolator && squashed_num < memDepViolator->seqNum) {
921        memDepViolator = NULL;
922    }
923
924    int store_idx = storeTail;
925    decrStIdx(store_idx);
926
927    while (stores != 0 &&
928           storeQueue[store_idx].inst->seqNum > squashed_num) {
929        // Instructions marked as can WB are already committed.
930        if (storeQueue[store_idx].canWB) {
931            break;
932        }
933
934        DPRINTF(LSQUnit,"Store Instruction PC %s squashed, "
935                "idx:%i [sn:%lli]\n",
936                storeQueue[store_idx].inst->pcState(),
937                store_idx, storeQueue[store_idx].inst->seqNum);
938
939        // I don't think this can happen.  It should have been cleared
940        // by the stalling load.
941        if (isStalled() &&
942            storeQueue[store_idx].inst->seqNum == stallingStoreIsn) {
943            panic("Is stalled should have been cleared by stalling load!\n");
944            stalled = false;
945            stallingStoreIsn = 0;
946        }
947
948        // Clear the smart pointer to make sure it is decremented.
949        storeQueue[store_idx].inst->setSquashed();
950        storeQueue[store_idx].inst = NULL;
951        storeQueue[store_idx].canWB = 0;
952
953        // Must delete request now that it wasn't handed off to
954        // memory.  This is quite ugly.  @todo: Figure out the proper
955        // place to really handle request deletes.
956        delete storeQueue[store_idx].req;
957        if (TheISA::HasUnalignedMemAcc && storeQueue[store_idx].isSplit) {
958            delete storeQueue[store_idx].sreqLow;
959            delete storeQueue[store_idx].sreqHigh;
960
961            storeQueue[store_idx].sreqLow = NULL;
962            storeQueue[store_idx].sreqHigh = NULL;
963        }
964
965        storeQueue[store_idx].req = NULL;
966        --stores;
967
968        // Inefficient!
969        storeTail = store_idx;
970
971        decrStIdx(store_idx);
972        ++lsqSquashedStores;
973    }
974}
975
976template <class Impl>
977void
978LSQUnit<Impl>::storePostSend(PacketPtr pkt)
979{
980    if (isStalled() &&
981        storeQueue[storeWBIdx].inst->seqNum == stallingStoreIsn) {
982        DPRINTF(LSQUnit, "Unstalling, stalling store [sn:%lli] "
983                "load idx:%i\n",
984                stallingStoreIsn, stallingLoadIdx);
985        stalled = false;
986        stallingStoreIsn = 0;
987        iewStage->replayMemInst(loadQueue[stallingLoadIdx]);
988    }
989
990    if (!storeQueue[storeWBIdx].inst->isStoreConditional()) {
991        // The store is basically completed at this time. This
992        // only works so long as the checker doesn't try to
993        // verify the value in memory for stores.
994        storeQueue[storeWBIdx].inst->setCompleted();
995#if USE_CHECKER
996        if (cpu->checker) {
997            cpu->checker->verify(storeQueue[storeWBIdx].inst);
998        }
999#endif
1000    }
1001
1002    incrStIdx(storeWBIdx);
1003}
1004
1005template <class Impl>
1006void
1007LSQUnit<Impl>::writeback(DynInstPtr &inst, PacketPtr pkt)
1008{
1009    iewStage->wakeCPU();
1010
1011    // Squashed instructions do not need to complete their access.
1012    if (inst->isSquashed()) {
1013        iewStage->decrWb(inst->seqNum);
1014        assert(!inst->isStore());
1015        ++lsqIgnoredResponses;
1016        return;
1017    }
1018
1019    if (!inst->isExecuted()) {
1020        inst->setExecuted();
1021
1022        // Complete access to copy data to proper place.
1023        inst->completeAcc(pkt);
1024    }
1025
1026    // Need to insert instruction into queue to commit
1027    iewStage->instToCommit(inst);
1028
1029    iewStage->activityThisCycle();
1030
1031    // see if this load changed the PC
1032    iewStage->checkMisprediction(inst);
1033}
1034
1035template <class Impl>
1036void
1037LSQUnit<Impl>::completeStore(int store_idx)
1038{
1039    assert(storeQueue[store_idx].inst);
1040    storeQueue[store_idx].completed = true;
1041    --storesToWB;
1042    // A bit conservative because a store completion may not free up entries,
1043    // but hopefully avoids two store completions in one cycle from making
1044    // the CPU tick twice.
1045    cpu->wakeCPU();
1046    cpu->activityThisCycle();
1047
1048    if (store_idx == storeHead) {
1049        do {
1050            incrStIdx(storeHead);
1051
1052            --stores;
1053        } while (storeQueue[storeHead].completed &&
1054                 storeHead != storeTail);
1055
1056        iewStage->updateLSQNextCycle = true;
1057    }
1058
1059    DPRINTF(LSQUnit, "Completing store [sn:%lli], idx:%i, store head "
1060            "idx:%i\n",
1061            storeQueue[store_idx].inst->seqNum, store_idx, storeHead);
1062
1063    if (isStalled() &&
1064        storeQueue[store_idx].inst->seqNum == stallingStoreIsn) {
1065        DPRINTF(LSQUnit, "Unstalling, stalling store [sn:%lli] "
1066                "load idx:%i\n",
1067                stallingStoreIsn, stallingLoadIdx);
1068        stalled = false;
1069        stallingStoreIsn = 0;
1070        iewStage->replayMemInst(loadQueue[stallingLoadIdx]);
1071    }
1072
1073    storeQueue[store_idx].inst->setCompleted();
1074
1075    // Tell the checker we've completed this instruction.  Some stores
1076    // may get reported twice to the checker, but the checker can
1077    // handle that case.
1078#if USE_CHECKER
1079    if (cpu->checker) {
1080        cpu->checker->verify(storeQueue[store_idx].inst);
1081    }
1082#endif
1083}
1084
1085template <class Impl>
1086bool
1087LSQUnit<Impl>::sendStore(PacketPtr data_pkt)
1088{
1089    if (!dcachePort->sendTiming(data_pkt)) {
1090        // Need to handle becoming blocked on a store.
1091        isStoreBlocked = true;
1092        ++lsqCacheBlocked;
1093        assert(retryPkt == NULL);
1094        retryPkt = data_pkt;
1095        lsq->setRetryTid(lsqID);
1096        return false;
1097    }
1098    return true;
1099}
1100
1101template <class Impl>
1102void
1103LSQUnit<Impl>::recvRetry()
1104{
1105    if (isStoreBlocked) {
1106        DPRINTF(LSQUnit, "Receiving retry: store blocked\n");
1107        assert(retryPkt != NULL);
1108
1109        if (dcachePort->sendTiming(retryPkt)) {
1110            LSQSenderState *state =
1111                dynamic_cast<LSQSenderState *>(retryPkt->senderState);
1112
1113            // Don't finish the store unless this is the last packet.
1114            if (!TheISA::HasUnalignedMemAcc || !state->pktToSend ||
1115                    state->pendingPacket == retryPkt) {
1116                state->pktToSend = false;
1117                storePostSend(retryPkt);
1118            }
1119            retryPkt = NULL;
1120            isStoreBlocked = false;
1121            lsq->setRetryTid(InvalidThreadID);
1122
1123            // Send any outstanding packet.
1124            if (TheISA::HasUnalignedMemAcc && state->pktToSend) {
1125                assert(state->pendingPacket);
1126                if (sendStore(state->pendingPacket)) {
1127                    storePostSend(state->pendingPacket);
1128                }
1129            }
1130        } else {
1131            // Still blocked!
1132            ++lsqCacheBlocked;
1133            lsq->setRetryTid(lsqID);
1134        }
1135    } else if (isLoadBlocked) {
1136        DPRINTF(LSQUnit, "Loads squash themselves and all younger insts, "
1137                "no need to resend packet.\n");
1138    } else {
1139        DPRINTF(LSQUnit, "Retry received but LSQ is no longer blocked.\n");
1140    }
1141}
1142
1143template <class Impl>
1144inline void
1145LSQUnit<Impl>::incrStIdx(int &store_idx)
1146{
1147    if (++store_idx >= SQEntries)
1148        store_idx = 0;
1149}
1150
1151template <class Impl>
1152inline void
1153LSQUnit<Impl>::decrStIdx(int &store_idx)
1154{
1155    if (--store_idx < 0)
1156        store_idx += SQEntries;
1157}
1158
1159template <class Impl>
1160inline void
1161LSQUnit<Impl>::incrLdIdx(int &load_idx)
1162{
1163    if (++load_idx >= LQEntries)
1164        load_idx = 0;
1165}
1166
1167template <class Impl>
1168inline void
1169LSQUnit<Impl>::decrLdIdx(int &load_idx)
1170{
1171    if (--load_idx < 0)
1172        load_idx += LQEntries;
1173}
1174
1175template <class Impl>
1176void
1177LSQUnit<Impl>::dumpInsts()
1178{
1179    cprintf("Load store queue: Dumping instructions.\n");
1180    cprintf("Load queue size: %i\n", loads);
1181    cprintf("Load queue: ");
1182
1183    int load_idx = loadHead;
1184
1185    while (load_idx != loadTail && loadQueue[load_idx]) {
1186        cprintf("%s ", loadQueue[load_idx]->pcState());
1187
1188        incrLdIdx(load_idx);
1189    }
1190
1191    cprintf("Store queue size: %i\n", stores);
1192    cprintf("Store queue: ");
1193
1194    int store_idx = storeHead;
1195
1196    while (store_idx != storeTail && storeQueue[store_idx].inst) {
1197        cprintf("%s ", storeQueue[store_idx].inst->pcState());
1198
1199        incrStIdx(store_idx);
1200    }
1201
1202    cprintf("\n");
1203}
1204