lsq_unit.hh (10824:308771bd2647) lsq_unit.hh (11168:f98eb2da15a4)
1/*
2 * Copyright (c) 2012-2014 ARM Limited
3 * All rights reserved
4 *
5 * The license below extends only to copyright in the software and shall
6 * not be construed as granting a license to any other intellectual
7 * property including but not limited to intellectual property relating
8 * to a hardware implementation of the functionality of the software
9 * licensed hereunder. You may use the software subject to the license
10 * terms below provided that you ensure that this notice is replicated
11 * unmodified and in its entirety in all distributions of the software,
12 * modified or unmodified, in source code or in binary form.
13 *
14 * Copyright (c) 2004-2006 The Regents of The University of Michigan
15 * Copyright (c) 2013 Advanced Micro Devices, Inc.
16 * All rights reserved.
17 *
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions are
20 * met: redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer;
22 * redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution;
25 * neither the name of the copyright holders nor the names of its
26 * contributors may be used to endorse or promote products derived from
27 * this software without specific prior written permission.
28 *
29 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
30 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
31 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
32 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
33 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
34 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
35 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
39 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 *
41 * Authors: Kevin Lim
42 * Korey Sewell
43 */
44
45#ifndef __CPU_O3_LSQ_UNIT_HH__
46#define __CPU_O3_LSQ_UNIT_HH__
47
48#include <algorithm>
49#include <cstring>
50#include <map>
51#include <queue>
52
53#include "arch/generic/debugfaults.hh"
54#include "arch/isa_traits.hh"
55#include "arch/locked_mem.hh"
56#include "arch/mmapped_ipr.hh"
1/*
2 * Copyright (c) 2012-2014 ARM Limited
3 * All rights reserved
4 *
5 * The license below extends only to copyright in the software and shall
6 * not be construed as granting a license to any other intellectual
7 * property including but not limited to intellectual property relating
8 * to a hardware implementation of the functionality of the software
9 * licensed hereunder. You may use the software subject to the license
10 * terms below provided that you ensure that this notice is replicated
11 * unmodified and in its entirety in all distributions of the software,
12 * modified or unmodified, in source code or in binary form.
13 *
14 * Copyright (c) 2004-2006 The Regents of The University of Michigan
15 * Copyright (c) 2013 Advanced Micro Devices, Inc.
16 * All rights reserved.
17 *
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions are
20 * met: redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer;
22 * redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution;
25 * neither the name of the copyright holders nor the names of its
26 * contributors may be used to endorse or promote products derived from
27 * this software without specific prior written permission.
28 *
29 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
30 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
31 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
32 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
33 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
34 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
35 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
39 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 *
41 * Authors: Kevin Lim
42 * Korey Sewell
43 */
44
45#ifndef __CPU_O3_LSQ_UNIT_HH__
46#define __CPU_O3_LSQ_UNIT_HH__
47
48#include <algorithm>
49#include <cstring>
50#include <map>
51#include <queue>
52
53#include "arch/generic/debugfaults.hh"
54#include "arch/isa_traits.hh"
55#include "arch/locked_mem.hh"
56#include "arch/mmapped_ipr.hh"
57#include "base/hashmap.hh"
58#include "config/the_isa.hh"
59#include "cpu/inst_seq.hh"
60#include "cpu/timebuf.hh"
61#include "debug/LSQUnit.hh"
62#include "mem/packet.hh"
63#include "mem/port.hh"
64
65struct DerivO3CPUParams;
66
67/**
68 * Class that implements the actual LQ and SQ for each specific
69 * thread. Both are circular queues; load entries are freed upon
70 * committing, while store entries are freed once they writeback. The
71 * LSQUnit tracks if there are memory ordering violations, and also
72 * detects partial load to store forwarding cases (a store only has
73 * part of a load's data) that requires the load to wait until the
74 * store writes back. In the former case it holds onto the instruction
75 * until the dependence unit looks at it, and in the latter it stalls
76 * the LSQ until the store writes back. At that point the load is
77 * replayed.
78 */
79template <class Impl>
80class LSQUnit {
81 public:
82 typedef typename Impl::O3CPU O3CPU;
83 typedef typename Impl::DynInstPtr DynInstPtr;
84 typedef typename Impl::CPUPol::IEW IEW;
85 typedef typename Impl::CPUPol::LSQ LSQ;
86 typedef typename Impl::CPUPol::IssueStruct IssueStruct;
87
88 public:
89 /** Constructs an LSQ unit. init() must be called prior to use. */
90 LSQUnit();
91
92 /** Initializes the LSQ unit with the specified number of entries. */
93 void init(O3CPU *cpu_ptr, IEW *iew_ptr, DerivO3CPUParams *params,
94 LSQ *lsq_ptr, unsigned maxLQEntries, unsigned maxSQEntries,
95 unsigned id);
96
97 /** Returns the name of the LSQ unit. */
98 std::string name() const;
99
100 /** Registers statistics. */
101 void regStats();
102
103 /** Sets the pointer to the dcache port. */
104 void setDcachePort(MasterPort *dcache_port);
105
106 /** Perform sanity checks after a drain. */
107 void drainSanityCheck() const;
108
109 /** Takes over from another CPU's thread. */
110 void takeOverFrom();
111
112 /** Ticks the LSQ unit, which in this case only resets the number of
113 * used cache ports.
114 * @todo: Move the number of used ports up to the LSQ level so it can
115 * be shared by all LSQ units.
116 */
117 void tick() { usedPorts = 0; }
118
119 /** Inserts an instruction. */
120 void insert(DynInstPtr &inst);
121 /** Inserts a load instruction. */
122 void insertLoad(DynInstPtr &load_inst);
123 /** Inserts a store instruction. */
124 void insertStore(DynInstPtr &store_inst);
125
126 /** Check for ordering violations in the LSQ. For a store squash if we
127 * ever find a conflicting load. For a load, only squash if we
128 * an external snoop invalidate has been seen for that load address
129 * @param load_idx index to start checking at
130 * @param inst the instruction to check
131 */
132 Fault checkViolations(int load_idx, DynInstPtr &inst);
133
134 /** Check if an incoming invalidate hits in the lsq on a load
135 * that might have issued out of order wrt another load beacuse
136 * of the intermediate invalidate.
137 */
138 void checkSnoop(PacketPtr pkt);
139
140 /** Executes a load instruction. */
141 Fault executeLoad(DynInstPtr &inst);
142
143 Fault executeLoad(int lq_idx) { panic("Not implemented"); return NoFault; }
144 /** Executes a store instruction. */
145 Fault executeStore(DynInstPtr &inst);
146
147 /** Commits the head load. */
148 void commitLoad();
149 /** Commits loads older than a specific sequence number. */
150 void commitLoads(InstSeqNum &youngest_inst);
151
152 /** Commits stores older than a specific sequence number. */
153 void commitStores(InstSeqNum &youngest_inst);
154
155 /** Writes back stores. */
156 void writebackStores();
157
158 /** Completes the data access that has been returned from the
159 * memory system. */
160 void completeDataAccess(PacketPtr pkt);
161
162 /** Clears all the entries in the LQ. */
163 void clearLQ();
164
165 /** Clears all the entries in the SQ. */
166 void clearSQ();
167
168 /** Resizes the LQ to a given size. */
169 void resizeLQ(unsigned size);
170
171 /** Resizes the SQ to a given size. */
172 void resizeSQ(unsigned size);
173
174 /** Squashes all instructions younger than a specific sequence number. */
175 void squash(const InstSeqNum &squashed_num);
176
177 /** Returns if there is a memory ordering violation. Value is reset upon
178 * call to getMemDepViolator().
179 */
180 bool violation() { return memDepViolator; }
181
182 /** Returns the memory ordering violator. */
183 DynInstPtr getMemDepViolator();
184
185 /** Returns the number of free LQ entries. */
186 unsigned numFreeLoadEntries();
187
188 /** Returns the number of free SQ entries. */
189 unsigned numFreeStoreEntries();
190
191 /** Returns the number of loads in the LQ. */
192 int numLoads() { return loads; }
193
194 /** Returns the number of stores in the SQ. */
195 int numStores() { return stores; }
196
197 /** Returns if either the LQ or SQ is full. */
198 bool isFull() { return lqFull() || sqFull(); }
199
200 /** Returns if both the LQ and SQ are empty. */
201 bool isEmpty() const { return lqEmpty() && sqEmpty(); }
202
203 /** Returns if the LQ is full. */
204 bool lqFull() { return loads >= (LQEntries - 1); }
205
206 /** Returns if the SQ is full. */
207 bool sqFull() { return stores >= (SQEntries - 1); }
208
209 /** Returns if the LQ is empty. */
210 bool lqEmpty() const { return loads == 0; }
211
212 /** Returns if the SQ is empty. */
213 bool sqEmpty() const { return stores == 0; }
214
215 /** Returns the number of instructions in the LSQ. */
216 unsigned getCount() { return loads + stores; }
217
218 /** Returns if there are any stores to writeback. */
219 bool hasStoresToWB() { return storesToWB; }
220
221 /** Returns the number of stores to writeback. */
222 int numStoresToWB() { return storesToWB; }
223
224 /** Returns if the LSQ unit will writeback on this cycle. */
225 bool willWB() { return storeQueue[storeWBIdx].canWB &&
226 !storeQueue[storeWBIdx].completed &&
227 !isStoreBlocked; }
228
229 /** Handles doing the retry. */
230 void recvRetry();
231
232 private:
233 /** Reset the LSQ state */
234 void resetState();
235
236 /** Writes back the instruction, sending it to IEW. */
237 void writeback(DynInstPtr &inst, PacketPtr pkt);
238
239 /** Writes back a store that couldn't be completed the previous cycle. */
240 void writebackPendingStore();
241
242 /** Handles completing the send of a store to memory. */
243 void storePostSend(PacketPtr pkt);
244
245 /** Completes the store at the specified index. */
246 void completeStore(int store_idx);
247
248 /** Attempts to send a store to the cache. */
249 bool sendStore(PacketPtr data_pkt);
250
251 /** Increments the given store index (circular queue). */
252 inline void incrStIdx(int &store_idx) const;
253 /** Decrements the given store index (circular queue). */
254 inline void decrStIdx(int &store_idx) const;
255 /** Increments the given load index (circular queue). */
256 inline void incrLdIdx(int &load_idx) const;
257 /** Decrements the given load index (circular queue). */
258 inline void decrLdIdx(int &load_idx) const;
259
260 public:
261 /** Debugging function to dump instructions in the LSQ. */
262 void dumpInsts() const;
263
264 private:
265 /** Pointer to the CPU. */
266 O3CPU *cpu;
267
268 /** Pointer to the IEW stage. */
269 IEW *iewStage;
270
271 /** Pointer to the LSQ. */
272 LSQ *lsq;
273
274 /** Pointer to the dcache port. Used only for sending. */
275 MasterPort *dcachePort;
276
277 /** Derived class to hold any sender state the LSQ needs. */
278 class LSQSenderState : public Packet::SenderState
279 {
280 public:
281 /** Default constructor. */
282 LSQSenderState()
283 : mainPkt(NULL), pendingPacket(NULL), idx(0), outstanding(1),
284 isLoad(false), noWB(false), isSplit(false),
285 pktToSend(false), cacheBlocked(false)
286 { }
287
288 /** Instruction who initiated the access to memory. */
289 DynInstPtr inst;
290 /** The main packet from a split load, used during writeback. */
291 PacketPtr mainPkt;
292 /** A second packet from a split store that needs sending. */
293 PacketPtr pendingPacket;
294 /** The LQ/SQ index of the instruction. */
295 uint8_t idx;
296 /** Number of outstanding packets to complete. */
297 uint8_t outstanding;
298 /** Whether or not it is a load. */
299 bool isLoad;
300 /** Whether or not the instruction will need to writeback. */
301 bool noWB;
302 /** Whether or not this access is split in two. */
303 bool isSplit;
304 /** Whether or not there is a packet that needs sending. */
305 bool pktToSend;
306 /** Whether or not the second packet of this split load was blocked */
307 bool cacheBlocked;
308
309 /** Completes a packet and returns whether the access is finished. */
310 inline bool complete() { return --outstanding == 0; }
311 };
312
313 /** Writeback event, specifically for when stores forward data to loads. */
314 class WritebackEvent : public Event {
315 public:
316 /** Constructs a writeback event. */
317 WritebackEvent(DynInstPtr &_inst, PacketPtr pkt, LSQUnit *lsq_ptr);
318
319 /** Processes the writeback event. */
320 void process();
321
322 /** Returns the description of this event. */
323 const char *description() const;
324
325 private:
326 /** Instruction whose results are being written back. */
327 DynInstPtr inst;
328
329 /** The packet that would have been sent to memory. */
330 PacketPtr pkt;
331
332 /** The pointer to the LSQ unit that issued the store. */
333 LSQUnit<Impl> *lsqPtr;
334 };
335
336 public:
337 struct SQEntry {
338 /** Constructs an empty store queue entry. */
339 SQEntry()
340 : inst(NULL), req(NULL), size(0),
341 canWB(0), committed(0), completed(0)
342 {
343 std::memset(data, 0, sizeof(data));
344 }
345
346 ~SQEntry()
347 {
348 inst = NULL;
349 }
350
351 /** Constructs a store queue entry for a given instruction. */
352 SQEntry(DynInstPtr &_inst)
353 : inst(_inst), req(NULL), sreqLow(NULL), sreqHigh(NULL), size(0),
354 isSplit(0), canWB(0), committed(0), completed(0), isAllZeros(0)
355 {
356 std::memset(data, 0, sizeof(data));
357 }
358 /** The store data. */
359 char data[16];
360 /** The store instruction. */
361 DynInstPtr inst;
362 /** The request for the store. */
363 RequestPtr req;
364 /** The split requests for the store. */
365 RequestPtr sreqLow;
366 RequestPtr sreqHigh;
367 /** The size of the store. */
368 uint8_t size;
369 /** Whether or not the store is split into two requests. */
370 bool isSplit;
371 /** Whether or not the store can writeback. */
372 bool canWB;
373 /** Whether or not the store is committed. */
374 bool committed;
375 /** Whether or not the store is completed. */
376 bool completed;
377 /** Does this request write all zeros and thus doesn't
378 * have any data attached to it. Used for cache block zero
379 * style instructs (ARM DC ZVA; ALPHA WH64)
380 */
381 bool isAllZeros;
382 };
383
384 private:
385 /** The LSQUnit thread id. */
386 ThreadID lsqID;
387
388 /** The store queue. */
389 std::vector<SQEntry> storeQueue;
390
391 /** The load queue. */
392 std::vector<DynInstPtr> loadQueue;
393
394 /** The number of LQ entries, plus a sentinel entry (circular queue).
395 * @todo: Consider having var that records the true number of LQ entries.
396 */
397 unsigned LQEntries;
398 /** The number of SQ entries, plus a sentinel entry (circular queue).
399 * @todo: Consider having var that records the true number of SQ entries.
400 */
401 unsigned SQEntries;
402
403 /** The number of places to shift addresses in the LSQ before checking
404 * for dependency violations
405 */
406 unsigned depCheckShift;
407
408 /** Should loads be checked for dependency issues */
409 bool checkLoads;
410
411 /** The number of load instructions in the LQ. */
412 int loads;
413 /** The number of store instructions in the SQ. */
414 int stores;
415 /** The number of store instructions in the SQ waiting to writeback. */
416 int storesToWB;
417
418 /** The index of the head instruction in the LQ. */
419 int loadHead;
420 /** The index of the tail instruction in the LQ. */
421 int loadTail;
422
423 /** The index of the head instruction in the SQ. */
424 int storeHead;
425 /** The index of the first instruction that may be ready to be
426 * written back, and has not yet been written back.
427 */
428 int storeWBIdx;
429 /** The index of the tail instruction in the SQ. */
430 int storeTail;
431
432 /// @todo Consider moving to a more advanced model with write vs read ports
433 /** The number of cache ports available each cycle. */
434 int cachePorts;
435
436 /** The number of used cache ports in this cycle. */
437 int usedPorts;
438
439 //list<InstSeqNum> mshrSeqNums;
440
441 /** Address Mask for a cache block (e.g. ~(cache_block_size-1)) */
442 Addr cacheBlockMask;
443
444 /** Wire to read information from the issue stage time queue. */
445 typename TimeBuffer<IssueStruct>::wire fromIssue;
446
447 /** Whether or not the LSQ is stalled. */
448 bool stalled;
449 /** The store that causes the stall due to partial store to load
450 * forwarding.
451 */
452 InstSeqNum stallingStoreIsn;
453 /** The index of the above store. */
454 int stallingLoadIdx;
455
456 /** The packet that needs to be retried. */
457 PacketPtr retryPkt;
458
459 /** Whehter or not a store is blocked due to the memory system. */
460 bool isStoreBlocked;
461
462 /** Whether or not a store is in flight. */
463 bool storeInFlight;
464
465 /** The oldest load that caused a memory ordering violation. */
466 DynInstPtr memDepViolator;
467
468 /** Whether or not there is a packet that couldn't be sent because of
469 * a lack of cache ports. */
470 bool hasPendingPkt;
471
472 /** The packet that is pending free cache ports. */
473 PacketPtr pendingPkt;
474
475 /** Flag for memory model. */
476 bool needsTSO;
477
478 // Will also need how many read/write ports the Dcache has. Or keep track
479 // of that in stage that is one level up, and only call executeLoad/Store
480 // the appropriate number of times.
481 /** Total number of loads forwaded from LSQ stores. */
482 Stats::Scalar lsqForwLoads;
483
484 /** Total number of loads ignored due to invalid addresses. */
485 Stats::Scalar invAddrLoads;
486
487 /** Total number of squashed loads. */
488 Stats::Scalar lsqSquashedLoads;
489
490 /** Total number of responses from the memory system that are
491 * ignored due to the instruction already being squashed. */
492 Stats::Scalar lsqIgnoredResponses;
493
494 /** Tota number of memory ordering violations. */
495 Stats::Scalar lsqMemOrderViolation;
496
497 /** Total number of squashed stores. */
498 Stats::Scalar lsqSquashedStores;
499
500 /** Total number of software prefetches ignored due to invalid addresses. */
501 Stats::Scalar invAddrSwpfs;
502
503 /** Ready loads blocked due to partial store-forwarding. */
504 Stats::Scalar lsqBlockedLoads;
505
506 /** Number of loads that were rescheduled. */
507 Stats::Scalar lsqRescheduledLoads;
508
509 /** Number of times the LSQ is blocked due to the cache. */
510 Stats::Scalar lsqCacheBlocked;
511
512 public:
513 /** Executes the load at the given index. */
514 Fault read(Request *req, Request *sreqLow, Request *sreqHigh,
515 uint8_t *data, int load_idx);
516
517 /** Executes the store at the given index. */
518 Fault write(Request *req, Request *sreqLow, Request *sreqHigh,
519 uint8_t *data, int store_idx);
520
521 /** Returns the index of the head load instruction. */
522 int getLoadHead() { return loadHead; }
523 /** Returns the sequence number of the head load instruction. */
524 InstSeqNum getLoadHeadSeqNum()
525 {
526 if (loadQueue[loadHead]) {
527 return loadQueue[loadHead]->seqNum;
528 } else {
529 return 0;
530 }
531
532 }
533
534 /** Returns the index of the head store instruction. */
535 int getStoreHead() { return storeHead; }
536 /** Returns the sequence number of the head store instruction. */
537 InstSeqNum getStoreHeadSeqNum()
538 {
539 if (storeQueue[storeHead].inst) {
540 return storeQueue[storeHead].inst->seqNum;
541 } else {
542 return 0;
543 }
544
545 }
546
547 /** Returns whether or not the LSQ unit is stalled. */
548 bool isStalled() { return stalled; }
549};
550
551template <class Impl>
552Fault
553LSQUnit<Impl>::read(Request *req, Request *sreqLow, Request *sreqHigh,
554 uint8_t *data, int load_idx)
555{
556 DynInstPtr load_inst = loadQueue[load_idx];
557
558 assert(load_inst);
559
560 assert(!load_inst->isExecuted());
561
562 // Make sure this isn't a strictly ordered load
563 // A bit of a hackish way to get strictly ordered accesses to work
564 // only if they're at the head of the LSQ and are ready to commit
565 // (at the head of the ROB too).
566 if (req->isStrictlyOrdered() &&
567 (load_idx != loadHead || !load_inst->isAtCommit())) {
568 iewStage->rescheduleMemInst(load_inst);
569 ++lsqRescheduledLoads;
570 DPRINTF(LSQUnit, "Strictly ordered load [sn:%lli] PC %s\n",
571 load_inst->seqNum, load_inst->pcState());
572
573 // Must delete request now that it wasn't handed off to
574 // memory. This is quite ugly. @todo: Figure out the proper
575 // place to really handle request deletes.
576 delete req;
577 if (TheISA::HasUnalignedMemAcc && sreqLow) {
578 delete sreqLow;
579 delete sreqHigh;
580 }
581 return std::make_shared<GenericISA::M5PanicFault>(
582 "Strictly ordered load [sn:%llx] PC %s\n",
583 load_inst->seqNum, load_inst->pcState());
584 }
585
586 // Check the SQ for any previous stores that might lead to forwarding
587 int store_idx = load_inst->sqIdx;
588
589 int store_size = 0;
590
591 DPRINTF(LSQUnit, "Read called, load idx: %i, store idx: %i, "
592 "storeHead: %i addr: %#x%s\n",
593 load_idx, store_idx, storeHead, req->getPaddr(),
594 sreqLow ? " split" : "");
595
596 if (req->isLLSC()) {
597 assert(!sreqLow);
598 // Disable recording the result temporarily. Writing to misc
599 // regs normally updates the result, but this is not the
600 // desired behavior when handling store conditionals.
601 load_inst->recordResult(false);
602 TheISA::handleLockedRead(load_inst.get(), req);
603 load_inst->recordResult(true);
604 }
605
606 if (req->isMmappedIpr()) {
607 assert(!load_inst->memData);
608 load_inst->memData = new uint8_t[64];
609
610 ThreadContext *thread = cpu->tcBase(lsqID);
611 Cycles delay(0);
612 PacketPtr data_pkt = new Packet(req, MemCmd::ReadReq);
613
614 if (!TheISA::HasUnalignedMemAcc || !sreqLow) {
615 data_pkt->dataStatic(load_inst->memData);
616 delay = TheISA::handleIprRead(thread, data_pkt);
617 } else {
618 assert(sreqLow->isMmappedIpr() && sreqHigh->isMmappedIpr());
619 PacketPtr fst_data_pkt = new Packet(sreqLow, MemCmd::ReadReq);
620 PacketPtr snd_data_pkt = new Packet(sreqHigh, MemCmd::ReadReq);
621
622 fst_data_pkt->dataStatic(load_inst->memData);
623 snd_data_pkt->dataStatic(load_inst->memData + sreqLow->getSize());
624
625 delay = TheISA::handleIprRead(thread, fst_data_pkt);
626 Cycles delay2 = TheISA::handleIprRead(thread, snd_data_pkt);
627 if (delay2 > delay)
628 delay = delay2;
629
630 delete sreqLow;
631 delete sreqHigh;
632 delete fst_data_pkt;
633 delete snd_data_pkt;
634 }
635 WritebackEvent *wb = new WritebackEvent(load_inst, data_pkt, this);
636 cpu->schedule(wb, cpu->clockEdge(delay));
637 return NoFault;
638 }
639
640 while (store_idx != -1) {
641 // End once we've reached the top of the LSQ
642 if (store_idx == storeWBIdx) {
643 break;
644 }
645
646 // Move the index to one younger
647 if (--store_idx < 0)
648 store_idx += SQEntries;
649
650 assert(storeQueue[store_idx].inst);
651
652 store_size = storeQueue[store_idx].size;
653
654 if (store_size == 0)
655 continue;
656 else if (storeQueue[store_idx].inst->strictlyOrdered())
657 continue;
658
659 assert(storeQueue[store_idx].inst->effAddrValid());
660
661 // Check if the store data is within the lower and upper bounds of
662 // addresses that the request needs.
663 bool store_has_lower_limit =
664 req->getVaddr() >= storeQueue[store_idx].inst->effAddr;
665 bool store_has_upper_limit =
666 (req->getVaddr() + req->getSize()) <=
667 (storeQueue[store_idx].inst->effAddr + store_size);
668 bool lower_load_has_store_part =
669 req->getVaddr() < (storeQueue[store_idx].inst->effAddr +
670 store_size);
671 bool upper_load_has_store_part =
672 (req->getVaddr() + req->getSize()) >
673 storeQueue[store_idx].inst->effAddr;
674
675 // If the store's data has all of the data needed, we can forward.
676 if ((store_has_lower_limit && store_has_upper_limit)) {
677 // Get shift amount for offset into the store's data.
678 int shift_amt = req->getVaddr() - storeQueue[store_idx].inst->effAddr;
679
680 if (storeQueue[store_idx].isAllZeros)
681 memset(data, 0, req->getSize());
682 else
683 memcpy(data, storeQueue[store_idx].data + shift_amt,
684 req->getSize());
685
686 // Allocate memory if this is the first time a load is issued.
687 if (!load_inst->memData) {
688 load_inst->memData = new uint8_t[req->getSize()];
689 }
690 if (storeQueue[store_idx].isAllZeros)
691 memset(load_inst->memData, 0, req->getSize());
692 else
693 memcpy(load_inst->memData,
694 storeQueue[store_idx].data + shift_amt, req->getSize());
695
696 DPRINTF(LSQUnit, "Forwarding from store idx %i to load to "
697 "addr %#x\n", store_idx, req->getVaddr());
698
699 PacketPtr data_pkt = new Packet(req, MemCmd::ReadReq);
700 data_pkt->dataStatic(load_inst->memData);
701
702 WritebackEvent *wb = new WritebackEvent(load_inst, data_pkt, this);
703
704 // We'll say this has a 1 cycle load-store forwarding latency
705 // for now.
706 // @todo: Need to make this a parameter.
707 cpu->schedule(wb, curTick());
708
709 // Don't need to do anything special for split loads.
710 if (TheISA::HasUnalignedMemAcc && sreqLow) {
711 delete sreqLow;
712 delete sreqHigh;
713 }
714
715 ++lsqForwLoads;
716 return NoFault;
717 } else if ((store_has_lower_limit && lower_load_has_store_part) ||
718 (store_has_upper_limit && upper_load_has_store_part) ||
719 (lower_load_has_store_part && upper_load_has_store_part)) {
720 // This is the partial store-load forwarding case where a store
721 // has only part of the load's data.
722
723 // If it's already been written back, then don't worry about
724 // stalling on it.
725 if (storeQueue[store_idx].completed) {
726 panic("Should not check one of these");
727 continue;
728 }
729
730 // Must stall load and force it to retry, so long as it's the oldest
731 // load that needs to do so.
732 if (!stalled ||
733 (stalled &&
734 load_inst->seqNum <
735 loadQueue[stallingLoadIdx]->seqNum)) {
736 stalled = true;
737 stallingStoreIsn = storeQueue[store_idx].inst->seqNum;
738 stallingLoadIdx = load_idx;
739 }
740
741 // Tell IQ/mem dep unit that this instruction will need to be
742 // rescheduled eventually
743 iewStage->rescheduleMemInst(load_inst);
744 load_inst->clearIssued();
745 ++lsqRescheduledLoads;
746
747 // Do not generate a writeback event as this instruction is not
748 // complete.
749 DPRINTF(LSQUnit, "Load-store forwarding mis-match. "
750 "Store idx %i to load addr %#x\n",
751 store_idx, req->getVaddr());
752
753 // Must delete request now that it wasn't handed off to
754 // memory. This is quite ugly. @todo: Figure out the
755 // proper place to really handle request deletes.
756 delete req;
757 if (TheISA::HasUnalignedMemAcc && sreqLow) {
758 delete sreqLow;
759 delete sreqHigh;
760 }
761
762 return NoFault;
763 }
764 }
765
766 // If there's no forwarding case, then go access memory
767 DPRINTF(LSQUnit, "Doing memory access for inst [sn:%lli] PC %s\n",
768 load_inst->seqNum, load_inst->pcState());
769
770 // Allocate memory if this is the first time a load is issued.
771 if (!load_inst->memData) {
772 load_inst->memData = new uint8_t[req->getSize()];
773 }
774
775 ++usedPorts;
776
777 // if we the cache is not blocked, do cache access
778 bool completedFirst = false;
779 PacketPtr data_pkt = Packet::createRead(req);
780 PacketPtr fst_data_pkt = NULL;
781 PacketPtr snd_data_pkt = NULL;
782
783 data_pkt->dataStatic(load_inst->memData);
784
785 LSQSenderState *state = new LSQSenderState;
786 state->isLoad = true;
787 state->idx = load_idx;
788 state->inst = load_inst;
789 data_pkt->senderState = state;
790
791 if (!TheISA::HasUnalignedMemAcc || !sreqLow) {
792 // Point the first packet at the main data packet.
793 fst_data_pkt = data_pkt;
794 } else {
795 // Create the split packets.
796 fst_data_pkt = Packet::createRead(sreqLow);
797 snd_data_pkt = Packet::createRead(sreqHigh);
798
799 fst_data_pkt->dataStatic(load_inst->memData);
800 snd_data_pkt->dataStatic(load_inst->memData + sreqLow->getSize());
801
802 fst_data_pkt->senderState = state;
803 snd_data_pkt->senderState = state;
804
805 state->isSplit = true;
806 state->outstanding = 2;
807 state->mainPkt = data_pkt;
808 }
809
810 bool successful_load = true;
811 if (!dcachePort->sendTimingReq(fst_data_pkt)) {
812 successful_load = false;
813 } else if (TheISA::HasUnalignedMemAcc && sreqLow) {
814 completedFirst = true;
815
816 // The first packet was sent without problems, so send this one
817 // too. If there is a problem with this packet then the whole
818 // load will be squashed, so indicate this to the state object.
819 // The first packet will return in completeDataAccess and be
820 // handled there.
821 ++usedPorts;
822 if (!dcachePort->sendTimingReq(snd_data_pkt)) {
823 // The main packet will be deleted in completeDataAccess.
824 state->complete();
825 // Signify to 1st half that the 2nd half was blocked via state
826 state->cacheBlocked = true;
827 successful_load = false;
828 }
829 }
830
831 // If the cache was blocked, or has become blocked due to the access,
832 // handle it.
833 if (!successful_load) {
834 if (!sreqLow) {
835 // Packet wasn't split, just delete main packet info
836 delete state;
837 delete req;
838 delete data_pkt;
839 }
840
841 if (TheISA::HasUnalignedMemAcc && sreqLow) {
842 if (!completedFirst) {
843 // Split packet, but first failed. Delete all state.
844 delete state;
845 delete req;
846 delete data_pkt;
847 delete fst_data_pkt;
848 delete snd_data_pkt;
849 delete sreqLow;
850 delete sreqHigh;
851 sreqLow = NULL;
852 sreqHigh = NULL;
853 } else {
854 // Can't delete main packet data or state because first packet
855 // was sent to the memory system
856 delete data_pkt;
857 delete req;
858 delete sreqHigh;
859 delete snd_data_pkt;
860 sreqHigh = NULL;
861 }
862 }
863
864 ++lsqCacheBlocked;
865
866 iewStage->blockMemInst(load_inst);
867
868 // No fault occurred, even though the interface is blocked.
869 return NoFault;
870 }
871
872 return NoFault;
873}
874
875template <class Impl>
876Fault
877LSQUnit<Impl>::write(Request *req, Request *sreqLow, Request *sreqHigh,
878 uint8_t *data, int store_idx)
879{
880 assert(storeQueue[store_idx].inst);
881
882 DPRINTF(LSQUnit, "Doing write to store idx %i, addr %#x"
883 " | storeHead:%i [sn:%i]\n",
884 store_idx, req->getPaddr(), storeHead,
885 storeQueue[store_idx].inst->seqNum);
886
887 storeQueue[store_idx].req = req;
888 storeQueue[store_idx].sreqLow = sreqLow;
889 storeQueue[store_idx].sreqHigh = sreqHigh;
890 unsigned size = req->getSize();
891 storeQueue[store_idx].size = size;
892 storeQueue[store_idx].isAllZeros = req->getFlags() & Request::CACHE_BLOCK_ZERO;
893 assert(size <= sizeof(storeQueue[store_idx].data) ||
894 (req->getFlags() & Request::CACHE_BLOCK_ZERO));
895
896 // Split stores can only occur in ISAs with unaligned memory accesses. If
897 // a store request has been split, sreqLow and sreqHigh will be non-null.
898 if (TheISA::HasUnalignedMemAcc && sreqLow) {
899 storeQueue[store_idx].isSplit = true;
900 }
901
902 if (!(req->getFlags() & Request::CACHE_BLOCK_ZERO))
903 memcpy(storeQueue[store_idx].data, data, size);
904
905 // This function only writes the data to the store queue, so no fault
906 // can happen here.
907 return NoFault;
908}
909
910#endif // __CPU_O3_LSQ_UNIT_HH__
57#include "config/the_isa.hh"
58#include "cpu/inst_seq.hh"
59#include "cpu/timebuf.hh"
60#include "debug/LSQUnit.hh"
61#include "mem/packet.hh"
62#include "mem/port.hh"
63
64struct DerivO3CPUParams;
65
66/**
67 * Class that implements the actual LQ and SQ for each specific
68 * thread. Both are circular queues; load entries are freed upon
69 * committing, while store entries are freed once they writeback. The
70 * LSQUnit tracks if there are memory ordering violations, and also
71 * detects partial load to store forwarding cases (a store only has
72 * part of a load's data) that requires the load to wait until the
73 * store writes back. In the former case it holds onto the instruction
74 * until the dependence unit looks at it, and in the latter it stalls
75 * the LSQ until the store writes back. At that point the load is
76 * replayed.
77 */
78template <class Impl>
79class LSQUnit {
80 public:
81 typedef typename Impl::O3CPU O3CPU;
82 typedef typename Impl::DynInstPtr DynInstPtr;
83 typedef typename Impl::CPUPol::IEW IEW;
84 typedef typename Impl::CPUPol::LSQ LSQ;
85 typedef typename Impl::CPUPol::IssueStruct IssueStruct;
86
87 public:
88 /** Constructs an LSQ unit. init() must be called prior to use. */
89 LSQUnit();
90
91 /** Initializes the LSQ unit with the specified number of entries. */
92 void init(O3CPU *cpu_ptr, IEW *iew_ptr, DerivO3CPUParams *params,
93 LSQ *lsq_ptr, unsigned maxLQEntries, unsigned maxSQEntries,
94 unsigned id);
95
96 /** Returns the name of the LSQ unit. */
97 std::string name() const;
98
99 /** Registers statistics. */
100 void regStats();
101
102 /** Sets the pointer to the dcache port. */
103 void setDcachePort(MasterPort *dcache_port);
104
105 /** Perform sanity checks after a drain. */
106 void drainSanityCheck() const;
107
108 /** Takes over from another CPU's thread. */
109 void takeOverFrom();
110
111 /** Ticks the LSQ unit, which in this case only resets the number of
112 * used cache ports.
113 * @todo: Move the number of used ports up to the LSQ level so it can
114 * be shared by all LSQ units.
115 */
116 void tick() { usedPorts = 0; }
117
118 /** Inserts an instruction. */
119 void insert(DynInstPtr &inst);
120 /** Inserts a load instruction. */
121 void insertLoad(DynInstPtr &load_inst);
122 /** Inserts a store instruction. */
123 void insertStore(DynInstPtr &store_inst);
124
125 /** Check for ordering violations in the LSQ. For a store squash if we
126 * ever find a conflicting load. For a load, only squash if we
127 * an external snoop invalidate has been seen for that load address
128 * @param load_idx index to start checking at
129 * @param inst the instruction to check
130 */
131 Fault checkViolations(int load_idx, DynInstPtr &inst);
132
133 /** Check if an incoming invalidate hits in the lsq on a load
134 * that might have issued out of order wrt another load beacuse
135 * of the intermediate invalidate.
136 */
137 void checkSnoop(PacketPtr pkt);
138
139 /** Executes a load instruction. */
140 Fault executeLoad(DynInstPtr &inst);
141
142 Fault executeLoad(int lq_idx) { panic("Not implemented"); return NoFault; }
143 /** Executes a store instruction. */
144 Fault executeStore(DynInstPtr &inst);
145
146 /** Commits the head load. */
147 void commitLoad();
148 /** Commits loads older than a specific sequence number. */
149 void commitLoads(InstSeqNum &youngest_inst);
150
151 /** Commits stores older than a specific sequence number. */
152 void commitStores(InstSeqNum &youngest_inst);
153
154 /** Writes back stores. */
155 void writebackStores();
156
157 /** Completes the data access that has been returned from the
158 * memory system. */
159 void completeDataAccess(PacketPtr pkt);
160
161 /** Clears all the entries in the LQ. */
162 void clearLQ();
163
164 /** Clears all the entries in the SQ. */
165 void clearSQ();
166
167 /** Resizes the LQ to a given size. */
168 void resizeLQ(unsigned size);
169
170 /** Resizes the SQ to a given size. */
171 void resizeSQ(unsigned size);
172
173 /** Squashes all instructions younger than a specific sequence number. */
174 void squash(const InstSeqNum &squashed_num);
175
176 /** Returns if there is a memory ordering violation. Value is reset upon
177 * call to getMemDepViolator().
178 */
179 bool violation() { return memDepViolator; }
180
181 /** Returns the memory ordering violator. */
182 DynInstPtr getMemDepViolator();
183
184 /** Returns the number of free LQ entries. */
185 unsigned numFreeLoadEntries();
186
187 /** Returns the number of free SQ entries. */
188 unsigned numFreeStoreEntries();
189
190 /** Returns the number of loads in the LQ. */
191 int numLoads() { return loads; }
192
193 /** Returns the number of stores in the SQ. */
194 int numStores() { return stores; }
195
196 /** Returns if either the LQ or SQ is full. */
197 bool isFull() { return lqFull() || sqFull(); }
198
199 /** Returns if both the LQ and SQ are empty. */
200 bool isEmpty() const { return lqEmpty() && sqEmpty(); }
201
202 /** Returns if the LQ is full. */
203 bool lqFull() { return loads >= (LQEntries - 1); }
204
205 /** Returns if the SQ is full. */
206 bool sqFull() { return stores >= (SQEntries - 1); }
207
208 /** Returns if the LQ is empty. */
209 bool lqEmpty() const { return loads == 0; }
210
211 /** Returns if the SQ is empty. */
212 bool sqEmpty() const { return stores == 0; }
213
214 /** Returns the number of instructions in the LSQ. */
215 unsigned getCount() { return loads + stores; }
216
217 /** Returns if there are any stores to writeback. */
218 bool hasStoresToWB() { return storesToWB; }
219
220 /** Returns the number of stores to writeback. */
221 int numStoresToWB() { return storesToWB; }
222
223 /** Returns if the LSQ unit will writeback on this cycle. */
224 bool willWB() { return storeQueue[storeWBIdx].canWB &&
225 !storeQueue[storeWBIdx].completed &&
226 !isStoreBlocked; }
227
228 /** Handles doing the retry. */
229 void recvRetry();
230
231 private:
232 /** Reset the LSQ state */
233 void resetState();
234
235 /** Writes back the instruction, sending it to IEW. */
236 void writeback(DynInstPtr &inst, PacketPtr pkt);
237
238 /** Writes back a store that couldn't be completed the previous cycle. */
239 void writebackPendingStore();
240
241 /** Handles completing the send of a store to memory. */
242 void storePostSend(PacketPtr pkt);
243
244 /** Completes the store at the specified index. */
245 void completeStore(int store_idx);
246
247 /** Attempts to send a store to the cache. */
248 bool sendStore(PacketPtr data_pkt);
249
250 /** Increments the given store index (circular queue). */
251 inline void incrStIdx(int &store_idx) const;
252 /** Decrements the given store index (circular queue). */
253 inline void decrStIdx(int &store_idx) const;
254 /** Increments the given load index (circular queue). */
255 inline void incrLdIdx(int &load_idx) const;
256 /** Decrements the given load index (circular queue). */
257 inline void decrLdIdx(int &load_idx) const;
258
259 public:
260 /** Debugging function to dump instructions in the LSQ. */
261 void dumpInsts() const;
262
263 private:
264 /** Pointer to the CPU. */
265 O3CPU *cpu;
266
267 /** Pointer to the IEW stage. */
268 IEW *iewStage;
269
270 /** Pointer to the LSQ. */
271 LSQ *lsq;
272
273 /** Pointer to the dcache port. Used only for sending. */
274 MasterPort *dcachePort;
275
276 /** Derived class to hold any sender state the LSQ needs. */
277 class LSQSenderState : public Packet::SenderState
278 {
279 public:
280 /** Default constructor. */
281 LSQSenderState()
282 : mainPkt(NULL), pendingPacket(NULL), idx(0), outstanding(1),
283 isLoad(false), noWB(false), isSplit(false),
284 pktToSend(false), cacheBlocked(false)
285 { }
286
287 /** Instruction who initiated the access to memory. */
288 DynInstPtr inst;
289 /** The main packet from a split load, used during writeback. */
290 PacketPtr mainPkt;
291 /** A second packet from a split store that needs sending. */
292 PacketPtr pendingPacket;
293 /** The LQ/SQ index of the instruction. */
294 uint8_t idx;
295 /** Number of outstanding packets to complete. */
296 uint8_t outstanding;
297 /** Whether or not it is a load. */
298 bool isLoad;
299 /** Whether or not the instruction will need to writeback. */
300 bool noWB;
301 /** Whether or not this access is split in two. */
302 bool isSplit;
303 /** Whether or not there is a packet that needs sending. */
304 bool pktToSend;
305 /** Whether or not the second packet of this split load was blocked */
306 bool cacheBlocked;
307
308 /** Completes a packet and returns whether the access is finished. */
309 inline bool complete() { return --outstanding == 0; }
310 };
311
312 /** Writeback event, specifically for when stores forward data to loads. */
313 class WritebackEvent : public Event {
314 public:
315 /** Constructs a writeback event. */
316 WritebackEvent(DynInstPtr &_inst, PacketPtr pkt, LSQUnit *lsq_ptr);
317
318 /** Processes the writeback event. */
319 void process();
320
321 /** Returns the description of this event. */
322 const char *description() const;
323
324 private:
325 /** Instruction whose results are being written back. */
326 DynInstPtr inst;
327
328 /** The packet that would have been sent to memory. */
329 PacketPtr pkt;
330
331 /** The pointer to the LSQ unit that issued the store. */
332 LSQUnit<Impl> *lsqPtr;
333 };
334
335 public:
336 struct SQEntry {
337 /** Constructs an empty store queue entry. */
338 SQEntry()
339 : inst(NULL), req(NULL), size(0),
340 canWB(0), committed(0), completed(0)
341 {
342 std::memset(data, 0, sizeof(data));
343 }
344
345 ~SQEntry()
346 {
347 inst = NULL;
348 }
349
350 /** Constructs a store queue entry for a given instruction. */
351 SQEntry(DynInstPtr &_inst)
352 : inst(_inst), req(NULL), sreqLow(NULL), sreqHigh(NULL), size(0),
353 isSplit(0), canWB(0), committed(0), completed(0), isAllZeros(0)
354 {
355 std::memset(data, 0, sizeof(data));
356 }
357 /** The store data. */
358 char data[16];
359 /** The store instruction. */
360 DynInstPtr inst;
361 /** The request for the store. */
362 RequestPtr req;
363 /** The split requests for the store. */
364 RequestPtr sreqLow;
365 RequestPtr sreqHigh;
366 /** The size of the store. */
367 uint8_t size;
368 /** Whether or not the store is split into two requests. */
369 bool isSplit;
370 /** Whether or not the store can writeback. */
371 bool canWB;
372 /** Whether or not the store is committed. */
373 bool committed;
374 /** Whether or not the store is completed. */
375 bool completed;
376 /** Does this request write all zeros and thus doesn't
377 * have any data attached to it. Used for cache block zero
378 * style instructs (ARM DC ZVA; ALPHA WH64)
379 */
380 bool isAllZeros;
381 };
382
383 private:
384 /** The LSQUnit thread id. */
385 ThreadID lsqID;
386
387 /** The store queue. */
388 std::vector<SQEntry> storeQueue;
389
390 /** The load queue. */
391 std::vector<DynInstPtr> loadQueue;
392
393 /** The number of LQ entries, plus a sentinel entry (circular queue).
394 * @todo: Consider having var that records the true number of LQ entries.
395 */
396 unsigned LQEntries;
397 /** The number of SQ entries, plus a sentinel entry (circular queue).
398 * @todo: Consider having var that records the true number of SQ entries.
399 */
400 unsigned SQEntries;
401
402 /** The number of places to shift addresses in the LSQ before checking
403 * for dependency violations
404 */
405 unsigned depCheckShift;
406
407 /** Should loads be checked for dependency issues */
408 bool checkLoads;
409
410 /** The number of load instructions in the LQ. */
411 int loads;
412 /** The number of store instructions in the SQ. */
413 int stores;
414 /** The number of store instructions in the SQ waiting to writeback. */
415 int storesToWB;
416
417 /** The index of the head instruction in the LQ. */
418 int loadHead;
419 /** The index of the tail instruction in the LQ. */
420 int loadTail;
421
422 /** The index of the head instruction in the SQ. */
423 int storeHead;
424 /** The index of the first instruction that may be ready to be
425 * written back, and has not yet been written back.
426 */
427 int storeWBIdx;
428 /** The index of the tail instruction in the SQ. */
429 int storeTail;
430
431 /// @todo Consider moving to a more advanced model with write vs read ports
432 /** The number of cache ports available each cycle. */
433 int cachePorts;
434
435 /** The number of used cache ports in this cycle. */
436 int usedPorts;
437
438 //list<InstSeqNum> mshrSeqNums;
439
440 /** Address Mask for a cache block (e.g. ~(cache_block_size-1)) */
441 Addr cacheBlockMask;
442
443 /** Wire to read information from the issue stage time queue. */
444 typename TimeBuffer<IssueStruct>::wire fromIssue;
445
446 /** Whether or not the LSQ is stalled. */
447 bool stalled;
448 /** The store that causes the stall due to partial store to load
449 * forwarding.
450 */
451 InstSeqNum stallingStoreIsn;
452 /** The index of the above store. */
453 int stallingLoadIdx;
454
455 /** The packet that needs to be retried. */
456 PacketPtr retryPkt;
457
458 /** Whehter or not a store is blocked due to the memory system. */
459 bool isStoreBlocked;
460
461 /** Whether or not a store is in flight. */
462 bool storeInFlight;
463
464 /** The oldest load that caused a memory ordering violation. */
465 DynInstPtr memDepViolator;
466
467 /** Whether or not there is a packet that couldn't be sent because of
468 * a lack of cache ports. */
469 bool hasPendingPkt;
470
471 /** The packet that is pending free cache ports. */
472 PacketPtr pendingPkt;
473
474 /** Flag for memory model. */
475 bool needsTSO;
476
477 // Will also need how many read/write ports the Dcache has. Or keep track
478 // of that in stage that is one level up, and only call executeLoad/Store
479 // the appropriate number of times.
480 /** Total number of loads forwaded from LSQ stores. */
481 Stats::Scalar lsqForwLoads;
482
483 /** Total number of loads ignored due to invalid addresses. */
484 Stats::Scalar invAddrLoads;
485
486 /** Total number of squashed loads. */
487 Stats::Scalar lsqSquashedLoads;
488
489 /** Total number of responses from the memory system that are
490 * ignored due to the instruction already being squashed. */
491 Stats::Scalar lsqIgnoredResponses;
492
493 /** Tota number of memory ordering violations. */
494 Stats::Scalar lsqMemOrderViolation;
495
496 /** Total number of squashed stores. */
497 Stats::Scalar lsqSquashedStores;
498
499 /** Total number of software prefetches ignored due to invalid addresses. */
500 Stats::Scalar invAddrSwpfs;
501
502 /** Ready loads blocked due to partial store-forwarding. */
503 Stats::Scalar lsqBlockedLoads;
504
505 /** Number of loads that were rescheduled. */
506 Stats::Scalar lsqRescheduledLoads;
507
508 /** Number of times the LSQ is blocked due to the cache. */
509 Stats::Scalar lsqCacheBlocked;
510
511 public:
512 /** Executes the load at the given index. */
513 Fault read(Request *req, Request *sreqLow, Request *sreqHigh,
514 uint8_t *data, int load_idx);
515
516 /** Executes the store at the given index. */
517 Fault write(Request *req, Request *sreqLow, Request *sreqHigh,
518 uint8_t *data, int store_idx);
519
520 /** Returns the index of the head load instruction. */
521 int getLoadHead() { return loadHead; }
522 /** Returns the sequence number of the head load instruction. */
523 InstSeqNum getLoadHeadSeqNum()
524 {
525 if (loadQueue[loadHead]) {
526 return loadQueue[loadHead]->seqNum;
527 } else {
528 return 0;
529 }
530
531 }
532
533 /** Returns the index of the head store instruction. */
534 int getStoreHead() { return storeHead; }
535 /** Returns the sequence number of the head store instruction. */
536 InstSeqNum getStoreHeadSeqNum()
537 {
538 if (storeQueue[storeHead].inst) {
539 return storeQueue[storeHead].inst->seqNum;
540 } else {
541 return 0;
542 }
543
544 }
545
546 /** Returns whether or not the LSQ unit is stalled. */
547 bool isStalled() { return stalled; }
548};
549
550template <class Impl>
551Fault
552LSQUnit<Impl>::read(Request *req, Request *sreqLow, Request *sreqHigh,
553 uint8_t *data, int load_idx)
554{
555 DynInstPtr load_inst = loadQueue[load_idx];
556
557 assert(load_inst);
558
559 assert(!load_inst->isExecuted());
560
561 // Make sure this isn't a strictly ordered load
562 // A bit of a hackish way to get strictly ordered accesses to work
563 // only if they're at the head of the LSQ and are ready to commit
564 // (at the head of the ROB too).
565 if (req->isStrictlyOrdered() &&
566 (load_idx != loadHead || !load_inst->isAtCommit())) {
567 iewStage->rescheduleMemInst(load_inst);
568 ++lsqRescheduledLoads;
569 DPRINTF(LSQUnit, "Strictly ordered load [sn:%lli] PC %s\n",
570 load_inst->seqNum, load_inst->pcState());
571
572 // Must delete request now that it wasn't handed off to
573 // memory. This is quite ugly. @todo: Figure out the proper
574 // place to really handle request deletes.
575 delete req;
576 if (TheISA::HasUnalignedMemAcc && sreqLow) {
577 delete sreqLow;
578 delete sreqHigh;
579 }
580 return std::make_shared<GenericISA::M5PanicFault>(
581 "Strictly ordered load [sn:%llx] PC %s\n",
582 load_inst->seqNum, load_inst->pcState());
583 }
584
585 // Check the SQ for any previous stores that might lead to forwarding
586 int store_idx = load_inst->sqIdx;
587
588 int store_size = 0;
589
590 DPRINTF(LSQUnit, "Read called, load idx: %i, store idx: %i, "
591 "storeHead: %i addr: %#x%s\n",
592 load_idx, store_idx, storeHead, req->getPaddr(),
593 sreqLow ? " split" : "");
594
595 if (req->isLLSC()) {
596 assert(!sreqLow);
597 // Disable recording the result temporarily. Writing to misc
598 // regs normally updates the result, but this is not the
599 // desired behavior when handling store conditionals.
600 load_inst->recordResult(false);
601 TheISA::handleLockedRead(load_inst.get(), req);
602 load_inst->recordResult(true);
603 }
604
605 if (req->isMmappedIpr()) {
606 assert(!load_inst->memData);
607 load_inst->memData = new uint8_t[64];
608
609 ThreadContext *thread = cpu->tcBase(lsqID);
610 Cycles delay(0);
611 PacketPtr data_pkt = new Packet(req, MemCmd::ReadReq);
612
613 if (!TheISA::HasUnalignedMemAcc || !sreqLow) {
614 data_pkt->dataStatic(load_inst->memData);
615 delay = TheISA::handleIprRead(thread, data_pkt);
616 } else {
617 assert(sreqLow->isMmappedIpr() && sreqHigh->isMmappedIpr());
618 PacketPtr fst_data_pkt = new Packet(sreqLow, MemCmd::ReadReq);
619 PacketPtr snd_data_pkt = new Packet(sreqHigh, MemCmd::ReadReq);
620
621 fst_data_pkt->dataStatic(load_inst->memData);
622 snd_data_pkt->dataStatic(load_inst->memData + sreqLow->getSize());
623
624 delay = TheISA::handleIprRead(thread, fst_data_pkt);
625 Cycles delay2 = TheISA::handleIprRead(thread, snd_data_pkt);
626 if (delay2 > delay)
627 delay = delay2;
628
629 delete sreqLow;
630 delete sreqHigh;
631 delete fst_data_pkt;
632 delete snd_data_pkt;
633 }
634 WritebackEvent *wb = new WritebackEvent(load_inst, data_pkt, this);
635 cpu->schedule(wb, cpu->clockEdge(delay));
636 return NoFault;
637 }
638
639 while (store_idx != -1) {
640 // End once we've reached the top of the LSQ
641 if (store_idx == storeWBIdx) {
642 break;
643 }
644
645 // Move the index to one younger
646 if (--store_idx < 0)
647 store_idx += SQEntries;
648
649 assert(storeQueue[store_idx].inst);
650
651 store_size = storeQueue[store_idx].size;
652
653 if (store_size == 0)
654 continue;
655 else if (storeQueue[store_idx].inst->strictlyOrdered())
656 continue;
657
658 assert(storeQueue[store_idx].inst->effAddrValid());
659
660 // Check if the store data is within the lower and upper bounds of
661 // addresses that the request needs.
662 bool store_has_lower_limit =
663 req->getVaddr() >= storeQueue[store_idx].inst->effAddr;
664 bool store_has_upper_limit =
665 (req->getVaddr() + req->getSize()) <=
666 (storeQueue[store_idx].inst->effAddr + store_size);
667 bool lower_load_has_store_part =
668 req->getVaddr() < (storeQueue[store_idx].inst->effAddr +
669 store_size);
670 bool upper_load_has_store_part =
671 (req->getVaddr() + req->getSize()) >
672 storeQueue[store_idx].inst->effAddr;
673
674 // If the store's data has all of the data needed, we can forward.
675 if ((store_has_lower_limit && store_has_upper_limit)) {
676 // Get shift amount for offset into the store's data.
677 int shift_amt = req->getVaddr() - storeQueue[store_idx].inst->effAddr;
678
679 if (storeQueue[store_idx].isAllZeros)
680 memset(data, 0, req->getSize());
681 else
682 memcpy(data, storeQueue[store_idx].data + shift_amt,
683 req->getSize());
684
685 // Allocate memory if this is the first time a load is issued.
686 if (!load_inst->memData) {
687 load_inst->memData = new uint8_t[req->getSize()];
688 }
689 if (storeQueue[store_idx].isAllZeros)
690 memset(load_inst->memData, 0, req->getSize());
691 else
692 memcpy(load_inst->memData,
693 storeQueue[store_idx].data + shift_amt, req->getSize());
694
695 DPRINTF(LSQUnit, "Forwarding from store idx %i to load to "
696 "addr %#x\n", store_idx, req->getVaddr());
697
698 PacketPtr data_pkt = new Packet(req, MemCmd::ReadReq);
699 data_pkt->dataStatic(load_inst->memData);
700
701 WritebackEvent *wb = new WritebackEvent(load_inst, data_pkt, this);
702
703 // We'll say this has a 1 cycle load-store forwarding latency
704 // for now.
705 // @todo: Need to make this a parameter.
706 cpu->schedule(wb, curTick());
707
708 // Don't need to do anything special for split loads.
709 if (TheISA::HasUnalignedMemAcc && sreqLow) {
710 delete sreqLow;
711 delete sreqHigh;
712 }
713
714 ++lsqForwLoads;
715 return NoFault;
716 } else if ((store_has_lower_limit && lower_load_has_store_part) ||
717 (store_has_upper_limit && upper_load_has_store_part) ||
718 (lower_load_has_store_part && upper_load_has_store_part)) {
719 // This is the partial store-load forwarding case where a store
720 // has only part of the load's data.
721
722 // If it's already been written back, then don't worry about
723 // stalling on it.
724 if (storeQueue[store_idx].completed) {
725 panic("Should not check one of these");
726 continue;
727 }
728
729 // Must stall load and force it to retry, so long as it's the oldest
730 // load that needs to do so.
731 if (!stalled ||
732 (stalled &&
733 load_inst->seqNum <
734 loadQueue[stallingLoadIdx]->seqNum)) {
735 stalled = true;
736 stallingStoreIsn = storeQueue[store_idx].inst->seqNum;
737 stallingLoadIdx = load_idx;
738 }
739
740 // Tell IQ/mem dep unit that this instruction will need to be
741 // rescheduled eventually
742 iewStage->rescheduleMemInst(load_inst);
743 load_inst->clearIssued();
744 ++lsqRescheduledLoads;
745
746 // Do not generate a writeback event as this instruction is not
747 // complete.
748 DPRINTF(LSQUnit, "Load-store forwarding mis-match. "
749 "Store idx %i to load addr %#x\n",
750 store_idx, req->getVaddr());
751
752 // Must delete request now that it wasn't handed off to
753 // memory. This is quite ugly. @todo: Figure out the
754 // proper place to really handle request deletes.
755 delete req;
756 if (TheISA::HasUnalignedMemAcc && sreqLow) {
757 delete sreqLow;
758 delete sreqHigh;
759 }
760
761 return NoFault;
762 }
763 }
764
765 // If there's no forwarding case, then go access memory
766 DPRINTF(LSQUnit, "Doing memory access for inst [sn:%lli] PC %s\n",
767 load_inst->seqNum, load_inst->pcState());
768
769 // Allocate memory if this is the first time a load is issued.
770 if (!load_inst->memData) {
771 load_inst->memData = new uint8_t[req->getSize()];
772 }
773
774 ++usedPorts;
775
776 // if we the cache is not blocked, do cache access
777 bool completedFirst = false;
778 PacketPtr data_pkt = Packet::createRead(req);
779 PacketPtr fst_data_pkt = NULL;
780 PacketPtr snd_data_pkt = NULL;
781
782 data_pkt->dataStatic(load_inst->memData);
783
784 LSQSenderState *state = new LSQSenderState;
785 state->isLoad = true;
786 state->idx = load_idx;
787 state->inst = load_inst;
788 data_pkt->senderState = state;
789
790 if (!TheISA::HasUnalignedMemAcc || !sreqLow) {
791 // Point the first packet at the main data packet.
792 fst_data_pkt = data_pkt;
793 } else {
794 // Create the split packets.
795 fst_data_pkt = Packet::createRead(sreqLow);
796 snd_data_pkt = Packet::createRead(sreqHigh);
797
798 fst_data_pkt->dataStatic(load_inst->memData);
799 snd_data_pkt->dataStatic(load_inst->memData + sreqLow->getSize());
800
801 fst_data_pkt->senderState = state;
802 snd_data_pkt->senderState = state;
803
804 state->isSplit = true;
805 state->outstanding = 2;
806 state->mainPkt = data_pkt;
807 }
808
809 bool successful_load = true;
810 if (!dcachePort->sendTimingReq(fst_data_pkt)) {
811 successful_load = false;
812 } else if (TheISA::HasUnalignedMemAcc && sreqLow) {
813 completedFirst = true;
814
815 // The first packet was sent without problems, so send this one
816 // too. If there is a problem with this packet then the whole
817 // load will be squashed, so indicate this to the state object.
818 // The first packet will return in completeDataAccess and be
819 // handled there.
820 ++usedPorts;
821 if (!dcachePort->sendTimingReq(snd_data_pkt)) {
822 // The main packet will be deleted in completeDataAccess.
823 state->complete();
824 // Signify to 1st half that the 2nd half was blocked via state
825 state->cacheBlocked = true;
826 successful_load = false;
827 }
828 }
829
830 // If the cache was blocked, or has become blocked due to the access,
831 // handle it.
832 if (!successful_load) {
833 if (!sreqLow) {
834 // Packet wasn't split, just delete main packet info
835 delete state;
836 delete req;
837 delete data_pkt;
838 }
839
840 if (TheISA::HasUnalignedMemAcc && sreqLow) {
841 if (!completedFirst) {
842 // Split packet, but first failed. Delete all state.
843 delete state;
844 delete req;
845 delete data_pkt;
846 delete fst_data_pkt;
847 delete snd_data_pkt;
848 delete sreqLow;
849 delete sreqHigh;
850 sreqLow = NULL;
851 sreqHigh = NULL;
852 } else {
853 // Can't delete main packet data or state because first packet
854 // was sent to the memory system
855 delete data_pkt;
856 delete req;
857 delete sreqHigh;
858 delete snd_data_pkt;
859 sreqHigh = NULL;
860 }
861 }
862
863 ++lsqCacheBlocked;
864
865 iewStage->blockMemInst(load_inst);
866
867 // No fault occurred, even though the interface is blocked.
868 return NoFault;
869 }
870
871 return NoFault;
872}
873
874template <class Impl>
875Fault
876LSQUnit<Impl>::write(Request *req, Request *sreqLow, Request *sreqHigh,
877 uint8_t *data, int store_idx)
878{
879 assert(storeQueue[store_idx].inst);
880
881 DPRINTF(LSQUnit, "Doing write to store idx %i, addr %#x"
882 " | storeHead:%i [sn:%i]\n",
883 store_idx, req->getPaddr(), storeHead,
884 storeQueue[store_idx].inst->seqNum);
885
886 storeQueue[store_idx].req = req;
887 storeQueue[store_idx].sreqLow = sreqLow;
888 storeQueue[store_idx].sreqHigh = sreqHigh;
889 unsigned size = req->getSize();
890 storeQueue[store_idx].size = size;
891 storeQueue[store_idx].isAllZeros = req->getFlags() & Request::CACHE_BLOCK_ZERO;
892 assert(size <= sizeof(storeQueue[store_idx].data) ||
893 (req->getFlags() & Request::CACHE_BLOCK_ZERO));
894
895 // Split stores can only occur in ISAs with unaligned memory accesses. If
896 // a store request has been split, sreqLow and sreqHigh will be non-null.
897 if (TheISA::HasUnalignedMemAcc && sreqLow) {
898 storeQueue[store_idx].isSplit = true;
899 }
900
901 if (!(req->getFlags() & Request::CACHE_BLOCK_ZERO))
902 memcpy(storeQueue[store_idx].data, data, size);
903
904 // This function only writes the data to the store queue, so no fault
905 // can happen here.
906 return NoFault;
907}
908
909#endif // __CPU_O3_LSQ_UNIT_HH__