lsq_unit_impl.hh revision 7852:07ba4754ae0a
12315SN/A/*
22332SN/A * Copyright (c) 2010 ARM Limited
32315SN/A * All rights reserved
42315SN/A *
52315SN/A * The license below extends only to copyright in the software and shall
62315SN/A * not be construed as granting a license to any other intellectual
72315SN/A * property including but not limited to intellectual property relating
82315SN/A * to a hardware implementation of the functionality of the software
92315SN/A * licensed hereunder.  You may use the software subject to the license
102315SN/A * terms below provided that you ensure that this notice is replicated
112315SN/A * unmodified and in its entirety in all distributions of the software,
122315SN/A * modified or unmodified, in source code or in binary form.
132315SN/A *
142315SN/A * Copyright (c) 2004-2005 The Regents of The University of Michigan
152315SN/A * All rights reserved.
162315SN/A *
172315SN/A * Redistribution and use in source and binary forms, with or without
182315SN/A * modification, are permitted provided that the following conditions are
192315SN/A * met: redistributions of source code must retain the above copyright
202315SN/A * notice, this list of conditions and the following disclaimer;
212315SN/A * redistributions in binary form must reproduce the above copyright
222315SN/A * notice, this list of conditions and the following disclaimer in the
232315SN/A * documentation and/or other materials provided with the distribution;
242315SN/A * neither the name of the copyright holders nor the names of its
252315SN/A * contributors may be used to endorse or promote products derived from
262315SN/A * this software without specific prior written permission.
272689SN/A *
282689SN/A * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
292315SN/A * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
302315SN/A * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
312315SN/A * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
322315SN/A * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
332315SN/A * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
342315SN/A * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
352315SN/A * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
362315SN/A * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
372683SN/A * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
382680SN/A * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
392315SN/A *
402722SN/A * Authors: Kevin Lim
412315SN/A *          Korey Sewell
422315SN/A */
432315SN/A
442315SN/A#include "arch/locked_mem.hh"
452315SN/A#include "config/the_isa.hh"
462315SN/A#include "config/use_checker.hh"
472315SN/A#include "cpu/o3/lsq.hh"
482315SN/A#include "cpu/o3/lsq_unit.hh"
492315SN/A#include "base/str.hh"
502315SN/A#include "mem/packet.hh"
512315SN/A#include "mem/request.hh"
522315SN/A
532315SN/A#if USE_CHECKER
542315SN/A#include "cpu/checker/cpu.hh"
552732SN/A#endif
562315SN/A
572315SN/Atemplate<class Impl>
582315SN/ALSQUnit<Impl>::WritebackEvent::WritebackEvent(DynInstPtr &_inst, PacketPtr _pkt,
592332SN/A                                              LSQUnit *lsq_ptr)
602332SN/A    : inst(_inst), pkt(_pkt), lsqPtr(lsq_ptr)
612332SN/A{
622332SN/A    this->setFlags(Event::AutoDelete);
632332SN/A}
642315SN/A
652315SN/Atemplate<class Impl>
662315SN/Avoid
672315SN/ALSQUnit<Impl>::WritebackEvent::process()
682315SN/A{
692315SN/A    if (!lsqPtr->isSwitchedOut()) {
702315SN/A        lsqPtr->writeback(inst, pkt);
712315SN/A    }
722315SN/A
732315SN/A    if (pkt->senderState)
742315SN/A        delete pkt->senderState;
752315SN/A
762315SN/A    delete pkt->req;
772315SN/A    delete pkt;
782315SN/A}
792315SN/A
802315SN/Atemplate<class Impl>
812315SN/Aconst char *
822315SN/ALSQUnit<Impl>::WritebackEvent::description() const
832315SN/A{
842315SN/A    return "Store writeback";
852315SN/A}
862315SN/A
872315SN/Atemplate<class Impl>
882315SN/Avoid
892315SN/ALSQUnit<Impl>::completeDataAccess(PacketPtr pkt)
902315SN/A{
912315SN/A    LSQSenderState *state = dynamic_cast<LSQSenderState *>(pkt->senderState);
922315SN/A    DynInstPtr inst = state->inst;
932315SN/A    DPRINTF(IEW, "Writeback event [sn:%lli].\n", inst->seqNum);
942315SN/A    DPRINTF(Activity, "Activity: Writeback event [sn:%lli].\n", inst->seqNum);
952315SN/A
962315SN/A    //iewStage->ldstQueue.removeMSHR(inst->threadNumber,inst->seqNum);
972354SN/A
982354SN/A    assert(!pkt->wasNacked());
992332SN/A
1002332SN/A    // If this is a split access, wait until all packets are received.
1012332SN/A    if (TheISA::HasUnalignedMemAcc && !state->complete()) {
1022315SN/A        delete pkt->req;
1032315SN/A        delete pkt;
1042315SN/A        return;
1052315SN/A    }
1062315SN/A
1072679SN/A    if (isSwitchedOut() || inst->isSquashed()) {
1082315SN/A        iewStage->decrWb(inst->seqNum);
1092315SN/A    } else {
1102315SN/A        if (!state->noWB) {
1112315SN/A            if (!TheISA::HasUnalignedMemAcc || !state->isSplit ||
1122315SN/A                !state->isLoad) {
1132683SN/A                writeback(inst, pkt);
1142315SN/A            } else {
1152683SN/A                writeback(inst, state->mainPkt);
1162315SN/A            }
1172315SN/A        }
1182332SN/A
1192332SN/A        if (inst->isStore()) {
1202332SN/A            completeStore(state->idx);
1212315SN/A        }
1222315SN/A    }
1232683SN/A
1242315SN/A    if (TheISA::HasUnalignedMemAcc && state->isSplit && state->isLoad) {
1252683SN/A        delete state->mainPkt->req;
1262315SN/A        delete state->mainPkt;
1272315SN/A    }
1282332SN/A    delete state;
1292332SN/A    delete pkt->req;
1302683SN/A    delete pkt;
1312732SN/A}
1322315SN/A
1332315SN/Atemplate <class Impl>
1342315SN/ALSQUnit<Impl>::LSQUnit()
1352315SN/A    : loads(0), stores(0), storesToWB(0), stalled(false),
1362315SN/A      isStoreBlocked(false), isLoadBlocked(false),
1372315SN/A      loadBlockedHandled(false), hasPendingPkt(false)
1382315SN/A{
1392683SN/A}
1402315SN/A
1412315SN/Atemplate<class Impl>
1422315SN/Avoid
1432332SN/ALSQUnit<Impl>::init(O3CPU *cpu_ptr, IEW *iew_ptr, DerivO3CPUParams *params,
1442332SN/A        LSQ *lsq_ptr, unsigned maxLQEntries, unsigned maxSQEntries,
1452332SN/A        unsigned id)
1462332SN/A{
1472332SN/A    cpu = cpu_ptr;
1482332SN/A    iewStage = iew_ptr;
1492332SN/A
1502332SN/A    DPRINTF(LSQUnit, "Creating LSQUnit%i object.\n",id);
1512683SN/A
1522679SN/A    switchedOut = false;
1532332SN/A
1542679SN/A    lsq = lsq_ptr;
1552679SN/A
1562683SN/A    lsqID = id;
1572683SN/A
1582315SN/A    // Add 1 for the sentinel entry (they are circular queues).
1592315SN/A    LQEntries = maxLQEntries + 1;
1602315SN/A    SQEntries = maxSQEntries + 1;
1612315SN/A
1622323SN/A    loadQueue.resize(LQEntries);
1632332SN/A    storeQueue.resize(SQEntries);
1642332SN/A
1652332SN/A    loadHead = loadTail = 0;
1662332SN/A
1672332SN/A    storeHead = storeWBIdx = storeTail = 0;
1682332SN/A
1692683SN/A    usedPorts = 0;
1702732SN/A    cachePorts = params->cachePorts;
1712315SN/A
1722323SN/A    retryPkt = NULL;
1732683SN/A    memDepViolator = NULL;
1742683SN/A
1752315SN/A    blockedLoadSeqNum = 0;
1762354SN/A}
1772323SN/A
1782332SN/Atemplate<class Impl>
1792332SN/Astd::string
1802332SN/ALSQUnit<Impl>::name() const
1812323SN/A{
1822323SN/A    if (Impl::MaxThreads == 1) {
1832315SN/A        return iewStage->name() + ".lsq";
1842315SN/A    } else {
1852323SN/A        return iewStage->name() + ".lsq.thread." + to_string(lsqID);
1862679SN/A    }
1872679SN/A}
1882679SN/A
1892679SN/Atemplate<class Impl>
1902679SN/Avoid
1912679SN/ALSQUnit<Impl>::regStats()
1922679SN/A{
1932679SN/A    lsqForwLoads
1942315SN/A        .name(name() + ".forwLoads")
1952332SN/A        .desc("Number of loads that had data forwarded from stores");
1962323SN/A
1972315SN/A    invAddrLoads
1982323SN/A        .name(name() + ".invAddrLoads")
1992323SN/A        .desc("Number of loads ignored due to an invalid address");
2002323SN/A
2012323SN/A    lsqSquashedLoads
2022323SN/A        .name(name() + ".squashedLoads")
2032315SN/A        .desc("Number of loads squashed");
2042332SN/A
2052683SN/A    lsqIgnoredResponses
2062315SN/A        .name(name() + ".ignoredResponses")
2072315SN/A        .desc("Number of memory responses ignored because the instruction is squashed");
2082683SN/A
2092315SN/A    lsqMemOrderViolation
2102315SN/A        .name(name() + ".memOrderViolation")
2112323SN/A        .desc("Number of memory ordering violations");
2122323SN/A
2132315SN/A    lsqSquashedStores
2142679SN/A        .name(name() + ".squashedStores")
2152679SN/A        .desc("Number of stores squashed");
2162679SN/A
2172679SN/A    invAddrSwpfs
2182315SN/A        .name(name() + ".invAddrSwpfs")
2192315SN/A        .desc("Number of software prefetches ignored due to an invalid address");
2202315SN/A
2212315SN/A    lsqBlockedLoads
2222315SN/A        .name(name() + ".blockedLoads")
2232683SN/A        .desc("Number of blocked loads due to partial load-store forwarding");
2242315SN/A
2252354SN/A    lsqRescheduledLoads
2262354SN/A        .name(name() + ".rescheduledLoads")
2272315SN/A        .desc("Number of loads that were rescheduled");
2282315SN/A
2292315SN/A    lsqCacheBlocked
2302315SN/A        .name(name() + ".cacheBlocked")
2312315SN/A        .desc("Number of times an access to memory failed due to the cache being blocked");
2322315SN/A}
2332315SN/A
2342315SN/Atemplate<class Impl>
2352315SN/Avoid
2362315SN/ALSQUnit<Impl>::setDcachePort(Port *dcache_port)
2372315SN/A{
2382690SN/A    dcachePort = dcache_port;
2392315SN/A
2402683SN/A#if USE_CHECKER
2412315SN/A    if (cpu->checker) {
2422838Sktlim@umich.edu        cpu->checker->setDcachePort(dcachePort);
2432315SN/A    }
2442315SN/A#endif
2452315SN/A}
2462683SN/A
2472683SN/Atemplate<class Impl>
2482315SN/Avoid
2492315SN/ALSQUnit<Impl>::clearLQ()
2502683SN/A{
2512683SN/A    loadQueue.clear();
2522683SN/A}
2532315SN/A
2542315SN/Atemplate<class Impl>
2552315SN/Avoid
2562315SN/ALSQUnit<Impl>::clearSQ()
2572315SN/A{
2582332SN/A    storeQueue.clear();
2592332SN/A}
2602332SN/A
2612315SN/Atemplate<class Impl>
2622315SN/Avoid
2632315SN/ALSQUnit<Impl>::switchOut()
2642683SN/A{
2652690SN/A    switchedOut = true;
2662315SN/A    for (int i = 0; i < loadQueue.size(); ++i) {
2672683SN/A        assert(!loadQueue[i]);
2682315SN/A        loadQueue[i] = NULL;
2692315SN/A    }
2702683SN/A
2712315SN/A    assert(storesToWB == 0);
2722315SN/A}
2732315SN/A
2742315SN/Atemplate<class Impl>
2752332SN/Avoid
2762315SN/ALSQUnit<Impl>::takeOverFrom()
2772315SN/A{
2782315SN/A    switchedOut = false;
2792679SN/A    loads = stores = storesToWB = 0;
2802679SN/A
2812679SN/A    loadHead = loadTail = 0;
2822679SN/A
2832679SN/A    storeHead = storeWBIdx = storeTail = 0;
2842332SN/A
2852332SN/A    usedPorts = 0;
2862315SN/A
2872315SN/A    memDepViolator = NULL;
2882315SN/A
2892315SN/A    blockedLoadSeqNum = 0;
2902315SN/A
2912315SN/A    stalled = false;
2922315SN/A    isLoadBlocked = false;
2932315SN/A    loadBlockedHandled = false;
2942315SN/A}
2952354SN/A
2962315SN/Atemplate<class Impl>
2972315SN/Avoid
2982315SN/ALSQUnit<Impl>::resizeLQ(unsigned size)
2992315SN/A{
3002840Sktlim@umich.edu    unsigned size_plus_sentinel = size + 1;
3012315SN/A    assert(size_plus_sentinel >= LQEntries);
3022315SN/A
3032315SN/A    if (size_plus_sentinel > LQEntries) {
3042315SN/A        while (size_plus_sentinel > loadQueue.size()) {
3052315SN/A            DynInstPtr dummy;
3062315SN/A            loadQueue.push_back(dummy);
3072315SN/A            LQEntries++;
3082315SN/A        }
3092315SN/A    } else {
3102315SN/A        LQEntries = size_plus_sentinel;
3112315SN/A    }
3122315SN/A
3132315SN/A}
3142315SN/A
3152683SN/Atemplate<class Impl>
3162332SN/Avoid
3172683SN/ALSQUnit<Impl>::resizeSQ(unsigned size)
3182315SN/A{
3192332SN/A    unsigned size_plus_sentinel = size + 1;
3202332SN/A    if (size_plus_sentinel > SQEntries) {
3212315SN/A        while (size_plus_sentinel > storeQueue.size()) {
3222732SN/A            SQEntry dummy;
3232315SN/A            storeQueue.push_back(dummy);
3242315SN/A            SQEntries++;
3252315SN/A        }
3262332SN/A    } else {
3272332SN/A        SQEntries = size_plus_sentinel;
3282332SN/A    }
3292332SN/A}
3302332SN/A
3312332SN/Atemplate <class Impl>
3322732SN/Avoid
3332315SN/ALSQUnit<Impl>::insert(DynInstPtr &inst)
3342315SN/A{
3352315SN/A    assert(inst->isMemRef());
3362315SN/A
3372315SN/A    assert(inst->isLoad() || inst->isStore());
3382315SN/A
3392315SN/A    if (inst->isLoad()) {
3402732SN/A        insertLoad(inst);
3412315SN/A    } else {
3422332SN/A        insertStore(inst);
3432315SN/A    }
3442332SN/A
3452332SN/A    inst->setInLSQ();
3462332SN/A}
3472732SN/A
3482315SN/Atemplate <class Impl>
3492732SN/Avoid
3502732SN/ALSQUnit<Impl>::insertLoad(DynInstPtr &load_inst)
3512732SN/A{
3522732SN/A    assert((loadTail + 1) % LQEntries != loadHead);
3532732SN/A    assert(loads < LQEntries);
3542732SN/A
3552732SN/A    DPRINTF(LSQUnit, "Inserting load PC %s, idx:%i [sn:%lli]\n",
3562732SN/A            load_inst->pcState(), loadTail, load_inst->seqNum);
3572732SN/A
3582732SN/A    load_inst->lqIdx = loadTail;
3592732SN/A
3602732SN/A    if (stores == 0) {
3612732SN/A        load_inst->sqIdx = -1;
3622732SN/A    } else {
3632732SN/A        load_inst->sqIdx = storeTail;
3642732SN/A    }
3652732SN/A
3662732SN/A    loadQueue[loadTail] = load_inst;
3672315SN/A
3682315SN/A    incrLdIdx(loadTail);
3692315SN/A
3702683SN/A    ++loads;
3712332SN/A}
3722332SN/A
3732683SN/Atemplate <class Impl>
3742732SN/Avoid
3752315SN/ALSQUnit<Impl>::insertStore(DynInstPtr &store_inst)
3762315SN/A{
3772315SN/A    // Make sure it is not full before inserting an instruction.
3782315SN/A    assert((storeTail + 1) % SQEntries != storeHead);
3792315SN/A    assert(stores < SQEntries);
3802315SN/A
3812315SN/A    DPRINTF(LSQUnit, "Inserting store PC %s, idx:%i [sn:%lli]\n",
3822315SN/A            store_inst->pcState(), storeTail, store_inst->seqNum);
3832315SN/A
3842315SN/A    store_inst->sqIdx = storeTail;
3852315SN/A    store_inst->lqIdx = loadTail;
3862680SN/A
3872683SN/A    storeQueue[storeTail] = SQEntry(store_inst);
3882332SN/A
3892332SN/A    incrStIdx(storeTail);
3902332SN/A
3912680SN/A    ++stores;
3922683SN/A}
3932732SN/A
3942315SN/Atemplate <class Impl>
3952315SN/Atypename Impl::DynInstPtr
3962315SN/ALSQUnit<Impl>::getMemDepViolator()
3972315SN/A{
3982315SN/A    DynInstPtr temp = memDepViolator;
3992315SN/A
4002315SN/A    memDepViolator = NULL;
4012315SN/A
4022354SN/A    return temp;
4032354SN/A}
4042356SN/A
4052354SN/Atemplate <class Impl>
4063126Sktlim@umich.eduunsigned
4072356SN/ALSQUnit<Impl>::numFreeEntries()
4082356SN/A{
4092356SN/A    unsigned free_lq_entries = LQEntries - loads;
4103126Sktlim@umich.edu    unsigned free_sq_entries = SQEntries - stores;
4113126Sktlim@umich.edu
4122356SN/A    // Both the LQ and SQ entries have an extra dummy entry to differentiate
4132356SN/A    // empty/full conditions.  Subtract 1 from the free entries.
4143126Sktlim@umich.edu    if (free_lq_entries < free_sq_entries) {
4153126Sktlim@umich.edu        return free_lq_entries - 1;
4163126Sktlim@umich.edu    } else {
4172356SN/A        return free_sq_entries - 1;
4182354SN/A    }
4193126Sktlim@umich.edu}
4202315SN/A
4212315SN/Atemplate <class Impl>
4222315SN/Aint
4232315SN/ALSQUnit<Impl>::numLoadsReady()
4242732SN/A{
4252732SN/A    int load_idx = loadHead;
4262732SN/A    int retval = 0;
4272732SN/A
4282732SN/A    while (load_idx != loadTail) {
4292732SN/A        assert(loadQueue[load_idx]);
4302732SN/A
4312732SN/A        if (loadQueue[load_idx]->readyToIssue()) {
4322732SN/A            ++retval;
4332732SN/A        }
4342732SN/A    }
4352732SN/A
4362732SN/A    return retval;
4372732SN/A}
4382732SN/A
4392732SN/Atemplate <class Impl>
4402732SN/AFault
4412732SN/ALSQUnit<Impl>::executeLoad(DynInstPtr &inst)
4422732SN/A{
4432732SN/A    using namespace TheISA;
4442732SN/A    // Execute a specific load.
4452732SN/A    Fault load_fault = NoFault;
4462732SN/A
4472732SN/A    DPRINTF(LSQUnit, "Executing load PC %s, [sn:%lli]\n",
4482732SN/A            inst->pcState(),inst->seqNum);
4492732SN/A
4502732SN/A    assert(!inst->isSquashed());
4512732SN/A
4522732SN/A    load_fault = inst->initiateAcc();
4532732SN/A
4542315SN/A    // If the instruction faulted or predicated false, then we need to send it
4552315SN/A    // along to commit without the instruction completing.
4562315SN/A    if (load_fault != NoFault || inst->readPredicate() == false) {
4572315SN/A        // Send this instruction to commit, also make sure iew stage
4582315SN/A        // realizes there is activity.
4592315SN/A        // Mark it as executed unless it is an uncached load that
4602315SN/A        // needs to hit the head of commit.
4612315SN/A        if (inst->readPredicate() == false)
4622315SN/A            inst->forwardOldRegs();
4632315SN/A        DPRINTF(LSQUnit, "Load [sn:%lli] not executed from %s\n",
4642315SN/A                inst->seqNum,
4652315SN/A                (load_fault != NoFault ? "fault" : "predication"));
4662315SN/A        if (!(inst->hasRequest() && inst->uncacheable()) ||
4672315SN/A            inst->isAtCommit()) {
4682315SN/A            inst->setExecuted();
4692315SN/A        }
4702315SN/A        iewStage->instToCommit(inst);
4712315SN/A        iewStage->activityThisCycle();
4722315SN/A    } else if (!loadBlocked()) {
4732315SN/A        assert(inst->effAddrValid);
4742315SN/A        int load_idx = inst->lqIdx;
4752315SN/A        incrLdIdx(load_idx);
4762315SN/A        while (load_idx != loadTail) {
4772315SN/A            // Really only need to check loads that have actually executed
4782315SN/A
4792315SN/A            // @todo: For now this is extra conservative, detecting a
4802315SN/A            // violation if the addresses match assuming all accesses
481            // are quad word accesses.
482
483            // @todo: Fix this, magic number being used here
484
485            // @todo: Uncachable load is not executed until it reaches
486            // the head of the ROB. Once this if checks only the executed
487            // loads(as noted above), this check can be removed
488            if (loadQueue[load_idx]->effAddrValid &&
489                ((loadQueue[load_idx]->effAddr >> 8)
490                 == (inst->effAddr >> 8)) &&
491                !loadQueue[load_idx]->uncacheable()) {
492                // A load incorrectly passed this load.  Squash and refetch.
493                // For now return a fault to show that it was unsuccessful.
494                DynInstPtr violator = loadQueue[load_idx];
495                if (!memDepViolator ||
496                    (violator->seqNum < memDepViolator->seqNum)) {
497                    memDepViolator = violator;
498                } else {
499                    break;
500                }
501
502                ++lsqMemOrderViolation;
503
504                return genMachineCheckFault();
505            }
506
507            incrLdIdx(load_idx);
508        }
509    }
510
511    return load_fault;
512}
513
514template <class Impl>
515Fault
516LSQUnit<Impl>::executeStore(DynInstPtr &store_inst)
517{
518    using namespace TheISA;
519    // Make sure that a store exists.
520    assert(stores != 0);
521
522    int store_idx = store_inst->sqIdx;
523
524    DPRINTF(LSQUnit, "Executing store PC %s [sn:%lli]\n",
525            store_inst->pcState(), store_inst->seqNum);
526
527    assert(!store_inst->isSquashed());
528
529    // Check the recently completed loads to see if any match this store's
530    // address.  If so, then we have a memory ordering violation.
531    int load_idx = store_inst->lqIdx;
532
533    Fault store_fault = store_inst->initiateAcc();
534
535    if (store_inst->readPredicate() == false)
536        store_inst->forwardOldRegs();
537
538    if (storeQueue[store_idx].size == 0) {
539        DPRINTF(LSQUnit,"Fault on Store PC %s, [sn:%lli], Size = 0\n",
540                store_inst->pcState(), store_inst->seqNum);
541
542        return store_fault;
543    } else if (store_inst->readPredicate() == false) {
544        DPRINTF(LSQUnit, "Store [sn:%lli] not executed from predication\n",
545                store_inst->seqNum);
546        return store_fault;
547    }
548
549    assert(store_fault == NoFault);
550
551    if (store_inst->isStoreConditional()) {
552        // Store conditionals need to set themselves as able to
553        // writeback if we haven't had a fault by here.
554        storeQueue[store_idx].canWB = true;
555
556        ++storesToWB;
557    }
558
559    assert(store_inst->effAddrValid);
560    while (load_idx != loadTail) {
561        // Really only need to check loads that have actually executed
562        // It's safe to check all loads because effAddr is set to
563        // InvalAddr when the dyn inst is created.
564
565        // @todo: For now this is extra conservative, detecting a
566        // violation if the addresses match assuming all accesses
567        // are quad word accesses.
568
569        // @todo: Fix this, magic number being used here
570
571        // @todo: Uncachable load is not executed until it reaches
572        // the head of the ROB. Once this if checks only the executed
573        // loads(as noted above), this check can be removed
574        if (loadQueue[load_idx]->effAddrValid &&
575            ((loadQueue[load_idx]->effAddr >> 8)
576             == (store_inst->effAddr >> 8)) &&
577            !loadQueue[load_idx]->uncacheable()) {
578            // A load incorrectly passed this store.  Squash and refetch.
579            // For now return a fault to show that it was unsuccessful.
580            DynInstPtr violator = loadQueue[load_idx];
581            if (!memDepViolator ||
582                (violator->seqNum < memDepViolator->seqNum)) {
583                memDepViolator = violator;
584            } else {
585                break;
586            }
587
588            ++lsqMemOrderViolation;
589
590            return genMachineCheckFault();
591        }
592
593        incrLdIdx(load_idx);
594    }
595
596    return store_fault;
597}
598
599template <class Impl>
600void
601LSQUnit<Impl>::commitLoad()
602{
603    assert(loadQueue[loadHead]);
604
605    DPRINTF(LSQUnit, "Committing head load instruction, PC %s\n",
606            loadQueue[loadHead]->pcState());
607
608    loadQueue[loadHead] = NULL;
609
610    incrLdIdx(loadHead);
611
612    --loads;
613}
614
615template <class Impl>
616void
617LSQUnit<Impl>::commitLoads(InstSeqNum &youngest_inst)
618{
619    assert(loads == 0 || loadQueue[loadHead]);
620
621    while (loads != 0 && loadQueue[loadHead]->seqNum <= youngest_inst) {
622        commitLoad();
623    }
624}
625
626template <class Impl>
627void
628LSQUnit<Impl>::commitStores(InstSeqNum &youngest_inst)
629{
630    assert(stores == 0 || storeQueue[storeHead].inst);
631
632    int store_idx = storeHead;
633
634    while (store_idx != storeTail) {
635        assert(storeQueue[store_idx].inst);
636        // Mark any stores that are now committed and have not yet
637        // been marked as able to write back.
638        if (!storeQueue[store_idx].canWB) {
639            if (storeQueue[store_idx].inst->seqNum > youngest_inst) {
640                break;
641            }
642            DPRINTF(LSQUnit, "Marking store as able to write back, PC "
643                    "%s [sn:%lli]\n",
644                    storeQueue[store_idx].inst->pcState(),
645                    storeQueue[store_idx].inst->seqNum);
646
647            storeQueue[store_idx].canWB = true;
648
649            ++storesToWB;
650        }
651
652        incrStIdx(store_idx);
653    }
654}
655
656template <class Impl>
657void
658LSQUnit<Impl>::writebackPendingStore()
659{
660    if (hasPendingPkt) {
661        assert(pendingPkt != NULL);
662
663        // If the cache is blocked, this will store the packet for retry.
664        if (sendStore(pendingPkt)) {
665            storePostSend(pendingPkt);
666        }
667        pendingPkt = NULL;
668        hasPendingPkt = false;
669    }
670}
671
672template <class Impl>
673void
674LSQUnit<Impl>::writebackStores()
675{
676    // First writeback the second packet from any split store that didn't
677    // complete last cycle because there weren't enough cache ports available.
678    if (TheISA::HasUnalignedMemAcc) {
679        writebackPendingStore();
680    }
681
682    while (storesToWB > 0 &&
683           storeWBIdx != storeTail &&
684           storeQueue[storeWBIdx].inst &&
685           storeQueue[storeWBIdx].canWB &&
686           usedPorts < cachePorts) {
687
688        if (isStoreBlocked || lsq->cacheBlocked()) {
689            DPRINTF(LSQUnit, "Unable to write back any more stores, cache"
690                    " is blocked!\n");
691            break;
692        }
693
694        // Store didn't write any data so no need to write it back to
695        // memory.
696        if (storeQueue[storeWBIdx].size == 0) {
697            completeStore(storeWBIdx);
698
699            incrStIdx(storeWBIdx);
700
701            continue;
702        }
703
704        ++usedPorts;
705
706        if (storeQueue[storeWBIdx].inst->isDataPrefetch()) {
707            incrStIdx(storeWBIdx);
708
709            continue;
710        }
711
712        assert(storeQueue[storeWBIdx].req);
713        assert(!storeQueue[storeWBIdx].committed);
714
715        if (TheISA::HasUnalignedMemAcc && storeQueue[storeWBIdx].isSplit) {
716            assert(storeQueue[storeWBIdx].sreqLow);
717            assert(storeQueue[storeWBIdx].sreqHigh);
718        }
719
720        DynInstPtr inst = storeQueue[storeWBIdx].inst;
721
722        Request *req = storeQueue[storeWBIdx].req;
723        storeQueue[storeWBIdx].committed = true;
724
725        assert(!inst->memData);
726        inst->memData = new uint8_t[64];
727
728        memcpy(inst->memData, storeQueue[storeWBIdx].data, req->getSize());
729
730        MemCmd command =
731            req->isSwap() ? MemCmd::SwapReq :
732            (req->isLLSC() ? MemCmd::StoreCondReq : MemCmd::WriteReq);
733        PacketPtr data_pkt;
734        PacketPtr snd_data_pkt = NULL;
735
736        LSQSenderState *state = new LSQSenderState;
737        state->isLoad = false;
738        state->idx = storeWBIdx;
739        state->inst = inst;
740
741        if (!TheISA::HasUnalignedMemAcc || !storeQueue[storeWBIdx].isSplit) {
742
743            // Build a single data packet if the store isn't split.
744            data_pkt = new Packet(req, command, Packet::Broadcast);
745            data_pkt->dataStatic(inst->memData);
746            data_pkt->senderState = state;
747        } else {
748            RequestPtr sreqLow = storeQueue[storeWBIdx].sreqLow;
749            RequestPtr sreqHigh = storeQueue[storeWBIdx].sreqHigh;
750
751            // Create two packets if the store is split in two.
752            data_pkt = new Packet(sreqLow, command, Packet::Broadcast);
753            snd_data_pkt = new Packet(sreqHigh, command, Packet::Broadcast);
754
755            data_pkt->dataStatic(inst->memData);
756            snd_data_pkt->dataStatic(inst->memData + sreqLow->getSize());
757
758            data_pkt->senderState = state;
759            snd_data_pkt->senderState = state;
760
761            state->isSplit = true;
762            state->outstanding = 2;
763
764            // Can delete the main request now.
765            delete req;
766            req = sreqLow;
767        }
768
769        DPRINTF(LSQUnit, "D-Cache: Writing back store idx:%i PC:%s "
770                "to Addr:%#x, data:%#x [sn:%lli]\n",
771                storeWBIdx, inst->pcState(),
772                req->getPaddr(), (int)*(inst->memData),
773                inst->seqNum);
774
775        // @todo: Remove this SC hack once the memory system handles it.
776        if (inst->isStoreConditional()) {
777            assert(!storeQueue[storeWBIdx].isSplit);
778            // Disable recording the result temporarily.  Writing to
779            // misc regs normally updates the result, but this is not
780            // the desired behavior when handling store conditionals.
781            inst->recordResult = false;
782            bool success = TheISA::handleLockedWrite(inst.get(), req);
783            inst->recordResult = true;
784
785            if (!success) {
786                // Instantly complete this store.
787                DPRINTF(LSQUnit, "Store conditional [sn:%lli] failed.  "
788                        "Instantly completing it.\n",
789                        inst->seqNum);
790                WritebackEvent *wb = new WritebackEvent(inst, data_pkt, this);
791                cpu->schedule(wb, curTick() + 1);
792                completeStore(storeWBIdx);
793                incrStIdx(storeWBIdx);
794                continue;
795            }
796        } else {
797            // Non-store conditionals do not need a writeback.
798            state->noWB = true;
799        }
800
801        if (!sendStore(data_pkt)) {
802            DPRINTF(IEW, "D-Cache became blocked when writing [sn:%lli], will"
803                    "retry later\n",
804                    inst->seqNum);
805
806            // Need to store the second packet, if split.
807            if (TheISA::HasUnalignedMemAcc && storeQueue[storeWBIdx].isSplit) {
808                state->pktToSend = true;
809                state->pendingPacket = snd_data_pkt;
810            }
811        } else {
812
813            // If split, try to send the second packet too
814            if (TheISA::HasUnalignedMemAcc && storeQueue[storeWBIdx].isSplit) {
815                assert(snd_data_pkt);
816
817                // Ensure there are enough ports to use.
818                if (usedPorts < cachePorts) {
819                    ++usedPorts;
820                    if (sendStore(snd_data_pkt)) {
821                        storePostSend(snd_data_pkt);
822                    } else {
823                        DPRINTF(IEW, "D-Cache became blocked when writing"
824                                " [sn:%lli] second packet, will retry later\n",
825                                inst->seqNum);
826                    }
827                } else {
828
829                    // Store the packet for when there's free ports.
830                    assert(pendingPkt == NULL);
831                    pendingPkt = snd_data_pkt;
832                    hasPendingPkt = true;
833                }
834            } else {
835
836                // Not a split store.
837                storePostSend(data_pkt);
838            }
839        }
840    }
841
842    // Not sure this should set it to 0.
843    usedPorts = 0;
844
845    assert(stores >= 0 && storesToWB >= 0);
846}
847
848/*template <class Impl>
849void
850LSQUnit<Impl>::removeMSHR(InstSeqNum seqNum)
851{
852    list<InstSeqNum>::iterator mshr_it = find(mshrSeqNums.begin(),
853                                              mshrSeqNums.end(),
854                                              seqNum);
855
856    if (mshr_it != mshrSeqNums.end()) {
857        mshrSeqNums.erase(mshr_it);
858        DPRINTF(LSQUnit, "Removing MSHR. count = %i\n",mshrSeqNums.size());
859    }
860}*/
861
862template <class Impl>
863void
864LSQUnit<Impl>::squash(const InstSeqNum &squashed_num)
865{
866    DPRINTF(LSQUnit, "Squashing until [sn:%lli]!"
867            "(Loads:%i Stores:%i)\n", squashed_num, loads, stores);
868
869    int load_idx = loadTail;
870    decrLdIdx(load_idx);
871
872    while (loads != 0 && loadQueue[load_idx]->seqNum > squashed_num) {
873        DPRINTF(LSQUnit,"Load Instruction PC %s squashed, "
874                "[sn:%lli]\n",
875                loadQueue[load_idx]->pcState(),
876                loadQueue[load_idx]->seqNum);
877
878        if (isStalled() && load_idx == stallingLoadIdx) {
879            stalled = false;
880            stallingStoreIsn = 0;
881            stallingLoadIdx = 0;
882        }
883
884        // Clear the smart pointer to make sure it is decremented.
885        loadQueue[load_idx]->setSquashed();
886        loadQueue[load_idx] = NULL;
887        --loads;
888
889        // Inefficient!
890        loadTail = load_idx;
891
892        decrLdIdx(load_idx);
893        ++lsqSquashedLoads;
894    }
895
896    if (isLoadBlocked) {
897        if (squashed_num < blockedLoadSeqNum) {
898            isLoadBlocked = false;
899            loadBlockedHandled = false;
900            blockedLoadSeqNum = 0;
901        }
902    }
903
904    if (memDepViolator && squashed_num < memDepViolator->seqNum) {
905        memDepViolator = NULL;
906    }
907
908    int store_idx = storeTail;
909    decrStIdx(store_idx);
910
911    while (stores != 0 &&
912           storeQueue[store_idx].inst->seqNum > squashed_num) {
913        // Instructions marked as can WB are already committed.
914        if (storeQueue[store_idx].canWB) {
915            break;
916        }
917
918        DPRINTF(LSQUnit,"Store Instruction PC %s squashed, "
919                "idx:%i [sn:%lli]\n",
920                storeQueue[store_idx].inst->pcState(),
921                store_idx, storeQueue[store_idx].inst->seqNum);
922
923        // I don't think this can happen.  It should have been cleared
924        // by the stalling load.
925        if (isStalled() &&
926            storeQueue[store_idx].inst->seqNum == stallingStoreIsn) {
927            panic("Is stalled should have been cleared by stalling load!\n");
928            stalled = false;
929            stallingStoreIsn = 0;
930        }
931
932        // Clear the smart pointer to make sure it is decremented.
933        storeQueue[store_idx].inst->setSquashed();
934        storeQueue[store_idx].inst = NULL;
935        storeQueue[store_idx].canWB = 0;
936
937        // Must delete request now that it wasn't handed off to
938        // memory.  This is quite ugly.  @todo: Figure out the proper
939        // place to really handle request deletes.
940        delete storeQueue[store_idx].req;
941        if (TheISA::HasUnalignedMemAcc && storeQueue[store_idx].isSplit) {
942            delete storeQueue[store_idx].sreqLow;
943            delete storeQueue[store_idx].sreqHigh;
944
945            storeQueue[store_idx].sreqLow = NULL;
946            storeQueue[store_idx].sreqHigh = NULL;
947        }
948
949        storeQueue[store_idx].req = NULL;
950        --stores;
951
952        // Inefficient!
953        storeTail = store_idx;
954
955        decrStIdx(store_idx);
956        ++lsqSquashedStores;
957    }
958}
959
960template <class Impl>
961void
962LSQUnit<Impl>::storePostSend(PacketPtr pkt)
963{
964    if (isStalled() &&
965        storeQueue[storeWBIdx].inst->seqNum == stallingStoreIsn) {
966        DPRINTF(LSQUnit, "Unstalling, stalling store [sn:%lli] "
967                "load idx:%i\n",
968                stallingStoreIsn, stallingLoadIdx);
969        stalled = false;
970        stallingStoreIsn = 0;
971        iewStage->replayMemInst(loadQueue[stallingLoadIdx]);
972    }
973
974    if (!storeQueue[storeWBIdx].inst->isStoreConditional()) {
975        // The store is basically completed at this time. This
976        // only works so long as the checker doesn't try to
977        // verify the value in memory for stores.
978        storeQueue[storeWBIdx].inst->setCompleted();
979#if USE_CHECKER
980        if (cpu->checker) {
981            cpu->checker->verify(storeQueue[storeWBIdx].inst);
982        }
983#endif
984    }
985
986    incrStIdx(storeWBIdx);
987}
988
989template <class Impl>
990void
991LSQUnit<Impl>::writeback(DynInstPtr &inst, PacketPtr pkt)
992{
993    iewStage->wakeCPU();
994
995    // Squashed instructions do not need to complete their access.
996    if (inst->isSquashed()) {
997        iewStage->decrWb(inst->seqNum);
998        assert(!inst->isStore());
999        ++lsqIgnoredResponses;
1000        return;
1001    }
1002
1003    if (!inst->isExecuted()) {
1004        inst->setExecuted();
1005
1006        // Complete access to copy data to proper place.
1007        inst->completeAcc(pkt);
1008    }
1009
1010    // Need to insert instruction into queue to commit
1011    iewStage->instToCommit(inst);
1012
1013    iewStage->activityThisCycle();
1014
1015    // see if this load changed the PC
1016    iewStage->checkMisprediction(inst);
1017}
1018
1019template <class Impl>
1020void
1021LSQUnit<Impl>::completeStore(int store_idx)
1022{
1023    assert(storeQueue[store_idx].inst);
1024    storeQueue[store_idx].completed = true;
1025    --storesToWB;
1026    // A bit conservative because a store completion may not free up entries,
1027    // but hopefully avoids two store completions in one cycle from making
1028    // the CPU tick twice.
1029    cpu->wakeCPU();
1030    cpu->activityThisCycle();
1031
1032    if (store_idx == storeHead) {
1033        do {
1034            incrStIdx(storeHead);
1035
1036            --stores;
1037        } while (storeQueue[storeHead].completed &&
1038                 storeHead != storeTail);
1039
1040        iewStage->updateLSQNextCycle = true;
1041    }
1042
1043    DPRINTF(LSQUnit, "Completing store [sn:%lli], idx:%i, store head "
1044            "idx:%i\n",
1045            storeQueue[store_idx].inst->seqNum, store_idx, storeHead);
1046
1047    if (isStalled() &&
1048        storeQueue[store_idx].inst->seqNum == stallingStoreIsn) {
1049        DPRINTF(LSQUnit, "Unstalling, stalling store [sn:%lli] "
1050                "load idx:%i\n",
1051                stallingStoreIsn, stallingLoadIdx);
1052        stalled = false;
1053        stallingStoreIsn = 0;
1054        iewStage->replayMemInst(loadQueue[stallingLoadIdx]);
1055    }
1056
1057    storeQueue[store_idx].inst->setCompleted();
1058
1059    // Tell the checker we've completed this instruction.  Some stores
1060    // may get reported twice to the checker, but the checker can
1061    // handle that case.
1062#if USE_CHECKER
1063    if (cpu->checker) {
1064        cpu->checker->verify(storeQueue[store_idx].inst);
1065    }
1066#endif
1067}
1068
1069template <class Impl>
1070bool
1071LSQUnit<Impl>::sendStore(PacketPtr data_pkt)
1072{
1073    if (!dcachePort->sendTiming(data_pkt)) {
1074        // Need to handle becoming blocked on a store.
1075        isStoreBlocked = true;
1076        ++lsqCacheBlocked;
1077        assert(retryPkt == NULL);
1078        retryPkt = data_pkt;
1079        lsq->setRetryTid(lsqID);
1080        return false;
1081    }
1082    return true;
1083}
1084
1085template <class Impl>
1086void
1087LSQUnit<Impl>::recvRetry()
1088{
1089    if (isStoreBlocked) {
1090        DPRINTF(LSQUnit, "Receiving retry: store blocked\n");
1091        assert(retryPkt != NULL);
1092
1093        if (dcachePort->sendTiming(retryPkt)) {
1094            LSQSenderState *state =
1095                dynamic_cast<LSQSenderState *>(retryPkt->senderState);
1096
1097            // Don't finish the store unless this is the last packet.
1098            if (!TheISA::HasUnalignedMemAcc || !state->pktToSend) {
1099                storePostSend(retryPkt);
1100            }
1101            retryPkt = NULL;
1102            isStoreBlocked = false;
1103            lsq->setRetryTid(InvalidThreadID);
1104
1105            // Send any outstanding packet.
1106            if (TheISA::HasUnalignedMemAcc && state->pktToSend) {
1107                assert(state->pendingPacket);
1108                if (sendStore(state->pendingPacket)) {
1109                    storePostSend(state->pendingPacket);
1110                }
1111            }
1112        } else {
1113            // Still blocked!
1114            ++lsqCacheBlocked;
1115            lsq->setRetryTid(lsqID);
1116        }
1117    } else if (isLoadBlocked) {
1118        DPRINTF(LSQUnit, "Loads squash themselves and all younger insts, "
1119                "no need to resend packet.\n");
1120    } else {
1121        DPRINTF(LSQUnit, "Retry received but LSQ is no longer blocked.\n");
1122    }
1123}
1124
1125template <class Impl>
1126inline void
1127LSQUnit<Impl>::incrStIdx(int &store_idx)
1128{
1129    if (++store_idx >= SQEntries)
1130        store_idx = 0;
1131}
1132
1133template <class Impl>
1134inline void
1135LSQUnit<Impl>::decrStIdx(int &store_idx)
1136{
1137    if (--store_idx < 0)
1138        store_idx += SQEntries;
1139}
1140
1141template <class Impl>
1142inline void
1143LSQUnit<Impl>::incrLdIdx(int &load_idx)
1144{
1145    if (++load_idx >= LQEntries)
1146        load_idx = 0;
1147}
1148
1149template <class Impl>
1150inline void
1151LSQUnit<Impl>::decrLdIdx(int &load_idx)
1152{
1153    if (--load_idx < 0)
1154        load_idx += LQEntries;
1155}
1156
1157template <class Impl>
1158void
1159LSQUnit<Impl>::dumpInsts()
1160{
1161    cprintf("Load store queue: Dumping instructions.\n");
1162    cprintf("Load queue size: %i\n", loads);
1163    cprintf("Load queue: ");
1164
1165    int load_idx = loadHead;
1166
1167    while (load_idx != loadTail && loadQueue[load_idx]) {
1168        cprintf("%s ", loadQueue[load_idx]->pcState());
1169
1170        incrLdIdx(load_idx);
1171    }
1172
1173    cprintf("Store queue size: %i\n", stores);
1174    cprintf("Store queue: ");
1175
1176    int store_idx = storeHead;
1177
1178    while (store_idx != storeTail && storeQueue[store_idx].inst) {
1179        cprintf("%s ", storeQueue[store_idx].inst->pcState());
1180
1181        incrStIdx(store_idx);
1182    }
1183
1184    cprintf("\n");
1185}
1186