lsq_unit_impl.hh revision 8272
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        storeQueue[storeWBIdx].committed = true;
720
721        assert(!inst->memData);
722        inst->memData = new uint8_t[64];
723
724        memcpy(inst->memData, storeQueue[storeWBIdx].data, req->getSize());
725
726        MemCmd command =
727            req->isSwap() ? MemCmd::SwapReq :
728            (req->isLLSC() ? MemCmd::StoreCondReq : MemCmd::WriteReq);
729        PacketPtr data_pkt;
730        PacketPtr snd_data_pkt = NULL;
731
732        LSQSenderState *state = new LSQSenderState;
733        state->isLoad = false;
734        state->idx = storeWBIdx;
735        state->inst = inst;
736
737        if (!TheISA::HasUnalignedMemAcc || !storeQueue[storeWBIdx].isSplit) {
738
739            // Build a single data packet if the store isn't split.
740            data_pkt = new Packet(req, command, Packet::Broadcast);
741            data_pkt->dataStatic(inst->memData);
742            data_pkt->senderState = state;
743        } else {
744            RequestPtr sreqLow = storeQueue[storeWBIdx].sreqLow;
745            RequestPtr sreqHigh = storeQueue[storeWBIdx].sreqHigh;
746
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        if (!sendStore(data_pkt)) {
798            DPRINTF(IEW, "D-Cache became blocked when writing [sn:%lli], will"
799                    "retry later\n",
800                    inst->seqNum);
801
802            // Need to store the second packet, if split.
803            if (TheISA::HasUnalignedMemAcc && storeQueue[storeWBIdx].isSplit) {
804                state->pktToSend = true;
805                state->pendingPacket = snd_data_pkt;
806            }
807        } else {
808
809            // If split, try to send the second packet too
810            if (TheISA::HasUnalignedMemAcc && storeQueue[storeWBIdx].isSplit) {
811                assert(snd_data_pkt);
812
813                // Ensure there are enough ports to use.
814                if (usedPorts < cachePorts) {
815                    ++usedPorts;
816                    if (sendStore(snd_data_pkt)) {
817                        storePostSend(snd_data_pkt);
818                    } else {
819                        DPRINTF(IEW, "D-Cache became blocked when writing"
820                                " [sn:%lli] second packet, will retry later\n",
821                                inst->seqNum);
822                    }
823                } else {
824
825                    // Store the packet for when there's free ports.
826                    assert(pendingPkt == NULL);
827                    pendingPkt = snd_data_pkt;
828                    hasPendingPkt = true;
829                }
830            } else {
831
832                // Not a split store.
833                storePostSend(data_pkt);
834            }
835        }
836    }
837
838    // Not sure this should set it to 0.
839    usedPorts = 0;
840
841    assert(stores >= 0 && storesToWB >= 0);
842}
843
844/*template <class Impl>
845void
846LSQUnit<Impl>::removeMSHR(InstSeqNum seqNum)
847{
848    list<InstSeqNum>::iterator mshr_it = find(mshrSeqNums.begin(),
849                                              mshrSeqNums.end(),
850                                              seqNum);
851
852    if (mshr_it != mshrSeqNums.end()) {
853        mshrSeqNums.erase(mshr_it);
854        DPRINTF(LSQUnit, "Removing MSHR. count = %i\n",mshrSeqNums.size());
855    }
856}*/
857
858template <class Impl>
859void
860LSQUnit<Impl>::squash(const InstSeqNum &squashed_num)
861{
862    DPRINTF(LSQUnit, "Squashing until [sn:%lli]!"
863            "(Loads:%i Stores:%i)\n", squashed_num, loads, stores);
864
865    int load_idx = loadTail;
866    decrLdIdx(load_idx);
867
868    while (loads != 0 && loadQueue[load_idx]->seqNum > squashed_num) {
869        DPRINTF(LSQUnit,"Load Instruction PC %s squashed, "
870                "[sn:%lli]\n",
871                loadQueue[load_idx]->pcState(),
872                loadQueue[load_idx]->seqNum);
873
874        if (isStalled() && load_idx == stallingLoadIdx) {
875            stalled = false;
876            stallingStoreIsn = 0;
877            stallingLoadIdx = 0;
878        }
879
880        // Clear the smart pointer to make sure it is decremented.
881        loadQueue[load_idx]->setSquashed();
882        loadQueue[load_idx] = NULL;
883        --loads;
884
885        // Inefficient!
886        loadTail = load_idx;
887
888        decrLdIdx(load_idx);
889        ++lsqSquashedLoads;
890    }
891
892    if (isLoadBlocked) {
893        if (squashed_num < blockedLoadSeqNum) {
894            isLoadBlocked = false;
895            loadBlockedHandled = false;
896            blockedLoadSeqNum = 0;
897        }
898    }
899
900    if (memDepViolator && squashed_num < memDepViolator->seqNum) {
901        memDepViolator = NULL;
902    }
903
904    int store_idx = storeTail;
905    decrStIdx(store_idx);
906
907    while (stores != 0 &&
908           storeQueue[store_idx].inst->seqNum > squashed_num) {
909        // Instructions marked as can WB are already committed.
910        if (storeQueue[store_idx].canWB) {
911            break;
912        }
913
914        DPRINTF(LSQUnit,"Store Instruction PC %s squashed, "
915                "idx:%i [sn:%lli]\n",
916                storeQueue[store_idx].inst->pcState(),
917                store_idx, storeQueue[store_idx].inst->seqNum);
918
919        // I don't think this can happen.  It should have been cleared
920        // by the stalling load.
921        if (isStalled() &&
922            storeQueue[store_idx].inst->seqNum == stallingStoreIsn) {
923            panic("Is stalled should have been cleared by stalling load!\n");
924            stalled = false;
925            stallingStoreIsn = 0;
926        }
927
928        // Clear the smart pointer to make sure it is decremented.
929        storeQueue[store_idx].inst->setSquashed();
930        storeQueue[store_idx].inst = NULL;
931        storeQueue[store_idx].canWB = 0;
932
933        // Must delete request now that it wasn't handed off to
934        // memory.  This is quite ugly.  @todo: Figure out the proper
935        // place to really handle request deletes.
936        delete storeQueue[store_idx].req;
937        if (TheISA::HasUnalignedMemAcc && storeQueue[store_idx].isSplit) {
938            delete storeQueue[store_idx].sreqLow;
939            delete storeQueue[store_idx].sreqHigh;
940
941            storeQueue[store_idx].sreqLow = NULL;
942            storeQueue[store_idx].sreqHigh = NULL;
943        }
944
945        storeQueue[store_idx].req = NULL;
946        --stores;
947
948        // Inefficient!
949        storeTail = store_idx;
950
951        decrStIdx(store_idx);
952        ++lsqSquashedStores;
953    }
954}
955
956template <class Impl>
957void
958LSQUnit<Impl>::storePostSend(PacketPtr pkt)
959{
960    if (isStalled() &&
961        storeQueue[storeWBIdx].inst->seqNum == stallingStoreIsn) {
962        DPRINTF(LSQUnit, "Unstalling, stalling store [sn:%lli] "
963                "load idx:%i\n",
964                stallingStoreIsn, stallingLoadIdx);
965        stalled = false;
966        stallingStoreIsn = 0;
967        iewStage->replayMemInst(loadQueue[stallingLoadIdx]);
968    }
969
970    if (!storeQueue[storeWBIdx].inst->isStoreConditional()) {
971        // The store is basically completed at this time. This
972        // only works so long as the checker doesn't try to
973        // verify the value in memory for stores.
974        storeQueue[storeWBIdx].inst->setCompleted();
975#if USE_CHECKER
976        if (cpu->checker) {
977            cpu->checker->verify(storeQueue[storeWBIdx].inst);
978        }
979#endif
980    }
981
982    incrStIdx(storeWBIdx);
983}
984
985template <class Impl>
986void
987LSQUnit<Impl>::writeback(DynInstPtr &inst, PacketPtr pkt)
988{
989    iewStage->wakeCPU();
990
991    // Squashed instructions do not need to complete their access.
992    if (inst->isSquashed()) {
993        iewStage->decrWb(inst->seqNum);
994        assert(!inst->isStore());
995        ++lsqIgnoredResponses;
996        return;
997    }
998
999    if (!inst->isExecuted()) {
1000        inst->setExecuted();
1001
1002        // Complete access to copy data to proper place.
1003        inst->completeAcc(pkt);
1004    }
1005
1006    // Need to insert instruction into queue to commit
1007    iewStage->instToCommit(inst);
1008
1009    iewStage->activityThisCycle();
1010
1011    // see if this load changed the PC
1012    iewStage->checkMisprediction(inst);
1013}
1014
1015template <class Impl>
1016void
1017LSQUnit<Impl>::completeStore(int store_idx)
1018{
1019    assert(storeQueue[store_idx].inst);
1020    storeQueue[store_idx].completed = true;
1021    --storesToWB;
1022    // A bit conservative because a store completion may not free up entries,
1023    // but hopefully avoids two store completions in one cycle from making
1024    // the CPU tick twice.
1025    cpu->wakeCPU();
1026    cpu->activityThisCycle();
1027
1028    if (store_idx == storeHead) {
1029        do {
1030            incrStIdx(storeHead);
1031
1032            --stores;
1033        } while (storeQueue[storeHead].completed &&
1034                 storeHead != storeTail);
1035
1036        iewStage->updateLSQNextCycle = true;
1037    }
1038
1039    DPRINTF(LSQUnit, "Completing store [sn:%lli], idx:%i, store head "
1040            "idx:%i\n",
1041            storeQueue[store_idx].inst->seqNum, store_idx, storeHead);
1042
1043    if (isStalled() &&
1044        storeQueue[store_idx].inst->seqNum == stallingStoreIsn) {
1045        DPRINTF(LSQUnit, "Unstalling, stalling store [sn:%lli] "
1046                "load idx:%i\n",
1047                stallingStoreIsn, stallingLoadIdx);
1048        stalled = false;
1049        stallingStoreIsn = 0;
1050        iewStage->replayMemInst(loadQueue[stallingLoadIdx]);
1051    }
1052
1053    storeQueue[store_idx].inst->setCompleted();
1054
1055    // Tell the checker we've completed this instruction.  Some stores
1056    // may get reported twice to the checker, but the checker can
1057    // handle that case.
1058#if USE_CHECKER
1059    if (cpu->checker) {
1060        cpu->checker->verify(storeQueue[store_idx].inst);
1061    }
1062#endif
1063}
1064
1065template <class Impl>
1066bool
1067LSQUnit<Impl>::sendStore(PacketPtr data_pkt)
1068{
1069    if (!dcachePort->sendTiming(data_pkt)) {
1070        // Need to handle becoming blocked on a store.
1071        isStoreBlocked = true;
1072        ++lsqCacheBlocked;
1073        assert(retryPkt == NULL);
1074        retryPkt = data_pkt;
1075        lsq->setRetryTid(lsqID);
1076        return false;
1077    }
1078    return true;
1079}
1080
1081template <class Impl>
1082void
1083LSQUnit<Impl>::recvRetry()
1084{
1085    if (isStoreBlocked) {
1086        DPRINTF(LSQUnit, "Receiving retry: store blocked\n");
1087        assert(retryPkt != NULL);
1088
1089        if (dcachePort->sendTiming(retryPkt)) {
1090            LSQSenderState *state =
1091                dynamic_cast<LSQSenderState *>(retryPkt->senderState);
1092
1093            // Don't finish the store unless this is the last packet.
1094            if (!TheISA::HasUnalignedMemAcc || !state->pktToSend ||
1095                    state->pendingPacket == retryPkt) {
1096                state->pktToSend = false;
1097                storePostSend(retryPkt);
1098            }
1099            retryPkt = NULL;
1100            isStoreBlocked = false;
1101            lsq->setRetryTid(InvalidThreadID);
1102
1103            // Send any outstanding packet.
1104            if (TheISA::HasUnalignedMemAcc && state->pktToSend) {
1105                assert(state->pendingPacket);
1106                if (sendStore(state->pendingPacket)) {
1107                    storePostSend(state->pendingPacket);
1108                }
1109            }
1110        } else {
1111            // Still blocked!
1112            ++lsqCacheBlocked;
1113            lsq->setRetryTid(lsqID);
1114        }
1115    } else if (isLoadBlocked) {
1116        DPRINTF(LSQUnit, "Loads squash themselves and all younger insts, "
1117                "no need to resend packet.\n");
1118    } else {
1119        DPRINTF(LSQUnit, "Retry received but LSQ is no longer blocked.\n");
1120    }
1121}
1122
1123template <class Impl>
1124inline void
1125LSQUnit<Impl>::incrStIdx(int &store_idx)
1126{
1127    if (++store_idx >= SQEntries)
1128        store_idx = 0;
1129}
1130
1131template <class Impl>
1132inline void
1133LSQUnit<Impl>::decrStIdx(int &store_idx)
1134{
1135    if (--store_idx < 0)
1136        store_idx += SQEntries;
1137}
1138
1139template <class Impl>
1140inline void
1141LSQUnit<Impl>::incrLdIdx(int &load_idx)
1142{
1143    if (++load_idx >= LQEntries)
1144        load_idx = 0;
1145}
1146
1147template <class Impl>
1148inline void
1149LSQUnit<Impl>::decrLdIdx(int &load_idx)
1150{
1151    if (--load_idx < 0)
1152        load_idx += LQEntries;
1153}
1154
1155template <class Impl>
1156void
1157LSQUnit<Impl>::dumpInsts()
1158{
1159    cprintf("Load store queue: Dumping instructions.\n");
1160    cprintf("Load queue size: %i\n", loads);
1161    cprintf("Load queue: ");
1162
1163    int load_idx = loadHead;
1164
1165    while (load_idx != loadTail && loadQueue[load_idx]) {
1166        cprintf("%s ", loadQueue[load_idx]->pcState());
1167
1168        incrLdIdx(load_idx);
1169    }
1170
1171    cprintf("Store queue size: %i\n", stores);
1172    cprintf("Store queue: ");
1173
1174    int store_idx = storeHead;
1175
1176    while (store_idx != storeTail && storeQueue[store_idx].inst) {
1177        cprintf("%s ", storeQueue[store_idx].inst->pcState());
1178
1179        incrStIdx(store_idx);
1180    }
1181
1182    cprintf("\n");
1183}
1184