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::FullCPU FullCPU;
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 class StoreCompletionEvent : public Event {
79 /** Constructs a store completion event. */
80 StoreCompletionEvent(DynInstPtr &inst, BackEnd *be,
81 Event *wb_event, OzoneLWLSQ *lsq_ptr);
83 /** Processes the store completion event. */
86 /** Returns the description of this event. */
87 const char *description();
90 /** The store index of the store being written back. */
94 /** The writeback event for the store. Needed for store
101 /** The pointer to the LSQ unit that issued the store. */
102 OzoneLWLSQ<Impl> *lsqPtr;
106 /** Constructs an LSQ unit. init() must be called prior to use. */
109 /** Initializes the LSQ unit with the specified number of entries. */
110 void init(Params *params, unsigned maxLQEntries,
111 unsigned maxSQEntries, unsigned id);
113 /** Returns the name of the LSQ unit. */
114 std::string name() const;
116 /** Sets the CPU pointer. */
117 void setCPU(FullCPU *cpu_ptr)
120 /** Sets the back-end stage pointer. */
121 void setBE(BackEnd *be_ptr)
124 /** Sets the page table pointer. */
125 // void setPageTable(PageTable *pt_ptr);
127 /** Ticks the LSQ unit, which in this case only resets the number of
129 * @todo: Move the number of used ports up to the LSQ level so it can
130 * be shared by all LSQ units.
132 void tick() { usedPorts = 0; }
134 /** Inserts an instruction. */
135 void insert(DynInstPtr &inst);
136 /** Inserts a load instruction. */
137 void insertLoad(DynInstPtr &load_inst);
138 /** Inserts a store instruction. */
139 void insertStore(DynInstPtr &store_inst);
141 /** Executes a load instruction. */
142 Fault executeLoad(DynInstPtr &inst);
144 /** Executes a store instruction. */
145 Fault executeStore(DynInstPtr &inst);
147 /** Commits the head load. */
149 /** Commits loads older than a specific sequence number. */
150 void commitLoads(InstSeqNum &youngest_inst);
152 /** Commits stores older than a specific sequence number. */
153 void commitStores(InstSeqNum &youngest_inst);
155 /** Writes back stores. */
156 void writebackStores();
158 // @todo: Include stats in the LSQ unit.
161 /** Clears all the entries in the LQ. */
164 /** Clears all the entries in the SQ. */
167 /** Resizes the LQ to a given size. */
168 void resizeLQ(unsigned size);
170 /** Resizes the SQ to a given size. */
171 void resizeSQ(unsigned size);
173 /** Squashes all instructions younger than a specific sequence number. */
174 void squash(const InstSeqNum &squashed_num);
176 /** Returns if there is a memory ordering violation. Value is reset upon
177 * call to getMemDepViolator().
179 bool violation() { return memDepViolator; }
181 /** Returns the memory ordering violator. */
182 DynInstPtr getMemDepViolator();
184 /** Returns if a load became blocked due to the memory system. It clears
185 * the bool's value upon this being called.
188 { return isLoadBlocked; }
190 void clearLoadBlocked()
191 { isLoadBlocked = false; }
193 bool isLoadBlockedHandled()
194 { return loadBlockedHandled; }
196 void setLoadBlockedHandled()
197 { loadBlockedHandled = true; }
199 /** Returns the number of free entries (min of free LQ and SQ entries). */
200 unsigned numFreeEntries();
202 /** Returns the number of loads ready to execute. */
205 /** Returns the number of loads in the LQ. */
206 int numLoads() { return loads; }
208 /** Returns the number of stores in the SQ. */
209 int numStores() { return stores; }
211 /** Returns if either the LQ or SQ is full. */
212 bool isFull() { return lqFull() || sqFull(); }
214 /** Returns if the LQ is full. */
215 bool lqFull() { return loads >= (LQEntries - 1); }
217 /** Returns if the SQ is full. */
218 bool sqFull() { return stores >= (SQEntries - 1); }
220 /** Debugging function to dump instructions in the LSQ. */
223 /** Returns the number of instructions in the LSQ. */
224 unsigned getCount() { return loads + stores; }
226 /** Returns if there are any stores to writeback. */
227 bool hasStoresToWB() { return storesToWB; }
229 /** Returns the number of stores to writeback. */
230 int numStoresToWB() { return storesToWB; }
232 /** Returns if the LSQ unit will writeback on this cycle. */
233 bool willWB() { return storeQueue.back().canWB &&
234 !storeQueue.back().completed/* &&
235 !dcacheInterface->isBlocked()*/; }
239 void takeOverFrom(ThreadContext *old_tc = NULL);
241 bool isSwitchedOut() { return switchedOut; }
246 /** Completes the store at the specified index. */
247 void completeStore(int store_idx);
250 /** Pointer to the CPU. */
253 /** Pointer to the back-end stage. */
258 class DcachePort : public Port
264 DcachePort(const std::string &_name, FullCPU *_cpu)
265 : Port(_name), cpu(_cpu)
269 virtual Tick recvAtomic(PacketPtr pkt);
271 virtual void recvFunctional(PacketPtr pkt);
273 virtual void recvStatusChange(Status status);
275 virtual void getDeviceAddressRanges(AddrRangeList &resp,
276 AddrRangeList &snoop)
277 { resp.clear(); snoop.clear(); }
279 virtual bool recvTiming(PacketPtr pkt);
281 virtual void recvRetry();
284 /** Pointer to the D-cache. */
285 DcachePort dcachePort;
287 /** Pointer to the page table. */
288 // PageTable *pTable;
292 /** Constructs an empty store queue entry. */
294 : inst(NULL), req(NULL), size(0), data(0),
295 canWB(0), committed(0), completed(0), lqIt(NULL)
298 /** Constructs a store queue entry for a given instruction. */
299 SQEntry(DynInstPtr &_inst)
300 : inst(_inst), req(NULL), size(0), data(0),
301 canWB(0), committed(0), completed(0), lqIt(NULL)
304 /** The store instruction. */
306 /** The memory request for the store. */
308 /** The size of the store. */
310 /** The store data. */
312 /** Whether or not the store can writeback. */
314 /** Whether or not the store is committed. */
316 /** Whether or not the store is completed. */
319 typename std::list<DynInstPtr>::iterator lqIt;
330 /** The OzoneLWLSQ thread id. */
333 /** The status of the LSQ unit. */
336 /** The store queue. */
337 std::list<SQEntry> storeQueue;
338 /** The load queue. */
339 std::list<DynInstPtr> loadQueue;
341 typedef typename std::list<SQEntry>::iterator SQIt;
342 typedef typename std::list<DynInstPtr>::iterator LQIt;
346 size_t operator() (const int a) const
348 unsigned hash = (((a >> 14) ^ ((a >> 2) & 0xffff))) & 0x7FFFFFFF;
354 m5::hash_map<int, SQIt, HashFn> SQItHash;
355 std::queue<int> SQIndices;
356 m5::hash_map<int, LQIt, HashFn> LQItHash;
357 std::queue<int> LQIndices;
359 typedef typename m5::hash_map<int, LQIt, HashFn>::iterator LQHashIt;
360 typedef typename m5::hash_map<int, SQIt, HashFn>::iterator SQHashIt;
361 // Consider making these 16 bits
362 /** The number of LQ entries. */
364 /** The number of SQ entries. */
367 /** The number of load instructions in the LQ. */
369 /** The number of store instructions in the SQ (excludes those waiting to
376 /// @todo Consider moving to a more advanced model with write vs read ports
377 /** The number of cache ports available each cycle. */
380 /** The number of used cache ports in this cycle. */
383 //list<InstSeqNum> mshrSeqNums;
385 //Stats::Scalar<> dcacheStallCycles;
386 Counter lastDcacheStall;
388 // Make these per thread?
389 /** Whether or not the LSQ is stalled. */
391 /** The store that causes the stall due to partial store to load
394 InstSeqNum stallingStoreIsn;
395 /** The index of the above store. */
398 /** Whether or not a load is blocked due to the memory system. It is
399 * cleared when this value is checked via loadBlocked().
403 bool loadBlockedHandled;
405 InstSeqNum blockedLoadSeqNum;
407 /** The oldest faulting load instruction. */
408 DynInstPtr loadFaultInst;
409 /** The oldest faulting store instruction. */
410 DynInstPtr storeFaultInst;
412 /** The oldest load that caused a memory ordering violation. */
413 DynInstPtr memDepViolator;
415 // Will also need how many read/write ports the Dcache has. Or keep track
416 // of that in stage that is one level up, and only call executeLoad/Store
417 // the appropriate number of times.
420 /** Executes the load at the given index. */
422 Fault read(RequestPtr req, T &data, int load_idx);
424 /** Executes the store at the given index. */
426 Fault write(RequestPtr req, T &data, int store_idx);
428 /** Returns the sequence number of the head load instruction. */
429 InstSeqNum getLoadHeadSeqNum()
431 if (!loadQueue.empty()) {
432 return loadQueue.back()->seqNum;
439 /** Returns the sequence number of the head store instruction. */
440 InstSeqNum getStoreHeadSeqNum()
442 if (!storeQueue.empty()) {
443 return storeQueue.back().inst->seqNum;
450 /** Returns whether or not the LSQ unit is stalled. */
451 bool isStalled() { return stalled; }
454 template <class Impl>
457 OzoneLWLSQ<Impl>::read(RequestPtr req, T &data, int load_idx)
459 //Depending on issue2execute delay a squashed load could
460 //execute if it is found to be squashed in the same
461 //cycle it is scheduled to execute
462 typename m5::hash_map<int, LQIt, HashFn>::iterator
463 lq_hash_it = LQItHash.find(load_idx);
464 assert(lq_hash_it != LQItHash.end());
465 DynInstPtr inst = (*(*lq_hash_it).second);
467 // Make sure this isn't an uncacheable access
468 // A bit of a hackish way to get uncached accesses to work only if they're
469 // at the head of the LSQ and are ready to commit (at the head of the ROB
471 // @todo: Fix uncached accesses.
472 if (req->getFlags() & UNCACHEABLE &&
473 (inst != loadQueue.back() || !inst->reachedCommit)) {
474 DPRINTF(OzoneLSQ, "[sn:%lli] Uncached load and not head of "
477 be->rescheduleMemInst(inst);
478 return TheISA::genMachineCheckFault();
481 // Check the SQ for any previous stores that might lead to forwarding
482 SQIt sq_it = storeQueue.begin();
485 DPRINTF(OzoneLSQ, "Read called, load idx: %i addr: %#x\n",
486 load_idx, req->getPaddr());
488 while (sq_it != storeQueue.end() && (*sq_it).inst->seqNum > inst->seqNum)
492 // End once we've reached the top of the LSQ
493 if (sq_it == storeQueue.end()) {
497 assert((*sq_it).inst);
499 store_size = (*sq_it).size;
501 if (store_size == 0) {
506 // Check if the store data is within the lower and upper bounds of
507 // addresses that the request needs.
508 bool store_has_lower_limit =
509 req->getVaddr() >= (*sq_it).inst->effAddr;
510 bool store_has_upper_limit =
511 (req->getVaddr() + req->getSize()) <= ((*sq_it).inst->effAddr +
513 bool lower_load_has_store_part =
514 req->getVaddr() < ((*sq_it).inst->effAddr +
516 bool upper_load_has_store_part =
517 (req->getVaddr() + req->getSize()) > (*sq_it).inst->effAddr;
519 // If the store's data has all of the data needed, we can forward.
520 if (store_has_lower_limit && store_has_upper_limit) {
521 int shift_amt = req->getVaddr() & (store_size - 1);
522 // Assumes byte addressing
523 shift_amt = shift_amt << 3;
525 // Cast this to type T?
526 data = (*sq_it).data >> shift_amt;
528 assert(!inst->memData);
529 inst->memData = new uint8_t[64];
531 memcpy(inst->memData, &data, req->getSize());
533 DPRINTF(OzoneLSQ, "Forwarding from store [sn:%lli] to load to "
534 "[sn:%lli] addr %#x, data %#x\n",
535 (*sq_it).inst->seqNum, inst->seqNum, req->vaddr, *(inst->memData));
537 typename BackEnd::LdWritebackEvent *wb =
538 new typename BackEnd::LdWritebackEvent(inst,
541 // We'll say this has a 1 cycle load-store forwarding latency
543 // FIXME - Need to make this a parameter.
544 wb->schedule(curTick);
546 // Should keep track of stat for forwarded data
548 } else if ((store_has_lower_limit && lower_load_has_store_part) ||
549 (store_has_upper_limit && upper_load_has_store_part) ||
550 (lower_load_has_store_part && upper_load_has_store_part)) {
551 // This is the partial store-load forwarding case where a store
552 // has only part of the load's data.
554 // If it's already been written back, then don't worry about
556 if ((*sq_it).completed) {
561 // Must stall load and force it to retry, so long as it's the oldest
562 // load that needs to do so.
566 (*stallingLoad)->seqNum)) {
568 stallingStoreIsn = (*sq_it).inst->seqNum;
569 stallingLoad = (*lq_hash_it).second;
572 // Tell IQ/mem dep unit that this instruction will need to be
573 // rescheduled eventually
574 be->rescheduleMemInst(inst);
576 DPRINTF(OzoneLSQ, "Load-store forwarding mis-match. "
577 "Store [sn:%lli] to load addr %#x\n",
578 (*sq_it).inst->seqNum, req->vaddr);
585 // If there's no forwarding case, then go access memory
586 DPRINTF(OzoneLSQ, "Doing functional access for inst PC %#x\n",
589 assert(!inst->memData);
590 inst->memData = new uint8_t[64];
594 DPRINTF(OzoneLSQ, "Doing timing access for inst PC %#x\n",
597 PacketPtr data_pkt = new Packet(req, Packet::ReadReq, Packet::Broadcast);
598 data_pkt->dataStatic(inst->memData);
600 // if we have a cache, do cache access too
601 if (!dcachePort.sendTiming(data_pkt)) {
602 // There's an older load that's already going to squash.
603 if (isLoadBlocked && blockedLoadSeqNum < inst->seqNum)
606 // Record that the load was blocked due to memory. This
607 // load will squash all instructions after it, be
608 // refetched, and re-executed.
609 isLoadBlocked = true;
610 loadBlockedHandled = false;
611 blockedLoadSeqNum = inst->seqNum;
612 // No fault occurred, even though the interface is blocked.
616 if (data_pkt->result != Packet::Success) {
617 DPRINTF(OzoneLSQ, "OzoneLSQ: D-cache miss!\n");
618 DPRINTF(Activity, "Activity: ld accessing mem miss [sn:%lli]\n",
621 DPRINTF(OzoneLSQ, "OzoneLSQ: D-cache hit!\n");
622 DPRINTF(Activity, "Activity: ld accessing mem hit [sn:%lli]\n",
629 template <class Impl>
632 OzoneLWLSQ<Impl>::write(RequestPtr req, T &data, int store_idx)
634 SQHashIt sq_hash_it = SQItHash.find(store_idx);
635 assert(sq_hash_it != SQItHash.end());
637 SQIt sq_it = (*sq_hash_it).second;
638 assert((*sq_it).inst);
640 DPRINTF(OzoneLSQ, "Doing write to store idx %i, addr %#x data %#x"
642 store_idx, req->getPaddr(), data, (*sq_it).inst->seqNum);
645 (*sq_it).size = sizeof(T);
646 (*sq_it).data = data;
649 req->data = new uint8_t[64];
650 memcpy(req->data, (uint8_t *)&(*sq_it).data, req->size);
653 // This function only writes the data to the store queue, so no fault
658 #endif // __CPU_OZONE_LW_LSQ_HH__