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