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