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__
40 #include "arch/faults.hh"
41 #include "arch/locked_mem.hh"
42 #include "config/full_system.hh"
43 #include "base/hashmap.hh"
44 #include "cpu/inst_seq.hh"
45 #include "mem/packet.hh"
46 #include "mem/port.hh"
49 * Class that implements the actual LQ and SQ for each specific
50 * thread. Both are circular queues; load entries are freed upon
51 * committing, while store entries are freed once they writeback. The
52 * LSQUnit tracks if there are memory ordering violations, and also
53 * detects partial load to store forwarding cases (a store only has
54 * part of a load's data) that requires the load to wait until the
55 * store writes back. In the former case it holds onto the instruction
56 * until the dependence unit looks at it, and in the latter it stalls
57 * the LSQ until the store writes back. At that point the load is
63 typedef TheISA::IntReg IntReg;
65 typedef typename Impl::Params Params;
66 typedef typename Impl::O3CPU O3CPU;
67 typedef typename Impl::DynInstPtr DynInstPtr;
68 typedef typename Impl::CPUPol::IEW IEW;
69 typedef typename Impl::CPUPol::LSQ LSQ;
70 typedef typename Impl::CPUPol::IssueStruct IssueStruct;
73 /** Constructs an LSQ unit. init() must be called prior to use. */
76 /** Initializes the LSQ unit with the specified number of entries. */
77 void init(O3CPU *cpu_ptr, IEW *iew_ptr, Params *params, LSQ *lsq_ptr,
78 unsigned maxLQEntries, unsigned maxSQEntries, unsigned id);
80 /** Returns the name of the LSQ unit. */
81 std::string name() const;
83 /** Registers statistics. */
86 /** Sets the pointer to the dcache port. */
87 void setDcachePort(Port *dcache_port);
89 /** Switches out LSQ unit. */
92 /** Takes over from another CPU's thread. */
95 /** Returns if the LSQ is switched out. */
96 bool isSwitchedOut() { return switchedOut; }
98 /** Ticks the LSQ unit, which in this case only resets the number of
100 * @todo: Move the number of used ports up to the LSQ level so it can
101 * be shared by all LSQ units.
103 void tick() { usedPorts = 0; }
105 /** Inserts an instruction. */
106 void insert(DynInstPtr &inst);
107 /** Inserts a load instruction. */
108 void insertLoad(DynInstPtr &load_inst);
109 /** Inserts a store instruction. */
110 void insertStore(DynInstPtr &store_inst);
112 /** Executes a load instruction. */
113 Fault executeLoad(DynInstPtr &inst);
115 Fault executeLoad(int lq_idx) { panic("Not implemented"); return NoFault; }
116 /** Executes a store instruction. */
117 Fault executeStore(DynInstPtr &inst);
119 /** Commits the head load. */
121 /** Commits loads older than a specific sequence number. */
122 void commitLoads(InstSeqNum &youngest_inst);
124 /** Commits stores older than a specific sequence number. */
125 void commitStores(InstSeqNum &youngest_inst);
127 /** Writes back stores. */
128 void writebackStores();
130 /** Completes the data access that has been returned from the
132 void completeDataAccess(PacketPtr pkt);
134 /** Clears all the entries in the LQ. */
137 /** Clears all the entries in the SQ. */
140 /** Resizes the LQ to a given size. */
141 void resizeLQ(unsigned size);
143 /** Resizes the SQ to a given size. */
144 void resizeSQ(unsigned size);
146 /** Squashes all instructions younger than a specific sequence number. */
147 void squash(const InstSeqNum &squashed_num);
149 /** Returns if there is a memory ordering violation. Value is reset upon
150 * call to getMemDepViolator().
152 bool violation() { return memDepViolator; }
154 /** Returns the memory ordering violator. */
155 DynInstPtr getMemDepViolator();
157 /** Returns if a load became blocked due to the memory system. */
159 { return isLoadBlocked; }
161 /** Clears the signal that a load became blocked. */
162 void clearLoadBlocked()
163 { isLoadBlocked = false; }
165 /** Returns if the blocked load was handled. */
166 bool isLoadBlockedHandled()
167 { return loadBlockedHandled; }
169 /** Records the blocked load as being handled. */
170 void setLoadBlockedHandled()
171 { loadBlockedHandled = true; }
173 /** Returns the number of free entries (min of free LQ and SQ entries). */
174 unsigned numFreeEntries();
176 /** Returns the number of loads ready to execute. */
179 /** Returns the number of loads in the LQ. */
180 int numLoads() { return loads; }
182 /** Returns the number of stores in the SQ. */
183 int numStores() { return stores; }
185 /** Returns if either the LQ or SQ is full. */
186 bool isFull() { return lqFull() || sqFull(); }
188 /** Returns if the LQ is full. */
189 bool lqFull() { return loads >= (LQEntries - 1); }
191 /** Returns if the SQ is full. */
192 bool sqFull() { return stores >= (SQEntries - 1); }
194 /** Returns the number of instructions in the LSQ. */
195 unsigned getCount() { return loads + stores; }
197 /** Returns if there are any stores to writeback. */
198 bool hasStoresToWB() { return storesToWB; }
200 /** Returns the number of stores to writeback. */
201 int numStoresToWB() { return storesToWB; }
203 /** Returns if the LSQ unit will writeback on this cycle. */
204 bool willWB() { return storeQueue[storeWBIdx].canWB &&
205 !storeQueue[storeWBIdx].completed &&
208 /** Handles doing the retry. */
212 /** Writes back the instruction, sending it to IEW. */
213 void writeback(DynInstPtr &inst, PacketPtr pkt);
215 /** Handles completing the send of a store to memory. */
216 void storePostSend(PacketPtr pkt);
218 /** Completes the store at the specified index. */
219 void completeStore(int store_idx);
221 /** Increments the given store index (circular queue). */
222 inline void incrStIdx(int &store_idx);
223 /** Decrements the given store index (circular queue). */
224 inline void decrStIdx(int &store_idx);
225 /** Increments the given load index (circular queue). */
226 inline void incrLdIdx(int &load_idx);
227 /** Decrements the given load index (circular queue). */
228 inline void decrLdIdx(int &load_idx);
231 /** Debugging function to dump instructions in the LSQ. */
235 /** Pointer to the CPU. */
238 /** Pointer to the IEW stage. */
241 /** Pointer to the LSQ. */
244 /** Pointer to the dcache port. Used only for sending. */
247 /** Derived class to hold any sender state the LSQ needs. */
248 class LSQSenderState : public Packet::SenderState
251 /** Default constructor. */
256 /** Instruction who initiated the access to memory. */
258 /** Whether or not it is a load. */
260 /** The LQ/SQ index of the instruction. */
262 /** Whether or not the instruction will need to writeback. */
266 /** Writeback event, specifically for when stores forward data to loads. */
267 class WritebackEvent : public Event {
269 /** Constructs a writeback event. */
270 WritebackEvent(DynInstPtr &_inst, PacketPtr pkt, LSQUnit *lsq_ptr);
272 /** Processes the writeback event. */
275 /** Returns the description of this event. */
276 const char *description();
279 /** Instruction whose results are being written back. */
282 /** The packet that would have been sent to memory. */
285 /** The pointer to the LSQ unit that issued the store. */
286 LSQUnit<Impl> *lsqPtr;
291 /** Constructs an empty store queue entry. */
293 : inst(NULL), req(NULL), size(0),
294 canWB(0), committed(0), completed(0)
296 std::memset(data, 0, sizeof(data));
299 /** Constructs a store queue entry for a given instruction. */
300 SQEntry(DynInstPtr &_inst)
301 : inst(_inst), req(NULL), size(0),
302 canWB(0), committed(0), completed(0)
304 std::memset(data, 0, sizeof(data));
307 /** The store instruction. */
309 /** The request for the store. */
311 /** The size of the store. */
313 /** The store data. */
314 char data[sizeof(IntReg)];
315 /** Whether or not the store can writeback. */
317 /** Whether or not the store is committed. */
319 /** Whether or not the store is completed. */
324 /** The LSQUnit thread id. */
327 /** The store queue. */
328 std::vector<SQEntry> storeQueue;
330 /** The load queue. */
331 std::vector<DynInstPtr> loadQueue;
333 /** The number of LQ entries, plus a sentinel entry (circular queue).
334 * @todo: Consider having var that records the true number of LQ entries.
337 /** The number of SQ entries, plus a sentinel entry (circular queue).
338 * @todo: Consider having var that records the true number of SQ entries.
342 /** The number of load instructions in the LQ. */
344 /** The number of store instructions in the SQ. */
346 /** The number of store instructions in the SQ waiting to writeback. */
349 /** The index of the head instruction in the LQ. */
351 /** The index of the tail instruction in the LQ. */
354 /** The index of the head instruction in the SQ. */
356 /** The index of the first instruction that may be ready to be
357 * written back, and has not yet been written back.
360 /** The index of the tail instruction in the SQ. */
363 /// @todo Consider moving to a more advanced model with write vs read ports
364 /** The number of cache ports available each cycle. */
367 /** The number of used cache ports in this cycle. */
370 /** Is the LSQ switched out. */
373 //list<InstSeqNum> mshrSeqNums;
375 /** Wire to read information from the issue stage time queue. */
376 typename TimeBuffer<IssueStruct>::wire fromIssue;
378 /** Whether or not the LSQ is stalled. */
380 /** The store that causes the stall due to partial store to load
383 InstSeqNum stallingStoreIsn;
384 /** The index of the above store. */
387 /** The packet that needs to be retried. */
390 /** Whehter or not a store is blocked due to the memory system. */
393 /** Whether or not a load is blocked due to the memory system. */
396 /** Has the blocked load been handled. */
397 bool loadBlockedHandled;
399 /** The sequence number of the blocked load. */
400 InstSeqNum blockedLoadSeqNum;
402 /** The oldest load that caused a memory ordering violation. */
403 DynInstPtr memDepViolator;
405 // Will also need how many read/write ports the Dcache has. Or keep track
406 // of that in stage that is one level up, and only call executeLoad/Store
407 // the appropriate number of times.
408 /** Total number of loads forwaded from LSQ stores. */
409 Stats::Scalar<> lsqForwLoads;
411 /** Total number of loads ignored due to invalid addresses. */
412 Stats::Scalar<> invAddrLoads;
414 /** Total number of squashed loads. */
415 Stats::Scalar<> lsqSquashedLoads;
417 /** Total number of responses from the memory system that are
418 * ignored due to the instruction already being squashed. */
419 Stats::Scalar<> lsqIgnoredResponses;
421 /** Tota number of memory ordering violations. */
422 Stats::Scalar<> lsqMemOrderViolation;
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->isUncacheable() &&
494 (load_idx != loadHead || !load_inst->isAtCommit())) {
495 iewStage->rescheduleMemInst(load_inst);
496 ++lsqRescheduledLoads;
498 // Must delete request now that it wasn't handed off to
499 // memory. This is quite ugly. @todo: Figure out the proper
500 // place to really handle request deletes.
502 return TheISA::genMachineCheckFault();
505 // Check the SQ for any previous stores that might lead to forwarding
506 int store_idx = load_inst->sqIdx;
510 DPRINTF(LSQUnit, "Read called, load idx: %i, store idx: %i, "
511 "storeHead: %i addr: %#x\n",
512 load_idx, store_idx, storeHead, req->getPaddr());
514 if (req->isLocked()) {
515 // Disable recording the result temporarily. Writing to misc
516 // regs normally updates the result, but this is not the
517 // desired behavior when handling store conditionals.
518 load_inst->recordResult = false;
519 TheISA::handleLockedRead(load_inst.get(), req);
520 load_inst->recordResult = true;
523 while (store_idx != -1) {
524 // End once we've reached the top of the LSQ
525 if (store_idx == storeWBIdx) {
529 // Move the index to one younger
531 store_idx += SQEntries;
533 assert(storeQueue[store_idx].inst);
535 store_size = storeQueue[store_idx].size;
539 else if (storeQueue[store_idx].inst->uncacheable())
542 assert(storeQueue[store_idx].inst->effAddrValid);
544 // Check if the store data is within the lower and upper bounds of
545 // addresses that the request needs.
546 bool store_has_lower_limit =
547 req->getVaddr() >= storeQueue[store_idx].inst->effAddr;
548 bool store_has_upper_limit =
549 (req->getVaddr() + req->getSize()) <=
550 (storeQueue[store_idx].inst->effAddr + store_size);
551 bool lower_load_has_store_part =
552 req->getVaddr() < (storeQueue[store_idx].inst->effAddr +
554 bool upper_load_has_store_part =
555 (req->getVaddr() + req->getSize()) >
556 storeQueue[store_idx].inst->effAddr;
558 // If the store's data has all of the data needed, we can forward.
559 if ((store_has_lower_limit && store_has_upper_limit)) {
560 // Get shift amount for offset into the store's data.
561 int shift_amt = req->getVaddr() & (store_size - 1);
563 memcpy(&data, storeQueue[store_idx].data + shift_amt, sizeof(T));
565 assert(!load_inst->memData);
566 load_inst->memData = new uint8_t[64];
568 memcpy(load_inst->memData,
569 storeQueue[store_idx].data + shift_amt, req->getSize());
571 DPRINTF(LSQUnit, "Forwarding from store idx %i to load to "
572 "addr %#x, data %#x\n",
573 store_idx, req->getVaddr(), data);
575 PacketPtr data_pkt = new Packet(req, MemCmd::ReadReq,
577 data_pkt->dataStatic(load_inst->memData);
579 WritebackEvent *wb = new WritebackEvent(load_inst, data_pkt, this);
581 // We'll say this has a 1 cycle load-store forwarding latency
583 // @todo: Need to make this a parameter.
584 wb->schedule(curTick);
588 } else if ((store_has_lower_limit && lower_load_has_store_part) ||
589 (store_has_upper_limit && upper_load_has_store_part) ||
590 (lower_load_has_store_part && upper_load_has_store_part)) {
591 // This is the partial store-load forwarding case where a store
592 // has only part of the load's data.
594 // If it's already been written back, then don't worry about
596 if (storeQueue[store_idx].completed) {
597 panic("Should not check one of these");
601 // Must stall load and force it to retry, so long as it's the oldest
602 // load that needs to do so.
606 loadQueue[stallingLoadIdx]->seqNum)) {
608 stallingStoreIsn = storeQueue[store_idx].inst->seqNum;
609 stallingLoadIdx = load_idx;
612 // Tell IQ/mem dep unit that this instruction will need to be
613 // rescheduled eventually
614 iewStage->rescheduleMemInst(load_inst);
615 iewStage->decrWb(load_inst->seqNum);
616 load_inst->clearIssued();
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());
625 // Must delete request now that it wasn't handed off to
626 // memory. This is quite ugly. @todo: Figure out the
627 // proper place to really handle request deletes.
634 // If there's no forwarding case, then go access memory
635 DPRINTF(LSQUnit, "Doing memory access for inst [sn:%lli] PC %#x\n",
636 load_inst->seqNum, load_inst->readPC());
638 assert(!load_inst->memData);
639 load_inst->memData = new uint8_t[64];
643 // if we the cache is not blocked, do cache access
644 if (!lsq->cacheBlocked()) {
646 new Packet(req, MemCmd::ReadReq, Packet::Broadcast);
647 data_pkt->dataStatic(load_inst->memData);
649 LSQSenderState *state = new LSQSenderState;
650 state->isLoad = true;
651 state->idx = load_idx;
652 state->inst = load_inst;
653 data_pkt->senderState = state;
655 if (!dcachePort->sendTiming(data_pkt)) {
656 Packet::Result result = data_pkt->result;
658 // Delete state and data packet because a load retry
659 // initiates a pipeline restart; it does not retry.
661 delete data_pkt->req;
666 if (result == Packet::BadAddress) {
667 return TheISA::genMachineCheckFault();
670 // If the access didn't succeed, tell the LSQ by setting
671 // the retry thread id.
672 lsq->setRetryTid(lsqID);
676 // If the cache was blocked, or has become blocked due to the access,
678 if (lsq->cacheBlocked()) {
684 iewStage->decrWb(load_inst->seqNum);
685 // There's an older load that's already going to squash.
686 if (isLoadBlocked && blockedLoadSeqNum < load_inst->seqNum)
689 // Record that the load was blocked due to memory. This
690 // load will squash all instructions after it, be
691 // refetched, and re-executed.
692 isLoadBlocked = true;
693 loadBlockedHandled = false;
694 blockedLoadSeqNum = load_inst->seqNum;
695 // No fault occurred, even though the interface is blocked.
702 template <class Impl>
705 LSQUnit<Impl>::write(Request *req, T &data, int store_idx)
707 assert(storeQueue[store_idx].inst);
709 DPRINTF(LSQUnit, "Doing write to store idx %i, addr %#x data %#x"
710 " | storeHead:%i [sn:%i]\n",
711 store_idx, req->getPaddr(), data, storeHead,
712 storeQueue[store_idx].inst->seqNum);
714 storeQueue[store_idx].req = req;
715 storeQueue[store_idx].size = sizeof(T);
716 assert(sizeof(T) <= sizeof(storeQueue[store_idx].data));
718 T gData = htog(data);
719 memcpy(storeQueue[store_idx].data, &gData, sizeof(T));
721 // This function only writes the data to the store queue, so no fault
726 #endif // __CPU_O3_LSQ_UNIT_HH__