2 * Copyright (c) 2004-2006 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 #ifndef __CPU_O3_LSQ_UNIT_HH__
33 #define __CPU_O3_LSQ_UNIT_HH__
39 #include "arch/faults.hh"
40 #include "arch/locked_mem.hh"
41 #include "config/full_system.hh"
42 #include "base/hashmap.hh"
43 #include "cpu/inst_seq.hh"
44 #include "mem/packet.hh"
45 #include "mem/port.hh"
48 * Class that implements the actual LQ and SQ for each specific
49 * thread. Both are circular queues; load entries are freed upon
50 * committing, while store entries are freed once they writeback. The
51 * LSQUnit tracks if there are memory ordering violations, and also
52 * detects partial load to store forwarding cases (a store only has
53 * part of a load's data) that requires the load to wait until the
54 * store writes back. In the former case it holds onto the instruction
55 * until the dependence unit looks at it, and in the latter it stalls
56 * the LSQ until the store writes back. At that point the load is
62 typedef TheISA::IntReg IntReg;
64 typedef typename Impl::Params Params;
65 typedef typename Impl::O3CPU O3CPU;
66 typedef typename Impl::DynInstPtr DynInstPtr;
67 typedef typename Impl::CPUPol::IEW IEW;
68 typedef typename Impl::CPUPol::LSQ LSQ;
69 typedef typename Impl::CPUPol::IssueStruct IssueStruct;
72 /** Constructs an LSQ unit. init() must be called prior to use. */
75 /** Initializes the LSQ unit with the specified number of entries. */
76 void init(Params *params, LSQ *lsq_ptr, unsigned maxLQEntries,
77 unsigned maxSQEntries, unsigned id);
79 /** Returns the name of the LSQ unit. */
80 std::string name() const;
82 /** Registers statistics. */
85 /** Sets the CPU pointer. */
86 void setCPU(O3CPU *cpu_ptr);
88 /** Sets the IEW stage pointer. */
89 void setIEW(IEW *iew_ptr)
90 { iewStage = iew_ptr; }
92 /** Sets the pointer to the dcache port. */
93 void setDcachePort(Port *dcache_port)
94 { dcachePort = dcache_port; }
96 /** Switches out LSQ unit. */
99 /** Takes over from another CPU's thread. */
102 /** Returns if the LSQ is switched out. */
103 bool isSwitchedOut() { return switchedOut; }
105 /** Ticks the LSQ unit, which in this case only resets the number of
107 * @todo: Move the number of used ports up to the LSQ level so it can
108 * be shared by all LSQ units.
110 void tick() { usedPorts = 0; }
112 /** Inserts an instruction. */
113 void insert(DynInstPtr &inst);
114 /** Inserts a load instruction. */
115 void insertLoad(DynInstPtr &load_inst);
116 /** Inserts a store instruction. */
117 void insertStore(DynInstPtr &store_inst);
119 /** Executes a load instruction. */
120 Fault executeLoad(DynInstPtr &inst);
122 Fault executeLoad(int lq_idx) { panic("Not implemented"); return NoFault; }
123 /** Executes a store instruction. */
124 Fault executeStore(DynInstPtr &inst);
126 /** Commits the head load. */
128 /** Commits loads older than a specific sequence number. */
129 void commitLoads(InstSeqNum &youngest_inst);
131 /** Commits stores older than a specific sequence number. */
132 void commitStores(InstSeqNum &youngest_inst);
134 /** Writes back stores. */
135 void writebackStores();
137 /** Completes the data access that has been returned from the
139 void completeDataAccess(PacketPtr pkt);
141 /** Clears all the entries in the LQ. */
144 /** Clears all the entries in the SQ. */
147 /** Resizes the LQ to a given size. */
148 void resizeLQ(unsigned size);
150 /** Resizes the SQ to a given size. */
151 void resizeSQ(unsigned size);
153 /** Squashes all instructions younger than a specific sequence number. */
154 void squash(const InstSeqNum &squashed_num);
156 /** Returns if there is a memory ordering violation. Value is reset upon
157 * call to getMemDepViolator().
159 bool violation() { return memDepViolator; }
161 /** Returns the memory ordering violator. */
162 DynInstPtr getMemDepViolator();
164 /** Returns if a load became blocked due to the memory system. */
166 { return isLoadBlocked; }
168 /** Clears the signal that a load became blocked. */
169 void clearLoadBlocked()
170 { isLoadBlocked = false; }
172 /** Returns if the blocked load was handled. */
173 bool isLoadBlockedHandled()
174 { return loadBlockedHandled; }
176 /** Records the blocked load as being handled. */
177 void setLoadBlockedHandled()
178 { loadBlockedHandled = true; }
180 /** Returns the number of free entries (min of free LQ and SQ entries). */
181 unsigned numFreeEntries();
183 /** Returns the number of loads ready to execute. */
186 /** Returns the number of loads in the LQ. */
187 int numLoads() { return loads; }
189 /** Returns the number of stores in the SQ. */
190 int numStores() { return stores; }
192 /** Returns if either the LQ or SQ is full. */
193 bool isFull() { return lqFull() || sqFull(); }
195 /** Returns if the LQ is full. */
196 bool lqFull() { return loads >= (LQEntries - 1); }
198 /** Returns if the SQ is full. */
199 bool sqFull() { return stores >= (SQEntries - 1); }
201 /** Returns the number of instructions in the LSQ. */
202 unsigned getCount() { return loads + stores; }
204 /** Returns if there are any stores to writeback. */
205 bool hasStoresToWB() { return storesToWB; }
207 /** Returns the number of stores to writeback. */
208 int numStoresToWB() { return storesToWB; }
210 /** Returns if the LSQ unit will writeback on this cycle. */
211 bool willWB() { return storeQueue[storeWBIdx].canWB &&
212 !storeQueue[storeWBIdx].completed &&
215 /** Handles doing the retry. */
219 /** Writes back the instruction, sending it to IEW. */
220 void writeback(DynInstPtr &inst, PacketPtr pkt);
222 /** Handles completing the send of a store to memory. */
223 void storePostSend(PacketPtr pkt);
225 /** Completes the store at the specified index. */
226 void completeStore(int store_idx);
228 /** Increments the given store index (circular queue). */
229 inline void incrStIdx(int &store_idx);
230 /** Decrements the given store index (circular queue). */
231 inline void decrStIdx(int &store_idx);
232 /** Increments the given load index (circular queue). */
233 inline void incrLdIdx(int &load_idx);
234 /** Decrements the given load index (circular queue). */
235 inline void decrLdIdx(int &load_idx);
238 /** Debugging function to dump instructions in the LSQ. */
242 /** Pointer to the CPU. */
245 /** Pointer to the IEW stage. */
248 /** Pointer to the LSQ. */
251 /** Pointer to the dcache port. Used only for sending. */
254 /** Derived class to hold any sender state the LSQ needs. */
255 class LSQSenderState : public Packet::SenderState
258 /** Default constructor. */
263 /** Instruction who initiated the access to memory. */
265 /** Whether or not it is a load. */
267 /** The LQ/SQ index of the instruction. */
269 /** Whether or not the instruction will need to writeback. */
273 /** Writeback event, specifically for when stores forward data to loads. */
274 class WritebackEvent : public Event {
276 /** Constructs a writeback event. */
277 WritebackEvent(DynInstPtr &_inst, PacketPtr pkt, LSQUnit *lsq_ptr);
279 /** Processes the writeback event. */
282 /** Returns the description of this event. */
283 const char *description();
286 /** Instruction whose results are being written back. */
289 /** The packet that would have been sent to memory. */
292 /** The pointer to the LSQ unit that issued the store. */
293 LSQUnit<Impl> *lsqPtr;
298 /** Constructs an empty store queue entry. */
300 : inst(NULL), req(NULL), size(0), data(0),
301 canWB(0), committed(0), completed(0)
304 /** Constructs a store queue entry for a given instruction. */
305 SQEntry(DynInstPtr &_inst)
306 : inst(_inst), req(NULL), size(0), data(0),
307 canWB(0), committed(0), completed(0)
310 /** The store instruction. */
312 /** The request for the store. */
314 /** The size of the store. */
316 /** The store data. */
318 /** Whether or not the store can writeback. */
320 /** Whether or not the store is committed. */
322 /** Whether or not the store is completed. */
327 /** The LSQUnit thread id. */
330 /** The store queue. */
331 std::vector<SQEntry> storeQueue;
333 /** The load queue. */
334 std::vector<DynInstPtr> loadQueue;
336 /** The number of LQ entries, plus a sentinel entry (circular queue).
337 * @todo: Consider having var that records the true number of LQ entries.
340 /** The number of SQ entries, plus a sentinel entry (circular queue).
341 * @todo: Consider having var that records the true number of SQ entries.
345 /** The number of load instructions in the LQ. */
347 /** The number of store instructions in the SQ. */
349 /** The number of store instructions in the SQ waiting to writeback. */
352 /** The index of the head instruction in the LQ. */
354 /** The index of the tail instruction in the LQ. */
357 /** The index of the head instruction in the SQ. */
359 /** The index of the first instruction that may be ready to be
360 * written back, and has not yet been written back.
363 /** The index of the tail instruction in the SQ. */
366 /// @todo Consider moving to a more advanced model with write vs read ports
367 /** The number of cache ports available each cycle. */
370 /** The number of used cache ports in this cycle. */
373 /** Is the LSQ switched out. */
376 //list<InstSeqNum> mshrSeqNums;
378 /** Wire to read information from the issue stage time queue. */
379 typename TimeBuffer<IssueStruct>::wire fromIssue;
381 /** Whether or not the LSQ is stalled. */
383 /** The store that causes the stall due to partial store to load
386 InstSeqNum stallingStoreIsn;
387 /** The index of the above store. */
390 /** The packet that needs to be retried. */
393 /** Whehter or not a store is blocked due to the memory system. */
396 /** Whether or not a load is blocked due to the memory system. */
399 /** Has the blocked load been handled. */
400 bool loadBlockedHandled;
402 /** The sequence number of the blocked load. */
403 InstSeqNum blockedLoadSeqNum;
405 /** The oldest load that caused a memory ordering violation. */
406 DynInstPtr memDepViolator;
408 // Will also need how many read/write ports the Dcache has. Or keep track
409 // of that in stage that is one level up, and only call executeLoad/Store
410 // the appropriate number of times.
411 /** Total number of loads forwaded from LSQ stores. */
412 Stats::Scalar<> lsqForwLoads;
414 /** Total number of loads ignored due to invalid addresses. */
415 Stats::Scalar<> invAddrLoads;
417 /** Total number of squashed loads. */
418 Stats::Scalar<> lsqSquashedLoads;
420 /** Total number of responses from the memory system that are
421 * ignored due to the instruction already being squashed. */
422 Stats::Scalar<> lsqIgnoredResponses;
424 /** Tota number of memory ordering violations. */
425 Stats::Scalar<> lsqMemOrderViolation;
427 /** Total number of squashed stores. */
428 Stats::Scalar<> lsqSquashedStores;
430 /** Total number of software prefetches ignored due to invalid addresses. */
431 Stats::Scalar<> invAddrSwpfs;
433 /** Ready loads blocked due to partial store-forwarding. */
434 Stats::Scalar<> lsqBlockedLoads;
436 /** Number of loads that were rescheduled. */
437 Stats::Scalar<> lsqRescheduledLoads;
439 /** Number of times the LSQ is blocked due to the cache. */
440 Stats::Scalar<> lsqCacheBlocked;
443 /** Executes the load at the given index. */
445 Fault read(Request *req, T &data, int load_idx);
447 /** Executes the store at the given index. */
449 Fault write(Request *req, T &data, int store_idx);
451 /** Returns the index of the head load instruction. */
452 int getLoadHead() { return loadHead; }
453 /** Returns the sequence number of the head load instruction. */
454 InstSeqNum getLoadHeadSeqNum()
456 if (loadQueue[loadHead]) {
457 return loadQueue[loadHead]->seqNum;
464 /** Returns the index of the head store instruction. */
465 int getStoreHead() { return storeHead; }
466 /** Returns the sequence number of the head store instruction. */
467 InstSeqNum getStoreHeadSeqNum()
469 if (storeQueue[storeHead].inst) {
470 return storeQueue[storeHead].inst->seqNum;
477 /** Returns whether or not the LSQ unit is stalled. */
478 bool isStalled() { return stalled; }
481 template <class Impl>
484 LSQUnit<Impl>::read(Request *req, T &data, int load_idx)
486 DynInstPtr load_inst = loadQueue[load_idx];
490 assert(!load_inst->isExecuted());
492 // Make sure this isn't an uncacheable access
493 // A bit of a hackish way to get uncached accesses to work only if they're
494 // at the head of the LSQ and are ready to commit (at the head of the ROB
496 if (req->isUncacheable() &&
497 (load_idx != loadHead || !load_inst->isAtCommit())) {
498 iewStage->rescheduleMemInst(load_inst);
499 ++lsqRescheduledLoads;
500 return TheISA::genMachineCheckFault();
503 // Check the SQ for any previous stores that might lead to forwarding
504 int store_idx = load_inst->sqIdx;
508 DPRINTF(LSQUnit, "Read called, load idx: %i, store idx: %i, "
509 "storeHead: %i addr: %#x\n",
510 load_idx, store_idx, storeHead, req->getPaddr());
512 if (req->isLocked()) {
513 // Disable recording the result temporarily. Writing to misc
514 // regs normally updates the result, but this is not the
515 // desired behavior when handling store conditionals.
516 load_inst->recordResult = false;
517 TheISA::handleLockedRead(load_inst.get(), req);
518 load_inst->recordResult = true;
521 while (store_idx != -1) {
522 // End once we've reached the top of the LSQ
523 if (store_idx == storeWBIdx) {
527 // Move the index to one younger
529 store_idx += SQEntries;
531 assert(storeQueue[store_idx].inst);
533 store_size = storeQueue[store_idx].size;
538 // Check if the store data is within the lower and upper bounds of
539 // addresses that the request needs.
540 bool store_has_lower_limit =
541 req->getVaddr() >= storeQueue[store_idx].inst->effAddr;
542 bool store_has_upper_limit =
543 (req->getVaddr() + req->getSize()) <=
544 (storeQueue[store_idx].inst->effAddr + store_size);
545 bool lower_load_has_store_part =
546 req->getVaddr() < (storeQueue[store_idx].inst->effAddr +
548 bool upper_load_has_store_part =
549 (req->getVaddr() + req->getSize()) >
550 storeQueue[store_idx].inst->effAddr;
552 // If the store's data has all of the data needed, we can forward.
553 if (store_has_lower_limit && store_has_upper_limit) {
554 // Get shift amount for offset into the store's data.
555 int shift_amt = req->getVaddr() & (store_size - 1);
556 // @todo: Magic number, assumes byte addressing
557 shift_amt = shift_amt << 3;
559 // Cast this to type T?
560 data = storeQueue[store_idx].data >> shift_amt;
562 // When the data comes from the store queue entry, it's in host
563 // order. When it gets sent to the load, it needs to be in guest
564 // order so when the load converts it again, it ends up back
565 // in host order like the inst expects.
566 data = TheISA::htog(data);
568 assert(!load_inst->memData);
569 load_inst->memData = new uint8_t[64];
571 memcpy(load_inst->memData, &data, req->getSize());
573 DPRINTF(LSQUnit, "Forwarding from store idx %i to load to "
574 "addr %#x, data %#x\n",
575 store_idx, req->getVaddr(), data);
577 PacketPtr data_pkt = new Packet(req, MemCmd::ReadReq,
579 data_pkt->dataStatic(load_inst->memData);
581 WritebackEvent *wb = new WritebackEvent(load_inst, data_pkt, this);
583 // We'll say this has a 1 cycle load-store forwarding latency
585 // @todo: Need to make this a parameter.
586 wb->schedule(curTick);
590 } else if ((store_has_lower_limit && lower_load_has_store_part) ||
591 (store_has_upper_limit && upper_load_has_store_part) ||
592 (lower_load_has_store_part && upper_load_has_store_part)) {
593 // This is the partial store-load forwarding case where a store
594 // has only part of the load's data.
596 // If it's already been written back, then don't worry about
598 if (storeQueue[store_idx].completed) {
602 // Must stall load and force it to retry, so long as it's the oldest
603 // load that needs to do so.
607 loadQueue[stallingLoadIdx]->seqNum)) {
609 stallingStoreIsn = storeQueue[store_idx].inst->seqNum;
610 stallingLoadIdx = load_idx;
613 // Tell IQ/mem dep unit that this instruction will need to be
614 // rescheduled eventually
615 iewStage->rescheduleMemInst(load_inst);
616 iewStage->decrWb(load_inst->seqNum);
617 ++lsqRescheduledLoads;
619 // Do not generate a writeback event as this instruction is not
621 DPRINTF(LSQUnit, "Load-store forwarding mis-match. "
622 "Store idx %i to load addr %#x\n",
623 store_idx, req->getVaddr());
630 // If there's no forwarding case, then go access memory
631 DPRINTF(LSQUnit, "Doing memory access for inst [sn:%lli] PC %#x\n",
632 load_inst->seqNum, load_inst->readPC());
634 assert(!load_inst->memData);
635 load_inst->memData = new uint8_t[64];
639 // if we the cache is not blocked, do cache access
640 if (!lsq->cacheBlocked()) {
642 new Packet(req, MemCmd::ReadReq, Packet::Broadcast);
643 data_pkt->dataStatic(load_inst->memData);
645 LSQSenderState *state = new LSQSenderState;
646 state->isLoad = true;
647 state->idx = load_idx;
648 state->inst = load_inst;
649 data_pkt->senderState = state;
651 if (!dcachePort->sendTiming(data_pkt)) {
652 Packet::Result result = data_pkt->result;
654 // Delete state and data packet because a load retry
655 // initiates a pipeline restart; it does not retry.
659 if (result == Packet::BadAddress) {
660 return TheISA::genMachineCheckFault();
663 // If the access didn't succeed, tell the LSQ by setting
664 // the retry thread id.
665 lsq->setRetryTid(lsqID);
669 // If the cache was blocked, or has become blocked due to the access,
671 if (lsq->cacheBlocked()) {
674 iewStage->decrWb(load_inst->seqNum);
675 // There's an older load that's already going to squash.
676 if (isLoadBlocked && blockedLoadSeqNum < load_inst->seqNum)
679 // Record that the load was blocked due to memory. This
680 // load will squash all instructions after it, be
681 // refetched, and re-executed.
682 isLoadBlocked = true;
683 loadBlockedHandled = false;
684 blockedLoadSeqNum = load_inst->seqNum;
685 // No fault occurred, even though the interface is blocked.
692 template <class Impl>
695 LSQUnit<Impl>::write(Request *req, T &data, int store_idx)
697 assert(storeQueue[store_idx].inst);
699 DPRINTF(LSQUnit, "Doing write to store idx %i, addr %#x data %#x"
700 " | storeHead:%i [sn:%i]\n",
701 store_idx, req->getPaddr(), data, storeHead,
702 storeQueue[store_idx].inst->seqNum);
704 storeQueue[store_idx].req = req;
705 storeQueue[store_idx].size = sizeof(T);
706 storeQueue[store_idx].data = data;
708 // This function only writes the data to the store queue, so no fault
713 #endif // __CPU_O3_LSQ_UNIT_HH__