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;
135 memDepViolator = NULL;
137 blockedLoadSeqNum = 0;
142 LSQUnit<Impl>::setCPU(O3CPU *cpu_ptr)
148 cpu->checker->setDcachePort(dcachePort);
155 LSQUnit<Impl>::name() const
157 if (Impl::MaxThreads == 1) {
158 return iewStage->name() + ".lsq";
160 return iewStage->name() + ".lsq.thread." + to_string(lsqID);
166 LSQUnit<Impl>::regStats()
169 .name(name() + ".forwLoads")
170 .desc("Number of loads that had data forwarded from stores");
173 .name(name() + ".invAddrLoads")
174 .desc("Number of loads ignored due to an invalid address");
177 .name(name() + ".squashedLoads")
178 .desc("Number of loads squashed");
181 .name(name() + ".ignoredResponses")
182 .desc("Number of memory responses ignored because the instruction is squashed");
185 .name(name() + ".memOrderViolation")
186 .desc("Number of memory ordering violations");
189 .name(name() + ".squashedStores")
190 .desc("Number of stores squashed");
193 .name(name() + ".invAddrSwpfs")
194 .desc("Number of software prefetches ignored due to an invalid address");
197 .name(name() + ".blockedLoads")
198 .desc("Number of blocked loads due to partial load-store forwarding");
201 .name(name() + ".rescheduledLoads")
202 .desc("Number of loads that were rescheduled");
205 .name(name() + ".cacheBlocked")
206 .desc("Number of times an access to memory failed due to the cache being blocked");
211 LSQUnit<Impl>::clearLQ()
218 LSQUnit<Impl>::clearSQ()
225 LSQUnit<Impl>::switchOut()
228 for (int i = 0; i < loadQueue.size(); ++i) {
229 assert(!loadQueue[i]);
233 assert(storesToWB == 0);
238 LSQUnit<Impl>::takeOverFrom()
241 loads = stores = storesToWB = 0;
243 loadHead = loadTail = 0;
245 storeHead = storeWBIdx = storeTail = 0;
249 memDepViolator = NULL;
251 blockedLoadSeqNum = 0;
254 isLoadBlocked = false;
255 loadBlockedHandled = false;
260 LSQUnit<Impl>::resizeLQ(unsigned size)
262 unsigned size_plus_sentinel = size + 1;
263 assert(size_plus_sentinel >= LQEntries);
265 if (size_plus_sentinel > LQEntries) {
266 while (size_plus_sentinel > loadQueue.size()) {
268 loadQueue.push_back(dummy);
272 LQEntries = size_plus_sentinel;
279 LSQUnit<Impl>::resizeSQ(unsigned size)
281 unsigned size_plus_sentinel = size + 1;
282 if (size_plus_sentinel > SQEntries) {
283 while (size_plus_sentinel > storeQueue.size()) {
285 storeQueue.push_back(dummy);
289 SQEntries = size_plus_sentinel;
293 template <class Impl>
295 LSQUnit<Impl>::insert(DynInstPtr &inst)
297 assert(inst->isMemRef());
299 assert(inst->isLoad() || inst->isStore());
301 if (inst->isLoad()) {
310 template <class Impl>
312 LSQUnit<Impl>::insertLoad(DynInstPtr &load_inst)
314 assert((loadTail + 1) % LQEntries != loadHead);
315 assert(loads < LQEntries);
317 DPRINTF(LSQUnit, "Inserting load PC %#x, idx:%i [sn:%lli]\n",
318 load_inst->readPC(), loadTail, load_inst->seqNum);
320 load_inst->lqIdx = loadTail;
323 load_inst->sqIdx = -1;
325 load_inst->sqIdx = storeTail;
328 loadQueue[loadTail] = load_inst;
335 template <class Impl>
337 LSQUnit<Impl>::insertStore(DynInstPtr &store_inst)
339 // Make sure it is not full before inserting an instruction.
340 assert((storeTail + 1) % SQEntries != storeHead);
341 assert(stores < SQEntries);
343 DPRINTF(LSQUnit, "Inserting store PC %#x, idx:%i [sn:%lli]\n",
344 store_inst->readPC(), storeTail, store_inst->seqNum);
346 store_inst->sqIdx = storeTail;
347 store_inst->lqIdx = loadTail;
349 storeQueue[storeTail] = SQEntry(store_inst);
351 incrStIdx(storeTail);
356 template <class Impl>
357 typename Impl::DynInstPtr
358 LSQUnit<Impl>::getMemDepViolator()
360 DynInstPtr temp = memDepViolator;
362 memDepViolator = NULL;
367 template <class Impl>
369 LSQUnit<Impl>::numFreeEntries()
371 unsigned free_lq_entries = LQEntries - loads;
372 unsigned free_sq_entries = SQEntries - stores;
374 // Both the LQ and SQ entries have an extra dummy entry to differentiate
375 // empty/full conditions. Subtract 1 from the free entries.
376 if (free_lq_entries < free_sq_entries) {
377 return free_lq_entries - 1;
379 return free_sq_entries - 1;
383 template <class Impl>
385 LSQUnit<Impl>::numLoadsReady()
387 int load_idx = loadHead;
390 while (load_idx != loadTail) {
391 assert(loadQueue[load_idx]);
393 if (loadQueue[load_idx]->readyToIssue()) {
401 template <class Impl>
403 LSQUnit<Impl>::executeLoad(DynInstPtr &inst)
405 // Execute a specific load.
406 Fault load_fault = NoFault;
408 DPRINTF(LSQUnit, "Executing load PC %#x, [sn:%lli]\n",
409 inst->readPC(),inst->seqNum);
411 load_fault = inst->initiateAcc();
413 // If the instruction faulted, then we need to send it along to commit
414 // without the instruction completing.
415 if (load_fault != NoFault) {
416 // Send this instruction to commit, also make sure iew stage
417 // realizes there is activity.
418 // Mark it as executed unless it is an uncached load that
419 // needs to hit the head of commit.
420 if (!(inst->req->isUncacheable()) || inst->isAtCommit()) {
423 iewStage->instToCommit(inst);
424 iewStage->activityThisCycle();
430 template <class Impl>
432 LSQUnit<Impl>::executeStore(DynInstPtr &store_inst)
434 using namespace TheISA;
435 // Make sure that a store exists.
438 int store_idx = store_inst->sqIdx;
440 DPRINTF(LSQUnit, "Executing store PC %#x [sn:%lli]\n",
441 store_inst->readPC(), store_inst->seqNum);
443 // Check the recently completed loads to see if any match this store's
444 // address. If so, then we have a memory ordering violation.
445 int load_idx = store_inst->lqIdx;
447 Fault store_fault = store_inst->initiateAcc();
449 if (storeQueue[store_idx].size == 0) {
450 DPRINTF(LSQUnit,"Fault on Store PC %#x, [sn:%lli],Size = 0\n",
451 store_inst->readPC(),store_inst->seqNum);
456 assert(store_fault == NoFault);
458 if (store_inst->isStoreConditional()) {
459 // Store conditionals need to set themselves as able to
460 // writeback if we haven't had a fault by here.
461 storeQueue[store_idx].canWB = true;
466 if (!memDepViolator) {
467 while (load_idx != loadTail) {
468 // Really only need to check loads that have actually executed
469 // It's safe to check all loads because effAddr is set to
470 // InvalAddr when the dyn inst is created.
472 // @todo: For now this is extra conservative, detecting a
473 // violation if the addresses match assuming all accesses
474 // are quad word accesses.
476 // @todo: Fix this, magic number being used here
477 if ((loadQueue[load_idx]->effAddr >> 8) ==
478 (store_inst->effAddr >> 8)) {
479 // A load incorrectly passed this store. Squash and refetch.
480 // For now return a fault to show that it was unsuccessful.
481 memDepViolator = loadQueue[load_idx];
482 ++lsqMemOrderViolation;
484 return genMachineCheckFault();
490 // If we've reached this point, there was no violation.
491 memDepViolator = NULL;
497 template <class Impl>
499 LSQUnit<Impl>::commitLoad()
501 assert(loadQueue[loadHead]);
503 DPRINTF(LSQUnit, "Committing head load instruction, PC %#x\n",
504 loadQueue[loadHead]->readPC());
506 loadQueue[loadHead] = NULL;
513 template <class Impl>
515 LSQUnit<Impl>::commitLoads(InstSeqNum &youngest_inst)
517 assert(loads == 0 || loadQueue[loadHead]);
519 while (loads != 0 && loadQueue[loadHead]->seqNum <= youngest_inst) {
524 template <class Impl>
526 LSQUnit<Impl>::commitStores(InstSeqNum &youngest_inst)
528 assert(stores == 0 || storeQueue[storeHead].inst);
530 int store_idx = storeHead;
532 while (store_idx != storeTail) {
533 assert(storeQueue[store_idx].inst);
534 // Mark any stores that are now committed and have not yet
535 // been marked as able to write back.
536 if (!storeQueue[store_idx].canWB) {
537 if (storeQueue[store_idx].inst->seqNum > youngest_inst) {
540 DPRINTF(LSQUnit, "Marking store as able to write back, PC "
542 storeQueue[store_idx].inst->readPC(),
543 storeQueue[store_idx].inst->seqNum);
545 storeQueue[store_idx].canWB = true;
550 incrStIdx(store_idx);
554 template <class Impl>
556 LSQUnit<Impl>::writebackStores()
558 while (storesToWB > 0 &&
559 storeWBIdx != storeTail &&
560 storeQueue[storeWBIdx].inst &&
561 storeQueue[storeWBIdx].canWB &&
562 usedPorts < cachePorts) {
564 if (isStoreBlocked || lsq->cacheBlocked()) {
565 DPRINTF(LSQUnit, "Unable to write back any more stores, cache"
570 // Store didn't write any data so no need to write it back to
572 if (storeQueue[storeWBIdx].size == 0) {
573 completeStore(storeWBIdx);
575 incrStIdx(storeWBIdx);
582 if (storeQueue[storeWBIdx].inst->isDataPrefetch()) {
583 incrStIdx(storeWBIdx);
588 assert(storeQueue[storeWBIdx].req);
589 assert(!storeQueue[storeWBIdx].committed);
591 DynInstPtr inst = storeQueue[storeWBIdx].inst;
593 Request *req = storeQueue[storeWBIdx].req;
594 storeQueue[storeWBIdx].committed = true;
596 assert(!inst->memData);
597 inst->memData = new uint8_t[64];
598 memcpy(inst->memData, (uint8_t *)&storeQueue[storeWBIdx].data,
601 PacketPtr data_pkt = new Packet(req, Packet::WriteReq, Packet::Broadcast);
602 data_pkt->dataStatic(inst->memData);
604 LSQSenderState *state = new LSQSenderState;
605 state->isLoad = false;
606 state->idx = storeWBIdx;
608 data_pkt->senderState = state;
610 DPRINTF(LSQUnit, "D-Cache: Writing back store idx:%i PC:%#x "
611 "to Addr:%#x, data:%#x [sn:%lli]\n",
612 storeWBIdx, inst->readPC(),
613 req->getPaddr(), *(inst->memData),
616 // @todo: Remove this SC hack once the memory system handles it.
617 if (req->isLocked()) {
618 if (req->isUncacheable()) {
623 DPRINTF(LSQUnit, "Store conditional [sn:%lli] succeeded.",
627 // Hack: Instantly complete this store.
628 // completeDataAccess(data_pkt);
629 DPRINTF(LSQUnit, "Store conditional [sn:%lli] failed. "
630 "Instantly completing it.\n",
632 WritebackEvent *wb = new WritebackEvent(inst, data_pkt, this);
633 wb->schedule(curTick + 1);
635 completeStore(storeWBIdx);
636 incrStIdx(storeWBIdx);
641 // Non-store conditionals do not need a writeback.
645 if (!dcachePort->sendTiming(data_pkt)) {
646 if (data_pkt->result == Packet::BadAddress) {
647 panic("LSQ sent out a bad address for a completed store!");
649 // Need to handle becoming blocked on a store.
650 DPRINTF(IEW, "D-Cache became blcoked when writing [sn:%lli], will"
653 isStoreBlocked = true;
655 assert(retryPkt == NULL);
657 lsq->setRetryTid(lsqID);
659 storePostSend(data_pkt);
663 // Not sure this should set it to 0.
666 assert(stores >= 0 && storesToWB >= 0);
669 /*template <class Impl>
671 LSQUnit<Impl>::removeMSHR(InstSeqNum seqNum)
673 list<InstSeqNum>::iterator mshr_it = find(mshrSeqNums.begin(),
677 if (mshr_it != mshrSeqNums.end()) {
678 mshrSeqNums.erase(mshr_it);
679 DPRINTF(LSQUnit, "Removing MSHR. count = %i\n",mshrSeqNums.size());
683 template <class Impl>
685 LSQUnit<Impl>::squash(const InstSeqNum &squashed_num)
687 DPRINTF(LSQUnit, "Squashing until [sn:%lli]!"
688 "(Loads:%i Stores:%i)\n", squashed_num, loads, stores);
690 int load_idx = loadTail;
693 while (loads != 0 && loadQueue[load_idx]->seqNum > squashed_num) {
694 DPRINTF(LSQUnit,"Load Instruction PC %#x squashed, "
696 loadQueue[load_idx]->readPC(),
697 loadQueue[load_idx]->seqNum);
699 if (isStalled() && load_idx == stallingLoadIdx) {
701 stallingStoreIsn = 0;
705 // Clear the smart pointer to make sure it is decremented.
706 loadQueue[load_idx]->setSquashed();
707 loadQueue[load_idx] = NULL;
718 if (squashed_num < blockedLoadSeqNum) {
719 isLoadBlocked = false;
720 loadBlockedHandled = false;
721 blockedLoadSeqNum = 0;
725 int store_idx = storeTail;
726 decrStIdx(store_idx);
728 while (stores != 0 &&
729 storeQueue[store_idx].inst->seqNum > squashed_num) {
730 // Instructions marked as can WB are already committed.
731 if (storeQueue[store_idx].canWB) {
735 DPRINTF(LSQUnit,"Store Instruction PC %#x squashed, "
736 "idx:%i [sn:%lli]\n",
737 storeQueue[store_idx].inst->readPC(),
738 store_idx, storeQueue[store_idx].inst->seqNum);
740 // I don't think this can happen. It should have been cleared
741 // by the stalling load.
743 storeQueue[store_idx].inst->seqNum == stallingStoreIsn) {
744 panic("Is stalled should have been cleared by stalling load!\n");
746 stallingStoreIsn = 0;
749 // Clear the smart pointer to make sure it is decremented.
750 storeQueue[store_idx].inst->setSquashed();
751 storeQueue[store_idx].inst = NULL;
752 storeQueue[store_idx].canWB = 0;
754 storeQueue[store_idx].req = NULL;
758 storeTail = store_idx;
760 decrStIdx(store_idx);
765 template <class Impl>
767 LSQUnit<Impl>::storePostSend(PacketPtr pkt)
770 storeQueue[storeWBIdx].inst->seqNum == stallingStoreIsn) {
771 DPRINTF(LSQUnit, "Unstalling, stalling store [sn:%lli] "
773 stallingStoreIsn, stallingLoadIdx);
775 stallingStoreIsn = 0;
776 iewStage->replayMemInst(loadQueue[stallingLoadIdx]);
779 if (!storeQueue[storeWBIdx].inst->isStoreConditional()) {
780 // The store is basically completed at this time. This
781 // only works so long as the checker doesn't try to
782 // verify the value in memory for stores.
783 storeQueue[storeWBIdx].inst->setCompleted();
786 cpu->checker->verify(storeQueue[storeWBIdx].inst);
791 if (pkt->result != Packet::Success) {
792 DPRINTF(LSQUnit,"D-Cache Write Miss on idx:%i!\n",
795 DPRINTF(Activity, "Active st accessing mem miss [sn:%lli]\n",
796 storeQueue[storeWBIdx].inst->seqNum);
798 //mshrSeqNums.push_back(storeQueue[storeWBIdx].inst->seqNum);
800 //DPRINTF(LSQUnit, "Added MSHR. count = %i\n",mshrSeqNums.size());
802 // @todo: Increment stat here.
804 DPRINTF(LSQUnit,"D-Cache: Write Hit on idx:%i !\n",
807 DPRINTF(Activity, "Active st accessing mem hit [sn:%lli]\n",
808 storeQueue[storeWBIdx].inst->seqNum);
811 incrStIdx(storeWBIdx);
814 template <class Impl>
816 LSQUnit<Impl>::writeback(DynInstPtr &inst, PacketPtr pkt)
820 // Squashed instructions do not need to complete their access.
821 if (inst->isSquashed()) {
822 iewStage->decrWb(inst->seqNum);
823 assert(!inst->isStore());
824 ++lsqIgnoredResponses;
828 if (!inst->isExecuted()) {
831 // Complete access to copy data to proper place.
832 inst->completeAcc(pkt);
835 // Need to insert instruction into queue to commit
836 iewStage->instToCommit(inst);
838 iewStage->activityThisCycle();
841 template <class Impl>
843 LSQUnit<Impl>::completeStore(int store_idx)
845 assert(storeQueue[store_idx].inst);
846 storeQueue[store_idx].completed = true;
848 // A bit conservative because a store completion may not free up entries,
849 // but hopefully avoids two store completions in one cycle from making
850 // the CPU tick twice.
852 cpu->activityThisCycle();
854 if (store_idx == storeHead) {
856 incrStIdx(storeHead);
859 } while (storeQueue[storeHead].completed &&
860 storeHead != storeTail);
862 iewStage->updateLSQNextCycle = true;
865 DPRINTF(LSQUnit, "Completing store [sn:%lli], idx:%i, store head "
867 storeQueue[store_idx].inst->seqNum, store_idx, storeHead);
870 storeQueue[store_idx].inst->seqNum == stallingStoreIsn) {
871 DPRINTF(LSQUnit, "Unstalling, stalling store [sn:%lli] "
873 stallingStoreIsn, stallingLoadIdx);
875 stallingStoreIsn = 0;
876 iewStage->replayMemInst(loadQueue[stallingLoadIdx]);
879 storeQueue[store_idx].inst->setCompleted();
881 // Tell the checker we've completed this instruction. Some stores
882 // may get reported twice to the checker, but the checker can
886 cpu->checker->verify(storeQueue[store_idx].inst);
891 template <class Impl>
893 LSQUnit<Impl>::recvRetry()
895 if (isStoreBlocked) {
896 assert(retryPkt != NULL);
898 if (dcachePort->sendTiming(retryPkt)) {
899 if (retryPkt->result == Packet::BadAddress) {
900 panic("LSQ sent out a bad address for a completed store!");
902 storePostSend(retryPkt);
904 isStoreBlocked = false;
905 lsq->setRetryTid(-1);
909 lsq->setRetryTid(lsqID);
911 } else if (isLoadBlocked) {
912 DPRINTF(LSQUnit, "Loads squash themselves and all younger insts, "
913 "no need to resend packet.\n");
915 DPRINTF(LSQUnit, "Retry received but LSQ is no longer blocked.\n");
919 template <class Impl>
921 LSQUnit<Impl>::incrStIdx(int &store_idx)
923 if (++store_idx >= SQEntries)
927 template <class Impl>
929 LSQUnit<Impl>::decrStIdx(int &store_idx)
932 store_idx += SQEntries;
935 template <class Impl>
937 LSQUnit<Impl>::incrLdIdx(int &load_idx)
939 if (++load_idx >= LQEntries)
943 template <class Impl>
945 LSQUnit<Impl>::decrLdIdx(int &load_idx)
948 load_idx += LQEntries;
951 template <class Impl>
953 LSQUnit<Impl>::dumpInsts()
955 cprintf("Load store queue: Dumping instructions.\n");
956 cprintf("Load queue size: %i\n", loads);
957 cprintf("Load queue: ");
959 int load_idx = loadHead;
961 while (load_idx != loadTail && loadQueue[load_idx]) {
962 cprintf("%#x ", loadQueue[load_idx]->readPC());
967 cprintf("Store queue size: %i\n", stores);
968 cprintf("Store queue: ");
970 int store_idx = storeHead;
972 while (store_idx != storeTail && storeQueue[store_idx].inst) {
973 cprintf("%#x ", storeQueue[store_idx].inst->readPC());
975 incrStIdx(store_idx);