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 "arch/locked_mem.hh"
33 #include "config/use_checker.hh"
35 #include "cpu/o3/lsq.hh"
36 #include "cpu/o3/lsq_unit.hh"
37 #include "base/str.hh"
38 #include "mem/packet.hh"
39 #include "mem/request.hh"
42 #include "cpu/checker/cpu.hh"
46 LSQUnit<Impl>::WritebackEvent::WritebackEvent(DynInstPtr &_inst, PacketPtr _pkt,
48 : Event(&mainEventQueue), inst(_inst), pkt(_pkt), lsqPtr(lsq_ptr)
50 this->setFlags(Event::AutoDelete);
55 LSQUnit<Impl>::WritebackEvent::process()
57 if (!lsqPtr->isSwitchedOut()) {
58 lsqPtr->writeback(inst, pkt);
65 LSQUnit<Impl>::WritebackEvent::description()
67 return "Store writeback event";
72 LSQUnit<Impl>::completeDataAccess(PacketPtr pkt)
74 LSQSenderState *state = dynamic_cast<LSQSenderState *>(pkt->senderState);
75 DynInstPtr inst = state->inst;
76 DPRINTF(IEW, "Writeback event [sn:%lli]\n", inst->seqNum);
77 DPRINTF(Activity, "Activity: Writeback event [sn:%lli]\n", inst->seqNum);
79 //iewStage->ldstQueue.removeMSHR(inst->threadNumber,inst->seqNum);
81 if (isSwitchedOut() || inst->isSquashed()) {
82 iewStage->decrWb(inst->seqNum);
91 if (inst->isStore()) {
92 completeStore(state->idx);
100 template <class Impl>
101 LSQUnit<Impl>::LSQUnit()
102 : loads(0), stores(0), storesToWB(0), stalled(false),
103 isStoreBlocked(false), isLoadBlocked(false),
104 loadBlockedHandled(false)
110 LSQUnit<Impl>::init(Params *params, LSQ *lsq_ptr, unsigned maxLQEntries,
111 unsigned maxSQEntries, unsigned id)
113 DPRINTF(LSQUnit, "Creating LSQUnit%i object.\n",id);
121 // Add 1 for the sentinel entry (they are circular queues).
122 LQEntries = maxLQEntries + 1;
123 SQEntries = maxSQEntries + 1;
125 loadQueue.resize(LQEntries);
126 storeQueue.resize(SQEntries);
128 loadHead = loadTail = 0;
130 storeHead = storeWBIdx = storeTail = 0;
133 cachePorts = params->cachePorts;
136 memDepViolator = NULL;
138 blockedLoadSeqNum = 0;
143 LSQUnit<Impl>::setCPU(O3CPU *cpu_ptr)
149 cpu->checker->setDcachePort(dcachePort);
156 LSQUnit<Impl>::name() const
158 if (Impl::MaxThreads == 1) {
159 return iewStage->name() + ".lsq";
161 return iewStage->name() + ".lsq.thread." + to_string(lsqID);
167 LSQUnit<Impl>::regStats()
170 .name(name() + ".forwLoads")
171 .desc("Number of loads that had data forwarded from stores");
174 .name(name() + ".invAddrLoads")
175 .desc("Number of loads ignored due to an invalid address");
178 .name(name() + ".squashedLoads")
179 .desc("Number of loads squashed");
182 .name(name() + ".ignoredResponses")
183 .desc("Number of memory responses ignored because the instruction is squashed");
186 .name(name() + ".memOrderViolation")
187 .desc("Number of memory ordering violations");
190 .name(name() + ".squashedStores")
191 .desc("Number of stores squashed");
194 .name(name() + ".invAddrSwpfs")
195 .desc("Number of software prefetches ignored due to an invalid address");
198 .name(name() + ".blockedLoads")
199 .desc("Number of blocked loads due to partial load-store forwarding");
202 .name(name() + ".rescheduledLoads")
203 .desc("Number of loads that were rescheduled");
206 .name(name() + ".cacheBlocked")
207 .desc("Number of times an access to memory failed due to the cache being blocked");
212 LSQUnit<Impl>::clearLQ()
219 LSQUnit<Impl>::clearSQ()
226 LSQUnit<Impl>::switchOut()
229 for (int i = 0; i < loadQueue.size(); ++i) {
230 assert(!loadQueue[i]);
234 assert(storesToWB == 0);
239 LSQUnit<Impl>::takeOverFrom()
242 loads = stores = storesToWB = 0;
244 loadHead = loadTail = 0;
246 storeHead = storeWBIdx = storeTail = 0;
250 memDepViolator = NULL;
252 blockedLoadSeqNum = 0;
255 isLoadBlocked = false;
256 loadBlockedHandled = false;
261 LSQUnit<Impl>::resizeLQ(unsigned size)
263 unsigned size_plus_sentinel = size + 1;
264 assert(size_plus_sentinel >= LQEntries);
266 if (size_plus_sentinel > LQEntries) {
267 while (size_plus_sentinel > loadQueue.size()) {
269 loadQueue.push_back(dummy);
273 LQEntries = size_plus_sentinel;
280 LSQUnit<Impl>::resizeSQ(unsigned size)
282 unsigned size_plus_sentinel = size + 1;
283 if (size_plus_sentinel > SQEntries) {
284 while (size_plus_sentinel > storeQueue.size()) {
286 storeQueue.push_back(dummy);
290 SQEntries = size_plus_sentinel;
294 template <class Impl>
296 LSQUnit<Impl>::insert(DynInstPtr &inst)
298 assert(inst->isMemRef());
300 assert(inst->isLoad() || inst->isStore());
302 if (inst->isLoad()) {
311 template <class Impl>
313 LSQUnit<Impl>::insertLoad(DynInstPtr &load_inst)
315 assert((loadTail + 1) % LQEntries != loadHead);
316 assert(loads < LQEntries);
318 DPRINTF(LSQUnit, "Inserting load PC %#x, idx:%i [sn:%lli]\n",
319 load_inst->readPC(), loadTail, load_inst->seqNum);
321 load_inst->lqIdx = loadTail;
324 load_inst->sqIdx = -1;
326 load_inst->sqIdx = storeTail;
329 loadQueue[loadTail] = load_inst;
336 template <class Impl>
338 LSQUnit<Impl>::insertStore(DynInstPtr &store_inst)
340 // Make sure it is not full before inserting an instruction.
341 assert((storeTail + 1) % SQEntries != storeHead);
342 assert(stores < SQEntries);
344 DPRINTF(LSQUnit, "Inserting store PC %#x, idx:%i [sn:%lli]\n",
345 store_inst->readPC(), storeTail, store_inst->seqNum);
347 store_inst->sqIdx = storeTail;
348 store_inst->lqIdx = loadTail;
350 storeQueue[storeTail] = SQEntry(store_inst);
352 incrStIdx(storeTail);
357 template <class Impl>
358 typename Impl::DynInstPtr
359 LSQUnit<Impl>::getMemDepViolator()
361 DynInstPtr temp = memDepViolator;
363 memDepViolator = NULL;
368 template <class Impl>
370 LSQUnit<Impl>::numFreeEntries()
372 unsigned free_lq_entries = LQEntries - loads;
373 unsigned free_sq_entries = SQEntries - stores;
375 // Both the LQ and SQ entries have an extra dummy entry to differentiate
376 // empty/full conditions. Subtract 1 from the free entries.
377 if (free_lq_entries < free_sq_entries) {
378 return free_lq_entries - 1;
380 return free_sq_entries - 1;
384 template <class Impl>
386 LSQUnit<Impl>::numLoadsReady()
388 int load_idx = loadHead;
391 while (load_idx != loadTail) {
392 assert(loadQueue[load_idx]);
394 if (loadQueue[load_idx]->readyToIssue()) {
402 template <class Impl>
404 LSQUnit<Impl>::executeLoad(DynInstPtr &inst)
406 // Execute a specific load.
407 Fault load_fault = NoFault;
409 DPRINTF(LSQUnit, "Executing load PC %#x, [sn:%lli]\n",
410 inst->readPC(),inst->seqNum);
412 load_fault = inst->initiateAcc();
414 // If the instruction faulted, then we need to send it along to commit
415 // without the instruction completing.
416 if (load_fault != NoFault) {
417 // Send this instruction to commit, also make sure iew stage
418 // realizes there is activity.
419 // Mark it as executed unless it is an uncached load that
420 // needs to hit the head of commit.
421 if (!(inst->req->isUncacheable()) || inst->isAtCommit()) {
424 iewStage->instToCommit(inst);
425 iewStage->activityThisCycle();
431 template <class Impl>
433 LSQUnit<Impl>::executeStore(DynInstPtr &store_inst)
435 using namespace TheISA;
436 // Make sure that a store exists.
439 int store_idx = store_inst->sqIdx;
441 DPRINTF(LSQUnit, "Executing store PC %#x [sn:%lli]\n",
442 store_inst->readPC(), store_inst->seqNum);
444 // Check the recently completed loads to see if any match this store's
445 // address. If so, then we have a memory ordering violation.
446 int load_idx = store_inst->lqIdx;
448 Fault store_fault = store_inst->initiateAcc();
450 if (storeQueue[store_idx].size == 0) {
451 DPRINTF(LSQUnit,"Fault on Store PC %#x, [sn:%lli],Size = 0\n",
452 store_inst->readPC(),store_inst->seqNum);
457 assert(store_fault == NoFault);
459 if (store_inst->isStoreConditional()) {
460 // Store conditionals need to set themselves as able to
461 // writeback if we haven't had a fault by here.
462 storeQueue[store_idx].canWB = true;
467 if (!memDepViolator) {
468 while (load_idx != loadTail) {
469 // Really only need to check loads that have actually executed
470 // It's safe to check all loads because effAddr is set to
471 // InvalAddr when the dyn inst is created.
473 // @todo: For now this is extra conservative, detecting a
474 // violation if the addresses match assuming all accesses
475 // are quad word accesses.
477 // @todo: Fix this, magic number being used here
478 if ((loadQueue[load_idx]->effAddr >> 8) ==
479 (store_inst->effAddr >> 8)) {
480 // A load incorrectly passed this store. Squash and refetch.
481 // For now return a fault to show that it was unsuccessful.
482 memDepViolator = loadQueue[load_idx];
483 ++lsqMemOrderViolation;
485 return genMachineCheckFault();
491 // If we've reached this point, there was no violation.
492 memDepViolator = NULL;
498 template <class Impl>
500 LSQUnit<Impl>::commitLoad()
502 assert(loadQueue[loadHead]);
504 DPRINTF(LSQUnit, "Committing head load instruction, PC %#x\n",
505 loadQueue[loadHead]->readPC());
507 loadQueue[loadHead] = NULL;
514 template <class Impl>
516 LSQUnit<Impl>::commitLoads(InstSeqNum &youngest_inst)
518 assert(loads == 0 || loadQueue[loadHead]);
520 while (loads != 0 && loadQueue[loadHead]->seqNum <= youngest_inst) {
525 template <class Impl>
527 LSQUnit<Impl>::commitStores(InstSeqNum &youngest_inst)
529 assert(stores == 0 || storeQueue[storeHead].inst);
531 int store_idx = storeHead;
533 while (store_idx != storeTail) {
534 assert(storeQueue[store_idx].inst);
535 // Mark any stores that are now committed and have not yet
536 // been marked as able to write back.
537 if (!storeQueue[store_idx].canWB) {
538 if (storeQueue[store_idx].inst->seqNum > youngest_inst) {
541 DPRINTF(LSQUnit, "Marking store as able to write back, PC "
543 storeQueue[store_idx].inst->readPC(),
544 storeQueue[store_idx].inst->seqNum);
546 storeQueue[store_idx].canWB = true;
551 incrStIdx(store_idx);
555 template <class Impl>
557 LSQUnit<Impl>::writebackStores()
559 while (storesToWB > 0 &&
560 storeWBIdx != storeTail &&
561 storeQueue[storeWBIdx].inst &&
562 storeQueue[storeWBIdx].canWB &&
563 usedPorts < cachePorts) {
565 if (isStoreBlocked || lsq->cacheBlocked()) {
566 DPRINTF(LSQUnit, "Unable to write back any more stores, cache"
571 // Store didn't write any data so no need to write it back to
573 if (storeQueue[storeWBIdx].size == 0) {
574 completeStore(storeWBIdx);
576 incrStIdx(storeWBIdx);
583 if (storeQueue[storeWBIdx].inst->isDataPrefetch()) {
584 incrStIdx(storeWBIdx);
589 assert(storeQueue[storeWBIdx].req);
590 assert(!storeQueue[storeWBIdx].committed);
592 DynInstPtr inst = storeQueue[storeWBIdx].inst;
594 Request *req = storeQueue[storeWBIdx].req;
595 storeQueue[storeWBIdx].committed = true;
597 assert(!inst->memData);
598 inst->memData = new uint8_t[64];
599 memcpy(inst->memData, (uint8_t *)&storeQueue[storeWBIdx].data,
602 PacketPtr data_pkt = new Packet(req, Packet::WriteReq, Packet::Broadcast);
603 data_pkt->dataStatic(inst->memData);
605 LSQSenderState *state = new LSQSenderState;
606 state->isLoad = false;
607 state->idx = storeWBIdx;
609 data_pkt->senderState = state;
611 DPRINTF(LSQUnit, "D-Cache: Writing back store idx:%i PC:%#x "
612 "to Addr:%#x, data:%#x [sn:%lli]\n",
613 storeWBIdx, inst->readPC(),
614 req->getPaddr(), *(inst->memData),
617 // @todo: Remove this SC hack once the memory system handles it.
618 if (req->isLocked()) {
619 // Disable recording the result temporarily. Writing to
620 // misc regs normally updates the result, but this is not
621 // the desired behavior when handling store conditionals.
622 inst->recordResult = false;
623 bool success = TheISA::handleLockedWrite(inst.get(), req);
624 inst->recordResult = true;
627 // Instantly complete this store.
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);
639 // Non-store conditionals do not need a writeback.
643 if (!dcachePort->sendTiming(data_pkt)) {
644 if (data_pkt->result == Packet::BadAddress) {
645 panic("LSQ sent out a bad address for a completed store!");
647 // Need to handle becoming blocked on a store.
648 DPRINTF(IEW, "D-Cache became blcoked when writing [sn:%lli], will"
651 isStoreBlocked = true;
653 assert(retryPkt == NULL);
655 lsq->setRetryTid(lsqID);
657 storePostSend(data_pkt);
661 // Not sure this should set it to 0.
664 assert(stores >= 0 && storesToWB >= 0);
667 /*template <class Impl>
669 LSQUnit<Impl>::removeMSHR(InstSeqNum seqNum)
671 list<InstSeqNum>::iterator mshr_it = find(mshrSeqNums.begin(),
675 if (mshr_it != mshrSeqNums.end()) {
676 mshrSeqNums.erase(mshr_it);
677 DPRINTF(LSQUnit, "Removing MSHR. count = %i\n",mshrSeqNums.size());
681 template <class Impl>
683 LSQUnit<Impl>::squash(const InstSeqNum &squashed_num)
685 DPRINTF(LSQUnit, "Squashing until [sn:%lli]!"
686 "(Loads:%i Stores:%i)\n", squashed_num, loads, stores);
688 int load_idx = loadTail;
691 while (loads != 0 && loadQueue[load_idx]->seqNum > squashed_num) {
692 DPRINTF(LSQUnit,"Load Instruction PC %#x squashed, "
694 loadQueue[load_idx]->readPC(),
695 loadQueue[load_idx]->seqNum);
697 if (isStalled() && load_idx == stallingLoadIdx) {
699 stallingStoreIsn = 0;
703 // Clear the smart pointer to make sure it is decremented.
704 loadQueue[load_idx]->setSquashed();
705 loadQueue[load_idx] = NULL;
716 if (squashed_num < blockedLoadSeqNum) {
717 isLoadBlocked = false;
718 loadBlockedHandled = false;
719 blockedLoadSeqNum = 0;
723 int store_idx = storeTail;
724 decrStIdx(store_idx);
726 while (stores != 0 &&
727 storeQueue[store_idx].inst->seqNum > squashed_num) {
728 // Instructions marked as can WB are already committed.
729 if (storeQueue[store_idx].canWB) {
733 DPRINTF(LSQUnit,"Store Instruction PC %#x squashed, "
734 "idx:%i [sn:%lli]\n",
735 storeQueue[store_idx].inst->readPC(),
736 store_idx, storeQueue[store_idx].inst->seqNum);
738 // I don't think this can happen. It should have been cleared
739 // by the stalling load.
741 storeQueue[store_idx].inst->seqNum == stallingStoreIsn) {
742 panic("Is stalled should have been cleared by stalling load!\n");
744 stallingStoreIsn = 0;
747 // Clear the smart pointer to make sure it is decremented.
748 storeQueue[store_idx].inst->setSquashed();
749 storeQueue[store_idx].inst = NULL;
750 storeQueue[store_idx].canWB = 0;
752 storeQueue[store_idx].req = NULL;
756 storeTail = store_idx;
758 decrStIdx(store_idx);
763 template <class Impl>
765 LSQUnit<Impl>::storePostSend(PacketPtr pkt)
768 storeQueue[storeWBIdx].inst->seqNum == stallingStoreIsn) {
769 DPRINTF(LSQUnit, "Unstalling, stalling store [sn:%lli] "
771 stallingStoreIsn, stallingLoadIdx);
773 stallingStoreIsn = 0;
774 iewStage->replayMemInst(loadQueue[stallingLoadIdx]);
777 if (!storeQueue[storeWBIdx].inst->isStoreConditional()) {
778 // The store is basically completed at this time. This
779 // only works so long as the checker doesn't try to
780 // verify the value in memory for stores.
781 storeQueue[storeWBIdx].inst->setCompleted();
784 cpu->checker->verify(storeQueue[storeWBIdx].inst);
789 if (pkt->result != Packet::Success) {
790 DPRINTF(LSQUnit,"D-Cache Write Miss on idx:%i!\n",
793 DPRINTF(Activity, "Active st accessing mem miss [sn:%lli]\n",
794 storeQueue[storeWBIdx].inst->seqNum);
796 //mshrSeqNums.push_back(storeQueue[storeWBIdx].inst->seqNum);
798 //DPRINTF(LSQUnit, "Added MSHR. count = %i\n",mshrSeqNums.size());
800 // @todo: Increment stat here.
802 DPRINTF(LSQUnit,"D-Cache: Write Hit on idx:%i !\n",
805 DPRINTF(Activity, "Active st accessing mem hit [sn:%lli]\n",
806 storeQueue[storeWBIdx].inst->seqNum);
809 incrStIdx(storeWBIdx);
812 template <class Impl>
814 LSQUnit<Impl>::writeback(DynInstPtr &inst, PacketPtr pkt)
818 // Squashed instructions do not need to complete their access.
819 if (inst->isSquashed()) {
820 iewStage->decrWb(inst->seqNum);
821 assert(!inst->isStore());
822 ++lsqIgnoredResponses;
826 if (!inst->isExecuted()) {
829 // Complete access to copy data to proper place.
830 inst->completeAcc(pkt);
833 // Need to insert instruction into queue to commit
834 iewStage->instToCommit(inst);
836 iewStage->activityThisCycle();
839 template <class Impl>
841 LSQUnit<Impl>::completeStore(int store_idx)
843 assert(storeQueue[store_idx].inst);
844 storeQueue[store_idx].completed = true;
846 // A bit conservative because a store completion may not free up entries,
847 // but hopefully avoids two store completions in one cycle from making
848 // the CPU tick twice.
850 cpu->activityThisCycle();
852 if (store_idx == storeHead) {
854 incrStIdx(storeHead);
857 } while (storeQueue[storeHead].completed &&
858 storeHead != storeTail);
860 iewStage->updateLSQNextCycle = true;
863 DPRINTF(LSQUnit, "Completing store [sn:%lli], idx:%i, store head "
865 storeQueue[store_idx].inst->seqNum, store_idx, storeHead);
868 storeQueue[store_idx].inst->seqNum == stallingStoreIsn) {
869 DPRINTF(LSQUnit, "Unstalling, stalling store [sn:%lli] "
871 stallingStoreIsn, stallingLoadIdx);
873 stallingStoreIsn = 0;
874 iewStage->replayMemInst(loadQueue[stallingLoadIdx]);
877 storeQueue[store_idx].inst->setCompleted();
879 // Tell the checker we've completed this instruction. Some stores
880 // may get reported twice to the checker, but the checker can
884 cpu->checker->verify(storeQueue[store_idx].inst);
889 template <class Impl>
891 LSQUnit<Impl>::recvRetry()
893 if (isStoreBlocked) {
894 assert(retryPkt != NULL);
896 if (dcachePort->sendTiming(retryPkt)) {
897 if (retryPkt->result == Packet::BadAddress) {
898 panic("LSQ sent out a bad address for a completed store!");
900 storePostSend(retryPkt);
902 isStoreBlocked = false;
903 lsq->setRetryTid(-1);
907 lsq->setRetryTid(lsqID);
909 } else if (isLoadBlocked) {
910 DPRINTF(LSQUnit, "Loads squash themselves and all younger insts, "
911 "no need to resend packet.\n");
913 DPRINTF(LSQUnit, "Retry received but LSQ is no longer blocked.\n");
917 template <class Impl>
919 LSQUnit<Impl>::incrStIdx(int &store_idx)
921 if (++store_idx >= SQEntries)
925 template <class Impl>
927 LSQUnit<Impl>::decrStIdx(int &store_idx)
930 store_idx += SQEntries;
933 template <class Impl>
935 LSQUnit<Impl>::incrLdIdx(int &load_idx)
937 if (++load_idx >= LQEntries)
941 template <class Impl>
943 LSQUnit<Impl>::decrLdIdx(int &load_idx)
946 load_idx += LQEntries;
949 template <class Impl>
951 LSQUnit<Impl>::dumpInsts()
953 cprintf("Load store queue: Dumping instructions.\n");
954 cprintf("Load queue size: %i\n", loads);
955 cprintf("Load queue: ");
957 int load_idx = loadHead;
959 while (load_idx != loadTail && loadQueue[load_idx]) {
960 cprintf("%#x ", loadQueue[load_idx]->readPC());
965 cprintf("Store queue size: %i\n", stores);
966 cprintf("Store queue: ");
968 int store_idx = storeHead;
970 while (store_idx != storeTail && storeQueue[store_idx].inst) {
971 cprintf("%#x ", storeQueue[store_idx].inst->readPC());
973 incrStIdx(store_idx);