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