lsq_unit_impl.hh revision 8232
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               inst_eff_addr1 == ld_eff_addr1) {
470            // A load/store incorrectly passed this load/store.
471            // Check if we already have a violator, or if it's newer
472            // squash and refetch.
473            if (memDepViolator && ld_inst->seqNum > memDepViolator->seqNum)
474                break;
475
476            DPRINTF(LSQUnit, "Detected fault with inst [sn:%lli] and [sn:%lli]"
477                    " at address %#x\n", inst->seqNum, ld_inst->seqNum,
478                    ld_eff_addr1);
479            memDepViolator = ld_inst;
480
481            ++lsqMemOrderViolation;
482
483            return TheISA::genMachineCheckFault();
484        }
485
486        incrLdIdx(load_idx);
487    }
488    return NoFault;
489}
490
491
492
493
494template <class Impl>
495Fault
496LSQUnit<Impl>::executeLoad(DynInstPtr &inst)
497{
498    using namespace TheISA;
499    // Execute a specific load.
500    Fault load_fault = NoFault;
501
502    DPRINTF(LSQUnit, "Executing load PC %s, [sn:%lli]\n",
503            inst->pcState(), inst->seqNum);
504
505    assert(!inst->isSquashed());
506
507    load_fault = inst->initiateAcc();
508
509    if (inst->isTranslationDelayed() &&
510        load_fault == NoFault)
511        return load_fault;
512
513    // If the instruction faulted or predicated false, then we need to send it
514    // along to commit without the instruction completing.
515    if (load_fault != NoFault || inst->readPredicate() == false) {
516        // Send this instruction to commit, also make sure iew stage
517        // realizes there is activity.
518        // Mark it as executed unless it is an uncached load that
519        // needs to hit the head of commit.
520        if (inst->readPredicate() == false)
521            inst->forwardOldRegs();
522        DPRINTF(LSQUnit, "Load [sn:%lli] not executed from %s\n",
523                inst->seqNum,
524                (load_fault != NoFault ? "fault" : "predication"));
525        if (!(inst->hasRequest() && inst->uncacheable()) ||
526            inst->isAtCommit()) {
527            inst->setExecuted();
528        }
529        iewStage->instToCommit(inst);
530        iewStage->activityThisCycle();
531    } else if (!loadBlocked()) {
532        assert(inst->effAddrValid);
533        int load_idx = inst->lqIdx;
534        incrLdIdx(load_idx);
535
536        if (checkLoads)
537            return checkViolations(load_idx, inst);
538    }
539
540    return load_fault;
541}
542
543template <class Impl>
544Fault
545LSQUnit<Impl>::executeStore(DynInstPtr &store_inst)
546{
547    using namespace TheISA;
548    // Make sure that a store exists.
549    assert(stores != 0);
550
551    int store_idx = store_inst->sqIdx;
552
553    DPRINTF(LSQUnit, "Executing store PC %s [sn:%lli]\n",
554            store_inst->pcState(), store_inst->seqNum);
555
556    assert(!store_inst->isSquashed());
557
558    // Check the recently completed loads to see if any match this store's
559    // address.  If so, then we have a memory ordering violation.
560    int load_idx = store_inst->lqIdx;
561
562    Fault store_fault = store_inst->initiateAcc();
563
564    if (store_inst->isTranslationDelayed() &&
565        store_fault == NoFault)
566        return store_fault;
567
568    if (store_inst->readPredicate() == false)
569        store_inst->forwardOldRegs();
570
571    if (storeQueue[store_idx].size == 0) {
572        DPRINTF(LSQUnit,"Fault on Store PC %s, [sn:%lli], Size = 0\n",
573                store_inst->pcState(), store_inst->seqNum);
574
575        return store_fault;
576    } else if (store_inst->readPredicate() == false) {
577        DPRINTF(LSQUnit, "Store [sn:%lli] not executed from predication\n",
578                store_inst->seqNum);
579        return store_fault;
580    }
581
582    assert(store_fault == NoFault);
583
584    if (store_inst->isStoreConditional()) {
585        // Store conditionals need to set themselves as able to
586        // writeback if we haven't had a fault by here.
587        storeQueue[store_idx].canWB = true;
588
589        ++storesToWB;
590    }
591
592    return checkViolations(load_idx, store_inst);
593
594}
595
596template <class Impl>
597void
598LSQUnit<Impl>::commitLoad()
599{
600    assert(loadQueue[loadHead]);
601
602    DPRINTF(LSQUnit, "Committing head load instruction, PC %s\n",
603            loadQueue[loadHead]->pcState());
604
605    loadQueue[loadHead] = NULL;
606
607    incrLdIdx(loadHead);
608
609    --loads;
610}
611
612template <class Impl>
613void
614LSQUnit<Impl>::commitLoads(InstSeqNum &youngest_inst)
615{
616    assert(loads == 0 || loadQueue[loadHead]);
617
618    while (loads != 0 && loadQueue[loadHead]->seqNum <= youngest_inst) {
619        commitLoad();
620    }
621}
622
623template <class Impl>
624void
625LSQUnit<Impl>::commitStores(InstSeqNum &youngest_inst)
626{
627    assert(stores == 0 || storeQueue[storeHead].inst);
628
629    int store_idx = storeHead;
630
631    while (store_idx != storeTail) {
632        assert(storeQueue[store_idx].inst);
633        // Mark any stores that are now committed and have not yet
634        // been marked as able to write back.
635        if (!storeQueue[store_idx].canWB) {
636            if (storeQueue[store_idx].inst->seqNum > youngest_inst) {
637                break;
638            }
639            DPRINTF(LSQUnit, "Marking store as able to write back, PC "
640                    "%s [sn:%lli]\n",
641                    storeQueue[store_idx].inst->pcState(),
642                    storeQueue[store_idx].inst->seqNum);
643
644            storeQueue[store_idx].canWB = true;
645
646            ++storesToWB;
647        }
648
649        incrStIdx(store_idx);
650    }
651}
652
653template <class Impl>
654void
655LSQUnit<Impl>::writebackPendingStore()
656{
657    if (hasPendingPkt) {
658        assert(pendingPkt != NULL);
659
660        // If the cache is blocked, this will store the packet for retry.
661        if (sendStore(pendingPkt)) {
662            storePostSend(pendingPkt);
663        }
664        pendingPkt = NULL;
665        hasPendingPkt = false;
666    }
667}
668
669template <class Impl>
670void
671LSQUnit<Impl>::writebackStores()
672{
673    // First writeback the second packet from any split store that didn't
674    // complete last cycle because there weren't enough cache ports available.
675    if (TheISA::HasUnalignedMemAcc) {
676        writebackPendingStore();
677    }
678
679    while (storesToWB > 0 &&
680           storeWBIdx != storeTail &&
681           storeQueue[storeWBIdx].inst &&
682           storeQueue[storeWBIdx].canWB &&
683           usedPorts < cachePorts) {
684
685        if (isStoreBlocked || lsq->cacheBlocked()) {
686            DPRINTF(LSQUnit, "Unable to write back any more stores, cache"
687                    " is blocked!\n");
688            break;
689        }
690
691        // Store didn't write any data so no need to write it back to
692        // memory.
693        if (storeQueue[storeWBIdx].size == 0) {
694            completeStore(storeWBIdx);
695
696            incrStIdx(storeWBIdx);
697
698            continue;
699        }
700
701        ++usedPorts;
702
703        if (storeQueue[storeWBIdx].inst->isDataPrefetch()) {
704            incrStIdx(storeWBIdx);
705
706            continue;
707        }
708
709        assert(storeQueue[storeWBIdx].req);
710        assert(!storeQueue[storeWBIdx].committed);
711
712        if (TheISA::HasUnalignedMemAcc && storeQueue[storeWBIdx].isSplit) {
713            assert(storeQueue[storeWBIdx].sreqLow);
714            assert(storeQueue[storeWBIdx].sreqHigh);
715        }
716
717        DynInstPtr inst = storeQueue[storeWBIdx].inst;
718
719        Request *req = storeQueue[storeWBIdx].req;
720        storeQueue[storeWBIdx].committed = true;
721
722        assert(!inst->memData);
723        inst->memData = new uint8_t[64];
724
725        memcpy(inst->memData, storeQueue[storeWBIdx].data, req->getSize());
726
727        MemCmd command =
728            req->isSwap() ? MemCmd::SwapReq :
729            (req->isLLSC() ? MemCmd::StoreCondReq : MemCmd::WriteReq);
730        PacketPtr data_pkt;
731        PacketPtr snd_data_pkt = NULL;
732
733        LSQSenderState *state = new LSQSenderState;
734        state->isLoad = false;
735        state->idx = storeWBIdx;
736        state->inst = inst;
737
738        if (!TheISA::HasUnalignedMemAcc || !storeQueue[storeWBIdx].isSplit) {
739
740            // Build a single data packet if the store isn't split.
741            data_pkt = new Packet(req, command, Packet::Broadcast);
742            data_pkt->dataStatic(inst->memData);
743            data_pkt->senderState = state;
744        } else {
745            RequestPtr sreqLow = storeQueue[storeWBIdx].sreqLow;
746            RequestPtr sreqHigh = storeQueue[storeWBIdx].sreqHigh;
747
748            // Create two packets if the store is split in two.
749            data_pkt = new Packet(sreqLow, command, Packet::Broadcast);
750            snd_data_pkt = new Packet(sreqHigh, command, Packet::Broadcast);
751
752            data_pkt->dataStatic(inst->memData);
753            snd_data_pkt->dataStatic(inst->memData + sreqLow->getSize());
754
755            data_pkt->senderState = state;
756            snd_data_pkt->senderState = state;
757
758            state->isSplit = true;
759            state->outstanding = 2;
760
761            // Can delete the main request now.
762            delete req;
763            req = sreqLow;
764        }
765
766        DPRINTF(LSQUnit, "D-Cache: Writing back store idx:%i PC:%s "
767                "to Addr:%#x, data:%#x [sn:%lli]\n",
768                storeWBIdx, inst->pcState(),
769                req->getPaddr(), (int)*(inst->memData),
770                inst->seqNum);
771
772        // @todo: Remove this SC hack once the memory system handles it.
773        if (inst->isStoreConditional()) {
774            assert(!storeQueue[storeWBIdx].isSplit);
775            // Disable recording the result temporarily.  Writing to
776            // misc regs normally updates the result, but this is not
777            // the desired behavior when handling store conditionals.
778            inst->recordResult = false;
779            bool success = TheISA::handleLockedWrite(inst.get(), req);
780            inst->recordResult = true;
781
782            if (!success) {
783                // Instantly complete this store.
784                DPRINTF(LSQUnit, "Store conditional [sn:%lli] failed.  "
785                        "Instantly completing it.\n",
786                        inst->seqNum);
787                WritebackEvent *wb = new WritebackEvent(inst, data_pkt, this);
788                cpu->schedule(wb, curTick() + 1);
789                completeStore(storeWBIdx);
790                incrStIdx(storeWBIdx);
791                continue;
792            }
793        } else {
794            // Non-store conditionals do not need a writeback.
795            state->noWB = true;
796        }
797
798        if (!sendStore(data_pkt)) {
799            DPRINTF(IEW, "D-Cache became blocked when writing [sn:%lli], will"
800                    "retry later\n",
801                    inst->seqNum);
802
803            // Need to store the second packet, if split.
804            if (TheISA::HasUnalignedMemAcc && storeQueue[storeWBIdx].isSplit) {
805                state->pktToSend = true;
806                state->pendingPacket = snd_data_pkt;
807            }
808        } else {
809
810            // If split, try to send the second packet too
811            if (TheISA::HasUnalignedMemAcc && storeQueue[storeWBIdx].isSplit) {
812                assert(snd_data_pkt);
813
814                // Ensure there are enough ports to use.
815                if (usedPorts < cachePorts) {
816                    ++usedPorts;
817                    if (sendStore(snd_data_pkt)) {
818                        storePostSend(snd_data_pkt);
819                    } else {
820                        DPRINTF(IEW, "D-Cache became blocked when writing"
821                                " [sn:%lli] second packet, will retry later\n",
822                                inst->seqNum);
823                    }
824                } else {
825
826                    // Store the packet for when there's free ports.
827                    assert(pendingPkt == NULL);
828                    pendingPkt = snd_data_pkt;
829                    hasPendingPkt = true;
830                }
831            } else {
832
833                // Not a split store.
834                storePostSend(data_pkt);
835            }
836        }
837    }
838
839    // Not sure this should set it to 0.
840    usedPorts = 0;
841
842    assert(stores >= 0 && storesToWB >= 0);
843}
844
845/*template <class Impl>
846void
847LSQUnit<Impl>::removeMSHR(InstSeqNum seqNum)
848{
849    list<InstSeqNum>::iterator mshr_it = find(mshrSeqNums.begin(),
850                                              mshrSeqNums.end(),
851                                              seqNum);
852
853    if (mshr_it != mshrSeqNums.end()) {
854        mshrSeqNums.erase(mshr_it);
855        DPRINTF(LSQUnit, "Removing MSHR. count = %i\n",mshrSeqNums.size());
856    }
857}*/
858
859template <class Impl>
860void
861LSQUnit<Impl>::squash(const InstSeqNum &squashed_num)
862{
863    DPRINTF(LSQUnit, "Squashing until [sn:%lli]!"
864            "(Loads:%i Stores:%i)\n", squashed_num, loads, stores);
865
866    int load_idx = loadTail;
867    decrLdIdx(load_idx);
868
869    while (loads != 0 && loadQueue[load_idx]->seqNum > squashed_num) {
870        DPRINTF(LSQUnit,"Load Instruction PC %s squashed, "
871                "[sn:%lli]\n",
872                loadQueue[load_idx]->pcState(),
873                loadQueue[load_idx]->seqNum);
874
875        if (isStalled() && load_idx == stallingLoadIdx) {
876            stalled = false;
877            stallingStoreIsn = 0;
878            stallingLoadIdx = 0;
879        }
880
881        // Clear the smart pointer to make sure it is decremented.
882        loadQueue[load_idx]->setSquashed();
883        loadQueue[load_idx] = NULL;
884        --loads;
885
886        // Inefficient!
887        loadTail = load_idx;
888
889        decrLdIdx(load_idx);
890        ++lsqSquashedLoads;
891    }
892
893    if (isLoadBlocked) {
894        if (squashed_num < blockedLoadSeqNum) {
895            isLoadBlocked = false;
896            loadBlockedHandled = false;
897            blockedLoadSeqNum = 0;
898        }
899    }
900
901    if (memDepViolator && squashed_num < memDepViolator->seqNum) {
902        memDepViolator = NULL;
903    }
904
905    int store_idx = storeTail;
906    decrStIdx(store_idx);
907
908    while (stores != 0 &&
909           storeQueue[store_idx].inst->seqNum > squashed_num) {
910        // Instructions marked as can WB are already committed.
911        if (storeQueue[store_idx].canWB) {
912            break;
913        }
914
915        DPRINTF(LSQUnit,"Store Instruction PC %s squashed, "
916                "idx:%i [sn:%lli]\n",
917                storeQueue[store_idx].inst->pcState(),
918                store_idx, storeQueue[store_idx].inst->seqNum);
919
920        // I don't think this can happen.  It should have been cleared
921        // by the stalling load.
922        if (isStalled() &&
923            storeQueue[store_idx].inst->seqNum == stallingStoreIsn) {
924            panic("Is stalled should have been cleared by stalling load!\n");
925            stalled = false;
926            stallingStoreIsn = 0;
927        }
928
929        // Clear the smart pointer to make sure it is decremented.
930        storeQueue[store_idx].inst->setSquashed();
931        storeQueue[store_idx].inst = NULL;
932        storeQueue[store_idx].canWB = 0;
933
934        // Must delete request now that it wasn't handed off to
935        // memory.  This is quite ugly.  @todo: Figure out the proper
936        // place to really handle request deletes.
937        delete storeQueue[store_idx].req;
938        if (TheISA::HasUnalignedMemAcc && storeQueue[store_idx].isSplit) {
939            delete storeQueue[store_idx].sreqLow;
940            delete storeQueue[store_idx].sreqHigh;
941
942            storeQueue[store_idx].sreqLow = NULL;
943            storeQueue[store_idx].sreqHigh = NULL;
944        }
945
946        storeQueue[store_idx].req = NULL;
947        --stores;
948
949        // Inefficient!
950        storeTail = store_idx;
951
952        decrStIdx(store_idx);
953        ++lsqSquashedStores;
954    }
955}
956
957template <class Impl>
958void
959LSQUnit<Impl>::storePostSend(PacketPtr pkt)
960{
961    if (isStalled() &&
962        storeQueue[storeWBIdx].inst->seqNum == stallingStoreIsn) {
963        DPRINTF(LSQUnit, "Unstalling, stalling store [sn:%lli] "
964                "load idx:%i\n",
965                stallingStoreIsn, stallingLoadIdx);
966        stalled = false;
967        stallingStoreIsn = 0;
968        iewStage->replayMemInst(loadQueue[stallingLoadIdx]);
969    }
970
971    if (!storeQueue[storeWBIdx].inst->isStoreConditional()) {
972        // The store is basically completed at this time. This
973        // only works so long as the checker doesn't try to
974        // verify the value in memory for stores.
975        storeQueue[storeWBIdx].inst->setCompleted();
976#if USE_CHECKER
977        if (cpu->checker) {
978            cpu->checker->verify(storeQueue[storeWBIdx].inst);
979        }
980#endif
981    }
982
983    incrStIdx(storeWBIdx);
984}
985
986template <class Impl>
987void
988LSQUnit<Impl>::writeback(DynInstPtr &inst, PacketPtr pkt)
989{
990    iewStage->wakeCPU();
991
992    // Squashed instructions do not need to complete their access.
993    if (inst->isSquashed()) {
994        iewStage->decrWb(inst->seqNum);
995        assert(!inst->isStore());
996        ++lsqIgnoredResponses;
997        return;
998    }
999
1000    if (!inst->isExecuted()) {
1001        inst->setExecuted();
1002
1003        // Complete access to copy data to proper place.
1004        inst->completeAcc(pkt);
1005    }
1006
1007    // Need to insert instruction into queue to commit
1008    iewStage->instToCommit(inst);
1009
1010    iewStage->activityThisCycle();
1011
1012    // see if this load changed the PC
1013    iewStage->checkMisprediction(inst);
1014}
1015
1016template <class Impl>
1017void
1018LSQUnit<Impl>::completeStore(int store_idx)
1019{
1020    assert(storeQueue[store_idx].inst);
1021    storeQueue[store_idx].completed = true;
1022    --storesToWB;
1023    // A bit conservative because a store completion may not free up entries,
1024    // but hopefully avoids two store completions in one cycle from making
1025    // the CPU tick twice.
1026    cpu->wakeCPU();
1027    cpu->activityThisCycle();
1028
1029    if (store_idx == storeHead) {
1030        do {
1031            incrStIdx(storeHead);
1032
1033            --stores;
1034        } while (storeQueue[storeHead].completed &&
1035                 storeHead != storeTail);
1036
1037        iewStage->updateLSQNextCycle = true;
1038    }
1039
1040    DPRINTF(LSQUnit, "Completing store [sn:%lli], idx:%i, store head "
1041            "idx:%i\n",
1042            storeQueue[store_idx].inst->seqNum, store_idx, storeHead);
1043
1044    if (isStalled() &&
1045        storeQueue[store_idx].inst->seqNum == stallingStoreIsn) {
1046        DPRINTF(LSQUnit, "Unstalling, stalling store [sn:%lli] "
1047                "load idx:%i\n",
1048                stallingStoreIsn, stallingLoadIdx);
1049        stalled = false;
1050        stallingStoreIsn = 0;
1051        iewStage->replayMemInst(loadQueue[stallingLoadIdx]);
1052    }
1053
1054    storeQueue[store_idx].inst->setCompleted();
1055
1056    // Tell the checker we've completed this instruction.  Some stores
1057    // may get reported twice to the checker, but the checker can
1058    // handle that case.
1059#if USE_CHECKER
1060    if (cpu->checker) {
1061        cpu->checker->verify(storeQueue[store_idx].inst);
1062    }
1063#endif
1064}
1065
1066template <class Impl>
1067bool
1068LSQUnit<Impl>::sendStore(PacketPtr data_pkt)
1069{
1070    if (!dcachePort->sendTiming(data_pkt)) {
1071        // Need to handle becoming blocked on a store.
1072        isStoreBlocked = true;
1073        ++lsqCacheBlocked;
1074        assert(retryPkt == NULL);
1075        retryPkt = data_pkt;
1076        lsq->setRetryTid(lsqID);
1077        return false;
1078    }
1079    return true;
1080}
1081
1082template <class Impl>
1083void
1084LSQUnit<Impl>::recvRetry()
1085{
1086    if (isStoreBlocked) {
1087        DPRINTF(LSQUnit, "Receiving retry: store blocked\n");
1088        assert(retryPkt != NULL);
1089
1090        if (dcachePort->sendTiming(retryPkt)) {
1091            LSQSenderState *state =
1092                dynamic_cast<LSQSenderState *>(retryPkt->senderState);
1093
1094            // Don't finish the store unless this is the last packet.
1095            if (!TheISA::HasUnalignedMemAcc || !state->pktToSend ||
1096                    state->pendingPacket == retryPkt) {
1097                state->pktToSend = false;
1098                storePostSend(retryPkt);
1099            }
1100            retryPkt = NULL;
1101            isStoreBlocked = false;
1102            lsq->setRetryTid(InvalidThreadID);
1103
1104            // Send any outstanding packet.
1105            if (TheISA::HasUnalignedMemAcc && state->pktToSend) {
1106                assert(state->pendingPacket);
1107                if (sendStore(state->pendingPacket)) {
1108                    storePostSend(state->pendingPacket);
1109                }
1110            }
1111        } else {
1112            // Still blocked!
1113            ++lsqCacheBlocked;
1114            lsq->setRetryTid(lsqID);
1115        }
1116    } else if (isLoadBlocked) {
1117        DPRINTF(LSQUnit, "Loads squash themselves and all younger insts, "
1118                "no need to resend packet.\n");
1119    } else {
1120        DPRINTF(LSQUnit, "Retry received but LSQ is no longer blocked.\n");
1121    }
1122}
1123
1124template <class Impl>
1125inline void
1126LSQUnit<Impl>::incrStIdx(int &store_idx)
1127{
1128    if (++store_idx >= SQEntries)
1129        store_idx = 0;
1130}
1131
1132template <class Impl>
1133inline void
1134LSQUnit<Impl>::decrStIdx(int &store_idx)
1135{
1136    if (--store_idx < 0)
1137        store_idx += SQEntries;
1138}
1139
1140template <class Impl>
1141inline void
1142LSQUnit<Impl>::incrLdIdx(int &load_idx)
1143{
1144    if (++load_idx >= LQEntries)
1145        load_idx = 0;
1146}
1147
1148template <class Impl>
1149inline void
1150LSQUnit<Impl>::decrLdIdx(int &load_idx)
1151{
1152    if (--load_idx < 0)
1153        load_idx += LQEntries;
1154}
1155
1156template <class Impl>
1157void
1158LSQUnit<Impl>::dumpInsts()
1159{
1160    cprintf("Load store queue: Dumping instructions.\n");
1161    cprintf("Load queue size: %i\n", loads);
1162    cprintf("Load queue: ");
1163
1164    int load_idx = loadHead;
1165
1166    while (load_idx != loadTail && loadQueue[load_idx]) {
1167        cprintf("%s ", loadQueue[load_idx]->pcState());
1168
1169        incrLdIdx(load_idx);
1170    }
1171
1172    cprintf("Store queue size: %i\n", stores);
1173    cprintf("Store queue: ");
1174
1175    int store_idx = storeHead;
1176
1177    while (store_idx != storeTail && storeQueue[store_idx].inst) {
1178        cprintf("%s ", storeQueue[store_idx].inst->pcState());
1179
1180        incrStIdx(store_idx);
1181    }
1182
1183    cprintf("\n");
1184}
1185