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