lsq_unit.hh (8232:b28d06a175be) lsq_unit.hh (8315:6173b87e7652)
1/*
2 * Copyright (c) 2004-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 * Korey Sewell
30 */
31
32#ifndef __CPU_O3_LSQ_UNIT_HH__
33#define __CPU_O3_LSQ_UNIT_HH__
34
35#include <algorithm>
36#include <cstring>
37#include <map>
38#include <queue>
39
40#include "arch/faults.hh"
41#include "arch/locked_mem.hh"
42#include "base/fast_alloc.hh"
43#include "base/hashmap.hh"
44#include "config/full_system.hh"
45#include "config/the_isa.hh"
46#include "cpu/inst_seq.hh"
47#include "cpu/timebuf.hh"
48#include "debug/LSQUnit.hh"
49#include "mem/packet.hh"
50#include "mem/port.hh"
51
52class DerivO3CPUParams;
53
54/**
55 * Class that implements the actual LQ and SQ for each specific
56 * thread. Both are circular queues; load entries are freed upon
57 * committing, while store entries are freed once they writeback. The
58 * LSQUnit tracks if there are memory ordering violations, and also
59 * detects partial load to store forwarding cases (a store only has
60 * part of a load's data) that requires the load to wait until the
61 * store writes back. In the former case it holds onto the instruction
62 * until the dependence unit looks at it, and in the latter it stalls
63 * the LSQ until the store writes back. At that point the load is
64 * replayed.
65 */
66template <class Impl>
67class LSQUnit {
68 public:
69 typedef typename Impl::O3CPU O3CPU;
70 typedef typename Impl::DynInstPtr DynInstPtr;
71 typedef typename Impl::CPUPol::IEW IEW;
72 typedef typename Impl::CPUPol::LSQ LSQ;
73 typedef typename Impl::CPUPol::IssueStruct IssueStruct;
74
75 public:
76 /** Constructs an LSQ unit. init() must be called prior to use. */
77 LSQUnit();
78
79 /** Initializes the LSQ unit with the specified number of entries. */
80 void init(O3CPU *cpu_ptr, IEW *iew_ptr, DerivO3CPUParams *params,
81 LSQ *lsq_ptr, unsigned maxLQEntries, unsigned maxSQEntries,
82 unsigned id);
83
84 /** Returns the name of the LSQ unit. */
85 std::string name() const;
86
87 /** Registers statistics. */
88 void regStats();
89
90 /** Sets the pointer to the dcache port. */
91 void setDcachePort(Port *dcache_port);
92
93 /** Switches out LSQ unit. */
94 void switchOut();
95
96 /** Takes over from another CPU's thread. */
97 void takeOverFrom();
98
99 /** Returns if the LSQ is switched out. */
100 bool isSwitchedOut() { return switchedOut; }
101
102 /** Ticks the LSQ unit, which in this case only resets the number of
103 * used cache ports.
104 * @todo: Move the number of used ports up to the LSQ level so it can
105 * be shared by all LSQ units.
106 */
107 void tick() { usedPorts = 0; }
108
109 /** Inserts an instruction. */
110 void insert(DynInstPtr &inst);
111 /** Inserts a load instruction. */
112 void insertLoad(DynInstPtr &load_inst);
113 /** Inserts a store instruction. */
114 void insertStore(DynInstPtr &store_inst);
115
116 /** Check for ordering violations in the LSQ
117 * @param load_idx index to start checking at
118 * @param inst the instruction to check
119 */
120 Fault checkViolations(int load_idx, DynInstPtr &inst);
121
122 /** Executes a load instruction. */
123 Fault executeLoad(DynInstPtr &inst);
124
125 Fault executeLoad(int lq_idx) { panic("Not implemented"); return NoFault; }
126 /** Executes a store instruction. */
127 Fault executeStore(DynInstPtr &inst);
128
129 /** Commits the head load. */
130 void commitLoad();
131 /** Commits loads older than a specific sequence number. */
132 void commitLoads(InstSeqNum &youngest_inst);
133
134 /** Commits stores older than a specific sequence number. */
135 void commitStores(InstSeqNum &youngest_inst);
136
137 /** Writes back stores. */
138 void writebackStores();
139
140 /** Completes the data access that has been returned from the
141 * memory system. */
142 void completeDataAccess(PacketPtr pkt);
143
144 /** Clears all the entries in the LQ. */
145 void clearLQ();
146
147 /** Clears all the entries in the SQ. */
148 void clearSQ();
149
150 /** Resizes the LQ to a given size. */
151 void resizeLQ(unsigned size);
152
153 /** Resizes the SQ to a given size. */
154 void resizeSQ(unsigned size);
155
156 /** Squashes all instructions younger than a specific sequence number. */
157 void squash(const InstSeqNum &squashed_num);
158
159 /** Returns if there is a memory ordering violation. Value is reset upon
160 * call to getMemDepViolator().
161 */
162 bool violation() { return memDepViolator; }
163
164 /** Returns the memory ordering violator. */
165 DynInstPtr getMemDepViolator();
166
167 /** Returns if a load became blocked due to the memory system. */
168 bool loadBlocked()
169 { return isLoadBlocked; }
170
171 /** Clears the signal that a load became blocked. */
172 void clearLoadBlocked()
173 { isLoadBlocked = false; }
174
175 /** Returns if the blocked load was handled. */
176 bool isLoadBlockedHandled()
177 { return loadBlockedHandled; }
178
179 /** Records the blocked load as being handled. */
180 void setLoadBlockedHandled()
181 { loadBlockedHandled = true; }
182
183 /** Returns the number of free entries (min of free LQ and SQ entries). */
184 unsigned numFreeEntries();
185
186 /** Returns the number of loads ready to execute. */
187 int numLoadsReady();
188
189 /** Returns the number of loads in the LQ. */
190 int numLoads() { return loads; }
191
192 /** Returns the number of stores in the SQ. */
193 int numStores() { return stores; }
194
195 /** Returns if either the LQ or SQ is full. */
196 bool isFull() { return lqFull() || sqFull(); }
197
198 /** Returns if the LQ is full. */
199 bool lqFull() { return loads >= (LQEntries - 1); }
200
201 /** Returns if the SQ is full. */
202 bool sqFull() { return stores >= (SQEntries - 1); }
203
204 /** Returns the number of instructions in the LSQ. */
205 unsigned getCount() { return loads + stores; }
206
207 /** Returns if there are any stores to writeback. */
208 bool hasStoresToWB() { return storesToWB; }
209
210 /** Returns the number of stores to writeback. */
211 int numStoresToWB() { return storesToWB; }
212
213 /** Returns if the LSQ unit will writeback on this cycle. */
214 bool willWB() { return storeQueue[storeWBIdx].canWB &&
215 !storeQueue[storeWBIdx].completed &&
216 !isStoreBlocked; }
217
218 /** Handles doing the retry. */
219 void recvRetry();
220
221 private:
222 /** Writes back the instruction, sending it to IEW. */
223 void writeback(DynInstPtr &inst, PacketPtr pkt);
224
225 /** Writes back a store that couldn't be completed the previous cycle. */
226 void writebackPendingStore();
227
228 /** Handles completing the send of a store to memory. */
229 void storePostSend(PacketPtr pkt);
230
231 /** Completes the store at the specified index. */
232 void completeStore(int store_idx);
233
234 /** Attempts to send a store to the cache. */
235 bool sendStore(PacketPtr data_pkt);
236
237 /** Increments the given store index (circular queue). */
238 inline void incrStIdx(int &store_idx);
239 /** Decrements the given store index (circular queue). */
240 inline void decrStIdx(int &store_idx);
241 /** Increments the given load index (circular queue). */
242 inline void incrLdIdx(int &load_idx);
243 /** Decrements the given load index (circular queue). */
244 inline void decrLdIdx(int &load_idx);
245
246 public:
247 /** Debugging function to dump instructions in the LSQ. */
248 void dumpInsts();
249
250 private:
251 /** Pointer to the CPU. */
252 O3CPU *cpu;
253
254 /** Pointer to the IEW stage. */
255 IEW *iewStage;
256
257 /** Pointer to the LSQ. */
258 LSQ *lsq;
259
260 /** Pointer to the dcache port. Used only for sending. */
261 Port *dcachePort;
262
263 /** Derived class to hold any sender state the LSQ needs. */
264 class LSQSenderState : public Packet::SenderState, public FastAlloc
265 {
266 public:
267 /** Default constructor. */
268 LSQSenderState()
269 : noWB(false), isSplit(false), pktToSend(false), outstanding(1),
270 mainPkt(NULL), pendingPacket(NULL)
271 { }
272
273 /** Instruction who initiated the access to memory. */
274 DynInstPtr inst;
275 /** Whether or not it is a load. */
276 bool isLoad;
277 /** The LQ/SQ index of the instruction. */
278 int idx;
279 /** Whether or not the instruction will need to writeback. */
280 bool noWB;
281 /** Whether or not this access is split in two. */
282 bool isSplit;
283 /** Whether or not there is a packet that needs sending. */
284 bool pktToSend;
285 /** Number of outstanding packets to complete. */
286 int outstanding;
287 /** The main packet from a split load, used during writeback. */
288 PacketPtr mainPkt;
289 /** A second packet from a split store that needs sending. */
290 PacketPtr pendingPacket;
291
292 /** Completes a packet and returns whether the access is finished. */
293 inline bool complete() { return --outstanding == 0; }
294 };
295
296 /** Writeback event, specifically for when stores forward data to loads. */
297 class WritebackEvent : public Event {
298 public:
299 /** Constructs a writeback event. */
300 WritebackEvent(DynInstPtr &_inst, PacketPtr pkt, LSQUnit *lsq_ptr);
301
302 /** Processes the writeback event. */
303 void process();
304
305 /** Returns the description of this event. */
306 const char *description() const;
307
308 private:
309 /** Instruction whose results are being written back. */
310 DynInstPtr inst;
311
312 /** The packet that would have been sent to memory. */
313 PacketPtr pkt;
314
315 /** The pointer to the LSQ unit that issued the store. */
316 LSQUnit<Impl> *lsqPtr;
317 };
318
319 public:
320 struct SQEntry {
321 /** Constructs an empty store queue entry. */
322 SQEntry()
323 : inst(NULL), req(NULL), size(0),
324 canWB(0), committed(0), completed(0)
325 {
326 std::memset(data, 0, sizeof(data));
327 }
328
329 /** Constructs a store queue entry for a given instruction. */
330 SQEntry(DynInstPtr &_inst)
331 : inst(_inst), req(NULL), sreqLow(NULL), sreqHigh(NULL), size(0),
332 isSplit(0), canWB(0), committed(0), completed(0)
333 {
334 std::memset(data, 0, sizeof(data));
335 }
336
337 /** The store instruction. */
338 DynInstPtr inst;
339 /** The request for the store. */
340 RequestPtr req;
341 /** The split requests for the store. */
342 RequestPtr sreqLow;
343 RequestPtr sreqHigh;
344 /** The size of the store. */
345 int size;
346 /** The store data. */
347 char data[16];
348 /** Whether or not the store is split into two requests. */
349 bool isSplit;
350 /** Whether or not the store can writeback. */
351 bool canWB;
352 /** Whether or not the store is committed. */
353 bool committed;
354 /** Whether or not the store is completed. */
355 bool completed;
356 };
357
358 private:
359 /** The LSQUnit thread id. */
360 ThreadID lsqID;
361
362 /** The store queue. */
363 std::vector<SQEntry> storeQueue;
364
365 /** The load queue. */
366 std::vector<DynInstPtr> loadQueue;
367
368 /** The number of LQ entries, plus a sentinel entry (circular queue).
369 * @todo: Consider having var that records the true number of LQ entries.
370 */
371 unsigned LQEntries;
372 /** The number of SQ entries, plus a sentinel entry (circular queue).
373 * @todo: Consider having var that records the true number of SQ entries.
374 */
375 unsigned SQEntries;
376
377 /** The number of places to shift addresses in the LSQ before checking
378 * for dependency violations
379 */
380 unsigned depCheckShift;
381
382 /** Should loads be checked for dependency issues */
383 bool checkLoads;
384
385 /** The number of load instructions in the LQ. */
386 int loads;
387 /** The number of store instructions in the SQ. */
388 int stores;
389 /** The number of store instructions in the SQ waiting to writeback. */
390 int storesToWB;
391
392 /** The index of the head instruction in the LQ. */
393 int loadHead;
394 /** The index of the tail instruction in the LQ. */
395 int loadTail;
396
397 /** The index of the head instruction in the SQ. */
398 int storeHead;
399 /** The index of the first instruction that may be ready to be
400 * written back, and has not yet been written back.
401 */
402 int storeWBIdx;
403 /** The index of the tail instruction in the SQ. */
404 int storeTail;
405
406 /// @todo Consider moving to a more advanced model with write vs read ports
407 /** The number of cache ports available each cycle. */
408 int cachePorts;
409
410 /** The number of used cache ports in this cycle. */
411 int usedPorts;
412
413 /** Is the LSQ switched out. */
414 bool switchedOut;
415
416 //list<InstSeqNum> mshrSeqNums;
417
418 /** Wire to read information from the issue stage time queue. */
419 typename TimeBuffer<IssueStruct>::wire fromIssue;
420
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 int stallingLoadIdx;
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. */
437 bool isLoadBlocked;
438
439 /** Has the blocked load been handled. */
440 bool loadBlockedHandled;
441
442 /** The sequence number of the blocked load. */
443 InstSeqNum blockedLoadSeqNum;
444
445 /** The oldest load that caused a memory ordering violation. */
446 DynInstPtr memDepViolator;
447
448 /** Whether or not there is a packet that couldn't be sent because of
449 * a lack of cache ports. */
450 bool hasPendingPkt;
451
452 /** The packet that is pending free cache ports. */
453 PacketPtr pendingPkt;
454
455 // Will also need how many read/write ports the Dcache has. Or keep track
456 // of that in stage that is one level up, and only call executeLoad/Store
457 // the appropriate number of times.
458 /** Total number of loads forwaded from LSQ stores. */
459 Stats::Scalar lsqForwLoads;
460
461 /** Total number of loads ignored due to invalid addresses. */
462 Stats::Scalar invAddrLoads;
463
464 /** Total number of squashed loads. */
465 Stats::Scalar lsqSquashedLoads;
466
467 /** Total number of responses from the memory system that are
468 * ignored due to the instruction already being squashed. */
469 Stats::Scalar lsqIgnoredResponses;
470
471 /** Tota number of memory ordering violations. */
472 Stats::Scalar lsqMemOrderViolation;
473
474 /** Total number of squashed stores. */
475 Stats::Scalar lsqSquashedStores;
476
477 /** Total number of software prefetches ignored due to invalid addresses. */
478 Stats::Scalar invAddrSwpfs;
479
480 /** Ready loads blocked due to partial store-forwarding. */
481 Stats::Scalar lsqBlockedLoads;
482
483 /** Number of loads that were rescheduled. */
484 Stats::Scalar lsqRescheduledLoads;
485
486 /** Number of times the LSQ is blocked due to the cache. */
487 Stats::Scalar lsqCacheBlocked;
488
489 public:
490 /** Executes the load at the given index. */
491 Fault read(Request *req, Request *sreqLow, Request *sreqHigh,
492 uint8_t *data, int load_idx);
493
494 /** Executes the store at the given index. */
495 Fault write(Request *req, Request *sreqLow, Request *sreqHigh,
496 uint8_t *data, int store_idx);
497
498 /** Returns the index of the head load instruction. */
499 int getLoadHead() { return loadHead; }
500 /** Returns the sequence number of the head load instruction. */
501 InstSeqNum getLoadHeadSeqNum()
502 {
503 if (loadQueue[loadHead]) {
504 return loadQueue[loadHead]->seqNum;
505 } else {
506 return 0;
507 }
508
509 }
510
511 /** Returns the index of the head store instruction. */
512 int getStoreHead() { return storeHead; }
513 /** Returns the sequence number of the head store instruction. */
514 InstSeqNum getStoreHeadSeqNum()
515 {
516 if (storeQueue[storeHead].inst) {
517 return storeQueue[storeHead].inst->seqNum;
518 } else {
519 return 0;
520 }
521
522 }
523
524 /** Returns whether or not the LSQ unit is stalled. */
525 bool isStalled() { return stalled; }
526};
527
528template <class Impl>
529Fault
530LSQUnit<Impl>::read(Request *req, Request *sreqLow, Request *sreqHigh,
531 uint8_t *data, int load_idx)
532{
533 DynInstPtr load_inst = loadQueue[load_idx];
534
535 assert(load_inst);
536
537 assert(!load_inst->isExecuted());
538
539 // Make sure this isn't an uncacheable access
540 // A bit of a hackish way to get uncached accesses to work only if they're
541 // at the head of the LSQ and are ready to commit (at the head of the ROB
542 // too).
543 if (req->isUncacheable() &&
544 (load_idx != loadHead || !load_inst->isAtCommit())) {
545 iewStage->rescheduleMemInst(load_inst);
546 ++lsqRescheduledLoads;
547 DPRINTF(LSQUnit, "Uncachable load [sn:%lli] PC %s\n",
548 load_inst->seqNum, load_inst->pcState());
549
550 // Must delete request now that it wasn't handed off to
551 // memory. This is quite ugly. @todo: Figure out the proper
552 // place to really handle request deletes.
553 delete req;
554 if (TheISA::HasUnalignedMemAcc && sreqLow) {
555 delete sreqLow;
556 delete sreqHigh;
557 }
558 return TheISA::genMachineCheckFault();
559 }
560
561 // Check the SQ for any previous stores that might lead to forwarding
562 int store_idx = load_inst->sqIdx;
563
564 int store_size = 0;
565
566 DPRINTF(LSQUnit, "Read called, load idx: %i, store idx: %i, "
567 "storeHead: %i addr: %#x%s\n",
568 load_idx, store_idx, storeHead, req->getPaddr(),
569 sreqLow ? " split" : "");
570
571 if (req->isLLSC()) {
572 assert(!sreqLow);
573 // Disable recording the result temporarily. Writing to misc
574 // regs normally updates the result, but this is not the
575 // desired behavior when handling store conditionals.
576 load_inst->recordResult = false;
577 TheISA::handleLockedRead(load_inst.get(), req);
578 load_inst->recordResult = true;
579 }
580
581 while (store_idx != -1) {
582 // End once we've reached the top of the LSQ
583 if (store_idx == storeWBIdx) {
584 break;
585 }
586
587 // Move the index to one younger
588 if (--store_idx < 0)
589 store_idx += SQEntries;
590
591 assert(storeQueue[store_idx].inst);
592
593 store_size = storeQueue[store_idx].size;
594
595 if (store_size == 0)
596 continue;
597 else if (storeQueue[store_idx].inst->uncacheable())
598 continue;
599
600 assert(storeQueue[store_idx].inst->effAddrValid);
601
602 // Check if the store data is within the lower and upper bounds of
603 // addresses that the request needs.
604 bool store_has_lower_limit =
605 req->getVaddr() >= storeQueue[store_idx].inst->effAddr;
606 bool store_has_upper_limit =
607 (req->getVaddr() + req->getSize()) <=
608 (storeQueue[store_idx].inst->effAddr + store_size);
609 bool lower_load_has_store_part =
610 req->getVaddr() < (storeQueue[store_idx].inst->effAddr +
611 store_size);
612 bool upper_load_has_store_part =
613 (req->getVaddr() + req->getSize()) >
614 storeQueue[store_idx].inst->effAddr;
615
616 // If the store's data has all of the data needed, we can forward.
617 if ((store_has_lower_limit && store_has_upper_limit)) {
618 // Get shift amount for offset into the store's data.
619 int shift_amt = req->getVaddr() & (store_size - 1);
620
621 memcpy(data, storeQueue[store_idx].data + shift_amt,
622 req->getSize());
623
624 assert(!load_inst->memData);
625 load_inst->memData = new uint8_t[64];
626
627 memcpy(load_inst->memData,
628 storeQueue[store_idx].data + shift_amt, req->getSize());
629
630 DPRINTF(LSQUnit, "Forwarding from store idx %i to load to "
631 "addr %#x, data %#x\n",
632 store_idx, req->getVaddr(), data);
633
634 PacketPtr data_pkt = new Packet(req, MemCmd::ReadReq,
635 Packet::Broadcast);
636 data_pkt->dataStatic(load_inst->memData);
637
638 WritebackEvent *wb = new WritebackEvent(load_inst, data_pkt, this);
639
640 // We'll say this has a 1 cycle load-store forwarding latency
641 // for now.
642 // @todo: Need to make this a parameter.
643 cpu->schedule(wb, curTick());
644
645 // Don't need to do anything special for split loads.
646 if (TheISA::HasUnalignedMemAcc && sreqLow) {
647 delete sreqLow;
648 delete sreqHigh;
649 }
650
651 ++lsqForwLoads;
652 return NoFault;
653 } else if ((store_has_lower_limit && lower_load_has_store_part) ||
654 (store_has_upper_limit && upper_load_has_store_part) ||
655 (lower_load_has_store_part && upper_load_has_store_part)) {
656 // This is the partial store-load forwarding case where a store
657 // has only part of the load's data.
658
659 // If it's already been written back, then don't worry about
660 // stalling on it.
661 if (storeQueue[store_idx].completed) {
662 panic("Should not check one of these");
663 continue;
664 }
665
666 // Must stall load and force it to retry, so long as it's the oldest
667 // load that needs to do so.
668 if (!stalled ||
669 (stalled &&
670 load_inst->seqNum <
671 loadQueue[stallingLoadIdx]->seqNum)) {
672 stalled = true;
673 stallingStoreIsn = storeQueue[store_idx].inst->seqNum;
674 stallingLoadIdx = load_idx;
675 }
676
677 // Tell IQ/mem dep unit that this instruction will need to be
678 // rescheduled eventually
679 iewStage->rescheduleMemInst(load_inst);
680 iewStage->decrWb(load_inst->seqNum);
681 load_inst->clearIssued();
682 ++lsqRescheduledLoads;
683
684 // Do not generate a writeback event as this instruction is not
685 // complete.
686 DPRINTF(LSQUnit, "Load-store forwarding mis-match. "
687 "Store idx %i to load addr %#x\n",
688 store_idx, req->getVaddr());
689
690 // Must delete request now that it wasn't handed off to
691 // memory. This is quite ugly. @todo: Figure out the
692 // proper place to really handle request deletes.
693 delete req;
694 if (TheISA::HasUnalignedMemAcc && sreqLow) {
695 delete sreqLow;
696 delete sreqHigh;
697 }
698
699 return NoFault;
700 }
701 }
702
703 // If there's no forwarding case, then go access memory
704 DPRINTF(LSQUnit, "Doing memory access for inst [sn:%lli] PC %s\n",
705 load_inst->seqNum, load_inst->pcState());
706
707 assert(!load_inst->memData);
708 load_inst->memData = new uint8_t[64];
709
710 ++usedPorts;
711
712 // if we the cache is not blocked, do cache access
713 bool completedFirst = false;
714 if (!lsq->cacheBlocked()) {
715 MemCmd command =
716 req->isLLSC() ? MemCmd::LoadLockedReq : MemCmd::ReadReq;
717 PacketPtr data_pkt = new Packet(req, command, Packet::Broadcast);
718 PacketPtr fst_data_pkt = NULL;
719 PacketPtr snd_data_pkt = NULL;
720
721 data_pkt->dataStatic(load_inst->memData);
722
723 LSQSenderState *state = new LSQSenderState;
724 state->isLoad = true;
725 state->idx = load_idx;
726 state->inst = load_inst;
727 data_pkt->senderState = state;
728
729 if (!TheISA::HasUnalignedMemAcc || !sreqLow) {
730
731 // Point the first packet at the main data packet.
732 fst_data_pkt = data_pkt;
733 } else {
734
735 // Create the split packets.
736 fst_data_pkt = new Packet(sreqLow, command, Packet::Broadcast);
737 snd_data_pkt = new Packet(sreqHigh, command, Packet::Broadcast);
738
739 fst_data_pkt->dataStatic(load_inst->memData);
740 snd_data_pkt->dataStatic(load_inst->memData + sreqLow->getSize());
741
742 fst_data_pkt->senderState = state;
743 snd_data_pkt->senderState = state;
744
745 state->isSplit = true;
746 state->outstanding = 2;
747 state->mainPkt = data_pkt;
748 }
749
750 if (!dcachePort->sendTiming(fst_data_pkt)) {
751 // Delete state and data packet because a load retry
752 // initiates a pipeline restart; it does not retry.
753 delete state;
754 delete data_pkt->req;
755 delete data_pkt;
756 if (TheISA::HasUnalignedMemAcc && sreqLow) {
757 delete fst_data_pkt->req;
758 delete fst_data_pkt;
759 delete snd_data_pkt->req;
760 delete snd_data_pkt;
761 sreqLow = NULL;
762 sreqHigh = NULL;
763 }
764
765 req = NULL;
766
767 // If the access didn't succeed, tell the LSQ by setting
768 // the retry thread id.
769 lsq->setRetryTid(lsqID);
770 } else if (TheISA::HasUnalignedMemAcc && sreqLow) {
771 completedFirst = true;
772
773 // The first packet was sent without problems, so send this one
774 // too. If there is a problem with this packet then the whole
775 // load will be squashed, so indicate this to the state object.
776 // The first packet will return in completeDataAccess and be
777 // handled there.
778 ++usedPorts;
779 if (!dcachePort->sendTiming(snd_data_pkt)) {
780
781 // The main packet will be deleted in completeDataAccess.
782 delete snd_data_pkt->req;
783 delete snd_data_pkt;
784
785 state->complete();
786
787 req = NULL;
788 sreqHigh = NULL;
789
790 lsq->setRetryTid(lsqID);
791 }
792 }
793 }
794
795 // If the cache was blocked, or has become blocked due to the access,
796 // handle it.
797 if (lsq->cacheBlocked()) {
798 if (req)
799 delete req;
800 if (TheISA::HasUnalignedMemAcc && sreqLow && !completedFirst) {
801 delete sreqLow;
802 delete sreqHigh;
803 }
804
805 ++lsqCacheBlocked;
806
1/*
2 * Copyright (c) 2004-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 * Korey Sewell
30 */
31
32#ifndef __CPU_O3_LSQ_UNIT_HH__
33#define __CPU_O3_LSQ_UNIT_HH__
34
35#include <algorithm>
36#include <cstring>
37#include <map>
38#include <queue>
39
40#include "arch/faults.hh"
41#include "arch/locked_mem.hh"
42#include "base/fast_alloc.hh"
43#include "base/hashmap.hh"
44#include "config/full_system.hh"
45#include "config/the_isa.hh"
46#include "cpu/inst_seq.hh"
47#include "cpu/timebuf.hh"
48#include "debug/LSQUnit.hh"
49#include "mem/packet.hh"
50#include "mem/port.hh"
51
52class DerivO3CPUParams;
53
54/**
55 * Class that implements the actual LQ and SQ for each specific
56 * thread. Both are circular queues; load entries are freed upon
57 * committing, while store entries are freed once they writeback. The
58 * LSQUnit tracks if there are memory ordering violations, and also
59 * detects partial load to store forwarding cases (a store only has
60 * part of a load's data) that requires the load to wait until the
61 * store writes back. In the former case it holds onto the instruction
62 * until the dependence unit looks at it, and in the latter it stalls
63 * the LSQ until the store writes back. At that point the load is
64 * replayed.
65 */
66template <class Impl>
67class LSQUnit {
68 public:
69 typedef typename Impl::O3CPU O3CPU;
70 typedef typename Impl::DynInstPtr DynInstPtr;
71 typedef typename Impl::CPUPol::IEW IEW;
72 typedef typename Impl::CPUPol::LSQ LSQ;
73 typedef typename Impl::CPUPol::IssueStruct IssueStruct;
74
75 public:
76 /** Constructs an LSQ unit. init() must be called prior to use. */
77 LSQUnit();
78
79 /** Initializes the LSQ unit with the specified number of entries. */
80 void init(O3CPU *cpu_ptr, IEW *iew_ptr, DerivO3CPUParams *params,
81 LSQ *lsq_ptr, unsigned maxLQEntries, unsigned maxSQEntries,
82 unsigned id);
83
84 /** Returns the name of the LSQ unit. */
85 std::string name() const;
86
87 /** Registers statistics. */
88 void regStats();
89
90 /** Sets the pointer to the dcache port. */
91 void setDcachePort(Port *dcache_port);
92
93 /** Switches out LSQ unit. */
94 void switchOut();
95
96 /** Takes over from another CPU's thread. */
97 void takeOverFrom();
98
99 /** Returns if the LSQ is switched out. */
100 bool isSwitchedOut() { return switchedOut; }
101
102 /** Ticks the LSQ unit, which in this case only resets the number of
103 * used cache ports.
104 * @todo: Move the number of used ports up to the LSQ level so it can
105 * be shared by all LSQ units.
106 */
107 void tick() { usedPorts = 0; }
108
109 /** Inserts an instruction. */
110 void insert(DynInstPtr &inst);
111 /** Inserts a load instruction. */
112 void insertLoad(DynInstPtr &load_inst);
113 /** Inserts a store instruction. */
114 void insertStore(DynInstPtr &store_inst);
115
116 /** Check for ordering violations in the LSQ
117 * @param load_idx index to start checking at
118 * @param inst the instruction to check
119 */
120 Fault checkViolations(int load_idx, DynInstPtr &inst);
121
122 /** Executes a load instruction. */
123 Fault executeLoad(DynInstPtr &inst);
124
125 Fault executeLoad(int lq_idx) { panic("Not implemented"); return NoFault; }
126 /** Executes a store instruction. */
127 Fault executeStore(DynInstPtr &inst);
128
129 /** Commits the head load. */
130 void commitLoad();
131 /** Commits loads older than a specific sequence number. */
132 void commitLoads(InstSeqNum &youngest_inst);
133
134 /** Commits stores older than a specific sequence number. */
135 void commitStores(InstSeqNum &youngest_inst);
136
137 /** Writes back stores. */
138 void writebackStores();
139
140 /** Completes the data access that has been returned from the
141 * memory system. */
142 void completeDataAccess(PacketPtr pkt);
143
144 /** Clears all the entries in the LQ. */
145 void clearLQ();
146
147 /** Clears all the entries in the SQ. */
148 void clearSQ();
149
150 /** Resizes the LQ to a given size. */
151 void resizeLQ(unsigned size);
152
153 /** Resizes the SQ to a given size. */
154 void resizeSQ(unsigned size);
155
156 /** Squashes all instructions younger than a specific sequence number. */
157 void squash(const InstSeqNum &squashed_num);
158
159 /** Returns if there is a memory ordering violation. Value is reset upon
160 * call to getMemDepViolator().
161 */
162 bool violation() { return memDepViolator; }
163
164 /** Returns the memory ordering violator. */
165 DynInstPtr getMemDepViolator();
166
167 /** Returns if a load became blocked due to the memory system. */
168 bool loadBlocked()
169 { return isLoadBlocked; }
170
171 /** Clears the signal that a load became blocked. */
172 void clearLoadBlocked()
173 { isLoadBlocked = false; }
174
175 /** Returns if the blocked load was handled. */
176 bool isLoadBlockedHandled()
177 { return loadBlockedHandled; }
178
179 /** Records the blocked load as being handled. */
180 void setLoadBlockedHandled()
181 { loadBlockedHandled = true; }
182
183 /** Returns the number of free entries (min of free LQ and SQ entries). */
184 unsigned numFreeEntries();
185
186 /** Returns the number of loads ready to execute. */
187 int numLoadsReady();
188
189 /** Returns the number of loads in the LQ. */
190 int numLoads() { return loads; }
191
192 /** Returns the number of stores in the SQ. */
193 int numStores() { return stores; }
194
195 /** Returns if either the LQ or SQ is full. */
196 bool isFull() { return lqFull() || sqFull(); }
197
198 /** Returns if the LQ is full. */
199 bool lqFull() { return loads >= (LQEntries - 1); }
200
201 /** Returns if the SQ is full. */
202 bool sqFull() { return stores >= (SQEntries - 1); }
203
204 /** Returns the number of instructions in the LSQ. */
205 unsigned getCount() { return loads + stores; }
206
207 /** Returns if there are any stores to writeback. */
208 bool hasStoresToWB() { return storesToWB; }
209
210 /** Returns the number of stores to writeback. */
211 int numStoresToWB() { return storesToWB; }
212
213 /** Returns if the LSQ unit will writeback on this cycle. */
214 bool willWB() { return storeQueue[storeWBIdx].canWB &&
215 !storeQueue[storeWBIdx].completed &&
216 !isStoreBlocked; }
217
218 /** Handles doing the retry. */
219 void recvRetry();
220
221 private:
222 /** Writes back the instruction, sending it to IEW. */
223 void writeback(DynInstPtr &inst, PacketPtr pkt);
224
225 /** Writes back a store that couldn't be completed the previous cycle. */
226 void writebackPendingStore();
227
228 /** Handles completing the send of a store to memory. */
229 void storePostSend(PacketPtr pkt);
230
231 /** Completes the store at the specified index. */
232 void completeStore(int store_idx);
233
234 /** Attempts to send a store to the cache. */
235 bool sendStore(PacketPtr data_pkt);
236
237 /** Increments the given store index (circular queue). */
238 inline void incrStIdx(int &store_idx);
239 /** Decrements the given store index (circular queue). */
240 inline void decrStIdx(int &store_idx);
241 /** Increments the given load index (circular queue). */
242 inline void incrLdIdx(int &load_idx);
243 /** Decrements the given load index (circular queue). */
244 inline void decrLdIdx(int &load_idx);
245
246 public:
247 /** Debugging function to dump instructions in the LSQ. */
248 void dumpInsts();
249
250 private:
251 /** Pointer to the CPU. */
252 O3CPU *cpu;
253
254 /** Pointer to the IEW stage. */
255 IEW *iewStage;
256
257 /** Pointer to the LSQ. */
258 LSQ *lsq;
259
260 /** Pointer to the dcache port. Used only for sending. */
261 Port *dcachePort;
262
263 /** Derived class to hold any sender state the LSQ needs. */
264 class LSQSenderState : public Packet::SenderState, public FastAlloc
265 {
266 public:
267 /** Default constructor. */
268 LSQSenderState()
269 : noWB(false), isSplit(false), pktToSend(false), outstanding(1),
270 mainPkt(NULL), pendingPacket(NULL)
271 { }
272
273 /** Instruction who initiated the access to memory. */
274 DynInstPtr inst;
275 /** Whether or not it is a load. */
276 bool isLoad;
277 /** The LQ/SQ index of the instruction. */
278 int idx;
279 /** Whether or not the instruction will need to writeback. */
280 bool noWB;
281 /** Whether or not this access is split in two. */
282 bool isSplit;
283 /** Whether or not there is a packet that needs sending. */
284 bool pktToSend;
285 /** Number of outstanding packets to complete. */
286 int outstanding;
287 /** The main packet from a split load, used during writeback. */
288 PacketPtr mainPkt;
289 /** A second packet from a split store that needs sending. */
290 PacketPtr pendingPacket;
291
292 /** Completes a packet and returns whether the access is finished. */
293 inline bool complete() { return --outstanding == 0; }
294 };
295
296 /** Writeback event, specifically for when stores forward data to loads. */
297 class WritebackEvent : public Event {
298 public:
299 /** Constructs a writeback event. */
300 WritebackEvent(DynInstPtr &_inst, PacketPtr pkt, LSQUnit *lsq_ptr);
301
302 /** Processes the writeback event. */
303 void process();
304
305 /** Returns the description of this event. */
306 const char *description() const;
307
308 private:
309 /** Instruction whose results are being written back. */
310 DynInstPtr inst;
311
312 /** The packet that would have been sent to memory. */
313 PacketPtr pkt;
314
315 /** The pointer to the LSQ unit that issued the store. */
316 LSQUnit<Impl> *lsqPtr;
317 };
318
319 public:
320 struct SQEntry {
321 /** Constructs an empty store queue entry. */
322 SQEntry()
323 : inst(NULL), req(NULL), size(0),
324 canWB(0), committed(0), completed(0)
325 {
326 std::memset(data, 0, sizeof(data));
327 }
328
329 /** Constructs a store queue entry for a given instruction. */
330 SQEntry(DynInstPtr &_inst)
331 : inst(_inst), req(NULL), sreqLow(NULL), sreqHigh(NULL), size(0),
332 isSplit(0), canWB(0), committed(0), completed(0)
333 {
334 std::memset(data, 0, sizeof(data));
335 }
336
337 /** The store instruction. */
338 DynInstPtr inst;
339 /** The request for the store. */
340 RequestPtr req;
341 /** The split requests for the store. */
342 RequestPtr sreqLow;
343 RequestPtr sreqHigh;
344 /** The size of the store. */
345 int size;
346 /** The store data. */
347 char data[16];
348 /** Whether or not the store is split into two requests. */
349 bool isSplit;
350 /** Whether or not the store can writeback. */
351 bool canWB;
352 /** Whether or not the store is committed. */
353 bool committed;
354 /** Whether or not the store is completed. */
355 bool completed;
356 };
357
358 private:
359 /** The LSQUnit thread id. */
360 ThreadID lsqID;
361
362 /** The store queue. */
363 std::vector<SQEntry> storeQueue;
364
365 /** The load queue. */
366 std::vector<DynInstPtr> loadQueue;
367
368 /** The number of LQ entries, plus a sentinel entry (circular queue).
369 * @todo: Consider having var that records the true number of LQ entries.
370 */
371 unsigned LQEntries;
372 /** The number of SQ entries, plus a sentinel entry (circular queue).
373 * @todo: Consider having var that records the true number of SQ entries.
374 */
375 unsigned SQEntries;
376
377 /** The number of places to shift addresses in the LSQ before checking
378 * for dependency violations
379 */
380 unsigned depCheckShift;
381
382 /** Should loads be checked for dependency issues */
383 bool checkLoads;
384
385 /** The number of load instructions in the LQ. */
386 int loads;
387 /** The number of store instructions in the SQ. */
388 int stores;
389 /** The number of store instructions in the SQ waiting to writeback. */
390 int storesToWB;
391
392 /** The index of the head instruction in the LQ. */
393 int loadHead;
394 /** The index of the tail instruction in the LQ. */
395 int loadTail;
396
397 /** The index of the head instruction in the SQ. */
398 int storeHead;
399 /** The index of the first instruction that may be ready to be
400 * written back, and has not yet been written back.
401 */
402 int storeWBIdx;
403 /** The index of the tail instruction in the SQ. */
404 int storeTail;
405
406 /// @todo Consider moving to a more advanced model with write vs read ports
407 /** The number of cache ports available each cycle. */
408 int cachePorts;
409
410 /** The number of used cache ports in this cycle. */
411 int usedPorts;
412
413 /** Is the LSQ switched out. */
414 bool switchedOut;
415
416 //list<InstSeqNum> mshrSeqNums;
417
418 /** Wire to read information from the issue stage time queue. */
419 typename TimeBuffer<IssueStruct>::wire fromIssue;
420
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 int stallingLoadIdx;
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. */
437 bool isLoadBlocked;
438
439 /** Has the blocked load been handled. */
440 bool loadBlockedHandled;
441
442 /** The sequence number of the blocked load. */
443 InstSeqNum blockedLoadSeqNum;
444
445 /** The oldest load that caused a memory ordering violation. */
446 DynInstPtr memDepViolator;
447
448 /** Whether or not there is a packet that couldn't be sent because of
449 * a lack of cache ports. */
450 bool hasPendingPkt;
451
452 /** The packet that is pending free cache ports. */
453 PacketPtr pendingPkt;
454
455 // Will also need how many read/write ports the Dcache has. Or keep track
456 // of that in stage that is one level up, and only call executeLoad/Store
457 // the appropriate number of times.
458 /** Total number of loads forwaded from LSQ stores. */
459 Stats::Scalar lsqForwLoads;
460
461 /** Total number of loads ignored due to invalid addresses. */
462 Stats::Scalar invAddrLoads;
463
464 /** Total number of squashed loads. */
465 Stats::Scalar lsqSquashedLoads;
466
467 /** Total number of responses from the memory system that are
468 * ignored due to the instruction already being squashed. */
469 Stats::Scalar lsqIgnoredResponses;
470
471 /** Tota number of memory ordering violations. */
472 Stats::Scalar lsqMemOrderViolation;
473
474 /** Total number of squashed stores. */
475 Stats::Scalar lsqSquashedStores;
476
477 /** Total number of software prefetches ignored due to invalid addresses. */
478 Stats::Scalar invAddrSwpfs;
479
480 /** Ready loads blocked due to partial store-forwarding. */
481 Stats::Scalar lsqBlockedLoads;
482
483 /** Number of loads that were rescheduled. */
484 Stats::Scalar lsqRescheduledLoads;
485
486 /** Number of times the LSQ is blocked due to the cache. */
487 Stats::Scalar lsqCacheBlocked;
488
489 public:
490 /** Executes the load at the given index. */
491 Fault read(Request *req, Request *sreqLow, Request *sreqHigh,
492 uint8_t *data, int load_idx);
493
494 /** Executes the store at the given index. */
495 Fault write(Request *req, Request *sreqLow, Request *sreqHigh,
496 uint8_t *data, int store_idx);
497
498 /** Returns the index of the head load instruction. */
499 int getLoadHead() { return loadHead; }
500 /** Returns the sequence number of the head load instruction. */
501 InstSeqNum getLoadHeadSeqNum()
502 {
503 if (loadQueue[loadHead]) {
504 return loadQueue[loadHead]->seqNum;
505 } else {
506 return 0;
507 }
508
509 }
510
511 /** Returns the index of the head store instruction. */
512 int getStoreHead() { return storeHead; }
513 /** Returns the sequence number of the head store instruction. */
514 InstSeqNum getStoreHeadSeqNum()
515 {
516 if (storeQueue[storeHead].inst) {
517 return storeQueue[storeHead].inst->seqNum;
518 } else {
519 return 0;
520 }
521
522 }
523
524 /** Returns whether or not the LSQ unit is stalled. */
525 bool isStalled() { return stalled; }
526};
527
528template <class Impl>
529Fault
530LSQUnit<Impl>::read(Request *req, Request *sreqLow, Request *sreqHigh,
531 uint8_t *data, int load_idx)
532{
533 DynInstPtr load_inst = loadQueue[load_idx];
534
535 assert(load_inst);
536
537 assert(!load_inst->isExecuted());
538
539 // Make sure this isn't an uncacheable access
540 // A bit of a hackish way to get uncached accesses to work only if they're
541 // at the head of the LSQ and are ready to commit (at the head of the ROB
542 // too).
543 if (req->isUncacheable() &&
544 (load_idx != loadHead || !load_inst->isAtCommit())) {
545 iewStage->rescheduleMemInst(load_inst);
546 ++lsqRescheduledLoads;
547 DPRINTF(LSQUnit, "Uncachable load [sn:%lli] PC %s\n",
548 load_inst->seqNum, load_inst->pcState());
549
550 // Must delete request now that it wasn't handed off to
551 // memory. This is quite ugly. @todo: Figure out the proper
552 // place to really handle request deletes.
553 delete req;
554 if (TheISA::HasUnalignedMemAcc && sreqLow) {
555 delete sreqLow;
556 delete sreqHigh;
557 }
558 return TheISA::genMachineCheckFault();
559 }
560
561 // Check the SQ for any previous stores that might lead to forwarding
562 int store_idx = load_inst->sqIdx;
563
564 int store_size = 0;
565
566 DPRINTF(LSQUnit, "Read called, load idx: %i, store idx: %i, "
567 "storeHead: %i addr: %#x%s\n",
568 load_idx, store_idx, storeHead, req->getPaddr(),
569 sreqLow ? " split" : "");
570
571 if (req->isLLSC()) {
572 assert(!sreqLow);
573 // Disable recording the result temporarily. Writing to misc
574 // regs normally updates the result, but this is not the
575 // desired behavior when handling store conditionals.
576 load_inst->recordResult = false;
577 TheISA::handleLockedRead(load_inst.get(), req);
578 load_inst->recordResult = true;
579 }
580
581 while (store_idx != -1) {
582 // End once we've reached the top of the LSQ
583 if (store_idx == storeWBIdx) {
584 break;
585 }
586
587 // Move the index to one younger
588 if (--store_idx < 0)
589 store_idx += SQEntries;
590
591 assert(storeQueue[store_idx].inst);
592
593 store_size = storeQueue[store_idx].size;
594
595 if (store_size == 0)
596 continue;
597 else if (storeQueue[store_idx].inst->uncacheable())
598 continue;
599
600 assert(storeQueue[store_idx].inst->effAddrValid);
601
602 // Check if the store data is within the lower and upper bounds of
603 // addresses that the request needs.
604 bool store_has_lower_limit =
605 req->getVaddr() >= storeQueue[store_idx].inst->effAddr;
606 bool store_has_upper_limit =
607 (req->getVaddr() + req->getSize()) <=
608 (storeQueue[store_idx].inst->effAddr + store_size);
609 bool lower_load_has_store_part =
610 req->getVaddr() < (storeQueue[store_idx].inst->effAddr +
611 store_size);
612 bool upper_load_has_store_part =
613 (req->getVaddr() + req->getSize()) >
614 storeQueue[store_idx].inst->effAddr;
615
616 // If the store's data has all of the data needed, we can forward.
617 if ((store_has_lower_limit && store_has_upper_limit)) {
618 // Get shift amount for offset into the store's data.
619 int shift_amt = req->getVaddr() & (store_size - 1);
620
621 memcpy(data, storeQueue[store_idx].data + shift_amt,
622 req->getSize());
623
624 assert(!load_inst->memData);
625 load_inst->memData = new uint8_t[64];
626
627 memcpy(load_inst->memData,
628 storeQueue[store_idx].data + shift_amt, req->getSize());
629
630 DPRINTF(LSQUnit, "Forwarding from store idx %i to load to "
631 "addr %#x, data %#x\n",
632 store_idx, req->getVaddr(), data);
633
634 PacketPtr data_pkt = new Packet(req, MemCmd::ReadReq,
635 Packet::Broadcast);
636 data_pkt->dataStatic(load_inst->memData);
637
638 WritebackEvent *wb = new WritebackEvent(load_inst, data_pkt, this);
639
640 // We'll say this has a 1 cycle load-store forwarding latency
641 // for now.
642 // @todo: Need to make this a parameter.
643 cpu->schedule(wb, curTick());
644
645 // Don't need to do anything special for split loads.
646 if (TheISA::HasUnalignedMemAcc && sreqLow) {
647 delete sreqLow;
648 delete sreqHigh;
649 }
650
651 ++lsqForwLoads;
652 return NoFault;
653 } else if ((store_has_lower_limit && lower_load_has_store_part) ||
654 (store_has_upper_limit && upper_load_has_store_part) ||
655 (lower_load_has_store_part && upper_load_has_store_part)) {
656 // This is the partial store-load forwarding case where a store
657 // has only part of the load's data.
658
659 // If it's already been written back, then don't worry about
660 // stalling on it.
661 if (storeQueue[store_idx].completed) {
662 panic("Should not check one of these");
663 continue;
664 }
665
666 // Must stall load and force it to retry, so long as it's the oldest
667 // load that needs to do so.
668 if (!stalled ||
669 (stalled &&
670 load_inst->seqNum <
671 loadQueue[stallingLoadIdx]->seqNum)) {
672 stalled = true;
673 stallingStoreIsn = storeQueue[store_idx].inst->seqNum;
674 stallingLoadIdx = load_idx;
675 }
676
677 // Tell IQ/mem dep unit that this instruction will need to be
678 // rescheduled eventually
679 iewStage->rescheduleMemInst(load_inst);
680 iewStage->decrWb(load_inst->seqNum);
681 load_inst->clearIssued();
682 ++lsqRescheduledLoads;
683
684 // Do not generate a writeback event as this instruction is not
685 // complete.
686 DPRINTF(LSQUnit, "Load-store forwarding mis-match. "
687 "Store idx %i to load addr %#x\n",
688 store_idx, req->getVaddr());
689
690 // Must delete request now that it wasn't handed off to
691 // memory. This is quite ugly. @todo: Figure out the
692 // proper place to really handle request deletes.
693 delete req;
694 if (TheISA::HasUnalignedMemAcc && sreqLow) {
695 delete sreqLow;
696 delete sreqHigh;
697 }
698
699 return NoFault;
700 }
701 }
702
703 // If there's no forwarding case, then go access memory
704 DPRINTF(LSQUnit, "Doing memory access for inst [sn:%lli] PC %s\n",
705 load_inst->seqNum, load_inst->pcState());
706
707 assert(!load_inst->memData);
708 load_inst->memData = new uint8_t[64];
709
710 ++usedPorts;
711
712 // if we the cache is not blocked, do cache access
713 bool completedFirst = false;
714 if (!lsq->cacheBlocked()) {
715 MemCmd command =
716 req->isLLSC() ? MemCmd::LoadLockedReq : MemCmd::ReadReq;
717 PacketPtr data_pkt = new Packet(req, command, Packet::Broadcast);
718 PacketPtr fst_data_pkt = NULL;
719 PacketPtr snd_data_pkt = NULL;
720
721 data_pkt->dataStatic(load_inst->memData);
722
723 LSQSenderState *state = new LSQSenderState;
724 state->isLoad = true;
725 state->idx = load_idx;
726 state->inst = load_inst;
727 data_pkt->senderState = state;
728
729 if (!TheISA::HasUnalignedMemAcc || !sreqLow) {
730
731 // Point the first packet at the main data packet.
732 fst_data_pkt = data_pkt;
733 } else {
734
735 // Create the split packets.
736 fst_data_pkt = new Packet(sreqLow, command, Packet::Broadcast);
737 snd_data_pkt = new Packet(sreqHigh, command, Packet::Broadcast);
738
739 fst_data_pkt->dataStatic(load_inst->memData);
740 snd_data_pkt->dataStatic(load_inst->memData + sreqLow->getSize());
741
742 fst_data_pkt->senderState = state;
743 snd_data_pkt->senderState = state;
744
745 state->isSplit = true;
746 state->outstanding = 2;
747 state->mainPkt = data_pkt;
748 }
749
750 if (!dcachePort->sendTiming(fst_data_pkt)) {
751 // Delete state and data packet because a load retry
752 // initiates a pipeline restart; it does not retry.
753 delete state;
754 delete data_pkt->req;
755 delete data_pkt;
756 if (TheISA::HasUnalignedMemAcc && sreqLow) {
757 delete fst_data_pkt->req;
758 delete fst_data_pkt;
759 delete snd_data_pkt->req;
760 delete snd_data_pkt;
761 sreqLow = NULL;
762 sreqHigh = NULL;
763 }
764
765 req = NULL;
766
767 // If the access didn't succeed, tell the LSQ by setting
768 // the retry thread id.
769 lsq->setRetryTid(lsqID);
770 } else if (TheISA::HasUnalignedMemAcc && sreqLow) {
771 completedFirst = true;
772
773 // The first packet was sent without problems, so send this one
774 // too. If there is a problem with this packet then the whole
775 // load will be squashed, so indicate this to the state object.
776 // The first packet will return in completeDataAccess and be
777 // handled there.
778 ++usedPorts;
779 if (!dcachePort->sendTiming(snd_data_pkt)) {
780
781 // The main packet will be deleted in completeDataAccess.
782 delete snd_data_pkt->req;
783 delete snd_data_pkt;
784
785 state->complete();
786
787 req = NULL;
788 sreqHigh = NULL;
789
790 lsq->setRetryTid(lsqID);
791 }
792 }
793 }
794
795 // If the cache was blocked, or has become blocked due to the access,
796 // handle it.
797 if (lsq->cacheBlocked()) {
798 if (req)
799 delete req;
800 if (TheISA::HasUnalignedMemAcc && sreqLow && !completedFirst) {
801 delete sreqLow;
802 delete sreqHigh;
803 }
804
805 ++lsqCacheBlocked;
806
807 iewStage->decrWb(load_inst->seqNum);
807 // If the first part of a split access succeeds, then let the LSQ
808 // handle the decrWb when completeDataAccess is called upon return
809 // of the requested first part of data
810 if (!completedFirst)
811 iewStage->decrWb(load_inst->seqNum);
812
808 // There's an older load that's already going to squash.
809 if (isLoadBlocked && blockedLoadSeqNum < load_inst->seqNum)
810 return NoFault;
811
812 // Record that the load was blocked due to memory. This
813 // load will squash all instructions after it, be
814 // refetched, and re-executed.
815 isLoadBlocked = true;
816 loadBlockedHandled = false;
817 blockedLoadSeqNum = load_inst->seqNum;
818 // No fault occurred, even though the interface is blocked.
819 return NoFault;
820 }
821
822 return NoFault;
823}
824
825template <class Impl>
826Fault
827LSQUnit<Impl>::write(Request *req, Request *sreqLow, Request *sreqHigh,
828 uint8_t *data, int store_idx)
829{
830 assert(storeQueue[store_idx].inst);
831
832 DPRINTF(LSQUnit, "Doing write to store idx %i, addr %#x data %#x"
833 " | storeHead:%i [sn:%i]\n",
834 store_idx, req->getPaddr(), data, storeHead,
835 storeQueue[store_idx].inst->seqNum);
836
837 storeQueue[store_idx].req = req;
838 storeQueue[store_idx].sreqLow = sreqLow;
839 storeQueue[store_idx].sreqHigh = sreqHigh;
840 unsigned size = req->getSize();
841 storeQueue[store_idx].size = size;
842 assert(size <= sizeof(storeQueue[store_idx].data));
843
844 // Split stores can only occur in ISAs with unaligned memory accesses. If
845 // a store request has been split, sreqLow and sreqHigh will be non-null.
846 if (TheISA::HasUnalignedMemAcc && sreqLow) {
847 storeQueue[store_idx].isSplit = true;
848 }
849
850 memcpy(storeQueue[store_idx].data, data, size);
851
852 // This function only writes the data to the store queue, so no fault
853 // can happen here.
854 return NoFault;
855}
856
857#endif // __CPU_O3_LSQ_UNIT_HH__
813 // There's an older load that's already going to squash.
814 if (isLoadBlocked && blockedLoadSeqNum < load_inst->seqNum)
815 return NoFault;
816
817 // Record that the load was blocked due to memory. This
818 // load will squash all instructions after it, be
819 // refetched, and re-executed.
820 isLoadBlocked = true;
821 loadBlockedHandled = false;
822 blockedLoadSeqNum = load_inst->seqNum;
823 // No fault occurred, even though the interface is blocked.
824 return NoFault;
825 }
826
827 return NoFault;
828}
829
830template <class Impl>
831Fault
832LSQUnit<Impl>::write(Request *req, Request *sreqLow, Request *sreqHigh,
833 uint8_t *data, int store_idx)
834{
835 assert(storeQueue[store_idx].inst);
836
837 DPRINTF(LSQUnit, "Doing write to store idx %i, addr %#x data %#x"
838 " | storeHead:%i [sn:%i]\n",
839 store_idx, req->getPaddr(), data, storeHead,
840 storeQueue[store_idx].inst->seqNum);
841
842 storeQueue[store_idx].req = req;
843 storeQueue[store_idx].sreqLow = sreqLow;
844 storeQueue[store_idx].sreqHigh = sreqHigh;
845 unsigned size = req->getSize();
846 storeQueue[store_idx].size = size;
847 assert(size <= sizeof(storeQueue[store_idx].data));
848
849 // Split stores can only occur in ISAs with unaligned memory accesses. If
850 // a store request has been split, sreqLow and sreqHigh will be non-null.
851 if (TheISA::HasUnalignedMemAcc && sreqLow) {
852 storeQueue[store_idx].isSplit = true;
853 }
854
855 memcpy(storeQueue[store_idx].data, data, size);
856
857 // This function only writes the data to the store queue, so no fault
858 // can happen here.
859 return NoFault;
860}
861
862#endif // __CPU_O3_LSQ_UNIT_HH__