O3: Track if the RAS has been pushed or not to pop the RAS if neccessary.
[gem5.git] / src / cpu / ozone / lw_lsq.hh
1 /*
2 * Copyright (c) 2006 The Regents of The University of Michigan
3 * All rights reserved.
4 *
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.
15 *
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.
27 *
28 * Authors: Kevin Lim
29 */
30
31 #ifndef __CPU_OZONE_LW_LSQ_HH__
32 #define __CPU_OZONE_LW_LSQ_HH__
33
34 #include <algorithm>
35 #include <list>
36 #include <map>
37 #include <queue>
38
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"
49
50 class MemObject;
51
52 /**
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.
62 */
63 template <class Impl>
64 class OzoneLWLSQ {
65 public:
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;
71
72 typedef TheISA::IntReg IntReg;
73
74 typedef typename std::map<InstSeqNum, DynInstPtr>::iterator LdMapIt;
75
76 public:
77 /** Constructs an LSQ unit. init() must be called prior to use. */
78 OzoneLWLSQ();
79
80 /** Initializes the LSQ unit with the specified number of entries. */
81 void init(Params *params, unsigned maxLQEntries,
82 unsigned maxSQEntries, unsigned id);
83
84 /** Returns the name of the LSQ unit. */
85 std::string name() const;
86
87 void regStats();
88
89 /** Sets the CPU pointer. */
90 void setCPU(OzoneCPU *cpu_ptr);
91
92 /** Sets the back-end stage pointer. */
93 void setBE(BackEnd *be_ptr)
94 { be = be_ptr; }
95
96 Port *getDcachePort() { return &dcachePort; }
97
98 /** Ticks the LSQ unit, which in this case only resets the number of
99 * used cache ports.
100 * @todo: Move the number of used ports up to the LSQ level so it can
101 * be shared by all LSQ units.
102 */
103 void tick() { usedPorts = 0; }
104
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);
111
112 /** Executes a load instruction. */
113 Fault executeLoad(DynInstPtr &inst);
114
115 /** Executes a store instruction. */
116 Fault executeStore(DynInstPtr &inst);
117
118 /** Commits the head load. */
119 void commitLoad();
120 /** Commits loads older than a specific sequence number. */
121 void commitLoads(InstSeqNum &youngest_inst);
122
123 /** Commits stores older than a specific sequence number. */
124 void commitStores(InstSeqNum &youngest_inst);
125
126 /** Writes back stores. */
127 void writebackStores();
128
129 /** Completes the data access that has been returned from the
130 * memory system. */
131 void completeDataAccess(PacketPtr pkt);
132
133 // @todo: Include stats in the LSQ unit.
134 //void regStats();
135
136 /** Clears all the entries in the LQ. */
137 void clearLQ();
138
139 /** Clears all the entries in the SQ. */
140 void clearSQ();
141
142 /** Resizes the LQ to a given size. */
143 void resizeLQ(unsigned size);
144
145 /** Resizes the SQ to a given size. */
146 void resizeSQ(unsigned size);
147
148 /** Squashes all instructions younger than a specific sequence number. */
149 void squash(const InstSeqNum &squashed_num);
150
151 /** Returns if there is a memory ordering violation. Value is reset upon
152 * call to getMemDepViolator().
153 */
154 bool violation() { return memDepViolator; }
155
156 /** Returns the memory ordering violator. */
157 DynInstPtr getMemDepViolator();
158
159 /** Returns if a load became blocked due to the memory system. It clears
160 * the bool's value upon this being called.
161 */
162 bool loadBlocked()
163 { return isLoadBlocked; }
164
165 void clearLoadBlocked()
166 { isLoadBlocked = false; }
167
168 bool isLoadBlockedHandled()
169 { return loadBlockedHandled; }
170
171 void setLoadBlockedHandled()
172 { loadBlockedHandled = true; }
173
174 /** Returns the number of free entries (min of free LQ and SQ entries). */
175 unsigned numFreeEntries();
176
177 /** Returns the number of loads ready to execute. */
178 int numLoadsReady();
179
180 /** Returns the number of loads in the LQ. */
181 int numLoads() { return loads; }
182
183 /** Returns the number of stores in the SQ. */
184 int numStores() { return stores + storesInFlight; }
185
186 /** Returns if either the LQ or SQ is full. */
187 bool isFull() { return lqFull() || sqFull(); }
188
189 /** Returns if the LQ is full. */
190 bool lqFull() { return loads >= (LQEntries - 1); }
191
192 /** Returns if the SQ is full. */
193 bool sqFull() { return (stores + storesInFlight) >= (SQEntries - 1); }
194
195 /** Debugging function to dump instructions in the LSQ. */
196 void dumpInsts();
197
198 /** Returns the number of instructions in the LSQ. */
199 unsigned getCount() { return loads + stores; }
200
201 /** Returns if there are any stores to writeback. */
202 bool hasStoresToWB() { return storesToWB; }
203
204 /** Returns the number of stores to writeback. */
205 int numStoresToWB() { return storesToWB; }
206
207 /** Returns if the LSQ unit will writeback on this cycle. */
208 bool willWB() { return storeQueue.back().canWB &&
209 !storeQueue.back().completed &&
210 !isStoreBlocked; }
211
212 void switchOut();
213
214 void takeOverFrom(ThreadContext *old_tc = NULL);
215
216 bool isSwitchedOut() { return switchedOut; }
217
218 bool switchedOut;
219
220 private:
221 /** Writes back the instruction, sending it to IEW. */
222 void writeback(DynInstPtr &inst, PacketPtr pkt);
223
224 /** Handles completing the send of a store to memory. */
225 void storePostSend(PacketPtr pkt, DynInstPtr &inst);
226
227 /** Completes the store at the specified index. */
228 void completeStore(DynInstPtr &inst);
229
230 void removeStore(int store_idx);
231
232 /** Handles doing the retry. */
233 void recvRetry();
234
235 private:
236 /** Pointer to the CPU. */
237 OzoneCPU *cpu;
238
239 /** Pointer to the back-end stage. */
240 BackEnd *be;
241
242 class DcachePort : public MasterPort
243 {
244 protected:
245 OzoneLWLSQ *lsq;
246
247 public:
248 DcachePort(OzoneLWLSQ *_lsq)
249 : lsq(_lsq)
250 { }
251
252 protected:
253 virtual Tick recvAtomic(PacketPtr pkt);
254
255 virtual void recvFunctional(PacketPtr pkt);
256
257 /**
258 * Is a snooper due to LSQ maintenance
259 */
260 virtual bool isSnooping() const { return true; }
261
262 virtual bool recvTiming(PacketPtr pkt);
263
264 virtual void recvRetry();
265 };
266
267 /** D-cache port. */
268 DcachePort dcachePort;
269
270 public:
271 struct SQEntry {
272 /** Constructs an empty store queue entry. */
273 SQEntry()
274 : inst(NULL), req(NULL), size(0), data(0),
275 canWB(0), committed(0), completed(0), lqIt(NULL)
276 { }
277
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)
282 { }
283
284 /** The store instruction. */
285 DynInstPtr inst;
286 /** The memory request for the store. */
287 RequestPtr req;
288 /** The size of the store. */
289 int size;
290 /** The store data. */
291 IntReg data;
292 /** Whether or not the store can writeback. */
293 bool canWB;
294 /** Whether or not the store is committed. */
295 bool committed;
296 /** Whether or not the store is completed. */
297 bool completed;
298
299 typename std::list<DynInstPtr>::iterator lqIt;
300 };
301
302 /** Derived class to hold any sender state the LSQ needs. */
303 class LSQSenderState : public Packet::SenderState
304 {
305 public:
306 /** Default constructor. */
307 LSQSenderState()
308 : noWB(false)
309 { }
310
311 /** Instruction who initiated the access to memory. */
312 DynInstPtr inst;
313 /** Whether or not it is a load. */
314 bool isLoad;
315 /** The LQ/SQ index of the instruction. */
316 int idx;
317 /** Whether or not the instruction will need to writeback. */
318 bool noWB;
319 };
320
321 /** Writeback event, specifically for when stores forward data to loads. */
322 class WritebackEvent : public Event {
323 public:
324 /** Constructs a writeback event. */
325 WritebackEvent(DynInstPtr &_inst, PacketPtr pkt, OzoneLWLSQ *lsq_ptr);
326
327 /** Processes the writeback event. */
328 void process();
329
330 /** Returns the description of this event. */
331 const char *description() const;
332
333 private:
334 /** Instruction whose results are being written back. */
335 DynInstPtr inst;
336
337 /** The packet that would have been sent to memory. */
338 PacketPtr pkt;
339
340 /** The pointer to the LSQ unit that issued the store. */
341 OzoneLWLSQ<Impl> *lsqPtr;
342 };
343
344 enum Status {
345 Running,
346 Idle,
347 DcacheMissStall,
348 DcacheMissSwitch
349 };
350
351 private:
352 /** The OzoneLWLSQ thread id. */
353 unsigned lsqID;
354
355 /** The status of the LSQ unit. */
356 Status _status;
357
358 /** The store queue. */
359 std::list<SQEntry> storeQueue;
360 /** The load queue. */
361 std::list<DynInstPtr> loadQueue;
362
363 typedef typename std::list<SQEntry>::iterator SQIt;
364 typedef typename std::list<DynInstPtr>::iterator LQIt;
365
366
367 struct HashFn {
368 size_t operator() (const int a) const
369 {
370 unsigned hash = (((a >> 14) ^ ((a >> 2) & 0xffff))) & 0x7FFFFFFF;
371
372 return hash;
373 }
374 };
375
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;
380
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. */
385 unsigned LQEntries;
386 /** The number of SQ entries. */
387 unsigned SQEntries;
388
389 /** The number of load instructions in the LQ. */
390 int loads;
391 /** The number of store instructions in the SQ (excludes those waiting to
392 * writeback).
393 */
394 int stores;
395
396 int storesToWB;
397
398 public:
399 int storesInFlight;
400
401 private:
402 /// @todo Consider moving to a more advanced model with write vs read ports
403 /** The number of cache ports available each cycle. */
404 int cachePorts;
405
406 /** The number of used cache ports in this cycle. */
407 int usedPorts;
408
409 //list<InstSeqNum> mshrSeqNums;
410
411 /** Tota number of memory ordering violations. */
412 Stats::Scalar lsqMemOrderViolation;
413
414 //Stats::Scalar dcacheStallCycles;
415 Counter lastDcacheStall;
416
417 // Make these per thread?
418 /** Whether or not the LSQ is stalled. */
419 bool stalled;
420 /** The store that causes the stall due to partial store to load
421 * forwarding.
422 */
423 InstSeqNum stallingStoreIsn;
424 /** The index of the above store. */
425 LQIt stallingLoad;
426
427 /** The packet that needs to be retried. */
428 PacketPtr retryPkt;
429
430 /** Whehter or not a store is blocked due to the memory system. */
431 bool isStoreBlocked;
432
433 /** Whether or not a load is blocked due to the memory system. It is
434 * cleared when this value is checked via loadBlocked().
435 */
436 bool isLoadBlocked;
437
438 bool loadBlockedHandled;
439
440 InstSeqNum blockedLoadSeqNum;
441
442 /** The oldest faulting load instruction. */
443 DynInstPtr loadFaultInst;
444 /** The oldest faulting store instruction. */
445 DynInstPtr storeFaultInst;
446
447 /** The oldest load that caused a memory ordering violation. */
448 DynInstPtr memDepViolator;
449
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.
453
454 public:
455 /** Executes the load at the given index. */
456 template <class T>
457 Fault read(RequestPtr req, T &data, int load_idx);
458
459 /** Executes the store at the given index. */
460 template <class T>
461 Fault write(RequestPtr req, T &data, int store_idx);
462
463 /** Returns the sequence number of the head load instruction. */
464 InstSeqNum getLoadHeadSeqNum()
465 {
466 if (!loadQueue.empty()) {
467 return loadQueue.back()->seqNum;
468 } else {
469 return 0;
470 }
471
472 }
473
474 /** Returns the sequence number of the head store instruction. */
475 InstSeqNum getStoreHeadSeqNum()
476 {
477 if (!storeQueue.empty()) {
478 return storeQueue.back().inst->seqNum;
479 } else {
480 return 0;
481 }
482
483 }
484
485 /** Returns whether or not the LSQ unit is stalled. */
486 bool isStalled() { return stalled; }
487 };
488
489 template <class Impl>
490 template <class T>
491 Fault
492 OzoneLWLSQ<Impl>::read(RequestPtr req, T &data, int load_idx)
493 {
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);
501
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
505 // too).
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 "
510 "commit/LSQ!\n",
511 inst->seqNum);
512 be->rescheduleMemInst(inst);
513 return TheISA::genMachineCheckFault();
514 }
515
516 // Check the SQ for any previous stores that might lead to forwarding
517 SQIt sq_it = storeQueue.begin();
518 int store_size = 0;
519
520 DPRINTF(OzoneLSQ, "Read called, load idx: %i addr: %#x\n",
521 load_idx, req->getPaddr());
522
523 while (sq_it != storeQueue.end() && (*sq_it).inst->seqNum > inst->seqNum)
524 ++sq_it;
525
526 while (1) {
527 // End once we've reached the top of the LSQ
528 if (sq_it == storeQueue.end()) {
529 break;
530 }
531
532 assert((*sq_it).inst);
533
534 store_size = (*sq_it).size;
535
536 if (store_size == 0 || (*sq_it).committed) {
537 sq_it++;
538 continue;
539 }
540
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 +
547 store_size);
548 bool lower_load_has_store_part =
549 req->getVaddr() < ((*sq_it).inst->effAddr +
550 store_size);
551 bool upper_load_has_store_part =
552 (req->getVaddr() + req->getSize()) > (*sq_it).inst->effAddr;
553
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;
559
560 // Cast this to type T?
561 data = (*sq_it).data >> shift_amt;
562
563 assert(!inst->memData);
564 inst->memData = new uint8_t[64];
565
566 memcpy(inst->memData, &data, req->getSize());
567
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(),
571 *(inst->memData));
572
573 PacketPtr data_pkt = new Packet(req, Packet::ReadReq);
574 data_pkt->dataStatic(inst->memData);
575
576 WritebackEvent *wb = new WritebackEvent(inst, data_pkt, this);
577
578 // We'll say this has a 1 cycle load-store forwarding latency
579 // for now.
580 // @todo: Need to make this a parameter.
581 wb->schedule(curTick());
582
583 // Should keep track of stat for forwarded data
584 return NoFault;
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.
590
591 // If it's already been written back, then don't worry about
592 // stalling on it.
593 if ((*sq_it).completed) {
594 sq_it++;
595 break;
596 }
597
598 // Must stall load and force it to retry, so long as it's the oldest
599 // load that needs to do so.
600 if (!stalled ||
601 (stalled &&
602 inst->seqNum <
603 (*stallingLoad)->seqNum)) {
604 stalled = true;
605 stallingStoreIsn = (*sq_it).inst->seqNum;
606 stallingLoad = (*lq_hash_it).second;
607 }
608
609 // Tell IQ/mem dep unit that this instruction will need to be
610 // rescheduled eventually
611 be->rescheduleMemInst(inst);
612
613 DPRINTF(OzoneLSQ, "Load-store forwarding mis-match. "
614 "Store [sn:%lli] to load addr %#x\n",
615 (*sq_it).inst->seqNum, req->getVaddr());
616
617 return NoFault;
618 }
619 sq_it++;
620 }
621
622 // If there's no forwarding case, then go access memory
623 DPRINTF(OzoneLSQ, "Doing functional access for inst PC %#x\n",
624 inst->readPC());
625
626 assert(!inst->memData);
627 inst->memData = new uint8_t[64];
628
629 ++usedPorts;
630
631 DPRINTF(OzoneLSQ, "Doing timing access for inst PC %#x\n",
632 inst->readPC());
633
634 PacketPtr data_pkt =
635 new Packet(req,
636 (req->isLLSC() ?
637 MemCmd::LoadLockedReq : Packet::ReadReq));
638 data_pkt->dataStatic(inst->memData);
639
640 LSQSenderState *state = new LSQSenderState;
641 state->isLoad = true;
642 state->idx = load_idx;
643 state->inst = inst;
644 data_pkt->senderState = state;
645
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)
650 return NoFault;
651
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.
659 return NoFault;
660 }
661
662 if (req->isLLSC()) {
663 cpu->lockFlag = true;
664 }
665
666 return NoFault;
667 }
668
669 template <class Impl>
670 template <class T>
671 Fault
672 OzoneLWLSQ<Impl>::write(RequestPtr req, T &data, int store_idx)
673 {
674 SQHashIt sq_hash_it = SQItHash.find(store_idx);
675 assert(sq_hash_it != SQItHash.end());
676
677 SQIt sq_it = (*sq_hash_it).second;
678 assert((*sq_it).inst);
679
680 DPRINTF(OzoneLSQ, "Doing write to store idx %i, addr %#x data %#x"
681 " | [sn:%lli]\n",
682 store_idx, req->getPaddr(), data, (*sq_it).inst->seqNum);
683
684 (*sq_it).req = req;
685 (*sq_it).size = sizeof(T);
686 (*sq_it).data = data;
687 /*
688 assert(!req->data);
689 req->data = new uint8_t[64];
690 memcpy(req->data, (uint8_t *)&(*sq_it).data, req->size);
691 */
692
693 // This function only writes the data to the store queue, so no fault
694 // can happen here.
695 return NoFault;
696 }
697
698 #endif // __CPU_OZONE_LW_LSQ_HH__