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