2 * Copyright (c) 2004-2005 The Regents of The University of Michigan
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met: redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer;
9 * redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution;
12 * neither the name of the copyright holders nor the names of its
13 * contributors may be used to endorse or promote products derived from
14 * this software without specific prior written permission.
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 #include "config/use_checker.hh"
34 #include "cpu/o3/lsq.hh"
35 #include "cpu/o3/lsq_unit.hh"
36 #include "base/str.hh"
37 #include "mem/packet.hh"
38 #include "mem/request.hh"
41 #include "cpu/checker/cpu.hh"
45 LSQUnit<Impl>::WritebackEvent::WritebackEvent(DynInstPtr &_inst, PacketPtr _pkt,
47 : Event(&mainEventQueue), inst(_inst), pkt(_pkt), lsqPtr(lsq_ptr)
49 this->setFlags(Event::AutoDelete);
54 LSQUnit<Impl>::WritebackEvent::process()
56 if (!lsqPtr->isSwitchedOut()) {
57 lsqPtr->writeback(inst, pkt);
64 LSQUnit<Impl>::WritebackEvent::description()
66 return "Store writeback event";
71 LSQUnit<Impl>::completeDataAccess(PacketPtr pkt)
73 LSQSenderState *state = dynamic_cast<LSQSenderState *>(pkt->senderState);
74 DynInstPtr inst = state->inst;
75 DPRINTF(IEW, "Writeback event [sn:%lli]\n", inst->seqNum);
76 DPRINTF(Activity, "Activity: Writeback event [sn:%lli]\n", inst->seqNum);
78 //iewStage->ldstQueue.removeMSHR(inst->threadNumber,inst->seqNum);
80 if (isSwitchedOut() || inst->isSquashed()) {
81 iewStage->decrWb(inst->seqNum);
90 if (inst->isStore()) {
91 completeStore(state->idx);
100 LSQUnit<Impl>::LSQUnit()
101 : loads(0), stores(0), storesToWB(0), stalled(false),
102 isStoreBlocked(false), isLoadBlocked(false),
103 loadBlockedHandled(false)
109 LSQUnit<Impl>::init(Params *params, LSQ *lsq_ptr, unsigned maxLQEntries,
110 unsigned maxSQEntries, unsigned id)
112 DPRINTF(LSQUnit, "Creating LSQUnit%i object.\n",id);
120 // Add 1 for the sentinel entry (they are circular queues).
121 LQEntries = maxLQEntries + 1;
122 SQEntries = maxSQEntries + 1;
124 loadQueue.resize(LQEntries);
125 storeQueue.resize(SQEntries);
127 loadHead = loadTail = 0;
129 storeHead = storeWBIdx = storeTail = 0;
132 cachePorts = params->cachePorts;
134 memDepViolator = NULL;
136 blockedLoadSeqNum = 0;
141 LSQUnit<Impl>::setCPU(O3CPU *cpu_ptr)
147 cpu->checker->setDcachePort(dcachePort);
154 LSQUnit<Impl>::name() const
156 if (Impl::MaxThreads == 1) {
157 return iewStage->name() + ".lsq";
159 return iewStage->name() + ".lsq.thread." + to_string(lsqID);
165 LSQUnit<Impl>::regStats()
168 .name(name() + ".forwLoads")
169 .desc("Number of loads that had data forwarded from stores");
172 .name(name() + ".invAddrLoads")
173 .desc("Number of loads ignored due to an invalid address");
176 .name(name() + ".squashedLoads")
177 .desc("Number of loads squashed");
180 .name(name() + ".ignoredResponses")
181 .desc("Number of memory responses ignored because the instruction is squashed");
184 .name(name() + ".memOrderViolation")
185 .desc("Number of memory ordering violations");
188 .name(name() + ".squashedStores")
189 .desc("Number of stores squashed");
192 .name(name() + ".invAddrSwpfs")
193 .desc("Number of software prefetches ignored due to an invalid address");
196 .name(name() + ".blockedLoads")
197 .desc("Number of blocked loads due to partial load-store forwarding");
200 .name(name() + ".rescheduledLoads")
201 .desc("Number of loads that were rescheduled");
204 .name(name() + ".cacheBlocked")
205 .desc("Number of times an access to memory failed due to the cache being blocked");
210 LSQUnit<Impl>::clearLQ()
217 LSQUnit<Impl>::clearSQ()
224 LSQUnit<Impl>::switchOut()
227 for (int i = 0; i < loadQueue.size(); ++i) {
228 assert(!loadQueue[i]);
232 assert(storesToWB == 0);
237 LSQUnit<Impl>::takeOverFrom()
240 loads = stores = storesToWB = 0;
242 loadHead = loadTail = 0;
244 storeHead = storeWBIdx = storeTail = 0;
248 memDepViolator = NULL;
250 blockedLoadSeqNum = 0;
253 isLoadBlocked = false;
254 loadBlockedHandled = false;
259 LSQUnit<Impl>::resizeLQ(unsigned size)
261 unsigned size_plus_sentinel = size + 1;
262 assert(size_plus_sentinel >= LQEntries);
264 if (size_plus_sentinel > LQEntries) {
265 while (size_plus_sentinel > loadQueue.size()) {
267 loadQueue.push_back(dummy);
271 LQEntries = size_plus_sentinel;
278 LSQUnit<Impl>::resizeSQ(unsigned size)
280 unsigned size_plus_sentinel = size + 1;
281 if (size_plus_sentinel > SQEntries) {
282 while (size_plus_sentinel > storeQueue.size()) {
284 storeQueue.push_back(dummy);
288 SQEntries = size_plus_sentinel;
292 template <class Impl>
294 LSQUnit<Impl>::insert(DynInstPtr &inst)
296 assert(inst->isMemRef());
298 assert(inst->isLoad() || inst->isStore());
300 if (inst->isLoad()) {
309 template <class Impl>
311 LSQUnit<Impl>::insertLoad(DynInstPtr &load_inst)
313 assert((loadTail + 1) % LQEntries != loadHead);
314 assert(loads < LQEntries);
316 DPRINTF(LSQUnit, "Inserting load PC %#x, idx:%i [sn:%lli]\n",
317 load_inst->readPC(), loadTail, load_inst->seqNum);
319 load_inst->lqIdx = loadTail;
322 load_inst->sqIdx = -1;
324 load_inst->sqIdx = storeTail;
327 loadQueue[loadTail] = load_inst;
334 template <class Impl>
336 LSQUnit<Impl>::insertStore(DynInstPtr &store_inst)
338 // Make sure it is not full before inserting an instruction.
339 assert((storeTail + 1) % SQEntries != storeHead);
340 assert(stores < SQEntries);
342 DPRINTF(LSQUnit, "Inserting store PC %#x, idx:%i [sn:%lli]\n",
343 store_inst->readPC(), storeTail, store_inst->seqNum);
345 store_inst->sqIdx = storeTail;
346 store_inst->lqIdx = loadTail;
348 storeQueue[storeTail] = SQEntry(store_inst);
350 incrStIdx(storeTail);
355 template <class Impl>
356 typename Impl::DynInstPtr
357 LSQUnit<Impl>::getMemDepViolator()
359 DynInstPtr temp = memDepViolator;
361 memDepViolator = NULL;
366 template <class Impl>
368 LSQUnit<Impl>::numFreeEntries()
370 unsigned free_lq_entries = LQEntries - loads;
371 unsigned free_sq_entries = SQEntries - stores;
373 // Both the LQ and SQ entries have an extra dummy entry to differentiate
374 // empty/full conditions. Subtract 1 from the free entries.
375 if (free_lq_entries < free_sq_entries) {
376 return free_lq_entries - 1;
378 return free_sq_entries - 1;
382 template <class Impl>
384 LSQUnit<Impl>::numLoadsReady()
386 int load_idx = loadHead;
389 while (load_idx != loadTail) {
390 assert(loadQueue[load_idx]);
392 if (loadQueue[load_idx]->readyToIssue()) {
400 template <class Impl>
402 LSQUnit<Impl>::executeLoad(DynInstPtr &inst)
404 // Execute a specific load.
405 Fault load_fault = NoFault;
407 DPRINTF(LSQUnit, "Executing load PC %#x, [sn:%lli]\n",
408 inst->readPC(),inst->seqNum);
410 load_fault = inst->initiateAcc();
412 // If the instruction faulted, then we need to send it along to commit
413 // without the instruction completing.
414 if (load_fault != NoFault) {
415 // Send this instruction to commit, also make sure iew stage
416 // realizes there is activity.
417 // Mark it as executed unless it is an uncached load that
418 // needs to hit the head of commit.
419 if (!(inst->req->isUncacheable()) || inst->isAtCommit()) {
422 iewStage->instToCommit(inst);
423 iewStage->activityThisCycle();
429 template <class Impl>
431 LSQUnit<Impl>::executeStore(DynInstPtr &store_inst)
433 using namespace TheISA;
434 // Make sure that a store exists.
437 int store_idx = store_inst->sqIdx;
439 DPRINTF(LSQUnit, "Executing store PC %#x [sn:%lli]\n",
440 store_inst->readPC(), store_inst->seqNum);
442 // Check the recently completed loads to see if any match this store's
443 // address. If so, then we have a memory ordering violation.
444 int load_idx = store_inst->lqIdx;
446 Fault store_fault = store_inst->initiateAcc();
448 if (storeQueue[store_idx].size == 0) {
449 DPRINTF(LSQUnit,"Fault on Store PC %#x, [sn:%lli],Size = 0\n",
450 store_inst->readPC(),store_inst->seqNum);
455 assert(store_fault == NoFault);
457 if (store_inst->isStoreConditional()) {
458 // Store conditionals need to set themselves as able to
459 // writeback if we haven't had a fault by here.
460 storeQueue[store_idx].canWB = true;
465 if (!memDepViolator) {
466 while (load_idx != loadTail) {
467 // Really only need to check loads that have actually executed
468 // It's safe to check all loads because effAddr is set to
469 // InvalAddr when the dyn inst is created.
471 // @todo: For now this is extra conservative, detecting a
472 // violation if the addresses match assuming all accesses
473 // are quad word accesses.
475 // @todo: Fix this, magic number being used here
476 if ((loadQueue[load_idx]->effAddr >> 8) ==
477 (store_inst->effAddr >> 8)) {
478 // A load incorrectly passed this store. Squash and refetch.
479 // For now return a fault to show that it was unsuccessful.
480 memDepViolator = loadQueue[load_idx];
481 ++lsqMemOrderViolation;
483 return genMachineCheckFault();
489 // If we've reached this point, there was no violation.
490 memDepViolator = NULL;
496 template <class Impl>
498 LSQUnit<Impl>::commitLoad()
500 assert(loadQueue[loadHead]);
502 DPRINTF(LSQUnit, "Committing head load instruction, PC %#x\n",
503 loadQueue[loadHead]->readPC());
505 loadQueue[loadHead] = NULL;
512 template <class Impl>
514 LSQUnit<Impl>::commitLoads(InstSeqNum &youngest_inst)
516 assert(loads == 0 || loadQueue[loadHead]);
518 while (loads != 0 && loadQueue[loadHead]->seqNum <= youngest_inst) {
523 template <class Impl>
525 LSQUnit<Impl>::commitStores(InstSeqNum &youngest_inst)
527 assert(stores == 0 || storeQueue[storeHead].inst);
529 int store_idx = storeHead;
531 while (store_idx != storeTail) {
532 assert(storeQueue[store_idx].inst);
533 // Mark any stores that are now committed and have not yet
534 // been marked as able to write back.
535 if (!storeQueue[store_idx].canWB) {
536 if (storeQueue[store_idx].inst->seqNum > youngest_inst) {
539 DPRINTF(LSQUnit, "Marking store as able to write back, PC "
541 storeQueue[store_idx].inst->readPC(),
542 storeQueue[store_idx].inst->seqNum);
544 storeQueue[store_idx].canWB = true;
549 incrStIdx(store_idx);
553 template <class Impl>
555 LSQUnit<Impl>::writebackStores()
557 while (storesToWB > 0 &&
558 storeWBIdx != storeTail &&
559 storeQueue[storeWBIdx].inst &&
560 storeQueue[storeWBIdx].canWB &&
561 usedPorts < cachePorts) {
563 if (isStoreBlocked || lsq->cacheBlocked()) {
564 DPRINTF(LSQUnit, "Unable to write back any more stores, cache"
569 // Store didn't write any data so no need to write it back to
571 if (storeQueue[storeWBIdx].size == 0) {
572 completeStore(storeWBIdx);
574 incrStIdx(storeWBIdx);
581 if (storeQueue[storeWBIdx].inst->isDataPrefetch()) {
582 incrStIdx(storeWBIdx);
587 assert(storeQueue[storeWBIdx].req);
588 assert(!storeQueue[storeWBIdx].committed);
590 DynInstPtr inst = storeQueue[storeWBIdx].inst;
592 Request *req = storeQueue[storeWBIdx].req;
593 storeQueue[storeWBIdx].committed = true;
595 assert(!inst->memData);
596 inst->memData = new uint8_t[64];
597 memcpy(inst->memData, (uint8_t *)&storeQueue[storeWBIdx].data,
600 PacketPtr data_pkt = new Packet(req, Packet::WriteReq, Packet::Broadcast);
601 data_pkt->dataStatic(inst->memData);
603 LSQSenderState *state = new LSQSenderState;
604 state->isLoad = false;
605 state->idx = storeWBIdx;
607 data_pkt->senderState = state;
609 DPRINTF(LSQUnit, "D-Cache: Writing back store idx:%i PC:%#x "
610 "to Addr:%#x, data:%#x [sn:%lli]\n",
611 storeWBIdx, inst->readPC(),
612 req->getPaddr(), *(inst->memData),
615 // @todo: Remove this SC hack once the memory system handles it.
616 if (req->isLocked()) {
617 if (req->isUncacheable()) {
622 DPRINTF(LSQUnit, "Store conditional [sn:%lli] succeeded.",
626 // Hack: Instantly complete this store.
627 // completeDataAccess(data_pkt);
628 DPRINTF(LSQUnit, "Store conditional [sn:%lli] failed. "
629 "Instantly completing it.\n",
631 WritebackEvent *wb = new WritebackEvent(inst, data_pkt, this);
632 wb->schedule(curTick + 1);
634 completeStore(storeWBIdx);
635 incrStIdx(storeWBIdx);
640 // Non-store conditionals do not need a writeback.
644 if (!dcachePort->sendTiming(data_pkt)) {
645 if (data_pkt->result == Packet::BadAddress) {
646 panic("LSQ sent out a bad address for a completed store!");
648 // Need to handle becoming blocked on a store.
649 DPRINTF(IEW, "D-Cache became blcoked when writing [sn:%lli], will"
652 isStoreBlocked = true;
654 assert(retryPkt == NULL);
656 lsq->setRetryTid(lsqID);
658 storePostSend(data_pkt);
662 // Not sure this should set it to 0.
665 assert(stores >= 0 && storesToWB >= 0);
668 /*template <class Impl>
670 LSQUnit<Impl>::removeMSHR(InstSeqNum seqNum)
672 list<InstSeqNum>::iterator mshr_it = find(mshrSeqNums.begin(),
676 if (mshr_it != mshrSeqNums.end()) {
677 mshrSeqNums.erase(mshr_it);
678 DPRINTF(LSQUnit, "Removing MSHR. count = %i\n",mshrSeqNums.size());
682 template <class Impl>
684 LSQUnit<Impl>::squash(const InstSeqNum &squashed_num)
686 DPRINTF(LSQUnit, "Squashing until [sn:%lli]!"
687 "(Loads:%i Stores:%i)\n", squashed_num, loads, stores);
689 int load_idx = loadTail;
692 while (loads != 0 && loadQueue[load_idx]->seqNum > squashed_num) {
693 DPRINTF(LSQUnit,"Load Instruction PC %#x squashed, "
695 loadQueue[load_idx]->readPC(),
696 loadQueue[load_idx]->seqNum);
698 if (isStalled() && load_idx == stallingLoadIdx) {
700 stallingStoreIsn = 0;
704 // Clear the smart pointer to make sure it is decremented.
705 loadQueue[load_idx]->setSquashed();
706 loadQueue[load_idx] = NULL;
717 if (squashed_num < blockedLoadSeqNum) {
718 isLoadBlocked = false;
719 loadBlockedHandled = false;
720 blockedLoadSeqNum = 0;
724 int store_idx = storeTail;
725 decrStIdx(store_idx);
727 while (stores != 0 &&
728 storeQueue[store_idx].inst->seqNum > squashed_num) {
729 // Instructions marked as can WB are already committed.
730 if (storeQueue[store_idx].canWB) {
734 DPRINTF(LSQUnit,"Store Instruction PC %#x squashed, "
735 "idx:%i [sn:%lli]\n",
736 storeQueue[store_idx].inst->readPC(),
737 store_idx, storeQueue[store_idx].inst->seqNum);
739 // I don't think this can happen. It should have been cleared
740 // by the stalling load.
742 storeQueue[store_idx].inst->seqNum == stallingStoreIsn) {
743 panic("Is stalled should have been cleared by stalling load!\n");
745 stallingStoreIsn = 0;
748 // Clear the smart pointer to make sure it is decremented.
749 storeQueue[store_idx].inst->setSquashed();
750 storeQueue[store_idx].inst = NULL;
751 storeQueue[store_idx].canWB = 0;
753 storeQueue[store_idx].req = NULL;
757 storeTail = store_idx;
759 decrStIdx(store_idx);
764 template <class Impl>
766 LSQUnit<Impl>::storePostSend(PacketPtr pkt)
769 storeQueue[storeWBIdx].inst->seqNum == stallingStoreIsn) {
770 DPRINTF(LSQUnit, "Unstalling, stalling store [sn:%lli] "
772 stallingStoreIsn, stallingLoadIdx);
774 stallingStoreIsn = 0;
775 iewStage->replayMemInst(loadQueue[stallingLoadIdx]);
778 if (!storeQueue[storeWBIdx].inst->isStoreConditional()) {
779 // The store is basically completed at this time. This
780 // only works so long as the checker doesn't try to
781 // verify the value in memory for stores.
782 storeQueue[storeWBIdx].inst->setCompleted();
785 cpu->checker->verify(storeQueue[storeWBIdx].inst);
790 if (pkt->result != Packet::Success) {
791 DPRINTF(LSQUnit,"D-Cache Write Miss on idx:%i!\n",
794 DPRINTF(Activity, "Active st accessing mem miss [sn:%lli]\n",
795 storeQueue[storeWBIdx].inst->seqNum);
797 //mshrSeqNums.push_back(storeQueue[storeWBIdx].inst->seqNum);
799 //DPRINTF(LSQUnit, "Added MSHR. count = %i\n",mshrSeqNums.size());
801 // @todo: Increment stat here.
803 DPRINTF(LSQUnit,"D-Cache: Write Hit on idx:%i !\n",
806 DPRINTF(Activity, "Active st accessing mem hit [sn:%lli]\n",
807 storeQueue[storeWBIdx].inst->seqNum);
810 incrStIdx(storeWBIdx);
813 template <class Impl>
815 LSQUnit<Impl>::writeback(DynInstPtr &inst, PacketPtr pkt)
819 // Squashed instructions do not need to complete their access.
820 if (inst->isSquashed()) {
821 iewStage->decrWb(inst->seqNum);
822 assert(!inst->isStore());
823 ++lsqIgnoredResponses;
827 if (!inst->isExecuted()) {
830 // Complete access to copy data to proper place.
831 inst->completeAcc(pkt);
834 // Need to insert instruction into queue to commit
835 iewStage->instToCommit(inst);
837 iewStage->activityThisCycle();
840 template <class Impl>
842 LSQUnit<Impl>::completeStore(int store_idx)
844 assert(storeQueue[store_idx].inst);
845 storeQueue[store_idx].completed = true;
847 // A bit conservative because a store completion may not free up entries,
848 // but hopefully avoids two store completions in one cycle from making
849 // the CPU tick twice.
851 cpu->activityThisCycle();
853 if (store_idx == storeHead) {
855 incrStIdx(storeHead);
858 } while (storeQueue[storeHead].completed &&
859 storeHead != storeTail);
861 iewStage->updateLSQNextCycle = true;
864 DPRINTF(LSQUnit, "Completing store [sn:%lli], idx:%i, store head "
866 storeQueue[store_idx].inst->seqNum, store_idx, storeHead);
869 storeQueue[store_idx].inst->seqNum == stallingStoreIsn) {
870 DPRINTF(LSQUnit, "Unstalling, stalling store [sn:%lli] "
872 stallingStoreIsn, stallingLoadIdx);
874 stallingStoreIsn = 0;
875 iewStage->replayMemInst(loadQueue[stallingLoadIdx]);
878 storeQueue[store_idx].inst->setCompleted();
880 // Tell the checker we've completed this instruction. Some stores
881 // may get reported twice to the checker, but the checker can
885 cpu->checker->verify(storeQueue[store_idx].inst);
890 template <class Impl>
892 LSQUnit<Impl>::recvRetry()
894 if (isStoreBlocked) {
895 assert(retryPkt != NULL);
897 if (dcachePort->sendTiming(retryPkt)) {
898 if (retryPkt->result == Packet::BadAddress) {
899 panic("LSQ sent out a bad address for a completed store!");
901 storePostSend(retryPkt);
903 isStoreBlocked = false;
904 lsq->setRetryTid(-1);
908 lsq->setRetryTid(lsqID);
910 } else if (isLoadBlocked) {
911 DPRINTF(LSQUnit, "Loads squash themselves and all younger insts, "
912 "no need to resend packet.\n");
914 DPRINTF(LSQUnit, "Retry received but LSQ is no longer blocked.\n");
918 template <class Impl>
920 LSQUnit<Impl>::incrStIdx(int &store_idx)
922 if (++store_idx >= SQEntries)
926 template <class Impl>
928 LSQUnit<Impl>::decrStIdx(int &store_idx)
931 store_idx += SQEntries;
934 template <class Impl>
936 LSQUnit<Impl>::incrLdIdx(int &load_idx)
938 if (++load_idx >= LQEntries)
942 template <class Impl>
944 LSQUnit<Impl>::decrLdIdx(int &load_idx)
947 load_idx += LQEntries;
950 template <class Impl>
952 LSQUnit<Impl>::dumpInsts()
954 cprintf("Load store queue: Dumping instructions.\n");
955 cprintf("Load queue size: %i\n", loads);
956 cprintf("Load queue: ");
958 int load_idx = loadHead;
960 while (load_idx != loadTail && loadQueue[load_idx]) {
961 cprintf("%#x ", loadQueue[load_idx]->readPC());
966 cprintf("Store queue size: %i\n", stores);
967 cprintf("Store queue: ");
969 int store_idx = storeHead;
971 while (store_idx != storeTail && storeQueue[store_idx].inst) {
972 cprintf("%#x ", storeQueue[store_idx].inst->readPC());
974 incrStIdx(store_idx);