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/faults.hh"
40 #include "arch/isa_traits.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"
46 //#include "mem/page_table.hh"
47 #include "sim/debug.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;
87 /** Sets the CPU pointer. */
88 void setCPU(OzoneCPU *cpu_ptr);
90 /** Sets the back-end stage pointer. */
91 void setBE(BackEnd *be_ptr)
94 /** Sets the page table pointer. */
95 // void setPageTable(PageTable *pt_ptr);
97 /** Ticks the LSQ unit, which in this case only resets the number of
99 * @todo: Move the number of used ports up to the LSQ level so it can
100 * be shared by all LSQ units.
102 void tick() { usedPorts = 0; }
104 /** Inserts an instruction. */
105 void insert(DynInstPtr &inst);
106 /** Inserts a load instruction. */
107 void insertLoad(DynInstPtr &load_inst);
108 /** Inserts a store instruction. */
109 void insertStore(DynInstPtr &store_inst);
111 /** Executes a load instruction. */
112 Fault executeLoad(DynInstPtr &inst);
114 /** Executes a store instruction. */
115 Fault executeStore(DynInstPtr &inst);
117 /** Commits the head load. */
119 /** Commits loads older than a specific sequence number. */
120 void commitLoads(InstSeqNum &youngest_inst);
122 /** Commits stores older than a specific sequence number. */
123 void commitStores(InstSeqNum &youngest_inst);
125 /** Writes back stores. */
126 void writebackStores();
128 /** Completes the data access that has been returned from the
130 void completeDataAccess(PacketPtr pkt);
132 // @todo: Include stats in the LSQ unit.
135 /** Clears all the entries in the LQ. */
138 /** Clears all the entries in the SQ. */
141 /** Resizes the LQ to a given size. */
142 void resizeLQ(unsigned size);
144 /** Resizes the SQ to a given size. */
145 void resizeSQ(unsigned size);
147 /** Squashes all instructions younger than a specific sequence number. */
148 void squash(const InstSeqNum &squashed_num);
150 /** Returns if there is a memory ordering violation. Value is reset upon
151 * call to getMemDepViolator().
153 bool violation() { return memDepViolator; }
155 /** Returns the memory ordering violator. */
156 DynInstPtr getMemDepViolator();
158 /** Returns if a load became blocked due to the memory system. It clears
159 * the bool's value upon this being called.
162 { return isLoadBlocked; }
164 void clearLoadBlocked()
165 { isLoadBlocked = false; }
167 bool isLoadBlockedHandled()
168 { return loadBlockedHandled; }
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 /** Debugging function to dump instructions in the LSQ. */
197 /** Returns the number of instructions in the LSQ. */
198 unsigned getCount() { return loads + stores; }
200 /** Returns if there are any stores to writeback. */
201 bool hasStoresToWB() { return storesToWB; }
203 /** Returns the number of stores to writeback. */
204 int numStoresToWB() { return storesToWB; }
206 /** Returns if the LSQ unit will writeback on this cycle. */
207 bool willWB() { return storeQueue.back().canWB &&
208 !storeQueue.back().completed &&
213 void takeOverFrom(ThreadContext *old_tc = NULL);
215 bool isSwitchedOut() { return switchedOut; }
220 /** Writes back the instruction, sending it to IEW. */
221 void writeback(DynInstPtr &inst, PacketPtr pkt);
223 /** Handles completing the send of a store to memory. */
224 void storePostSend(Packet *pkt, DynInstPtr &inst);
226 /** Completes the store at the specified index. */
227 void completeStore(int store_idx);
229 /** Handles doing the retry. */
233 /** Pointer to the CPU. */
236 /** Pointer to the back-end stage. */
241 class DcachePort : public Port
249 DcachePort(OzoneCPU *_cpu, OzoneLWLSQ *_lsq)
250 : Port(_lsq->name() + "-dport"), cpu(_cpu), lsq(_lsq)
254 virtual Tick recvAtomic(PacketPtr pkt);
256 virtual void recvFunctional(PacketPtr pkt);
258 virtual void recvStatusChange(Status status);
260 virtual void getDeviceAddressRanges(AddrRangeList &resp,
261 AddrRangeList &snoop)
262 { resp.clear(); snoop.clear(); }
264 virtual bool recvTiming(PacketPtr pkt);
266 virtual void recvRetry();
269 /** Pointer to the D-cache. */
270 DcachePort *dcachePort;
272 /** Pointer to the page table. */
273 // PageTable *pTable;
277 /** Constructs an empty store queue entry. */
279 : inst(NULL), req(NULL), size(0), data(0),
280 canWB(0), committed(0), completed(0), lqIt(NULL)
283 /** Constructs a store queue entry for a given instruction. */
284 SQEntry(DynInstPtr &_inst)
285 : inst(_inst), req(NULL), size(0), data(0),
286 canWB(0), committed(0), completed(0), lqIt(NULL)
289 /** The store instruction. */
291 /** The memory request for the store. */
293 /** The size of the store. */
295 /** The store data. */
297 /** Whether or not the store can writeback. */
299 /** Whether or not the store is committed. */
301 /** Whether or not the store is completed. */
304 typename std::list<DynInstPtr>::iterator lqIt;
307 /** Derived class to hold any sender state the LSQ needs. */
308 class LSQSenderState : public Packet::SenderState
311 /** Default constructor. */
316 /** Instruction who initiated the access to memory. */
318 /** Whether or not it is a load. */
320 /** The LQ/SQ index of the instruction. */
322 /** Whether or not the instruction will need to writeback. */
326 /** Writeback event, specifically for when stores forward data to loads. */
327 class WritebackEvent : public Event {
329 /** Constructs a writeback event. */
330 WritebackEvent(DynInstPtr &_inst, PacketPtr pkt, OzoneLWLSQ *lsq_ptr);
332 /** Processes the writeback event. */
335 /** Returns the description of this event. */
336 const char *description();
339 /** Instruction whose results are being written back. */
342 /** The packet that would have been sent to memory. */
345 /** The pointer to the LSQ unit that issued the store. */
346 OzoneLWLSQ<Impl> *lsqPtr;
357 /** The OzoneLWLSQ thread id. */
360 /** The status of the LSQ unit. */
363 /** The store queue. */
364 std::list<SQEntry> storeQueue;
365 /** The load queue. */
366 std::list<DynInstPtr> loadQueue;
368 typedef typename std::list<SQEntry>::iterator SQIt;
369 typedef typename std::list<DynInstPtr>::iterator LQIt;
373 size_t operator() (const int a) const
375 unsigned hash = (((a >> 14) ^ ((a >> 2) & 0xffff))) & 0x7FFFFFFF;
381 m5::hash_map<int, SQIt, HashFn> SQItHash;
382 std::queue<int> SQIndices;
383 m5::hash_map<int, LQIt, HashFn> LQItHash;
384 std::queue<int> LQIndices;
386 typedef typename m5::hash_map<int, LQIt, HashFn>::iterator LQHashIt;
387 typedef typename m5::hash_map<int, SQIt, HashFn>::iterator SQHashIt;
388 // Consider making these 16 bits
389 /** The number of LQ entries. */
391 /** The number of SQ entries. */
394 /** The number of load instructions in the LQ. */
396 /** The number of store instructions in the SQ (excludes those waiting to
403 /// @todo Consider moving to a more advanced model with write vs read ports
404 /** The number of cache ports available each cycle. */
407 /** The number of used cache ports in this cycle. */
410 //list<InstSeqNum> mshrSeqNums;
412 //Stats::Scalar<> dcacheStallCycles;
413 Counter lastDcacheStall;
415 // Make these per thread?
416 /** Whether or not the LSQ is stalled. */
418 /** The store that causes the stall due to partial store to load
421 InstSeqNum stallingStoreIsn;
422 /** The index of the above store. */
425 /** The packet that needs to be retried. */
428 /** Whehter or not a store is blocked due to the memory system. */
431 /** Whether or not a load is blocked due to the memory system. It is
432 * cleared when this value is checked via loadBlocked().
436 bool loadBlockedHandled;
438 InstSeqNum blockedLoadSeqNum;
440 /** The oldest faulting load instruction. */
441 DynInstPtr loadFaultInst;
442 /** The oldest faulting store instruction. */
443 DynInstPtr storeFaultInst;
445 /** The oldest load that caused a memory ordering violation. */
446 DynInstPtr memDepViolator;
448 // Will also need how many read/write ports the Dcache has. Or keep track
449 // of that in stage that is one level up, and only call executeLoad/Store
450 // the appropriate number of times.
453 /** Executes the load at the given index. */
455 Fault read(RequestPtr req, T &data, int load_idx);
457 /** Executes the store at the given index. */
459 Fault write(RequestPtr req, T &data, int store_idx);
461 /** Returns the sequence number of the head load instruction. */
462 InstSeqNum getLoadHeadSeqNum()
464 if (!loadQueue.empty()) {
465 return loadQueue.back()->seqNum;
472 /** Returns the sequence number of the head store instruction. */
473 InstSeqNum getStoreHeadSeqNum()
475 if (!storeQueue.empty()) {
476 return storeQueue.back().inst->seqNum;
483 /** Returns whether or not the LSQ unit is stalled. */
484 bool isStalled() { return stalled; }
487 template <class Impl>
490 OzoneLWLSQ<Impl>::read(RequestPtr req, T &data, int load_idx)
492 //Depending on issue2execute delay a squashed load could
493 //execute if it is found to be squashed in the same
494 //cycle it is scheduled to execute
495 typename m5::hash_map<int, LQIt, HashFn>::iterator
496 lq_hash_it = LQItHash.find(load_idx);
497 assert(lq_hash_it != LQItHash.end());
498 DynInstPtr inst = (*(*lq_hash_it).second);
500 // Make sure this isn't an uncacheable access
501 // A bit of a hackish way to get uncached accesses to work only if they're
502 // at the head of the LSQ and are ready to commit (at the head of the ROB
504 // @todo: Fix uncached accesses.
505 if (req->getFlags() & UNCACHEABLE &&
506 (inst != loadQueue.back() || !inst->isAtCommit())) {
507 DPRINTF(OzoneLSQ, "[sn:%lli] Uncached load and not head of "
510 be->rescheduleMemInst(inst);
511 return TheISA::genMachineCheckFault();
514 // Check the SQ for any previous stores that might lead to forwarding
515 SQIt sq_it = storeQueue.begin();
518 DPRINTF(OzoneLSQ, "Read called, load idx: %i addr: %#x\n",
519 load_idx, req->getPaddr());
521 while (sq_it != storeQueue.end() && (*sq_it).inst->seqNum > inst->seqNum)
525 // End once we've reached the top of the LSQ
526 if (sq_it == storeQueue.end()) {
530 assert((*sq_it).inst);
532 store_size = (*sq_it).size;
534 if (store_size == 0) {
539 // Check if the store data is within the lower and upper bounds of
540 // addresses that the request needs.
541 bool store_has_lower_limit =
542 req->getVaddr() >= (*sq_it).inst->effAddr;
543 bool store_has_upper_limit =
544 (req->getVaddr() + req->getSize()) <= ((*sq_it).inst->effAddr +
546 bool lower_load_has_store_part =
547 req->getVaddr() < ((*sq_it).inst->effAddr +
549 bool upper_load_has_store_part =
550 (req->getVaddr() + req->getSize()) > (*sq_it).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 int shift_amt = req->getVaddr() & (store_size - 1);
555 // Assumes byte addressing
556 shift_amt = shift_amt << 3;
558 // Cast this to type T?
559 data = (*sq_it).data >> shift_amt;
561 assert(!inst->memData);
562 inst->memData = new uint8_t[64];
564 memcpy(inst->memData, &data, req->getSize());
566 DPRINTF(OzoneLSQ, "Forwarding from store [sn:%lli] to load to "
567 "[sn:%lli] addr %#x, data %#x\n",
568 (*sq_it).inst->seqNum, inst->seqNum, req->getVaddr(),
571 PacketPtr data_pkt = new Packet(req, Packet::ReadReq, Packet::Broadcast);
572 data_pkt->dataStatic(inst->memData);
574 WritebackEvent *wb = new WritebackEvent(inst, data_pkt, this);
576 // We'll say this has a 1 cycle load-store forwarding latency
578 // @todo: Need to make this a parameter.
579 wb->schedule(curTick);
581 // Should keep track of stat for forwarded data
583 } else if ((store_has_lower_limit && lower_load_has_store_part) ||
584 (store_has_upper_limit && upper_load_has_store_part) ||
585 (lower_load_has_store_part && upper_load_has_store_part)) {
586 // This is the partial store-load forwarding case where a store
587 // has only part of the load's data.
589 // If it's already been written back, then don't worry about
591 if ((*sq_it).completed) {
596 // Must stall load and force it to retry, so long as it's the oldest
597 // load that needs to do so.
601 (*stallingLoad)->seqNum)) {
603 stallingStoreIsn = (*sq_it).inst->seqNum;
604 stallingLoad = (*lq_hash_it).second;
607 // Tell IQ/mem dep unit that this instruction will need to be
608 // rescheduled eventually
609 be->rescheduleMemInst(inst);
611 DPRINTF(OzoneLSQ, "Load-store forwarding mis-match. "
612 "Store [sn:%lli] to load addr %#x\n",
613 (*sq_it).inst->seqNum, req->getVaddr());
620 // If there's no forwarding case, then go access memory
621 DPRINTF(OzoneLSQ, "Doing functional access for inst PC %#x\n",
624 assert(!inst->memData);
625 inst->memData = new uint8_t[64];
629 DPRINTF(OzoneLSQ, "Doing timing access for inst PC %#x\n",
632 PacketPtr data_pkt = new Packet(req, Packet::ReadReq, Packet::Broadcast);
633 data_pkt->dataStatic(inst->memData);
635 LSQSenderState *state = new LSQSenderState;
636 state->isLoad = true;
637 state->idx = load_idx;
639 data_pkt->senderState = state;
641 // if we have a cache, do cache access too
642 if (!dcachePort->sendTiming(data_pkt)) {
643 // There's an older load that's already going to squash.
644 if (isLoadBlocked && blockedLoadSeqNum < inst->seqNum)
647 // Record that the load was blocked due to memory. This
648 // load will squash all instructions after it, be
649 // refetched, and re-executed.
650 isLoadBlocked = true;
651 loadBlockedHandled = false;
652 blockedLoadSeqNum = inst->seqNum;
653 // No fault occurred, even though the interface is blocked.
657 if (req->getFlags() & LOCKED) {
658 cpu->lockFlag = true;
661 if (data_pkt->result != Packet::Success) {
662 DPRINTF(OzoneLSQ, "OzoneLSQ: D-cache miss!\n");
663 DPRINTF(Activity, "Activity: ld accessing mem miss [sn:%lli]\n",
666 DPRINTF(OzoneLSQ, "OzoneLSQ: D-cache hit!\n");
667 DPRINTF(Activity, "Activity: ld accessing mem hit [sn:%lli]\n",
674 template <class Impl>
677 OzoneLWLSQ<Impl>::write(RequestPtr req, T &data, int store_idx)
679 SQHashIt sq_hash_it = SQItHash.find(store_idx);
680 assert(sq_hash_it != SQItHash.end());
682 SQIt sq_it = (*sq_hash_it).second;
683 assert((*sq_it).inst);
685 DPRINTF(OzoneLSQ, "Doing write to store idx %i, addr %#x data %#x"
687 store_idx, req->getPaddr(), data, (*sq_it).inst->seqNum);
690 (*sq_it).size = sizeof(T);
691 (*sq_it).data = data;
694 req->data = new uint8_t[64];
695 memcpy(req->data, (uint8_t *)&(*sq_it).data, req->size);
698 // This function only writes the data to the store queue, so no fault
703 #endif // __CPU_OZONE_LW_LSQ_HH__