Decoder: Remove the thread context get/set from the decoder.
[gem5.git] / src / cpu / inorder / resources / fetch_unit.cc
1 /*
2 * Copyright (c) 2011 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: Korey Sewell
29 *
30 */
31
32 #include <list>
33 #include <vector>
34
35 #include "arch/isa_traits.hh"
36 #include "arch/locked_mem.hh"
37 #include "arch/utility.hh"
38 #include "config/the_isa.hh"
39 #include "cpu/inorder/resources/cache_unit.hh"
40 #include "cpu/inorder/resources/fetch_unit.hh"
41 #include "cpu/inorder/cpu.hh"
42 #include "cpu/inorder/pipeline_traits.hh"
43 #include "cpu/inorder/resource_pool.hh"
44 #include "debug/Activity.hh"
45 #include "debug/InOrderCachePort.hh"
46 #include "debug/InOrderStall.hh"
47 #include "debug/RefCount.hh"
48 #include "debug/ThreadModel.hh"
49 #include "mem/request.hh"
50
51 using namespace std;
52 using namespace TheISA;
53 using namespace ThePipeline;
54
55 FetchUnit::FetchUnit(string res_name, int res_id, int res_width,
56 Cycles res_latency, InOrderCPU *_cpu,
57 ThePipeline::Params *params)
58 : CacheUnit(res_name, res_id, res_width, res_latency, _cpu, params),
59 instSize(sizeof(TheISA::MachInst)), fetchBuffSize(params->fetchBuffSize)
60 {
61 for (int tid = 0; tid < MaxThreads; tid++)
62 decoder[tid] = new Decoder;
63 }
64
65 FetchUnit::~FetchUnit()
66 {
67 std::list<FetchBlock*>::iterator fetch_it = fetchBuffer.begin();
68 std::list<FetchBlock*>::iterator end_it = fetchBuffer.end();
69 while (fetch_it != end_it) {
70 delete (*fetch_it)->block;
71 delete *fetch_it;
72 fetch_it++;
73 }
74 fetchBuffer.clear();
75
76
77 std::list<FetchBlock*>::iterator pend_it = pendingFetch.begin();
78 std::list<FetchBlock*>::iterator pend_end = pendingFetch.end();
79 while (pend_it != pend_end) {
80 if ((*pend_it)->block) {
81 delete (*pend_it)->block;
82 }
83
84 delete *pend_it;
85 pend_it++;
86 }
87 pendingFetch.clear();
88 }
89
90 void
91 FetchUnit::createMachInst(std::list<FetchBlock*>::iterator fetch_it,
92 DynInstPtr inst)
93 {
94 Addr block_addr = cacheBlockAlign(inst->getMemAddr());
95 Addr fetch_addr = inst->getMemAddr();
96 unsigned fetch_offset = (fetch_addr - block_addr) / instSize;
97 ThreadID tid = inst->readTid();
98 TheISA::PCState instPC = inst->pcState();
99
100
101 DPRINTF(InOrderCachePort, "Creating instruction [sn:%i] w/fetch data @"
102 "addr:%08p block:%08p\n", inst->seqNum, fetch_addr, block_addr);
103
104 assert((*fetch_it)->valid);
105
106 TheISA::MachInst *fetchInsts =
107 reinterpret_cast<TheISA::MachInst *>((*fetch_it)->block);
108
109 MachInst mach_inst =
110 TheISA::gtoh(fetchInsts[fetch_offset]);
111
112 decoder[tid]->moreBytes(instPC, inst->instAddr(), mach_inst);
113 assert(decoder[tid]->instReady());
114 inst->setStaticInst(decoder[tid]->decode(instPC));
115 inst->pcState(instPC);
116 }
117
118 void
119 FetchUnit::removeAddrDependency(DynInstPtr inst)
120 {
121 inst->unsetMemAddr();
122 }
123
124 ResReqPtr
125 FetchUnit::getRequest(DynInstPtr inst, int stage_num, int res_idx,
126 int slot_num, unsigned cmd)
127 {
128 ScheduleEntry* sched_entry = *inst->curSkedEntry;
129 CacheRequest* cache_req = dynamic_cast<CacheRequest*>(reqs[slot_num]);
130
131 if (!inst->validMemAddr()) {
132 panic("Mem. Addr. must be set before requesting cache access\n");
133 }
134
135 assert(sched_entry->cmd == InitiateFetch);
136
137 DPRINTF(InOrderCachePort,
138 "[tid:%i]: Fetch request from [sn:%i] for addr %08p\n",
139 inst->readTid(), inst->seqNum, inst->getMemAddr());
140
141 cache_req->setRequest(inst, stage_num, id, slot_num,
142 sched_entry->cmd, MemCmd::ReadReq,
143 inst->curSkedEntry->idx);
144
145 return cache_req;
146 }
147
148 void
149 FetchUnit::setupMemRequest(DynInstPtr inst, CacheReqPtr cache_req,
150 int acc_size, int flags)
151 {
152 ThreadID tid = inst->readTid();
153 Addr aligned_addr = cacheBlockAlign(inst->getMemAddr());
154 if (cache_req->memReq == NULL) {
155 cache_req->memReq =
156 new Request(tid, aligned_addr, acc_size, flags,
157 cpu->instMasterId(), inst->instAddr(), cpu->readCpuId(),
158 tid);
159 DPRINTF(InOrderCachePort, "[sn:%i] Created memReq @%x, ->%x\n",
160 inst->seqNum, &cache_req->memReq, cache_req->memReq);
161 }
162 }
163
164 std::list<FetchUnit::FetchBlock*>::iterator
165 FetchUnit::findBlock(std::list<FetchBlock*> &fetch_blocks, int asid,
166 Addr block_addr)
167 {
168 std::list<FetchBlock*>::iterator fetch_it = fetch_blocks.begin();
169 std::list<FetchBlock*>::iterator end_it = fetch_blocks.end();
170
171 while (fetch_it != end_it) {
172 if ((*fetch_it)->asid == asid &&
173 (*fetch_it)->addr == block_addr) {
174 return fetch_it;
175 }
176
177 fetch_it++;
178 }
179
180 return fetch_it;
181 }
182
183 std::list<FetchUnit::FetchBlock*>::iterator
184 FetchUnit::findReplacementBlock()
185 {
186 std::list<FetchBlock*>::iterator fetch_it = fetchBuffer.begin();
187 std::list<FetchBlock*>::iterator end_it = fetchBuffer.end();
188
189 while (fetch_it != end_it) {
190 if ((*fetch_it)->cnt == 0) {
191 return fetch_it;
192 } else {
193 DPRINTF(InOrderCachePort, "Block %08p has %i insts pending.\n",
194 (*fetch_it)->addr, (*fetch_it)->cnt);
195 }
196 fetch_it++;
197 }
198
199 return fetch_it;
200 }
201
202 void
203 FetchUnit::markBlockUsed(std::list<FetchBlock*>::iterator block_it)
204 {
205 // Move block from whatever location it is in fetch buffer
206 // to the back (represents most-recently-used location)
207 if (block_it != fetchBuffer.end()) {
208 FetchBlock *mru_blk = *block_it;
209 fetchBuffer.erase(block_it);
210 fetchBuffer.push_back(mru_blk);
211 }
212 }
213
214 int
215 FetchUnit::blocksInUse()
216 {
217 std::list<FetchBlock*>::iterator fetch_it = fetchBuffer.begin();
218 std::list<FetchBlock*>::iterator end_it = fetchBuffer.end();
219
220 int cnt = 0;
221 while (fetch_it != end_it) {
222 if ((*fetch_it)->cnt > 0)
223 cnt++;
224
225 fetch_it++;
226 }
227
228 return cnt;
229 }
230
231 void
232 FetchUnit::clearFetchBuffer()
233 {
234 std::list<FetchBlock*>::iterator fetch_it = fetchBuffer.begin();
235 std::list<FetchBlock*>::iterator end_it = fetchBuffer.end();
236
237 while (fetch_it != end_it) {
238 if ((*fetch_it)->block) {
239 delete [] (*fetch_it)->block;
240 }
241 delete *fetch_it;
242 fetch_it++;
243 }
244 fetchBuffer.clear();
245 }
246
247 void
248 FetchUnit::execute(int slot_num)
249 {
250 CacheReqPtr cache_req = dynamic_cast<CacheReqPtr>(reqs[slot_num]);
251 assert(cache_req);
252
253 if (cachePortBlocked && cache_req->cmd == InitiateFetch) {
254 DPRINTF(InOrderCachePort, "Cache Port Blocked. Cannot Access\n");
255 cache_req->done(false);
256 return;
257 }
258
259 DynInstPtr inst = cache_req->inst;
260 ThreadID tid = inst->readTid();
261 Addr block_addr = cacheBlockAlign(inst->getMemAddr());
262 int asid = cpu->asid[tid];
263
264 if (inst->fault != NoFault) {
265 DPRINTF(InOrderCachePort,
266 "[tid:%i]: [sn:%i]: Detected %s fault @ %x. Forwarding to "
267 "next stage.\n", tid, inst->seqNum, inst->fault->name(),
268 cacheBlockAlign(inst->getMemAddr()));
269 finishCacheUnitReq(inst, cache_req);
270 return;
271 }
272
273 switch (cache_req->cmd)
274 {
275 case InitiateFetch:
276 {
277 // Check to see if we've already got this request buffered
278 // or pending to be buffered
279 bool do_fetch = true;
280 int total_pending = pendingFetch.size() + blocksInUse();
281
282 std::list<FetchBlock*>::iterator pending_it;
283 pending_it = findBlock(pendingFetch, asid, block_addr);
284 if (pending_it != pendingFetch.end()) {
285 (*pending_it)->cnt++;
286 do_fetch = false;
287
288 DPRINTF(InOrderCachePort, "%08p is a pending fetch block "
289 "(pending:%i).\n", block_addr,
290 (*pending_it)->cnt);
291 } else if (total_pending < fetchBuffSize) {
292 std::list<FetchBlock*>::iterator buff_it;
293 buff_it = findBlock(fetchBuffer, asid, block_addr);
294 if (buff_it != fetchBuffer.end()) {
295 (*buff_it)->cnt++;
296 do_fetch = false;
297
298 DPRINTF(InOrderCachePort, "%08p is in fetch buffer "
299 "(pending:%i).\n", block_addr, (*buff_it)->cnt);
300 }
301 }
302
303 if (!do_fetch) {
304 DPRINTF(InOrderCachePort, "Inst. [sn:%i] marked to be filled "
305 "through fetch buffer.\n", inst->seqNum);
306 cache_req->fetchBufferFill = true;
307 cache_req->setCompleted(true);
308 return;
309 }
310
311 // Check to see if there is room in the fetchbuffer for this instruction.
312 // If not, block this request.
313 if (total_pending >= fetchBuffSize) {
314 DPRINTF(InOrderCachePort, "No room available in fetch buffer.\n");
315 cache_req->done(false);
316 return;
317 }
318
319 doTLBAccess(inst, cache_req, cacheBlkSize, Request::INST_FETCH, TheISA::TLB::Execute);
320
321 if (inst->fault == NoFault) {
322 DPRINTF(InOrderCachePort,
323 "[tid:%u]: Initiating fetch access to %s for "
324 "addr:%#x (block:%#x)\n", tid, name(),
325 cache_req->inst->getMemAddr(), block_addr);
326
327 cache_req->reqData = new uint8_t[cacheBlkSize];
328
329 inst->setCurResSlot(slot_num);
330
331 doCacheAccess(inst);
332
333 if (cache_req->isMemAccPending()) {
334 pendingFetch.push_back(new FetchBlock(asid, block_addr));
335
336 // mark replacement block
337 }
338 }
339
340 break;
341 }
342
343 case CompleteFetch:
344 if (inst->fault != NoFault) {
345 DPRINTF(InOrderCachePort,
346 "[tid:%i]: [sn:%i]: Detected %s fault @ %x. Forwarding to "
347 "next stage.\n", tid, inst->seqNum, inst->fault->name(),
348 inst->getMemAddr());
349 finishCacheUnitReq(inst, cache_req);
350 return;
351 }
352
353 if (cache_req->fetchBufferFill) {
354 // Block request if it's depending on a previous fetch, but it hasnt made it yet
355 std::list<FetchBlock*>::iterator fetch_it = findBlock(fetchBuffer, asid, block_addr);
356 if (fetch_it == fetchBuffer.end()) {
357 DPRINTF(InOrderCachePort, "%#x not available yet\n",
358 block_addr);
359 cache_req->setCompleted(false);
360 return;
361 }
362
363 // Make New Instruction
364 createMachInst(fetch_it, inst);
365 if (inst->traceData) {
366 inst->traceData->setStaticInst(inst->staticInst);
367 inst->traceData->setPC(inst->pcState());
368 }
369
370 // FetchBuffer Book-Keeping
371 (*fetch_it)->cnt--;
372 assert((*fetch_it)->cnt >= 0);
373 markBlockUsed(fetch_it);
374
375 cache_req->done();
376 return;
377 }
378
379 if (cache_req->isMemAccComplete()) {
380 if (fetchBuffer.size() >= fetchBuffSize) {
381 // If there is no replacement block, then we'll just have
382 // to wait till that gets cleared before satisfying the fetch
383 // for this instruction
384 std::list<FetchBlock*>::iterator repl_it =
385 findReplacementBlock();
386 if (repl_it == fetchBuffer.end()) {
387 DPRINTF(InOrderCachePort, "Unable to find replacement block"
388 " and complete fetch.\n");
389 cache_req->setCompleted(false);
390 return;
391 }
392
393 delete [] (*repl_it)->block;
394 delete *repl_it;
395 fetchBuffer.erase(repl_it);
396 }
397
398 DPRINTF(InOrderCachePort,
399 "[tid:%i]: Completing Fetch Access for [sn:%i]\n",
400 tid, inst->seqNum);
401
402 // Make New Instruction
403 std::list<FetchBlock*>::iterator fetch_it =
404 findBlock(pendingFetch, asid, block_addr);
405
406 assert(fetch_it != pendingFetch.end());
407 assert((*fetch_it)->valid);
408
409 createMachInst(fetch_it, inst);
410 if (inst->traceData) {
411 inst->traceData->setStaticInst(inst->staticInst);
412 inst->traceData->setPC(inst->pcState());
413 }
414
415
416 // Update instructions waiting on new fetch block
417 FetchBlock *new_block = (*fetch_it);
418 new_block->cnt--;
419 assert(new_block->cnt >= 0);
420
421 // Finally, update FetchBuffer w/Pending Block into the
422 // MRU location
423 pendingFetch.erase(fetch_it);
424 fetchBuffer.push_back(new_block);
425
426 DPRINTF(InOrderCachePort, "[tid:%i]: Instruction [sn:%i] is: %s\n",
427 tid, inst->seqNum,
428 inst->staticInst->disassemble(inst->instAddr()));
429
430 inst->unsetMemAddr();
431
432 cache_req->done();
433 } else {
434 DPRINTF(InOrderCachePort,
435 "[tid:%i]: [sn:%i]: Unable to Complete Fetch Access\n",
436 tid, inst->seqNum);
437 DPRINTF(InOrderStall,
438 "STALL: [tid:%i]: Fetch miss from %08p\n",
439 tid, cache_req->inst->instAddr());
440 cache_req->setCompleted(false);
441 // NOTE: For SwitchOnCacheMiss ThreadModel, we *don't* switch on
442 // fetch miss, but we could ...
443 // cache_req->setMemStall(true);
444 }
445 break;
446
447 default:
448 fatal("Unrecognized command to %s", resName);
449 }
450 }
451
452 void
453 FetchUnit::processCacheCompletion(PacketPtr pkt)
454 {
455 // Cast to correct packet type
456 // @todo: use pkt Sender state here to be consistent with other
457 // cpu models
458 CacheReqPacket* cache_pkt = dynamic_cast<CacheReqPacket*>(pkt);
459 assert(cache_pkt);
460
461 DPRINTF(InOrderCachePort, "Finished request for %x\n",
462 cache_pkt->getAddr());
463
464 if (processSquash(cache_pkt))
465 return;
466
467 Addr block_addr = cacheBlockAlign(cache_pkt->cacheReq->
468 getInst()->getMemAddr());
469
470 DPRINTF(InOrderCachePort,
471 "[tid:%u]: [sn:%i]: Waking from fetch access to addr:%#x(phys:%#x), size:%i\n",
472 cache_pkt->cacheReq->getInst()->readTid(),
473 cache_pkt->cacheReq->getInst()->seqNum,
474 block_addr, cache_pkt->getAddr(), cache_pkt->getSize());
475
476 // Cast to correct request type
477 CacheRequest *cache_req = dynamic_cast<CacheReqPtr>(
478 findRequest(cache_pkt->cacheReq->getInst(), cache_pkt->instIdx));
479
480 if (!cache_req) {
481 panic("[tid:%u]: [sn:%i]: Can't find slot for fetch access to "
482 "addr. %08p\n", cache_pkt->cacheReq->getInst()->readTid(),
483 cache_pkt->cacheReq->getInst()->seqNum,
484 block_addr);
485 }
486
487 // Get resource request info
488 unsigned stage_num = cache_req->getStageNum();
489 DynInstPtr inst = cache_req->inst;
490 ThreadID tid = cache_req->inst->readTid();
491 short asid = cpu->asid[tid];
492
493 assert(!cache_req->isSquashed());
494 assert(inst->curSkedEntry->cmd == CompleteFetch);
495
496 DPRINTF(InOrderCachePort,
497 "[tid:%u]: [sn:%i]: Processing fetch access for block %#x\n",
498 tid, inst->seqNum, block_addr);
499
500 std::list<FetchBlock*>::iterator pend_it = findBlock(pendingFetch, asid,
501 block_addr);
502 assert(pend_it != pendingFetch.end());
503
504 // Copy Data to pendingFetch queue...
505 (*pend_it)->block = new uint8_t[cacheBlkSize];
506 memcpy((*pend_it)->block, cache_pkt->getPtr<uint8_t>(), cacheBlkSize);
507 (*pend_it)->valid = true;
508
509 cache_req->setMemAccPending(false);
510 cache_req->setMemAccCompleted();
511
512 if (cache_req->isMemStall() &&
513 cpu->threadModel == InOrderCPU::SwitchOnCacheMiss) {
514 DPRINTF(InOrderCachePort, "[tid:%u] Waking up from Cache Miss.\n",
515 tid);
516
517 cpu->activateContext(tid);
518
519 DPRINTF(ThreadModel, "Activating [tid:%i] after return from cache"
520 "miss.\n", tid);
521 }
522
523 // Wake up the CPU (if it went to sleep and was waiting on this
524 // completion event).
525 cpu->wakeCPU();
526
527 DPRINTF(Activity, "[tid:%u] Activating %s due to cache completion\n",
528 tid, cpu->pipelineStage[stage_num]->name());
529
530 cpu->switchToActive(stage_num);
531 }
532
533 void
534 FetchUnit::squashCacheRequest(CacheReqPtr req_ptr)
535 {
536 DynInstPtr inst = req_ptr->getInst();
537 ThreadID tid = inst->readTid();
538 Addr block_addr = cacheBlockAlign(inst->getMemAddr());
539 int asid = cpu->asid[tid];
540
541 // Check Fetch Buffer (or pending fetch) for this block and
542 // update pending counts
543 std::list<FetchBlock*>::iterator buff_it = findBlock(fetchBuffer,
544 asid,
545 block_addr);
546 if (buff_it != fetchBuffer.end()) {
547 (*buff_it)->cnt--;
548 DPRINTF(InOrderCachePort, "[sn:%i] Removing Pending Access "
549 "for Fetch Buffer block %08p (cnt=%i)\n", inst->seqNum,
550 block_addr, (*buff_it)->cnt);
551 assert((*buff_it)->cnt >= 0);
552 } else {
553 std::list<FetchBlock*>::iterator block_it = findBlock(pendingFetch,
554 asid,
555 block_addr);
556 if (block_it != pendingFetch.end()) {
557 (*block_it)->cnt--;
558 DPRINTF(InOrderCachePort, "[sn:%i] Removing Pending Access "
559 "for Pending Buffer Block %08p (cnt=%i)\n",
560 inst->seqNum,
561 block_addr, (*block_it)->cnt);
562 assert((*block_it)->cnt >= 0);
563 if ((*block_it)->cnt == 0) {
564 if ((*block_it)->block) {
565 delete [] (*block_it)->block;
566 }
567 delete *block_it;
568 pendingFetch.erase(block_it);
569 }
570 }
571 }
572
573 CacheUnit::squashCacheRequest(req_ptr);
574 }
575
576 void
577 FetchUnit::trap(Fault fault, ThreadID tid, DynInstPtr inst)
578 {
579 //@todo: per thread?
580 decoder[tid]->reset();
581
582 //@todo: squash using dummy inst seq num
583 squash(NULL, NumStages - 1, 0, tid);
584
585 //@todo: make sure no blocks are in use
586 assert(blocksInUse() == 0);
587 assert(pendingFetch.size() == 0);
588
589 //@todo: clear pendingFetch and fetchBuffer
590 clearFetchBuffer();
591 }