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 "config/full_system.hh"
41 #include "base/hashmap.hh"
42 #include "cpu/inst_seq.hh"
43 #include "mem/packet_impl.hh"
44 #include "mem/port.hh"
47 * Class that implements the actual LQ and SQ for each specific
48 * thread. Both are circular queues; load entries are freed upon
49 * committing, while store entries are freed once they writeback. The
50 * LSQUnit tracks if there are memory ordering violations, and also
51 * detects partial load to store forwarding cases (a store only has
52 * part of a load's data) that requires the load to wait until the
53 * store writes back. In the former case it holds onto the instruction
54 * until the dependence unit looks at it, and in the latter it stalls
55 * the LSQ until the store writes back. At that point the load is
61 typedef TheISA::IntReg IntReg;
63 typedef typename Impl::Params Params;
64 typedef typename Impl::O3CPU O3CPU;
65 typedef typename Impl::DynInstPtr DynInstPtr;
66 typedef typename Impl::CPUPol::IEW IEW;
67 typedef typename Impl::CPUPol::LSQ LSQ;
68 typedef typename Impl::CPUPol::IssueStruct IssueStruct;
71 /** Constructs an LSQ unit. init() must be called prior to use. */
74 /** Initializes the LSQ unit with the specified number of entries. */
75 void init(Params *params, LSQ *lsq_ptr, unsigned maxLQEntries,
76 unsigned maxSQEntries, unsigned id);
78 /** Returns the name of the LSQ unit. */
79 std::string name() const;
81 /** Registers statistics. */
84 /** Sets the CPU pointer. */
85 void setCPU(O3CPU *cpu_ptr);
87 /** Sets the IEW stage pointer. */
88 void setIEW(IEW *iew_ptr)
89 { iewStage = iew_ptr; }
91 /** Sets the pointer to the dcache port. */
92 void setDcachePort(Port *dcache_port)
93 { dcachePort = dcache_port; }
95 /** Switches out LSQ unit. */
98 /** Takes over from another CPU's thread. */
101 /** Returns if the LSQ is switched out. */
102 bool isSwitchedOut() { return switchedOut; }
104 /** Ticks the LSQ unit, which in this case only resets the number of
106 * @todo: Move the number of used ports up to the LSQ level so it can
107 * be shared by all LSQ units.
109 void tick() { usedPorts = 0; }
111 /** Inserts an instruction. */
112 void insert(DynInstPtr &inst);
113 /** Inserts a load instruction. */
114 void insertLoad(DynInstPtr &load_inst);
115 /** Inserts a store instruction. */
116 void insertStore(DynInstPtr &store_inst);
118 /** Executes a load instruction. */
119 Fault executeLoad(DynInstPtr &inst);
121 Fault executeLoad(int lq_idx) { panic("Not implemented"); return NoFault; }
122 /** Executes a store instruction. */
123 Fault executeStore(DynInstPtr &inst);
125 /** Commits the head load. */
127 /** Commits loads older than a specific sequence number. */
128 void commitLoads(InstSeqNum &youngest_inst);
130 /** Commits stores older than a specific sequence number. */
131 void commitStores(InstSeqNum &youngest_inst);
133 /** Writes back stores. */
134 void writebackStores();
136 /** Completes the data access that has been returned from the
138 void completeDataAccess(PacketPtr pkt);
140 /** Clears all the entries in the LQ. */
143 /** Clears all the entries in the SQ. */
146 /** Resizes the LQ to a given size. */
147 void resizeLQ(unsigned size);
149 /** Resizes the SQ to a given size. */
150 void resizeSQ(unsigned size);
152 /** Squashes all instructions younger than a specific sequence number. */
153 void squash(const InstSeqNum &squashed_num);
155 /** Returns if there is a memory ordering violation. Value is reset upon
156 * call to getMemDepViolator().
158 bool violation() { return memDepViolator; }
160 /** Returns the memory ordering violator. */
161 DynInstPtr getMemDepViolator();
163 /** Returns if a load became blocked due to the memory system. */
165 { return isLoadBlocked; }
167 /** Clears the signal that a load became blocked. */
168 void clearLoadBlocked()
169 { isLoadBlocked = false; }
171 /** Returns if the blocked load was handled. */
172 bool isLoadBlockedHandled()
173 { return loadBlockedHandled; }
175 /** Records the blocked load as being handled. */
176 void setLoadBlockedHandled()
177 { loadBlockedHandled = true; }
179 /** Returns the number of free entries (min of free LQ and SQ entries). */
180 unsigned numFreeEntries();
182 /** Returns the number of loads ready to execute. */
185 /** Returns the number of loads in the LQ. */
186 int numLoads() { return loads; }
188 /** Returns the number of stores in the SQ. */
189 int numStores() { return stores; }
191 /** Returns if either the LQ or SQ is full. */
192 bool isFull() { return lqFull() || sqFull(); }
194 /** Returns if the LQ is full. */
195 bool lqFull() { return loads >= (LQEntries - 1); }
197 /** Returns if the SQ is full. */
198 bool sqFull() { return stores >= (SQEntries - 1); }
200 /** Returns the number of instructions in the LSQ. */
201 unsigned getCount() { return loads + stores; }
203 /** Returns if there are any stores to writeback. */
204 bool hasStoresToWB() { return storesToWB; }
206 /** Returns the number of stores to writeback. */
207 int numStoresToWB() { return storesToWB; }
209 /** Returns if the LSQ unit will writeback on this cycle. */
210 bool willWB() { return storeQueue[storeWBIdx].canWB &&
211 !storeQueue[storeWBIdx].completed &&
214 /** Handles doing the retry. */
218 /** Writes back the instruction, sending it to IEW. */
219 void writeback(DynInstPtr &inst, PacketPtr pkt);
221 /** Handles completing the send of a store to memory. */
222 void storePostSend(Packet *pkt);
224 /** Completes the store at the specified index. */
225 void completeStore(int store_idx);
227 /** Increments the given store index (circular queue). */
228 inline void incrStIdx(int &store_idx);
229 /** Decrements the given store index (circular queue). */
230 inline void decrStIdx(int &store_idx);
231 /** Increments the given load index (circular queue). */
232 inline void incrLdIdx(int &load_idx);
233 /** Decrements the given load index (circular queue). */
234 inline void decrLdIdx(int &load_idx);
237 /** Debugging function to dump instructions in the LSQ. */
241 /** Pointer to the CPU. */
244 /** Pointer to the IEW stage. */
247 /** Pointer to the LSQ. */
250 /** Pointer to the dcache port. Used only for sending. */
253 /** Derived class to hold any sender state the LSQ needs. */
254 class LSQSenderState : public Packet::SenderState
257 /** Default constructor. */
262 /** Instruction who initiated the access to memory. */
264 /** Whether or not it is a load. */
266 /** The LQ/SQ index of the instruction. */
268 /** Whether or not the instruction will need to writeback. */
272 /** Writeback event, specifically for when stores forward data to loads. */
273 class WritebackEvent : public Event {
275 /** Constructs a writeback event. */
276 WritebackEvent(DynInstPtr &_inst, PacketPtr pkt, LSQUnit *lsq_ptr);
278 /** Processes the writeback event. */
281 /** Returns the description of this event. */
282 const char *description();
285 /** Instruction whose results are being written back. */
288 /** The packet that would have been sent to memory. */
291 /** The pointer to the LSQ unit that issued the store. */
292 LSQUnit<Impl> *lsqPtr;
297 /** Constructs an empty store queue entry. */
299 : inst(NULL), req(NULL), size(0), data(0),
300 canWB(0), committed(0), completed(0)
303 /** Constructs a store queue entry for a given instruction. */
304 SQEntry(DynInstPtr &_inst)
305 : inst(_inst), req(NULL), size(0), data(0),
306 canWB(0), committed(0), completed(0)
309 /** The store instruction. */
311 /** The request for the store. */
313 /** The size of the store. */
315 /** The store data. */
317 /** Whether or not the store can writeback. */
319 /** Whether or not the store is committed. */
321 /** Whether or not the store is completed. */
326 /** The LSQUnit thread id. */
329 /** The store queue. */
330 std::vector<SQEntry> storeQueue;
332 /** The load queue. */
333 std::vector<DynInstPtr> loadQueue;
335 /** The number of LQ entries, plus a sentinel entry (circular queue).
336 * @todo: Consider having var that records the true number of LQ entries.
339 /** The number of SQ entries, plus a sentinel entry (circular queue).
340 * @todo: Consider having var that records the true number of SQ entries.
344 /** The number of load instructions in the LQ. */
346 /** The number of store instructions in the SQ. */
348 /** The number of store instructions in the SQ waiting to writeback. */
351 /** The index of the head instruction in the LQ. */
353 /** The index of the tail instruction in the LQ. */
356 /** The index of the head instruction in the SQ. */
358 /** The index of the first instruction that may be ready to be
359 * written back, and has not yet been written back.
362 /** The index of the tail instruction in the SQ. */
365 /// @todo Consider moving to a more advanced model with write vs read ports
366 /** The number of cache ports available each cycle. */
369 /** The number of used cache ports in this cycle. */
372 /** Is the LSQ switched out. */
375 //list<InstSeqNum> mshrSeqNums;
377 /** Wire to read information from the issue stage time queue. */
378 typename TimeBuffer<IssueStruct>::wire fromIssue;
380 /** Whether or not the LSQ is stalled. */
382 /** The store that causes the stall due to partial store to load
385 InstSeqNum stallingStoreIsn;
386 /** The index of the above store. */
389 /** The packet that needs to be retried. */
392 /** Whehter or not a store is blocked due to the memory system. */
395 /** Whether or not a load is blocked due to the memory system. */
398 /** Has the blocked load been handled. */
399 bool loadBlockedHandled;
401 /** The sequence number of the blocked load. */
402 InstSeqNum blockedLoadSeqNum;
404 /** The oldest load that caused a memory ordering violation. */
405 DynInstPtr memDepViolator;
407 // Will also need how many read/write ports the Dcache has. Or keep track
408 // of that in stage that is one level up, and only call executeLoad/Store
409 // 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 /** Total number of squashed stores. */
425 Stats::Scalar<> lsqSquashedStores;
427 /** Total number of software prefetches ignored due to invalid addresses. */
428 Stats::Scalar<> invAddrSwpfs;
430 /** Ready loads blocked due to partial store-forwarding. */
431 Stats::Scalar<> lsqBlockedLoads;
433 /** Number of loads that were rescheduled. */
434 Stats::Scalar<> lsqRescheduledLoads;
436 /** Number of times the LSQ is blocked due to the cache. */
437 Stats::Scalar<> lsqCacheBlocked;
440 /** Executes the load at the given index. */
442 Fault read(Request *req, T &data, int load_idx);
444 /** Executes the store at the given index. */
446 Fault write(Request *req, T &data, int store_idx);
448 /** Returns the index of the head load instruction. */
449 int getLoadHead() { return loadHead; }
450 /** Returns the sequence number of the head load instruction. */
451 InstSeqNum getLoadHeadSeqNum()
453 if (loadQueue[loadHead]) {
454 return loadQueue[loadHead]->seqNum;
461 /** Returns the index of the head store instruction. */
462 int getStoreHead() { return storeHead; }
463 /** Returns the sequence number of the head store instruction. */
464 InstSeqNum getStoreHeadSeqNum()
466 if (storeQueue[storeHead].inst) {
467 return storeQueue[storeHead].inst->seqNum;
474 /** Returns whether or not the LSQ unit is stalled. */
475 bool isStalled() { return stalled; }
478 template <class Impl>
481 LSQUnit<Impl>::read(Request *req, T &data, int load_idx)
483 DynInstPtr load_inst = loadQueue[load_idx];
487 assert(!load_inst->isExecuted());
489 // Make sure this isn't an uncacheable access
490 // A bit of a hackish way to get uncached accesses to work only if they're
491 // at the head of the LSQ and are ready to commit (at the head of the ROB
493 if (req->getFlags() & UNCACHEABLE &&
494 (load_idx != loadHead || !load_inst->isAtCommit())) {
495 iewStage->rescheduleMemInst(load_inst);
496 ++lsqRescheduledLoads;
497 return TheISA::genMachineCheckFault();
500 // Check the SQ for any previous stores that might lead to forwarding
501 int store_idx = load_inst->sqIdx;
505 DPRINTF(LSQUnit, "Read called, load idx: %i, store idx: %i, "
506 "storeHead: %i addr: %#x\n",
507 load_idx, store_idx, storeHead, req->getPaddr());
510 if (req->getFlags() & LOCKED) {
511 cpu->lockAddr = req->getPaddr();
512 cpu->lockFlag = true;
516 while (store_idx != -1) {
517 // End once we've reached the top of the LSQ
518 if (store_idx == storeWBIdx) {
522 // Move the index to one younger
524 store_idx += SQEntries;
526 assert(storeQueue[store_idx].inst);
528 store_size = storeQueue[store_idx].size;
533 // Check if the store data is within the lower and upper bounds of
534 // addresses that the request needs.
535 bool store_has_lower_limit =
536 req->getVaddr() >= storeQueue[store_idx].inst->effAddr;
537 bool store_has_upper_limit =
538 (req->getVaddr() + req->getSize()) <=
539 (storeQueue[store_idx].inst->effAddr + store_size);
540 bool lower_load_has_store_part =
541 req->getVaddr() < (storeQueue[store_idx].inst->effAddr +
543 bool upper_load_has_store_part =
544 (req->getVaddr() + req->getSize()) >
545 storeQueue[store_idx].inst->effAddr;
547 // If the store's data has all of the data needed, we can forward.
548 if (store_has_lower_limit && store_has_upper_limit) {
549 // Get shift amount for offset into the store's data.
550 int shift_amt = req->getVaddr() & (store_size - 1);
551 // @todo: Magic number, assumes byte addressing
552 shift_amt = shift_amt << 3;
554 // Cast this to type T?
555 data = storeQueue[store_idx].data >> shift_amt;
557 assert(!load_inst->memData);
558 load_inst->memData = new uint8_t[64];
560 memcpy(load_inst->memData, &data, req->getSize());
562 DPRINTF(LSQUnit, "Forwarding from store idx %i to load to "
563 "addr %#x, data %#x\n",
564 store_idx, req->getVaddr(), data);
566 PacketPtr data_pkt = new Packet(req, Packet::ReadReq, Packet::Broadcast);
567 data_pkt->dataStatic(load_inst->memData);
569 WritebackEvent *wb = new WritebackEvent(load_inst, data_pkt, this);
571 // We'll say this has a 1 cycle load-store forwarding latency
573 // @todo: Need to make this a parameter.
574 wb->schedule(curTick);
578 } else if ((store_has_lower_limit && lower_load_has_store_part) ||
579 (store_has_upper_limit && upper_load_has_store_part) ||
580 (lower_load_has_store_part && upper_load_has_store_part)) {
581 // This is the partial store-load forwarding case where a store
582 // has only part of the load's data.
584 // If it's already been written back, then don't worry about
586 if (storeQueue[store_idx].completed) {
590 // Must stall load and force it to retry, so long as it's the oldest
591 // load that needs to do so.
595 loadQueue[stallingLoadIdx]->seqNum)) {
597 stallingStoreIsn = storeQueue[store_idx].inst->seqNum;
598 stallingLoadIdx = load_idx;
601 // Tell IQ/mem dep unit that this instruction will need to be
602 // rescheduled eventually
603 iewStage->rescheduleMemInst(load_inst);
604 iewStage->decrWb(load_inst->seqNum);
605 ++lsqRescheduledLoads;
607 // Do not generate a writeback event as this instruction is not
609 DPRINTF(LSQUnit, "Load-store forwarding mis-match. "
610 "Store idx %i to load addr %#x\n",
611 store_idx, req->getVaddr());
618 // If there's no forwarding case, then go access memory
619 DPRINTF(LSQUnit, "Doing memory access for inst [sn:%lli] PC %#x\n",
620 load_inst->seqNum, load_inst->readPC());
622 assert(!load_inst->memData);
623 load_inst->memData = new uint8_t[64];
627 PacketPtr data_pkt = new Packet(req, Packet::ReadReq, Packet::Broadcast);
628 data_pkt->dataStatic(load_inst->memData);
630 LSQSenderState *state = new LSQSenderState;
631 state->isLoad = true;
632 state->idx = load_idx;
633 state->inst = load_inst;
634 data_pkt->senderState = state;
636 // if we the cache is not blocked, do cache access
637 if (!lsq->cacheBlocked()) {
638 if (!dcachePort->sendTiming(data_pkt)) {
639 // If the access didn't succeed, tell the LSQ by setting
640 // the retry thread id.
641 lsq->setRetryTid(lsqID);
645 // If the cache was blocked, or has become blocked due to the access,
647 if (lsq->cacheBlocked()) {
650 iewStage->decrWb(load_inst->seqNum);
651 // There's an older load that's already going to squash.
652 if (isLoadBlocked && blockedLoadSeqNum < load_inst->seqNum)
655 // Record that the load was blocked due to memory. This
656 // load will squash all instructions after it, be
657 // refetched, and re-executed.
658 isLoadBlocked = true;
659 loadBlockedHandled = false;
660 blockedLoadSeqNum = load_inst->seqNum;
661 // No fault occurred, even though the interface is blocked.
665 if (data_pkt->result != Packet::Success) {
666 DPRINTF(LSQUnit, "LSQUnit: D-cache miss!\n");
667 DPRINTF(Activity, "Activity: ld accessing mem miss [sn:%lli]\n",
670 DPRINTF(LSQUnit, "LSQUnit: D-cache hit!\n");
671 DPRINTF(Activity, "Activity: ld accessing mem hit [sn:%lli]\n",
678 template <class Impl>
681 LSQUnit<Impl>::write(Request *req, T &data, int store_idx)
683 assert(storeQueue[store_idx].inst);
685 DPRINTF(LSQUnit, "Doing write to store idx %i, addr %#x data %#x"
686 " | storeHead:%i [sn:%i]\n",
687 store_idx, req->getPaddr(), data, storeHead,
688 storeQueue[store_idx].inst->seqNum);
690 storeQueue[store_idx].req = req;
691 storeQueue[store_idx].size = sizeof(T);
692 storeQueue[store_idx].data = data;
694 // This function only writes the data to the store queue, so no fault
699 #endif // __CPU_O3_LSQ_UNIT_HH__