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