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