2 * Copyright (c) 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.
31 #ifndef __CPU_OZONE_LW_LSQ_HH__
32 #define __CPU_OZONE_LW_LSQ_HH__
39 #include "arch/types.hh"
40 #include "base/hashmap.hh"
41 #include "config/the_isa.hh"
42 #include "cpu/inst_seq.hh"
43 #include "mem/packet.hh"
44 #include "mem/port.hh"
45 //#include "mem/page_table.hh"
46 #include "sim/debug.hh"
47 #include "sim/fault_fwd.hh"
48 #include "sim/sim_object.hh"
53 * Class that implements the actual LQ and SQ for each specific thread.
54 * Both are circular queues; load entries are freed upon committing, while
55 * store entries are freed once they writeback. The LSQUnit tracks if there
56 * are memory ordering violations, and also detects partial load to store
57 * forwarding cases (a store only has part of a load's data) that requires
58 * the load to wait until the store writes back. In the former case it
59 * holds onto the instruction until the dependence unit looks at it, and
60 * in the latter it stalls the LSQ until the store writes back. At that
61 * point the load is replayed.
66 typedef typename Impl::Params Params;
67 typedef typename Impl::OzoneCPU OzoneCPU;
68 typedef typename Impl::BackEnd BackEnd;
69 typedef typename Impl::DynInstPtr DynInstPtr;
70 typedef typename Impl::IssueStruct IssueStruct;
72 typedef TheISA::IntReg IntReg;
74 typedef typename std::map<InstSeqNum, DynInstPtr>::iterator LdMapIt;
77 /** Constructs an LSQ unit. init() must be called prior to use. */
80 /** Initializes the LSQ unit with the specified number of entries. */
81 void init(Params *params, unsigned maxLQEntries,
82 unsigned maxSQEntries, unsigned id);
84 /** Returns the name of the LSQ unit. */
85 std::string name() const;
89 /** Sets the CPU pointer. */
90 void setCPU(OzoneCPU *cpu_ptr);
92 /** Sets the back-end stage pointer. */
93 void setBE(BackEnd *be_ptr)
96 Port *getDcachePort() { return &dcachePort; }
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 /** Executes a store instruction. */
116 Fault executeStore(DynInstPtr &inst);
118 /** Commits the head load. */
120 /** Commits loads older than a specific sequence number. */
121 void commitLoads(InstSeqNum &youngest_inst);
123 /** Commits stores older than a specific sequence number. */
124 void commitStores(InstSeqNum &youngest_inst);
126 /** Writes back stores. */
127 void writebackStores();
129 /** Completes the data access that has been returned from the
131 void completeDataAccess(PacketPtr pkt);
133 // @todo: Include stats in the LSQ unit.
136 /** Clears all the entries in the LQ. */
139 /** Clears all the entries in the SQ. */
142 /** Resizes the LQ to a given size. */
143 void resizeLQ(unsigned size);
145 /** Resizes the SQ to a given size. */
146 void resizeSQ(unsigned size);
148 /** Squashes all instructions younger than a specific sequence number. */
149 void squash(const InstSeqNum &squashed_num);
151 /** Returns if there is a memory ordering violation. Value is reset upon
152 * call to getMemDepViolator().
154 bool violation() { return memDepViolator; }
156 /** Returns the memory ordering violator. */
157 DynInstPtr getMemDepViolator();
159 /** Returns if a load became blocked due to the memory system. It clears
160 * the bool's value upon this being called.
163 { return isLoadBlocked; }
165 void clearLoadBlocked()
166 { isLoadBlocked = false; }
168 bool isLoadBlockedHandled()
169 { return loadBlockedHandled; }
171 void setLoadBlockedHandled()
172 { loadBlockedHandled = true; }
174 /** Returns the number of free entries (min of free LQ and SQ entries). */
175 unsigned numFreeEntries();
177 /** Returns the number of loads ready to execute. */
180 /** Returns the number of loads in the LQ. */
181 int numLoads() { return loads; }
183 /** Returns the number of stores in the SQ. */
184 int numStores() { return stores + storesInFlight; }
186 /** Returns if either the LQ or SQ is full. */
187 bool isFull() { return lqFull() || sqFull(); }
189 /** Returns if the LQ is full. */
190 bool lqFull() { return loads >= (LQEntries - 1); }
192 /** Returns if the SQ is full. */
193 bool sqFull() { return (stores + storesInFlight) >= (SQEntries - 1); }
195 /** Debugging function to dump instructions in the LSQ. */
198 /** Returns the number of instructions in the LSQ. */
199 unsigned getCount() { return loads + stores; }
201 /** Returns if there are any stores to writeback. */
202 bool hasStoresToWB() { return storesToWB; }
204 /** Returns the number of stores to writeback. */
205 int numStoresToWB() { return storesToWB; }
207 /** Returns if the LSQ unit will writeback on this cycle. */
208 bool willWB() { return storeQueue.back().canWB &&
209 !storeQueue.back().completed &&
214 void takeOverFrom(ThreadContext *old_tc = NULL);
216 bool isSwitchedOut() { return switchedOut; }
221 /** Writes back the instruction, sending it to IEW. */
222 void writeback(DynInstPtr &inst, PacketPtr pkt);
224 /** Handles completing the send of a store to memory. */
225 void storePostSend(PacketPtr pkt, DynInstPtr &inst);
227 /** Completes the store at the specified index. */
228 void completeStore(DynInstPtr &inst);
230 void removeStore(int store_idx);
232 /** Handles doing the retry. */
236 /** Pointer to the CPU. */
239 /** Pointer to the back-end stage. */
242 class DcachePort : public MasterPort
248 DcachePort(OzoneLWLSQ *_lsq)
253 virtual Tick recvAtomic(PacketPtr pkt);
255 virtual void recvFunctional(PacketPtr pkt);
258 * Is a snooper due to LSQ maintenance
260 virtual bool isSnooping() const { return true; }
262 virtual bool recvTiming(PacketPtr pkt);
264 virtual void recvRetry();
268 DcachePort dcachePort;
272 /** Constructs an empty store queue entry. */
274 : inst(NULL), req(NULL), size(0), data(0),
275 canWB(0), committed(0), completed(0), lqIt(NULL)
278 /** Constructs a store queue entry for a given instruction. */
279 SQEntry(DynInstPtr &_inst)
280 : inst(_inst), req(NULL), size(0), data(0),
281 canWB(0), committed(0), completed(0), lqIt(NULL)
284 /** The store instruction. */
286 /** The memory request for the store. */
288 /** The size of the store. */
290 /** The store data. */
292 /** Whether or not the store can writeback. */
294 /** Whether or not the store is committed. */
296 /** Whether or not the store is completed. */
299 typename std::list<DynInstPtr>::iterator lqIt;
302 /** Derived class to hold any sender state the LSQ needs. */
303 class LSQSenderState : public Packet::SenderState
306 /** Default constructor. */
311 /** Instruction who initiated the access to memory. */
313 /** Whether or not it is a load. */
315 /** The LQ/SQ index of the instruction. */
317 /** Whether or not the instruction will need to writeback. */
321 /** Writeback event, specifically for when stores forward data to loads. */
322 class WritebackEvent : public Event {
324 /** Constructs a writeback event. */
325 WritebackEvent(DynInstPtr &_inst, PacketPtr pkt, OzoneLWLSQ *lsq_ptr);
327 /** Processes the writeback event. */
330 /** Returns the description of this event. */
331 const char *description() const;
334 /** Instruction whose results are being written back. */
337 /** The packet that would have been sent to memory. */
340 /** The pointer to the LSQ unit that issued the store. */
341 OzoneLWLSQ<Impl> *lsqPtr;
352 /** The OzoneLWLSQ thread id. */
355 /** The status of the LSQ unit. */
358 /** The store queue. */
359 std::list<SQEntry> storeQueue;
360 /** The load queue. */
361 std::list<DynInstPtr> loadQueue;
363 typedef typename std::list<SQEntry>::iterator SQIt;
364 typedef typename std::list<DynInstPtr>::iterator LQIt;
368 size_t operator() (const int a) const
370 unsigned hash = (((a >> 14) ^ ((a >> 2) & 0xffff))) & 0x7FFFFFFF;
376 m5::hash_map<int, SQIt, HashFn> SQItHash;
377 std::queue<int> SQIndices;
378 m5::hash_map<int, LQIt, HashFn> LQItHash;
379 std::queue<int> LQIndices;
381 typedef typename m5::hash_map<int, LQIt, HashFn>::iterator LQHashIt;
382 typedef typename m5::hash_map<int, SQIt, HashFn>::iterator SQHashIt;
383 // Consider making these 16 bits
384 /** The number of LQ entries. */
386 /** The number of SQ entries. */
389 /** The number of load instructions in the LQ. */
391 /** The number of store instructions in the SQ (excludes those waiting to
402 /// @todo Consider moving to a more advanced model with write vs read ports
403 /** The number of cache ports available each cycle. */
406 /** The number of used cache ports in this cycle. */
409 //list<InstSeqNum> mshrSeqNums;
411 /** Tota number of memory ordering violations. */
412 Stats::Scalar lsqMemOrderViolation;
414 //Stats::Scalar dcacheStallCycles;
415 Counter lastDcacheStall;
417 // Make these per thread?
418 /** Whether or not the LSQ is stalled. */
420 /** The store that causes the stall due to partial store to load
423 InstSeqNum stallingStoreIsn;
424 /** The index of the above store. */
427 /** The packet that needs to be retried. */
430 /** Whehter or not a store is blocked due to the memory system. */
433 /** Whether or not a load is blocked due to the memory system. It is
434 * cleared when this value is checked via loadBlocked().
438 bool loadBlockedHandled;
440 InstSeqNum blockedLoadSeqNum;
442 /** The oldest faulting load instruction. */
443 DynInstPtr loadFaultInst;
444 /** The oldest faulting store instruction. */
445 DynInstPtr storeFaultInst;
447 /** The oldest load that caused a memory ordering violation. */
448 DynInstPtr memDepViolator;
450 // Will also need how many read/write ports the Dcache has. Or keep track
451 // of that in stage that is one level up, and only call executeLoad/Store
452 // the appropriate number of times.
455 /** Executes the load at the given index. */
457 Fault read(RequestPtr req, T &data, int load_idx);
459 /** Executes the store at the given index. */
461 Fault write(RequestPtr req, T &data, int store_idx);
463 /** Returns the sequence number of the head load instruction. */
464 InstSeqNum getLoadHeadSeqNum()
466 if (!loadQueue.empty()) {
467 return loadQueue.back()->seqNum;
474 /** Returns the sequence number of the head store instruction. */
475 InstSeqNum getStoreHeadSeqNum()
477 if (!storeQueue.empty()) {
478 return storeQueue.back().inst->seqNum;
485 /** Returns whether or not the LSQ unit is stalled. */
486 bool isStalled() { return stalled; }
489 template <class Impl>
492 OzoneLWLSQ<Impl>::read(RequestPtr req, T &data, int load_idx)
494 //Depending on issue2execute delay a squashed load could
495 //execute if it is found to be squashed in the same
496 //cycle it is scheduled to execute
497 typename m5::hash_map<int, LQIt, HashFn>::iterator
498 lq_hash_it = LQItHash.find(load_idx);
499 assert(lq_hash_it != LQItHash.end());
500 DynInstPtr inst = (*(*lq_hash_it).second);
502 // Make sure this isn't an uncacheable access
503 // A bit of a hackish way to get uncached accesses to work only if they're
504 // at the head of the LSQ and are ready to commit (at the head of the ROB
506 // @todo: Fix uncached accesses.
507 if (req->isUncacheable() &&
508 (inst != loadQueue.back() || !inst->isAtCommit())) {
509 DPRINTF(OzoneLSQ, "[sn:%lli] Uncached load and not head of "
512 be->rescheduleMemInst(inst);
513 return TheISA::genMachineCheckFault();
516 // Check the SQ for any previous stores that might lead to forwarding
517 SQIt sq_it = storeQueue.begin();
520 DPRINTF(OzoneLSQ, "Read called, load idx: %i addr: %#x\n",
521 load_idx, req->getPaddr());
523 while (sq_it != storeQueue.end() && (*sq_it).inst->seqNum > inst->seqNum)
527 // End once we've reached the top of the LSQ
528 if (sq_it == storeQueue.end()) {
532 assert((*sq_it).inst);
534 store_size = (*sq_it).size;
536 if (store_size == 0 || (*sq_it).committed) {
541 // Check if the store data is within the lower and upper bounds of
542 // addresses that the request needs.
543 bool store_has_lower_limit =
544 req->getVaddr() >= (*sq_it).inst->effAddr;
545 bool store_has_upper_limit =
546 (req->getVaddr() + req->getSize()) <= ((*sq_it).inst->effAddr +
548 bool lower_load_has_store_part =
549 req->getVaddr() < ((*sq_it).inst->effAddr +
551 bool upper_load_has_store_part =
552 (req->getVaddr() + req->getSize()) > (*sq_it).inst->effAddr;
554 // If the store's data has all of the data needed, we can forward.
555 if (store_has_lower_limit && store_has_upper_limit) {
556 int shift_amt = req->getVaddr() & (store_size - 1);
557 // Assumes byte addressing
558 shift_amt = shift_amt << 3;
560 // Cast this to type T?
561 data = (*sq_it).data >> shift_amt;
563 assert(!inst->memData);
564 inst->memData = new uint8_t[64];
566 memcpy(inst->memData, &data, req->getSize());
568 DPRINTF(OzoneLSQ, "Forwarding from store [sn:%lli] to load to "
569 "[sn:%lli] addr %#x, data %#x\n",
570 (*sq_it).inst->seqNum, inst->seqNum, req->getVaddr(),
573 PacketPtr data_pkt = new Packet(req, Packet::ReadReq);
574 data_pkt->dataStatic(inst->memData);
576 WritebackEvent *wb = new WritebackEvent(inst, data_pkt, this);
578 // We'll say this has a 1 cycle load-store forwarding latency
580 // @todo: Need to make this a parameter.
581 wb->schedule(curTick());
583 // Should keep track of stat for forwarded data
585 } else if ((store_has_lower_limit && lower_load_has_store_part) ||
586 (store_has_upper_limit && upper_load_has_store_part) ||
587 (lower_load_has_store_part && upper_load_has_store_part)) {
588 // This is the partial store-load forwarding case where a store
589 // has only part of the load's data.
591 // If it's already been written back, then don't worry about
593 if ((*sq_it).completed) {
598 // Must stall load and force it to retry, so long as it's the oldest
599 // load that needs to do so.
603 (*stallingLoad)->seqNum)) {
605 stallingStoreIsn = (*sq_it).inst->seqNum;
606 stallingLoad = (*lq_hash_it).second;
609 // Tell IQ/mem dep unit that this instruction will need to be
610 // rescheduled eventually
611 be->rescheduleMemInst(inst);
613 DPRINTF(OzoneLSQ, "Load-store forwarding mis-match. "
614 "Store [sn:%lli] to load addr %#x\n",
615 (*sq_it).inst->seqNum, req->getVaddr());
622 // If there's no forwarding case, then go access memory
623 DPRINTF(OzoneLSQ, "Doing functional access for inst PC %#x\n",
626 assert(!inst->memData);
627 inst->memData = new uint8_t[64];
631 DPRINTF(OzoneLSQ, "Doing timing access for inst PC %#x\n",
637 MemCmd::LoadLockedReq : Packet::ReadReq));
638 data_pkt->dataStatic(inst->memData);
640 LSQSenderState *state = new LSQSenderState;
641 state->isLoad = true;
642 state->idx = load_idx;
644 data_pkt->senderState = state;
646 // if we have a cache, do cache access too
647 if (!dcachePort.sendTiming(data_pkt)) {
648 // There's an older load that's already going to squash.
649 if (isLoadBlocked && blockedLoadSeqNum < inst->seqNum)
652 // Record that the load was blocked due to memory. This
653 // load will squash all instructions after it, be
654 // refetched, and re-executed.
655 isLoadBlocked = true;
656 loadBlockedHandled = false;
657 blockedLoadSeqNum = inst->seqNum;
658 // No fault occurred, even though the interface is blocked.
663 cpu->lockFlag = true;
669 template <class Impl>
672 OzoneLWLSQ<Impl>::write(RequestPtr req, T &data, int store_idx)
674 SQHashIt sq_hash_it = SQItHash.find(store_idx);
675 assert(sq_hash_it != SQItHash.end());
677 SQIt sq_it = (*sq_hash_it).second;
678 assert((*sq_it).inst);
680 DPRINTF(OzoneLSQ, "Doing write to store idx %i, addr %#x data %#x"
682 store_idx, req->getPaddr(), data, (*sq_it).inst->seqNum);
685 (*sq_it).size = sizeof(T);
686 (*sq_it).data = data;
689 req->data = new uint8_t[64];
690 memcpy(req->data, (uint8_t *)&(*sq_it).data, req->size);
693 // This function only writes the data to the store queue, so no fault
698 #endif // __CPU_OZONE_LW_LSQ_HH__