cpu.cc revision 2863
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#include "config/full_system.hh"
33#include "config/use_checker.hh"
34
35#if FULL_SYSTEM
36#include "sim/system.hh"
37#else
38#include "sim/process.hh"
39#endif
40
41#include "cpu/activity.hh"
42#include "cpu/simple_thread.hh"
43#include "cpu/thread_context.hh"
44#include "cpu/o3/isa_specific.hh"
45#include "cpu/o3/cpu.hh"
46
47#include "sim/root.hh"
48#include "sim/stat_control.hh"
49
50#if USE_CHECKER
51#include "cpu/checker/cpu.hh"
52#endif
53
54using namespace std;
55using namespace TheISA;
56
57BaseO3CPU::BaseO3CPU(Params *params)
58    : BaseCPU(params), cpu_id(0)
59{
60}
61
62void
63BaseO3CPU::regStats()
64{
65    BaseCPU::regStats();
66}
67
68template <class Impl>
69FullO3CPU<Impl>::TickEvent::TickEvent(FullO3CPU<Impl> *c)
70    : Event(&mainEventQueue, CPU_Tick_Pri), cpu(c)
71{
72}
73
74template <class Impl>
75void
76FullO3CPU<Impl>::TickEvent::process()
77{
78    cpu->tick();
79}
80
81template <class Impl>
82const char *
83FullO3CPU<Impl>::TickEvent::description()
84{
85    return "FullO3CPU tick event";
86}
87
88template <class Impl>
89FullO3CPU<Impl>::ActivateThreadEvent::ActivateThreadEvent()
90    : Event(&mainEventQueue, CPU_Tick_Pri)
91{
92}
93
94template <class Impl>
95void
96FullO3CPU<Impl>::ActivateThreadEvent::init(int thread_num,
97                                           FullO3CPU<Impl> *thread_cpu)
98{
99    tid = thread_num;
100    cpu = thread_cpu;
101}
102
103template <class Impl>
104void
105FullO3CPU<Impl>::ActivateThreadEvent::process()
106{
107    cpu->activateThread(tid);
108}
109
110template <class Impl>
111const char *
112FullO3CPU<Impl>::ActivateThreadEvent::description()
113{
114    return "FullO3CPU \"Activate Thread\" event";
115}
116
117template <class Impl>
118FullO3CPU<Impl>::FullO3CPU(Params *params)
119    : BaseO3CPU(params),
120      tickEvent(this),
121      removeInstsThisCycle(false),
122      fetch(params),
123      decode(params),
124      rename(params),
125      iew(params),
126      commit(params),
127
128      regFile(params->numPhysIntRegs, params->numPhysFloatRegs),
129
130      freeList(params->numberOfThreads,
131               TheISA::NumIntRegs, params->numPhysIntRegs,
132               TheISA::NumFloatRegs, params->numPhysFloatRegs),
133
134      rob(params->numROBEntries, params->squashWidth,
135          params->smtROBPolicy, params->smtROBThreshold,
136          params->numberOfThreads),
137
138      scoreboard(params->numberOfThreads,
139                 TheISA::NumIntRegs, params->numPhysIntRegs,
140                 TheISA::NumFloatRegs, params->numPhysFloatRegs,
141                 TheISA::NumMiscRegs * number_of_threads,
142                 TheISA::ZeroReg),
143
144      // For now just have these time buffers be pretty big.
145      // @todo: Make these time buffer sizes parameters or derived
146      // from latencies
147      timeBuffer(5, 5),
148      fetchQueue(5, 5),
149      decodeQueue(5, 5),
150      renameQueue(5, 5),
151      iewQueue(5, 5),
152      activityRec(NumStages, 10, params->activity),
153
154      globalSeqNum(1),
155
156#if FULL_SYSTEM
157      system(params->system),
158      physmem(system->physmem),
159#endif // FULL_SYSTEM
160      mem(params->mem),
161      drainCount(0),
162      deferRegistration(params->deferRegistration),
163      numThreads(number_of_threads)
164{
165    _status = Idle;
166
167    checker = NULL;
168
169    if (params->checker) {
170#if USE_CHECKER
171        BaseCPU *temp_checker = params->checker;
172        checker = dynamic_cast<Checker<DynInstPtr> *>(temp_checker);
173        checker->setMemory(mem);
174#if FULL_SYSTEM
175        checker->setSystem(params->system);
176#endif
177#else
178        panic("Checker enabled but not compiled in!");
179#endif // USE_CHECKER
180    }
181
182#if !FULL_SYSTEM
183    thread.resize(number_of_threads);
184    tids.resize(number_of_threads);
185#endif
186
187    // The stages also need their CPU pointer setup.  However this
188    // must be done at the upper level CPU because they have pointers
189    // to the upper level CPU, and not this FullO3CPU.
190
191    // Set up Pointers to the activeThreads list for each stage
192    fetch.setActiveThreads(&activeThreads);
193    decode.setActiveThreads(&activeThreads);
194    rename.setActiveThreads(&activeThreads);
195    iew.setActiveThreads(&activeThreads);
196    commit.setActiveThreads(&activeThreads);
197
198    // Give each of the stages the time buffer they will use.
199    fetch.setTimeBuffer(&timeBuffer);
200    decode.setTimeBuffer(&timeBuffer);
201    rename.setTimeBuffer(&timeBuffer);
202    iew.setTimeBuffer(&timeBuffer);
203    commit.setTimeBuffer(&timeBuffer);
204
205    // Also setup each of the stages' queues.
206    fetch.setFetchQueue(&fetchQueue);
207    decode.setFetchQueue(&fetchQueue);
208    commit.setFetchQueue(&fetchQueue);
209    decode.setDecodeQueue(&decodeQueue);
210    rename.setDecodeQueue(&decodeQueue);
211    rename.setRenameQueue(&renameQueue);
212    iew.setRenameQueue(&renameQueue);
213    iew.setIEWQueue(&iewQueue);
214    commit.setIEWQueue(&iewQueue);
215    commit.setRenameQueue(&renameQueue);
216
217    commit.setFetchStage(&fetch);
218    commit.setIEWStage(&iew);
219    rename.setIEWStage(&iew);
220    rename.setCommitStage(&commit);
221
222#if !FULL_SYSTEM
223    int active_threads = params->workload.size();
224
225    if (active_threads > Impl::MaxThreads) {
226        panic("Workload Size too large. Increase the 'MaxThreads'"
227              "constant in your O3CPU impl. file (e.g. o3/alpha/impl.hh) or "
228              "edit your workload size.");
229    }
230#else
231    int active_threads = 1;
232#endif
233
234    //Make Sure That this a Valid Architeture
235    assert(params->numPhysIntRegs   >= numThreads * TheISA::NumIntRegs);
236    assert(params->numPhysFloatRegs >= numThreads * TheISA::NumFloatRegs);
237
238    rename.setScoreboard(&scoreboard);
239    iew.setScoreboard(&scoreboard);
240
241    // Setup the rename map for whichever stages need it.
242    PhysRegIndex lreg_idx = 0;
243    PhysRegIndex freg_idx = params->numPhysIntRegs; //Index to 1 after int regs
244
245    for (int tid=0; tid < numThreads; tid++) {
246        bool bindRegs = (tid <= active_threads - 1);
247
248        commitRenameMap[tid].init(TheISA::NumIntRegs,
249                                  params->numPhysIntRegs,
250                                  lreg_idx,            //Index for Logical. Regs
251
252                                  TheISA::NumFloatRegs,
253                                  params->numPhysFloatRegs,
254                                  freg_idx,            //Index for Float Regs
255
256                                  TheISA::NumMiscRegs,
257
258                                  TheISA::ZeroReg,
259                                  TheISA::ZeroReg,
260
261                                  tid,
262                                  false);
263
264        renameMap[tid].init(TheISA::NumIntRegs,
265                            params->numPhysIntRegs,
266                            lreg_idx,                  //Index for Logical. Regs
267
268                            TheISA::NumFloatRegs,
269                            params->numPhysFloatRegs,
270                            freg_idx,                  //Index for Float Regs
271
272                            TheISA::NumMiscRegs,
273
274                            TheISA::ZeroReg,
275                            TheISA::ZeroReg,
276
277                            tid,
278                            bindRegs);
279    }
280
281    rename.setRenameMap(renameMap);
282    commit.setRenameMap(commitRenameMap);
283
284    // Give renameMap & rename stage access to the freeList;
285    for (int i=0; i < numThreads; i++) {
286        renameMap[i].setFreeList(&freeList);
287    }
288    rename.setFreeList(&freeList);
289
290    // Setup the ROB for whichever stages need it.
291    commit.setROB(&rob);
292
293    lastRunningCycle = curTick;
294
295    lastActivatedCycle = -1;
296
297    contextSwitch = false;
298}
299
300template <class Impl>
301FullO3CPU<Impl>::~FullO3CPU()
302{
303}
304
305template <class Impl>
306void
307FullO3CPU<Impl>::fullCPURegStats()
308{
309    BaseO3CPU::regStats();
310
311    // Register any of the O3CPU's stats here.
312    timesIdled
313        .name(name() + ".timesIdled")
314        .desc("Number of times that the entire CPU went into an idle state and"
315              " unscheduled itself")
316        .prereq(timesIdled);
317
318    idleCycles
319        .name(name() + ".idleCycles")
320        .desc("Total number of cycles that the CPU has spent unscheduled due "
321              "to idling")
322        .prereq(idleCycles);
323
324    // Number of Instructions simulated
325    // --------------------------------
326    // Should probably be in Base CPU but need templated
327    // MaxThreads so put in here instead
328    committedInsts
329        .init(numThreads)
330        .name(name() + ".committedInsts")
331        .desc("Number of Instructions Simulated");
332
333    totalCommittedInsts
334        .name(name() + ".committedInsts_total")
335        .desc("Number of Instructions Simulated");
336
337    cpi
338        .name(name() + ".cpi")
339        .desc("CPI: Cycles Per Instruction")
340        .precision(6);
341    cpi = simTicks / committedInsts;
342
343    totalCpi
344        .name(name() + ".cpi_total")
345        .desc("CPI: Total CPI of All Threads")
346        .precision(6);
347    totalCpi = simTicks / totalCommittedInsts;
348
349    ipc
350        .name(name() + ".ipc")
351        .desc("IPC: Instructions Per Cycle")
352        .precision(6);
353    ipc =  committedInsts / simTicks;
354
355    totalIpc
356        .name(name() + ".ipc_total")
357        .desc("IPC: Total IPC of All Threads")
358        .precision(6);
359    totalIpc =  totalCommittedInsts / simTicks;
360
361}
362
363template <class Impl>
364void
365FullO3CPU<Impl>::tick()
366{
367    DPRINTF(O3CPU, "\n\nFullO3CPU: Ticking main, FullO3CPU.\n");
368
369    ++numCycles;
370
371//    activity = false;
372
373    //Tick each of the stages
374    fetch.tick();
375
376    decode.tick();
377
378    rename.tick();
379
380    iew.tick();
381
382    commit.tick();
383
384#if !FULL_SYSTEM
385    doContextSwitch();
386#endif
387
388    // Now advance the time buffers
389    timeBuffer.advance();
390
391    fetchQueue.advance();
392    decodeQueue.advance();
393    renameQueue.advance();
394    iewQueue.advance();
395
396    activityRec.advance();
397
398    if (removeInstsThisCycle) {
399        cleanUpRemovedInsts();
400    }
401
402    if (!tickEvent.scheduled()) {
403        if (_status == SwitchedOut) {
404            // increment stat
405            lastRunningCycle = curTick;
406        } else if (!activityRec.active()) {
407            lastRunningCycle = curTick;
408            timesIdled++;
409        } else {
410            tickEvent.schedule(curTick + cycles(1));
411        }
412    }
413
414#if !FULL_SYSTEM
415    updateThreadPriority();
416#endif
417
418}
419
420template <class Impl>
421void
422FullO3CPU<Impl>::init()
423{
424    if (!deferRegistration) {
425        registerThreadContexts();
426    }
427
428    // Set inSyscall so that the CPU doesn't squash when initially
429    // setting up registers.
430    for (int i = 0; i < number_of_threads; ++i)
431        thread[i]->inSyscall = true;
432
433    for (int tid=0; tid < number_of_threads; tid++) {
434#if FULL_SYSTEM
435        ThreadContext *src_tc = threadContexts[tid];
436#else
437        ThreadContext *src_tc = thread[tid]->getTC();
438#endif
439        // Threads start in the Suspended State
440        if (src_tc->status() != ThreadContext::Suspended) {
441            continue;
442        }
443
444#if FULL_SYSTEM
445        TheISA::initCPU(src_tc, src_tc->readCpuId());
446#endif
447    }
448
449    // Clear inSyscall.
450    for (int i = 0; i < number_of_threads; ++i)
451        thread[i]->inSyscall = false;
452
453    // Initialize stages.
454    fetch.initStage();
455    iew.initStage();
456    rename.initStage();
457    commit.initStage();
458
459    commit.setThreads(thread);
460}
461
462template <class Impl>
463void
464FullO3CPU<Impl>::insertThread(unsigned tid)
465{
466    DPRINTF(O3CPU,"[tid:%i] Initializing thread into CPU");
467    // Will change now that the PC and thread state is internal to the CPU
468    // and not in the ThreadContext.
469#if FULL_SYSTEM
470    ThreadContext *src_tc = system->threadContexts[tid];
471#else
472    ThreadContext *src_tc = tcBase(tid);
473#endif
474
475    //Bind Int Regs to Rename Map
476    for (int ireg = 0; ireg < TheISA::NumIntRegs; ireg++) {
477        PhysRegIndex phys_reg = freeList.getIntReg();
478
479        renameMap[tid].setEntry(ireg,phys_reg);
480        scoreboard.setReg(phys_reg);
481    }
482
483    //Bind Float Regs to Rename Map
484    for (int freg = 0; freg < TheISA::NumFloatRegs; freg++) {
485        PhysRegIndex phys_reg = freeList.getFloatReg();
486
487        renameMap[tid].setEntry(freg,phys_reg);
488        scoreboard.setReg(phys_reg);
489    }
490
491    //Copy Thread Data Into RegFile
492    //this->copyFromTC(tid);
493
494    //Set PC/NPC/NNPC
495    setPC(src_tc->readPC(), tid);
496    setNextPC(src_tc->readNextPC(), tid);
497#if THE_ISA != ALPHA_ISA
498    setNextNPC(src_tc->readNextNPC(), tid);
499#endif
500
501    src_tc->setStatus(ThreadContext::Active);
502
503    activateContext(tid,1);
504
505    //Reset ROB/IQ/LSQ Entries
506    commit.rob->resetEntries();
507    iew.resetEntries();
508}
509
510template <class Impl>
511void
512FullO3CPU<Impl>::removeThread(unsigned tid)
513{
514    DPRINTF(O3CPU,"[tid:%i] Removing thread from CPU.");
515
516    // Copy Thread Data From RegFile
517    // If thread is suspended, it might be re-allocated
518    //this->copyToTC(tid);
519
520    // Unbind Int Regs from Rename Map
521    for (int ireg = 0; ireg < TheISA::NumIntRegs; ireg++) {
522        PhysRegIndex phys_reg = renameMap[tid].lookup(ireg);
523
524        scoreboard.unsetReg(phys_reg);
525        freeList.addReg(phys_reg);
526    }
527
528    // Unbind Float Regs from Rename Map
529    for (int freg = 0; freg < TheISA::NumFloatRegs; freg++) {
530        PhysRegIndex phys_reg = renameMap[tid].lookup(freg);
531
532        scoreboard.unsetReg(phys_reg);
533        freeList.addReg(phys_reg);
534    }
535
536    // Squash Throughout Pipeline
537    fetch.squash(0,tid);
538    decode.squash(tid);
539    rename.squash(tid);
540
541    assert(iew.ldstQueue.getCount(tid) == 0);
542
543    // Reset ROB/IQ/LSQ Entries
544    if (activeThreads.size() >= 1) {
545        commit.rob->resetEntries();
546        iew.resetEntries();
547    }
548}
549
550
551template <class Impl>
552void
553FullO3CPU<Impl>::activateWhenReady(int tid)
554{
555    DPRINTF(O3CPU,"[tid:%i]: Checking if resources are available for incoming"
556            "(e.g. PhysRegs/ROB/IQ/LSQ) \n",
557            tid);
558
559    bool ready = true;
560
561    if (freeList.numFreeIntRegs() >= TheISA::NumIntRegs) {
562        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
563                "Phys. Int. Regs.\n",
564                tid);
565        ready = false;
566    } else if (freeList.numFreeFloatRegs() >= TheISA::NumFloatRegs) {
567        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
568                "Phys. Float. Regs.\n",
569                tid);
570        ready = false;
571    } else if (commit.rob->numFreeEntries() >=
572               commit.rob->entryAmount(activeThreads.size() + 1)) {
573        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
574                "ROB entries.\n",
575                tid);
576        ready = false;
577    } else if (iew.instQueue.numFreeEntries() >=
578               iew.instQueue.entryAmount(activeThreads.size() + 1)) {
579        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
580                "IQ entries.\n",
581                tid);
582        ready = false;
583    } else if (iew.ldstQueue.numFreeEntries() >=
584               iew.ldstQueue.entryAmount(activeThreads.size() + 1)) {
585        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
586                "LSQ entries.\n",
587                tid);
588        ready = false;
589    }
590
591    if (ready) {
592        insertThread(tid);
593
594        contextSwitch = false;
595
596        cpuWaitList.remove(tid);
597    } else {
598        suspendContext(tid);
599
600        //blocks fetch
601        contextSwitch = true;
602
603        //do waitlist
604        cpuWaitList.push_back(tid);
605    }
606}
607
608template <class Impl>
609void
610FullO3CPU<Impl>::activateThread(unsigned int tid)
611{
612    list<unsigned>::iterator isActive = find(
613        activeThreads.begin(), activeThreads.end(), tid);
614
615    if (isActive == activeThreads.end()) {
616        DPRINTF(O3CPU, "[tid:%i]: Adding to active threads list\n",
617                tid);
618
619        activeThreads.push_back(tid);
620    }
621}
622
623
624template <class Impl>
625void
626FullO3CPU<Impl>::activateContext(int tid, int delay)
627{
628    // Needs to set each stage to running as well.
629    if (delay){
630        DPRINTF(O3CPU, "[tid:%i]: Scheduling thread context to activate "
631                "on cycle %d\n", tid, curTick + cycles(delay));
632        scheduleActivateThreadEvent(tid, delay);
633    } else {
634        activateThread(tid);
635    }
636
637    if(lastActivatedCycle < curTick) {
638        scheduleTickEvent(delay);
639
640        // Be sure to signal that there's some activity so the CPU doesn't
641        // deschedule itself.
642        activityRec.activity();
643        fetch.wakeFromQuiesce();
644
645        lastActivatedCycle = curTick;
646
647        _status = Running;
648    }
649}
650
651template <class Impl>
652void
653FullO3CPU<Impl>::suspendContext(int tid)
654{
655    DPRINTF(O3CPU,"[tid: %i]: Suspending Thread Context.\n", tid);
656    unscheduleTickEvent();
657    _status = Idle;
658/*
659    //Remove From Active List, if Active
660    list<unsigned>::iterator isActive = find(
661        activeThreads.begin(), activeThreads.end(), tid);
662
663    if (isActive != activeThreads.end()) {
664        DPRINTF(O3CPU,"[tid:%i]: Removing from active threads list\n",
665                tid);
666        activeThreads.erase(isActive);
667    }
668*/
669}
670
671template <class Impl>
672void
673FullO3CPU<Impl>::deallocateContext(int tid)
674{
675    DPRINTF(O3CPU,"[tid:%i]: Deallocating Thread Context", tid);
676
677    //Remove From Active List, if Active
678    list<unsigned>::iterator thread_it =
679        find(activeThreads.begin(), activeThreads.end(), tid);
680
681    if (thread_it != activeThreads.end()) {
682        DPRINTF(O3CPU,"[tid:%i]: Removing from active threads list\n",
683                tid);
684        activeThreads.erase(thread_it);
685
686        removeThread(tid);
687    }
688}
689
690template <class Impl>
691void
692FullO3CPU<Impl>::haltContext(int tid)
693{
694    DPRINTF(O3CPU,"[tid:%i]: Halting Thread Context", tid);
695/*
696    //Remove From Active List, if Active
697    list<unsigned>::iterator isActive = find(
698        activeThreads.begin(), activeThreads.end(), tid);
699
700    if (isActive != activeThreads.end()) {
701        DPRINTF(O3CPU,"[tid:%i]: Removing from active threads list\n",
702                tid);
703        activeThreads.erase(isActive);
704
705        removeThread(tid);
706    }
707*/
708}
709
710template <class Impl>
711bool
712FullO3CPU<Impl>::drain(Event *drain_event)
713{
714    drainCount = 0;
715    fetch.drain();
716    decode.drain();
717    rename.drain();
718    iew.drain();
719    commit.drain();
720    // A bit of a hack...set the drainEvent after all the drain()
721    // calls have been made, that way if all of the stages drain
722    // immediately, the signalDrained() function knows not to call
723    // process on the drain event.
724    drainEvent = drain_event;
725
726    // Wake the CPU and record activity so everything can drain out if
727    // the CPU was not able to immediately drain.
728    if (_status != Drained) {
729        wakeCPU();
730        activityRec.activity();
731
732        return false;
733    } else {
734        return true;
735    }
736}
737
738template <class Impl>
739void
740FullO3CPU<Impl>::resume()
741{
742    if (_status == SwitchedOut)
743        return;
744    fetch.resume();
745    decode.resume();
746    rename.resume();
747    iew.resume();
748    commit.resume();
749
750    if (!tickEvent.scheduled())
751        tickEvent.schedule(curTick);
752    _status = Running;
753}
754
755template <class Impl>
756void
757FullO3CPU<Impl>::signalDrained()
758{
759    if (++drainCount == NumStages) {
760        if (tickEvent.scheduled())
761            tickEvent.squash();
762
763        _status = Drained;
764
765        if (drainEvent) {
766            drainEvent->process();
767            drainEvent = NULL;
768        }
769    }
770    assert(drainCount <= 5);
771}
772
773template <class Impl>
774void
775FullO3CPU<Impl>::switchOut()
776{
777    fetch.switchOut();
778    rename.switchOut();
779    commit.switchOut();
780    instList.clear();
781    while (!removeList.empty()) {
782        removeList.pop();
783    }
784
785    _status = SwitchedOut;
786#if USE_CHECKER
787    if (checker)
788        checker->switchOut();
789#endif
790}
791
792template <class Impl>
793void
794FullO3CPU<Impl>::takeOverFrom(BaseCPU *oldCPU)
795{
796    // Flush out any old data from the time buffers.
797    for (int i = 0; i < 10; ++i) {
798        timeBuffer.advance();
799        fetchQueue.advance();
800        decodeQueue.advance();
801        renameQueue.advance();
802        iewQueue.advance();
803    }
804
805    activityRec.reset();
806
807    BaseCPU::takeOverFrom(oldCPU);
808
809    fetch.takeOverFrom();
810    decode.takeOverFrom();
811    rename.takeOverFrom();
812    iew.takeOverFrom();
813    commit.takeOverFrom();
814
815    assert(!tickEvent.scheduled());
816
817    // @todo: Figure out how to properly select the tid to put onto
818    // the active threads list.
819    int tid = 0;
820
821    list<unsigned>::iterator isActive = find(
822        activeThreads.begin(), activeThreads.end(), tid);
823
824    if (isActive == activeThreads.end()) {
825        //May Need to Re-code this if the delay variable is the delay
826        //needed for thread to activate
827        DPRINTF(O3CPU, "Adding Thread %i to active threads list\n",
828                tid);
829
830        activeThreads.push_back(tid);
831    }
832
833    // Set all statuses to active, schedule the CPU's tick event.
834    // @todo: Fix up statuses so this is handled properly
835    for (int i = 0; i < threadContexts.size(); ++i) {
836        ThreadContext *tc = threadContexts[i];
837        if (tc->status() == ThreadContext::Active && _status != Running) {
838            _status = Running;
839            tickEvent.schedule(curTick);
840        }
841    }
842    if (!tickEvent.scheduled())
843        tickEvent.schedule(curTick);
844}
845
846template <class Impl>
847uint64_t
848FullO3CPU<Impl>::readIntReg(int reg_idx)
849{
850    return regFile.readIntReg(reg_idx);
851}
852
853template <class Impl>
854FloatReg
855FullO3CPU<Impl>::readFloatReg(int reg_idx, int width)
856{
857    return regFile.readFloatReg(reg_idx, width);
858}
859
860template <class Impl>
861FloatReg
862FullO3CPU<Impl>::readFloatReg(int reg_idx)
863{
864    return regFile.readFloatReg(reg_idx);
865}
866
867template <class Impl>
868FloatRegBits
869FullO3CPU<Impl>::readFloatRegBits(int reg_idx, int width)
870{
871    return regFile.readFloatRegBits(reg_idx, width);
872}
873
874template <class Impl>
875FloatRegBits
876FullO3CPU<Impl>::readFloatRegBits(int reg_idx)
877{
878    return regFile.readFloatRegBits(reg_idx);
879}
880
881template <class Impl>
882void
883FullO3CPU<Impl>::setIntReg(int reg_idx, uint64_t val)
884{
885    regFile.setIntReg(reg_idx, val);
886}
887
888template <class Impl>
889void
890FullO3CPU<Impl>::setFloatReg(int reg_idx, FloatReg val, int width)
891{
892    regFile.setFloatReg(reg_idx, val, width);
893}
894
895template <class Impl>
896void
897FullO3CPU<Impl>::setFloatReg(int reg_idx, FloatReg val)
898{
899    regFile.setFloatReg(reg_idx, val);
900}
901
902template <class Impl>
903void
904FullO3CPU<Impl>::setFloatRegBits(int reg_idx, FloatRegBits val, int width)
905{
906    regFile.setFloatRegBits(reg_idx, val, width);
907}
908
909template <class Impl>
910void
911FullO3CPU<Impl>::setFloatRegBits(int reg_idx, FloatRegBits val)
912{
913    regFile.setFloatRegBits(reg_idx, val);
914}
915
916template <class Impl>
917uint64_t
918FullO3CPU<Impl>::readArchIntReg(int reg_idx, unsigned tid)
919{
920    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(reg_idx);
921
922    return regFile.readIntReg(phys_reg);
923}
924
925template <class Impl>
926float
927FullO3CPU<Impl>::readArchFloatRegSingle(int reg_idx, unsigned tid)
928{
929    int idx = reg_idx + TheISA::FP_Base_DepTag;
930    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
931
932    return regFile.readFloatReg(phys_reg);
933}
934
935template <class Impl>
936double
937FullO3CPU<Impl>::readArchFloatRegDouble(int reg_idx, unsigned tid)
938{
939    int idx = reg_idx + TheISA::FP_Base_DepTag;
940    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
941
942    return regFile.readFloatReg(phys_reg, 64);
943}
944
945template <class Impl>
946uint64_t
947FullO3CPU<Impl>::readArchFloatRegInt(int reg_idx, unsigned tid)
948{
949    int idx = reg_idx + TheISA::FP_Base_DepTag;
950    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
951
952    return regFile.readFloatRegBits(phys_reg);
953}
954
955template <class Impl>
956void
957FullO3CPU<Impl>::setArchIntReg(int reg_idx, uint64_t val, unsigned tid)
958{
959    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(reg_idx);
960
961    regFile.setIntReg(phys_reg, val);
962}
963
964template <class Impl>
965void
966FullO3CPU<Impl>::setArchFloatRegSingle(int reg_idx, float val, unsigned tid)
967{
968    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(reg_idx);
969
970    regFile.setFloatReg(phys_reg, val);
971}
972
973template <class Impl>
974void
975FullO3CPU<Impl>::setArchFloatRegDouble(int reg_idx, double val, unsigned tid)
976{
977    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(reg_idx);
978
979    regFile.setFloatReg(phys_reg, val, 64);
980}
981
982template <class Impl>
983void
984FullO3CPU<Impl>::setArchFloatRegInt(int reg_idx, uint64_t val, unsigned tid)
985{
986    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(reg_idx);
987
988    regFile.setFloatRegBits(phys_reg, val);
989}
990
991template <class Impl>
992uint64_t
993FullO3CPU<Impl>::readPC(unsigned tid)
994{
995    return commit.readPC(tid);
996}
997
998template <class Impl>
999void
1000FullO3CPU<Impl>::setPC(Addr new_PC,unsigned tid)
1001{
1002    commit.setPC(new_PC, tid);
1003}
1004
1005template <class Impl>
1006uint64_t
1007FullO3CPU<Impl>::readNextPC(unsigned tid)
1008{
1009    return commit.readNextPC(tid);
1010}
1011
1012template <class Impl>
1013void
1014FullO3CPU<Impl>::setNextPC(uint64_t val,unsigned tid)
1015{
1016    commit.setNextPC(val, tid);
1017}
1018
1019#if THE_ISA != ALPHA_ISA
1020template <class Impl>
1021uint64_t
1022FullO3CPU<Impl>::readNextNPC(unsigned tid)
1023{
1024    return commit.readNextNPC(tid);
1025}
1026
1027template <class Impl>
1028void
1029FullO3CPU<Impl>::setNextNNPC(uint64_t val,unsigned tid)
1030{
1031    commit.setNextNPC(val, tid);
1032}
1033#endif
1034
1035template <class Impl>
1036typename FullO3CPU<Impl>::ListIt
1037FullO3CPU<Impl>::addInst(DynInstPtr &inst)
1038{
1039    instList.push_back(inst);
1040
1041    return --(instList.end());
1042}
1043
1044template <class Impl>
1045void
1046FullO3CPU<Impl>::instDone(unsigned tid)
1047{
1048    // Keep an instruction count.
1049    thread[tid]->numInst++;
1050    thread[tid]->numInsts++;
1051    committedInsts[tid]++;
1052    totalCommittedInsts++;
1053
1054    // Check for instruction-count-based events.
1055    comInstEventQueue[tid]->serviceEvents(thread[tid]->numInst);
1056}
1057
1058template <class Impl>
1059void
1060FullO3CPU<Impl>::addToRemoveList(DynInstPtr &inst)
1061{
1062    removeInstsThisCycle = true;
1063
1064    removeList.push(inst->getInstListIt());
1065}
1066
1067template <class Impl>
1068void
1069FullO3CPU<Impl>::removeFrontInst(DynInstPtr &inst)
1070{
1071    DPRINTF(O3CPU, "Removing committed instruction [tid:%i] PC %#x "
1072            "[sn:%lli]\n",
1073            inst->threadNumber, inst->readPC(), inst->seqNum);
1074
1075    removeInstsThisCycle = true;
1076
1077    // Remove the front instruction.
1078    removeList.push(inst->getInstListIt());
1079}
1080
1081template <class Impl>
1082void
1083FullO3CPU<Impl>::removeInstsNotInROB(unsigned tid)
1084{
1085    DPRINTF(O3CPU, "Thread %i: Deleting instructions from instruction"
1086            " list.\n", tid);
1087
1088    ListIt end_it;
1089
1090    bool rob_empty = false;
1091
1092    if (instList.empty()) {
1093        return;
1094    } else if (rob.isEmpty(/*tid*/)) {
1095        DPRINTF(O3CPU, "ROB is empty, squashing all insts.\n");
1096        end_it = instList.begin();
1097        rob_empty = true;
1098    } else {
1099        end_it = (rob.readTailInst(tid))->getInstListIt();
1100        DPRINTF(O3CPU, "ROB is not empty, squashing insts not in ROB.\n");
1101    }
1102
1103    removeInstsThisCycle = true;
1104
1105    ListIt inst_it = instList.end();
1106
1107    inst_it--;
1108
1109    // Walk through the instruction list, removing any instructions
1110    // that were inserted after the given instruction iterator, end_it.
1111    while (inst_it != end_it) {
1112        assert(!instList.empty());
1113
1114        squashInstIt(inst_it, tid);
1115
1116        inst_it--;
1117    }
1118
1119    // If the ROB was empty, then we actually need to remove the first
1120    // instruction as well.
1121    if (rob_empty) {
1122        squashInstIt(inst_it, tid);
1123    }
1124}
1125
1126template <class Impl>
1127void
1128FullO3CPU<Impl>::removeInstsUntil(const InstSeqNum &seq_num,
1129                                  unsigned tid)
1130{
1131    assert(!instList.empty());
1132
1133    removeInstsThisCycle = true;
1134
1135    ListIt inst_iter = instList.end();
1136
1137    inst_iter--;
1138
1139    DPRINTF(O3CPU, "Deleting instructions from instruction "
1140            "list that are from [tid:%i] and above [sn:%lli] (end=%lli).\n",
1141            tid, seq_num, (*inst_iter)->seqNum);
1142
1143    while ((*inst_iter)->seqNum > seq_num) {
1144
1145        bool break_loop = (inst_iter == instList.begin());
1146
1147        squashInstIt(inst_iter, tid);
1148
1149        inst_iter--;
1150
1151        if (break_loop)
1152            break;
1153    }
1154}
1155
1156template <class Impl>
1157inline void
1158FullO3CPU<Impl>::squashInstIt(const ListIt &instIt, const unsigned &tid)
1159{
1160    if ((*instIt)->threadNumber == tid) {
1161        DPRINTF(O3CPU, "Squashing instruction, "
1162                "[tid:%i] [sn:%lli] PC %#x\n",
1163                (*instIt)->threadNumber,
1164                (*instIt)->seqNum,
1165                (*instIt)->readPC());
1166
1167        // Mark it as squashed.
1168        (*instIt)->setSquashed();
1169
1170        // @todo: Formulate a consistent method for deleting
1171        // instructions from the instruction list
1172        // Remove the instruction from the list.
1173        removeList.push(instIt);
1174    }
1175}
1176
1177template <class Impl>
1178void
1179FullO3CPU<Impl>::cleanUpRemovedInsts()
1180{
1181    while (!removeList.empty()) {
1182        DPRINTF(O3CPU, "Removing instruction, "
1183                "[tid:%i] [sn:%lli] PC %#x\n",
1184                (*removeList.front())->threadNumber,
1185                (*removeList.front())->seqNum,
1186                (*removeList.front())->readPC());
1187
1188        instList.erase(removeList.front());
1189
1190        removeList.pop();
1191    }
1192
1193    removeInstsThisCycle = false;
1194}
1195/*
1196template <class Impl>
1197void
1198FullO3CPU<Impl>::removeAllInsts()
1199{
1200    instList.clear();
1201}
1202*/
1203template <class Impl>
1204void
1205FullO3CPU<Impl>::dumpInsts()
1206{
1207    int num = 0;
1208
1209    ListIt inst_list_it = instList.begin();
1210
1211    cprintf("Dumping Instruction List\n");
1212
1213    while (inst_list_it != instList.end()) {
1214        cprintf("Instruction:%i\nPC:%#x\n[tid:%i]\n[sn:%lli]\nIssued:%i\n"
1215                "Squashed:%i\n\n",
1216                num, (*inst_list_it)->readPC(), (*inst_list_it)->threadNumber,
1217                (*inst_list_it)->seqNum, (*inst_list_it)->isIssued(),
1218                (*inst_list_it)->isSquashed());
1219        inst_list_it++;
1220        ++num;
1221    }
1222}
1223/*
1224template <class Impl>
1225void
1226FullO3CPU<Impl>::wakeDependents(DynInstPtr &inst)
1227{
1228    iew.wakeDependents(inst);
1229}
1230*/
1231template <class Impl>
1232void
1233FullO3CPU<Impl>::wakeCPU()
1234{
1235    if (activityRec.active() || tickEvent.scheduled()) {
1236        DPRINTF(Activity, "CPU already running.\n");
1237        return;
1238    }
1239
1240    DPRINTF(Activity, "Waking up CPU\n");
1241
1242    idleCycles += (curTick - 1) - lastRunningCycle;
1243
1244    tickEvent.schedule(curTick);
1245}
1246
1247template <class Impl>
1248int
1249FullO3CPU<Impl>::getFreeTid()
1250{
1251    for (int i=0; i < numThreads; i++) {
1252        if (!tids[i]) {
1253            tids[i] = true;
1254            return i;
1255        }
1256    }
1257
1258    return -1;
1259}
1260
1261template <class Impl>
1262void
1263FullO3CPU<Impl>::doContextSwitch()
1264{
1265    if (contextSwitch) {
1266
1267        //ADD CODE TO DEACTIVE THREAD HERE (???)
1268
1269        for (int tid=0; tid < cpuWaitList.size(); tid++) {
1270            activateWhenReady(tid);
1271        }
1272
1273        if (cpuWaitList.size() == 0)
1274            contextSwitch = true;
1275    }
1276}
1277
1278template <class Impl>
1279void
1280FullO3CPU<Impl>::updateThreadPriority()
1281{
1282    if (activeThreads.size() > 1)
1283    {
1284        //DEFAULT TO ROUND ROBIN SCHEME
1285        //e.g. Move highest priority to end of thread list
1286        list<unsigned>::iterator list_begin = activeThreads.begin();
1287        list<unsigned>::iterator list_end   = activeThreads.end();
1288
1289        unsigned high_thread = *list_begin;
1290
1291        activeThreads.erase(list_begin);
1292
1293        activeThreads.push_back(high_thread);
1294    }
1295}
1296
1297// Forward declaration of FullO3CPU.
1298template class FullO3CPU<O3CPUImpl>;
1299