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 Port *getDcachePort() { return &dcachePort; }
96 /** Ticks the LSQ unit, which in this case only resets the number of
98 * @todo: Move the number of used ports up to the LSQ level so it can
99 * be shared by all LSQ units.
101 void tick() { usedPorts = 0; }
103 /** Inserts an instruction. */
104 void insert(DynInstPtr &inst);
105 /** Inserts a load instruction. */
106 void insertLoad(DynInstPtr &load_inst);
107 /** Inserts a store instruction. */
108 void insertStore(DynInstPtr &store_inst);
110 /** Executes a load instruction. */
111 Fault executeLoad(DynInstPtr &inst);
113 /** Executes a store instruction. */
114 Fault executeStore(DynInstPtr &inst);
116 /** Commits the head load. */
118 /** Commits loads older than a specific sequence number. */
119 void commitLoads(InstSeqNum &youngest_inst);
121 /** Commits stores older than a specific sequence number. */
122 void commitStores(InstSeqNum &youngest_inst);
124 /** Writes back stores. */
125 void writebackStores();
127 /** Completes the data access that has been returned from the
129 void completeDataAccess(PacketPtr pkt);
131 // @todo: Include stats in the LSQ unit.
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. It clears
158 * the bool's value upon this being called.
161 { return isLoadBlocked; }
163 void clearLoadBlocked()
164 { isLoadBlocked = false; }
166 bool isLoadBlockedHandled()
167 { return loadBlockedHandled; }
169 void setLoadBlockedHandled()
170 { loadBlockedHandled = true; }
172 /** Returns the number of free entries (min of free LQ and SQ entries). */
173 unsigned numFreeEntries();
175 /** Returns the number of loads ready to execute. */
178 /** Returns the number of loads in the LQ. */
179 int numLoads() { return loads; }
181 /** Returns the number of stores in the SQ. */
182 int numStores() { return stores; }
184 /** Returns if either the LQ or SQ is full. */
185 bool isFull() { return lqFull() || sqFull(); }
187 /** Returns if the LQ is full. */
188 bool lqFull() { return loads >= (LQEntries - 1); }
190 /** Returns if the SQ is full. */
191 bool sqFull() { return stores >= (SQEntries - 1); }
193 /** Debugging function to dump instructions in the LSQ. */
196 /** Returns the number of instructions in the LSQ. */
197 unsigned getCount() { return loads + stores; }
199 /** Returns if there are any stores to writeback. */
200 bool hasStoresToWB() { return storesToWB; }
202 /** Returns the number of stores to writeback. */
203 int numStoresToWB() { return storesToWB; }
205 /** Returns if the LSQ unit will writeback on this cycle. */
206 bool willWB() { return storeQueue.back().canWB &&
207 !storeQueue.back().completed &&
212 void takeOverFrom(ThreadContext *old_tc = NULL);
214 bool isSwitchedOut() { return switchedOut; }
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(Packet *pkt, DynInstPtr &inst);
225 /** Completes the store at the specified index. */
226 void completeStore(int store_idx);
228 /** Handles doing the retry. */
232 /** Pointer to the CPU. */
235 /** Pointer to the back-end stage. */
240 class DcachePort : public Port
246 DcachePort(OzoneLWLSQ *_lsq)
251 virtual Tick recvAtomic(PacketPtr pkt);
253 virtual void recvFunctional(PacketPtr pkt);
255 virtual void recvStatusChange(Status status);
257 virtual void getDeviceAddressRanges(AddrRangeList &resp,
258 AddrRangeList &snoop)
259 { resp.clear(); snoop.clear(); }
261 virtual bool recvTiming(PacketPtr pkt);
263 virtual void recvRetry();
267 DcachePort dcachePort;
271 /** Constructs an empty store queue entry. */
273 : inst(NULL), req(NULL), size(0), data(0),
274 canWB(0), committed(0), completed(0), lqIt(NULL)
277 /** Constructs a store queue entry for a given instruction. */
278 SQEntry(DynInstPtr &_inst)
279 : inst(_inst), req(NULL), size(0), data(0),
280 canWB(0), committed(0), completed(0), lqIt(NULL)
283 /** The store instruction. */
285 /** The memory request for the store. */
287 /** The size of the store. */
289 /** The store data. */
291 /** Whether or not the store can writeback. */
293 /** Whether or not the store is committed. */
295 /** Whether or not the store is completed. */
298 typename std::list<DynInstPtr>::iterator lqIt;
301 /** Derived class to hold any sender state the LSQ needs. */
302 class LSQSenderState : public Packet::SenderState
305 /** Default constructor. */
310 /** Instruction who initiated the access to memory. */
312 /** Whether or not it is a load. */
314 /** The LQ/SQ index of the instruction. */
316 /** Whether or not the instruction will need to writeback. */
320 /** Writeback event, specifically for when stores forward data to loads. */
321 class WritebackEvent : public Event {
323 /** Constructs a writeback event. */
324 WritebackEvent(DynInstPtr &_inst, PacketPtr pkt, OzoneLWLSQ *lsq_ptr);
326 /** Processes the writeback event. */
329 /** Returns the description of this event. */
330 const char *description();
333 /** Instruction whose results are being written back. */
336 /** The packet that would have been sent to memory. */
339 /** The pointer to the LSQ unit that issued the store. */
340 OzoneLWLSQ<Impl> *lsqPtr;
351 /** The OzoneLWLSQ thread id. */
354 /** The status of the LSQ unit. */
357 /** The store queue. */
358 std::list<SQEntry> storeQueue;
359 /** The load queue. */
360 std::list<DynInstPtr> loadQueue;
362 typedef typename std::list<SQEntry>::iterator SQIt;
363 typedef typename std::list<DynInstPtr>::iterator LQIt;
367 size_t operator() (const int a) const
369 unsigned hash = (((a >> 14) ^ ((a >> 2) & 0xffff))) & 0x7FFFFFFF;
375 m5::hash_map<int, SQIt, HashFn> SQItHash;
376 std::queue<int> SQIndices;
377 m5::hash_map<int, LQIt, HashFn> LQItHash;
378 std::queue<int> LQIndices;
380 typedef typename m5::hash_map<int, LQIt, HashFn>::iterator LQHashIt;
381 typedef typename m5::hash_map<int, SQIt, HashFn>::iterator SQHashIt;
382 // Consider making these 16 bits
383 /** The number of LQ entries. */
385 /** The number of SQ entries. */
388 /** The number of load instructions in the LQ. */
390 /** The number of store instructions in the SQ (excludes those waiting to
397 /// @todo Consider moving to a more advanced model with write vs read ports
398 /** The number of cache ports available each cycle. */
401 /** The number of used cache ports in this cycle. */
404 //list<InstSeqNum> mshrSeqNums;
406 //Stats::Scalar<> dcacheStallCycles;
407 Counter lastDcacheStall;
409 // Make these per thread?
410 /** Whether or not the LSQ is stalled. */
412 /** The store that causes the stall due to partial store to load
415 InstSeqNum stallingStoreIsn;
416 /** The index of the above store. */
419 /** The packet that needs to be retried. */
422 /** Whehter or not a store is blocked due to the memory system. */
425 /** Whether or not a load is blocked due to the memory system. It is
426 * cleared when this value is checked via loadBlocked().
430 bool loadBlockedHandled;
432 InstSeqNum blockedLoadSeqNum;
434 /** The oldest faulting load instruction. */
435 DynInstPtr loadFaultInst;
436 /** The oldest faulting store instruction. */
437 DynInstPtr storeFaultInst;
439 /** The oldest load that caused a memory ordering violation. */
440 DynInstPtr memDepViolator;
442 // Will also need how many read/write ports the Dcache has. Or keep track
443 // of that in stage that is one level up, and only call executeLoad/Store
444 // the appropriate number of times.
447 /** Executes the load at the given index. */
449 Fault read(RequestPtr req, T &data, int load_idx);
451 /** Executes the store at the given index. */
453 Fault write(RequestPtr req, T &data, int store_idx);
455 /** Returns the sequence number of the head load instruction. */
456 InstSeqNum getLoadHeadSeqNum()
458 if (!loadQueue.empty()) {
459 return loadQueue.back()->seqNum;
466 /** Returns the sequence number of the head store instruction. */
467 InstSeqNum getStoreHeadSeqNum()
469 if (!storeQueue.empty()) {
470 return storeQueue.back().inst->seqNum;
477 /** Returns whether or not the LSQ unit is stalled. */
478 bool isStalled() { return stalled; }
481 template <class Impl>
484 OzoneLWLSQ<Impl>::read(RequestPtr req, T &data, int load_idx)
486 //Depending on issue2execute delay a squashed load could
487 //execute if it is found to be squashed in the same
488 //cycle it is scheduled to execute
489 typename m5::hash_map<int, LQIt, HashFn>::iterator
490 lq_hash_it = LQItHash.find(load_idx);
491 assert(lq_hash_it != LQItHash.end());
492 DynInstPtr inst = (*(*lq_hash_it).second);
494 // Make sure this isn't an uncacheable access
495 // A bit of a hackish way to get uncached accesses to work only if they're
496 // at the head of the LSQ and are ready to commit (at the head of the ROB
498 // @todo: Fix uncached accesses.
499 if (req->getFlags() & UNCACHEABLE &&
500 (inst != loadQueue.back() || !inst->isAtCommit())) {
501 DPRINTF(OzoneLSQ, "[sn:%lli] Uncached load and not head of "
504 be->rescheduleMemInst(inst);
505 return TheISA::genMachineCheckFault();
508 // Check the SQ for any previous stores that might lead to forwarding
509 SQIt sq_it = storeQueue.begin();
512 DPRINTF(OzoneLSQ, "Read called, load idx: %i addr: %#x\n",
513 load_idx, req->getPaddr());
515 while (sq_it != storeQueue.end() && (*sq_it).inst->seqNum > inst->seqNum)
519 // End once we've reached the top of the LSQ
520 if (sq_it == storeQueue.end()) {
524 assert((*sq_it).inst);
526 store_size = (*sq_it).size;
528 if (store_size == 0) {
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() >= (*sq_it).inst->effAddr;
537 bool store_has_upper_limit =
538 (req->getVaddr() + req->getSize()) <= ((*sq_it).inst->effAddr +
540 bool lower_load_has_store_part =
541 req->getVaddr() < ((*sq_it).inst->effAddr +
543 bool upper_load_has_store_part =
544 (req->getVaddr() + req->getSize()) > (*sq_it).inst->effAddr;
546 // If the store's data has all of the data needed, we can forward.
547 if (store_has_lower_limit && store_has_upper_limit) {
548 int shift_amt = req->getVaddr() & (store_size - 1);
549 // Assumes byte addressing
550 shift_amt = shift_amt << 3;
552 // Cast this to type T?
553 data = (*sq_it).data >> shift_amt;
555 assert(!inst->memData);
556 inst->memData = new uint8_t[64];
558 memcpy(inst->memData, &data, req->getSize());
560 DPRINTF(OzoneLSQ, "Forwarding from store [sn:%lli] to load to "
561 "[sn:%lli] addr %#x, data %#x\n",
562 (*sq_it).inst->seqNum, inst->seqNum, req->getVaddr(),
565 PacketPtr data_pkt = new Packet(req, Packet::ReadReq, Packet::Broadcast);
566 data_pkt->dataStatic(inst->memData);
568 WritebackEvent *wb = new WritebackEvent(inst, data_pkt, this);
570 // We'll say this has a 1 cycle load-store forwarding latency
572 // @todo: Need to make this a parameter.
573 wb->schedule(curTick);
575 // Should keep track of stat for forwarded data
577 } else if ((store_has_lower_limit && lower_load_has_store_part) ||
578 (store_has_upper_limit && upper_load_has_store_part) ||
579 (lower_load_has_store_part && upper_load_has_store_part)) {
580 // This is the partial store-load forwarding case where a store
581 // has only part of the load's data.
583 // If it's already been written back, then don't worry about
585 if ((*sq_it).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 (*stallingLoad)->seqNum)) {
597 stallingStoreIsn = (*sq_it).inst->seqNum;
598 stallingLoad = (*lq_hash_it).second;
601 // Tell IQ/mem dep unit that this instruction will need to be
602 // rescheduled eventually
603 be->rescheduleMemInst(inst);
605 DPRINTF(OzoneLSQ, "Load-store forwarding mis-match. "
606 "Store [sn:%lli] to load addr %#x\n",
607 (*sq_it).inst->seqNum, req->getVaddr());
614 // If there's no forwarding case, then go access memory
615 DPRINTF(OzoneLSQ, "Doing functional access for inst PC %#x\n",
618 assert(!inst->memData);
619 inst->memData = new uint8_t[64];
623 DPRINTF(OzoneLSQ, "Doing timing access for inst PC %#x\n",
626 PacketPtr data_pkt = new Packet(req, Packet::ReadReq, Packet::Broadcast);
627 data_pkt->dataStatic(inst->memData);
629 LSQSenderState *state = new LSQSenderState;
630 state->isLoad = true;
631 state->idx = load_idx;
633 data_pkt->senderState = state;
635 // if we have a cache, do cache access too
636 if (!dcachePort.sendTiming(data_pkt)) {
637 // There's an older load that's already going to squash.
638 if (isLoadBlocked && blockedLoadSeqNum < inst->seqNum)
641 // Record that the load was blocked due to memory. This
642 // load will squash all instructions after it, be
643 // refetched, and re-executed.
644 isLoadBlocked = true;
645 loadBlockedHandled = false;
646 blockedLoadSeqNum = inst->seqNum;
647 // No fault occurred, even though the interface is blocked.
651 if (req->getFlags() & LOCKED) {
652 cpu->lockFlag = true;
655 if (data_pkt->result != Packet::Success) {
656 DPRINTF(OzoneLSQ, "OzoneLSQ: D-cache miss!\n");
657 DPRINTF(Activity, "Activity: ld accessing mem miss [sn:%lli]\n",
660 DPRINTF(OzoneLSQ, "OzoneLSQ: D-cache hit!\n");
661 DPRINTF(Activity, "Activity: ld accessing mem hit [sn:%lli]\n",
668 template <class Impl>
671 OzoneLWLSQ<Impl>::write(RequestPtr req, T &data, int store_idx)
673 SQHashIt sq_hash_it = SQItHash.find(store_idx);
674 assert(sq_hash_it != SQItHash.end());
676 SQIt sq_it = (*sq_hash_it).second;
677 assert((*sq_it).inst);
679 DPRINTF(OzoneLSQ, "Doing write to store idx %i, addr %#x data %#x"
681 store_idx, req->getPaddr(), data, (*sq_it).inst->seqNum);
684 (*sq_it).size = sizeof(T);
685 (*sq_it).data = data;
688 req->data = new uint8_t[64];
689 memcpy(req->data, (uint8_t *)&(*sq_it).data, req->size);
692 // This function only writes the data to the store queue, so no fault
697 #endif // __CPU_OZONE_LW_LSQ_HH__