commit_impl.hh revision 9513:690357ffbce2
1/*
2 * Copyright (c) 2010-2012 ARM Limited
3 * All rights reserved
4 *
5 * The license below extends only to copyright in the software and shall
6 * not be construed as granting a license to any other intellectual
7 * property including but not limited to intellectual property relating
8 * to a hardware implementation of the functionality of the software
9 * licensed hereunder.  You may use the software subject to the license
10 * terms below provided that you ensure that this notice is replicated
11 * unmodified and in its entirety in all distributions of the software,
12 * modified or unmodified, in source code or in binary form.
13 *
14 * Copyright (c) 2004-2006 The Regents of The University of Michigan
15 * All rights reserved.
16 *
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions are
19 * met: redistributions of source code must retain the above copyright
20 * notice, this list of conditions and the following disclaimer;
21 * redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in the
23 * documentation and/or other materials provided with the distribution;
24 * neither the name of the copyright holders nor the names of its
25 * contributors may be used to endorse or promote products derived from
26 * this software without specific prior written permission.
27 *
28 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
31 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
33 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
34 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
38 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 *
40 * Authors: Kevin Lim
41 *          Korey Sewell
42 */
43
44#include <algorithm>
45#include <string>
46
47#include "arch/utility.hh"
48#include "base/loader/symtab.hh"
49#include "base/cp_annotate.hh"
50#include "config/the_isa.hh"
51#include "cpu/checker/cpu.hh"
52#include "cpu/o3/commit.hh"
53#include "cpu/o3/thread_state.hh"
54#include "cpu/base.hh"
55#include "cpu/exetrace.hh"
56#include "cpu/timebuf.hh"
57#include "debug/Activity.hh"
58#include "debug/Commit.hh"
59#include "debug/CommitRate.hh"
60#include "debug/Drain.hh"
61#include "debug/ExecFaulting.hh"
62#include "params/DerivO3CPU.hh"
63#include "sim/faults.hh"
64#include "sim/full_system.hh"
65
66using namespace std;
67
68template <class Impl>
69DefaultCommit<Impl>::TrapEvent::TrapEvent(DefaultCommit<Impl> *_commit,
70                                          ThreadID _tid)
71    : Event(CPU_Tick_Pri, AutoDelete), commit(_commit), tid(_tid)
72{
73}
74
75template <class Impl>
76void
77DefaultCommit<Impl>::TrapEvent::process()
78{
79    // This will get reset by commit if it was switched out at the
80    // time of this event processing.
81    commit->trapSquash[tid] = true;
82}
83
84template <class Impl>
85const char *
86DefaultCommit<Impl>::TrapEvent::description() const
87{
88    return "Trap";
89}
90
91template <class Impl>
92DefaultCommit<Impl>::DefaultCommit(O3CPU *_cpu, DerivO3CPUParams *params)
93    : cpu(_cpu),
94      squashCounter(0),
95      iewToCommitDelay(params->iewToCommitDelay),
96      commitToIEWDelay(params->commitToIEWDelay),
97      renameToROBDelay(params->renameToROBDelay),
98      fetchToCommitDelay(params->commitToFetchDelay),
99      renameWidth(params->renameWidth),
100      commitWidth(params->commitWidth),
101      numThreads(params->numThreads),
102      drainPending(false),
103      trapLatency(params->trapLatency),
104      canHandleInterrupts(true),
105      avoidQuiesceLiveLock(false)
106{
107    _status = Active;
108    _nextStatus = Inactive;
109    std::string policy = params->smtCommitPolicy;
110
111    //Convert string to lowercase
112    std::transform(policy.begin(), policy.end(), policy.begin(),
113                   (int(*)(int)) tolower);
114
115    //Assign commit policy
116    if (policy == "aggressive"){
117        commitPolicy = Aggressive;
118
119        DPRINTF(Commit,"Commit Policy set to Aggressive.\n");
120    } else if (policy == "roundrobin"){
121        commitPolicy = RoundRobin;
122
123        //Set-Up Priority List
124        for (ThreadID tid = 0; tid < numThreads; tid++) {
125            priority_list.push_back(tid);
126        }
127
128        DPRINTF(Commit,"Commit Policy set to Round Robin.\n");
129    } else if (policy == "oldestready"){
130        commitPolicy = OldestReady;
131
132        DPRINTF(Commit,"Commit Policy set to Oldest Ready.");
133    } else {
134        assert(0 && "Invalid SMT Commit Policy. Options Are: {Aggressive,"
135               "RoundRobin,OldestReady}");
136    }
137
138    for (ThreadID tid = 0; tid < numThreads; tid++) {
139        commitStatus[tid] = Idle;
140        changedROBNumEntries[tid] = false;
141        checkEmptyROB[tid] = false;
142        trapInFlight[tid] = false;
143        committedStores[tid] = false;
144        trapSquash[tid] = false;
145        tcSquash[tid] = false;
146        pc[tid].set(0);
147        lastCommitedSeqNum[tid] = 0;
148        squashAfterInst[tid] = NULL;
149    }
150    interrupt = NoFault;
151}
152
153template <class Impl>
154std::string
155DefaultCommit<Impl>::name() const
156{
157    return cpu->name() + ".commit";
158}
159
160template <class Impl>
161void
162DefaultCommit<Impl>::regStats()
163{
164    using namespace Stats;
165    commitSquashedInsts
166        .name(name() + ".commitSquashedInsts")
167        .desc("The number of squashed insts skipped by commit")
168        .prereq(commitSquashedInsts);
169    commitSquashEvents
170        .name(name() + ".commitSquashEvents")
171        .desc("The number of times commit is told to squash")
172        .prereq(commitSquashEvents);
173    commitNonSpecStalls
174        .name(name() + ".commitNonSpecStalls")
175        .desc("The number of times commit has been forced to stall to "
176              "communicate backwards")
177        .prereq(commitNonSpecStalls);
178    branchMispredicts
179        .name(name() + ".branchMispredicts")
180        .desc("The number of times a branch was mispredicted")
181        .prereq(branchMispredicts);
182    numCommittedDist
183        .init(0,commitWidth,1)
184        .name(name() + ".committed_per_cycle")
185        .desc("Number of insts commited each cycle")
186        .flags(Stats::pdf)
187        ;
188
189    instsCommitted
190        .init(cpu->numThreads)
191        .name(name() + ".committedInsts")
192        .desc("Number of instructions committed")
193        .flags(total)
194        ;
195
196    opsCommitted
197        .init(cpu->numThreads)
198        .name(name() + ".committedOps")
199        .desc("Number of ops (including micro ops) committed")
200        .flags(total)
201        ;
202
203    statComSwp
204        .init(cpu->numThreads)
205        .name(name() + ".swp_count")
206        .desc("Number of s/w prefetches committed")
207        .flags(total)
208        ;
209
210    statComRefs
211        .init(cpu->numThreads)
212        .name(name() +  ".refs")
213        .desc("Number of memory references committed")
214        .flags(total)
215        ;
216
217    statComLoads
218        .init(cpu->numThreads)
219        .name(name() +  ".loads")
220        .desc("Number of loads committed")
221        .flags(total)
222        ;
223
224    statComMembars
225        .init(cpu->numThreads)
226        .name(name() +  ".membars")
227        .desc("Number of memory barriers committed")
228        .flags(total)
229        ;
230
231    statComBranches
232        .init(cpu->numThreads)
233        .name(name() + ".branches")
234        .desc("Number of branches committed")
235        .flags(total)
236        ;
237
238    statComFloating
239        .init(cpu->numThreads)
240        .name(name() + ".fp_insts")
241        .desc("Number of committed floating point instructions.")
242        .flags(total)
243        ;
244
245    statComInteger
246        .init(cpu->numThreads)
247        .name(name()+".int_insts")
248        .desc("Number of committed integer instructions.")
249        .flags(total)
250        ;
251
252    statComFunctionCalls
253        .init(cpu->numThreads)
254        .name(name()+".function_calls")
255        .desc("Number of function calls committed.")
256        .flags(total)
257        ;
258
259    commitEligible
260        .init(cpu->numThreads)
261        .name(name() + ".bw_limited")
262        .desc("number of insts not committed due to BW limits")
263        .flags(total)
264        ;
265
266    commitEligibleSamples
267        .name(name() + ".bw_lim_events")
268        .desc("number cycles where commit BW limit reached")
269        ;
270}
271
272template <class Impl>
273void
274DefaultCommit<Impl>::setThreads(std::vector<Thread *> &threads)
275{
276    thread = threads;
277}
278
279template <class Impl>
280void
281DefaultCommit<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *tb_ptr)
282{
283    timeBuffer = tb_ptr;
284
285    // Setup wire to send information back to IEW.
286    toIEW = timeBuffer->getWire(0);
287
288    // Setup wire to read data from IEW (for the ROB).
289    robInfoFromIEW = timeBuffer->getWire(-iewToCommitDelay);
290}
291
292template <class Impl>
293void
294DefaultCommit<Impl>::setFetchQueue(TimeBuffer<FetchStruct> *fq_ptr)
295{
296    fetchQueue = fq_ptr;
297
298    // Setup wire to get instructions from rename (for the ROB).
299    fromFetch = fetchQueue->getWire(-fetchToCommitDelay);
300}
301
302template <class Impl>
303void
304DefaultCommit<Impl>::setRenameQueue(TimeBuffer<RenameStruct> *rq_ptr)
305{
306    renameQueue = rq_ptr;
307
308    // Setup wire to get instructions from rename (for the ROB).
309    fromRename = renameQueue->getWire(-renameToROBDelay);
310}
311
312template <class Impl>
313void
314DefaultCommit<Impl>::setIEWQueue(TimeBuffer<IEWStruct> *iq_ptr)
315{
316    iewQueue = iq_ptr;
317
318    // Setup wire to get instructions from IEW.
319    fromIEW = iewQueue->getWire(-iewToCommitDelay);
320}
321
322template <class Impl>
323void
324DefaultCommit<Impl>::setIEWStage(IEW *iew_stage)
325{
326    iewStage = iew_stage;
327}
328
329template<class Impl>
330void
331DefaultCommit<Impl>::setActiveThreads(list<ThreadID> *at_ptr)
332{
333    activeThreads = at_ptr;
334}
335
336template <class Impl>
337void
338DefaultCommit<Impl>::setRenameMap(RenameMap rm_ptr[])
339{
340    for (ThreadID tid = 0; tid < numThreads; tid++)
341        renameMap[tid] = &rm_ptr[tid];
342}
343
344template <class Impl>
345void
346DefaultCommit<Impl>::setROB(ROB *rob_ptr)
347{
348    rob = rob_ptr;
349}
350
351template <class Impl>
352void
353DefaultCommit<Impl>::startupStage()
354{
355    rob->setActiveThreads(activeThreads);
356    rob->resetEntries();
357
358    // Broadcast the number of free entries.
359    for (ThreadID tid = 0; tid < numThreads; tid++) {
360        toIEW->commitInfo[tid].usedROB = true;
361        toIEW->commitInfo[tid].freeROBEntries = rob->numFreeEntries(tid);
362        toIEW->commitInfo[tid].emptyROB = true;
363    }
364
365    // Commit must broadcast the number of free entries it has at the
366    // start of the simulation, so it starts as active.
367    cpu->activateStage(O3CPU::CommitIdx);
368
369    cpu->activityThisCycle();
370}
371
372template <class Impl>
373void
374DefaultCommit<Impl>::drain()
375{
376    drainPending = true;
377}
378
379template <class Impl>
380void
381DefaultCommit<Impl>::drainResume()
382{
383    drainPending = false;
384}
385
386template <class Impl>
387void
388DefaultCommit<Impl>::drainSanityCheck() const
389{
390    assert(isDrained());
391    rob->drainSanityCheck();
392}
393
394template <class Impl>
395bool
396DefaultCommit<Impl>::isDrained() const
397{
398    /* Make sure no one is executing microcode. There are two reasons
399     * for this:
400     * - Hardware virtualized CPUs can't switch into the middle of a
401     *   microcode sequence.
402     * - The current fetch implementation will most likely get very
403     *   confused if it tries to start fetching an instruction that
404     *   is executing in the middle of a ucode sequence that changes
405     *   address mappings. This can happen on for example x86.
406     */
407    for (ThreadID tid = 0; tid < numThreads; tid++) {
408        if (pc[tid].microPC() != 0)
409            return false;
410    }
411
412    /* Make sure that all instructions have finished committing before
413     * declaring the system as drained. We want the pipeline to be
414     * completely empty when we declare the CPU to be drained. This
415     * makes debugging easier since CPU handover and restoring from a
416     * checkpoint with a different CPU should have the same timing.
417     */
418    return rob->isEmpty() &&
419        interrupt == NoFault;
420}
421
422template <class Impl>
423void
424DefaultCommit<Impl>::takeOverFrom()
425{
426    _status = Active;
427    _nextStatus = Inactive;
428    for (ThreadID tid = 0; tid < numThreads; tid++) {
429        commitStatus[tid] = Idle;
430        changedROBNumEntries[tid] = false;
431        trapSquash[tid] = false;
432        tcSquash[tid] = false;
433        squashAfterInst[tid] = NULL;
434    }
435    squashCounter = 0;
436    rob->takeOverFrom();
437}
438
439template <class Impl>
440void
441DefaultCommit<Impl>::updateStatus()
442{
443    // reset ROB changed variable
444    list<ThreadID>::iterator threads = activeThreads->begin();
445    list<ThreadID>::iterator end = activeThreads->end();
446
447    while (threads != end) {
448        ThreadID tid = *threads++;
449
450        changedROBNumEntries[tid] = false;
451
452        // Also check if any of the threads has a trap pending
453        if (commitStatus[tid] == TrapPending ||
454            commitStatus[tid] == FetchTrapPending) {
455            _nextStatus = Active;
456        }
457    }
458
459    if (_nextStatus == Inactive && _status == Active) {
460        DPRINTF(Activity, "Deactivating stage.\n");
461        cpu->deactivateStage(O3CPU::CommitIdx);
462    } else if (_nextStatus == Active && _status == Inactive) {
463        DPRINTF(Activity, "Activating stage.\n");
464        cpu->activateStage(O3CPU::CommitIdx);
465    }
466
467    _status = _nextStatus;
468}
469
470template <class Impl>
471void
472DefaultCommit<Impl>::setNextStatus()
473{
474    int squashes = 0;
475
476    list<ThreadID>::iterator threads = activeThreads->begin();
477    list<ThreadID>::iterator end = activeThreads->end();
478
479    while (threads != end) {
480        ThreadID tid = *threads++;
481
482        if (commitStatus[tid] == ROBSquashing) {
483            squashes++;
484        }
485    }
486
487    squashCounter = squashes;
488
489    // If commit is currently squashing, then it will have activity for the
490    // next cycle. Set its next status as active.
491    if (squashCounter) {
492        _nextStatus = Active;
493    }
494}
495
496template <class Impl>
497bool
498DefaultCommit<Impl>::changedROBEntries()
499{
500    list<ThreadID>::iterator threads = activeThreads->begin();
501    list<ThreadID>::iterator end = activeThreads->end();
502
503    while (threads != end) {
504        ThreadID tid = *threads++;
505
506        if (changedROBNumEntries[tid]) {
507            return true;
508        }
509    }
510
511    return false;
512}
513
514template <class Impl>
515size_t
516DefaultCommit<Impl>::numROBFreeEntries(ThreadID tid)
517{
518    return rob->numFreeEntries(tid);
519}
520
521template <class Impl>
522void
523DefaultCommit<Impl>::generateTrapEvent(ThreadID tid)
524{
525    DPRINTF(Commit, "Generating trap event for [tid:%i]\n", tid);
526
527    TrapEvent *trap = new TrapEvent(this, tid);
528
529    cpu->schedule(trap, cpu->clockEdge(trapLatency));
530    trapInFlight[tid] = true;
531    thread[tid]->trapPending = true;
532}
533
534template <class Impl>
535void
536DefaultCommit<Impl>::generateTCEvent(ThreadID tid)
537{
538    assert(!trapInFlight[tid]);
539    DPRINTF(Commit, "Generating TC squash event for [tid:%i]\n", tid);
540
541    tcSquash[tid] = true;
542}
543
544template <class Impl>
545void
546DefaultCommit<Impl>::squashAll(ThreadID tid)
547{
548    // If we want to include the squashing instruction in the squash,
549    // then use one older sequence number.
550    // Hopefully this doesn't mess things up.  Basically I want to squash
551    // all instructions of this thread.
552    InstSeqNum squashed_inst = rob->isEmpty() ?
553        lastCommitedSeqNum[tid] : rob->readHeadInst(tid)->seqNum - 1;
554
555    // All younger instructions will be squashed. Set the sequence
556    // number as the youngest instruction in the ROB (0 in this case.
557    // Hopefully nothing breaks.)
558    youngestSeqNum[tid] = lastCommitedSeqNum[tid];
559
560    rob->squash(squashed_inst, tid);
561    changedROBNumEntries[tid] = true;
562
563    // Send back the sequence number of the squashed instruction.
564    toIEW->commitInfo[tid].doneSeqNum = squashed_inst;
565
566    // Send back the squash signal to tell stages that they should
567    // squash.
568    toIEW->commitInfo[tid].squash = true;
569
570    // Send back the rob squashing signal so other stages know that
571    // the ROB is in the process of squashing.
572    toIEW->commitInfo[tid].robSquashing = true;
573
574    toIEW->commitInfo[tid].mispredictInst = NULL;
575    toIEW->commitInfo[tid].squashInst = NULL;
576
577    toIEW->commitInfo[tid].pc = pc[tid];
578}
579
580template <class Impl>
581void
582DefaultCommit<Impl>::squashFromTrap(ThreadID tid)
583{
584    squashAll(tid);
585
586    DPRINTF(Commit, "Squashing from trap, restarting at PC %s\n", pc[tid]);
587
588    thread[tid]->trapPending = false;
589    thread[tid]->noSquashFromTC = false;
590    trapInFlight[tid] = false;
591
592    trapSquash[tid] = false;
593
594    commitStatus[tid] = ROBSquashing;
595    cpu->activityThisCycle();
596}
597
598template <class Impl>
599void
600DefaultCommit<Impl>::squashFromTC(ThreadID tid)
601{
602    squashAll(tid);
603
604    DPRINTF(Commit, "Squashing from TC, restarting at PC %s\n", pc[tid]);
605
606    thread[tid]->noSquashFromTC = false;
607    assert(!thread[tid]->trapPending);
608
609    commitStatus[tid] = ROBSquashing;
610    cpu->activityThisCycle();
611
612    tcSquash[tid] = false;
613}
614
615template <class Impl>
616void
617DefaultCommit<Impl>::squashFromSquashAfter(ThreadID tid)
618{
619    DPRINTF(Commit, "Squashing after squash after request, "
620            "restarting at PC %s\n", pc[tid]);
621
622    squashAll(tid);
623    // Make sure to inform the fetch stage of which instruction caused
624    // the squash. It'll try to re-fetch an instruction executing in
625    // microcode unless this is set.
626    toIEW->commitInfo[tid].squashInst = squashAfterInst[tid];
627    squashAfterInst[tid] = NULL;
628
629    commitStatus[tid] = ROBSquashing;
630    cpu->activityThisCycle();
631}
632
633template <class Impl>
634void
635DefaultCommit<Impl>::squashAfter(ThreadID tid, DynInstPtr &head_inst)
636{
637    DPRINTF(Commit, "Executing squash after for [tid:%i] inst [sn:%lli]\n",
638            tid, head_inst->seqNum);
639
640    assert(!squashAfterInst[tid] || squashAfterInst[tid] == head_inst);
641    commitStatus[tid] = SquashAfterPending;
642    squashAfterInst[tid] = head_inst;
643}
644
645template <class Impl>
646void
647DefaultCommit<Impl>::tick()
648{
649    wroteToTimeBuffer = false;
650    _nextStatus = Inactive;
651
652    if (activeThreads->empty())
653        return;
654
655    list<ThreadID>::iterator threads = activeThreads->begin();
656    list<ThreadID>::iterator end = activeThreads->end();
657
658    // Check if any of the threads are done squashing.  Change the
659    // status if they are done.
660    while (threads != end) {
661        ThreadID tid = *threads++;
662
663        // Clear the bit saying if the thread has committed stores
664        // this cycle.
665        committedStores[tid] = false;
666
667        if (commitStatus[tid] == ROBSquashing) {
668
669            if (rob->isDoneSquashing(tid)) {
670                commitStatus[tid] = Running;
671            } else {
672                DPRINTF(Commit,"[tid:%u]: Still Squashing, cannot commit any"
673                        " insts this cycle.\n", tid);
674                rob->doSquash(tid);
675                toIEW->commitInfo[tid].robSquashing = true;
676                wroteToTimeBuffer = true;
677            }
678        }
679    }
680
681    commit();
682
683    markCompletedInsts();
684
685    threads = activeThreads->begin();
686
687    while (threads != end) {
688        ThreadID tid = *threads++;
689
690        if (!rob->isEmpty(tid) && rob->readHeadInst(tid)->readyToCommit()) {
691            // The ROB has more instructions it can commit. Its next status
692            // will be active.
693            _nextStatus = Active;
694
695            DynInstPtr inst = rob->readHeadInst(tid);
696
697            DPRINTF(Commit,"[tid:%i]: Instruction [sn:%lli] PC %s is head of"
698                    " ROB and ready to commit\n",
699                    tid, inst->seqNum, inst->pcState());
700
701        } else if (!rob->isEmpty(tid)) {
702            DynInstPtr inst = rob->readHeadInst(tid);
703
704            DPRINTF(Commit,"[tid:%i]: Can't commit, Instruction [sn:%lli] PC "
705                    "%s is head of ROB and not ready\n",
706                    tid, inst->seqNum, inst->pcState());
707        }
708
709        DPRINTF(Commit, "[tid:%i]: ROB has %d insts & %d free entries.\n",
710                tid, rob->countInsts(tid), rob->numFreeEntries(tid));
711    }
712
713
714    if (wroteToTimeBuffer) {
715        DPRINTF(Activity, "Activity This Cycle.\n");
716        cpu->activityThisCycle();
717    }
718
719    updateStatus();
720}
721
722template <class Impl>
723void
724DefaultCommit<Impl>::handleInterrupt()
725{
726    // Verify that we still have an interrupt to handle
727    if (!cpu->checkInterrupts(cpu->tcBase(0))) {
728        DPRINTF(Commit, "Pending interrupt is cleared by master before "
729                "it got handled. Restart fetching from the orig path.\n");
730        toIEW->commitInfo[0].clearInterrupt = true;
731        interrupt = NoFault;
732        avoidQuiesceLiveLock = true;
733        return;
734    }
735
736    // Wait until all in flight instructions are finished before enterring
737    // the interrupt.
738    if (canHandleInterrupts && cpu->instList.empty()) {
739        // Squash or record that I need to squash this cycle if
740        // an interrupt needed to be handled.
741        DPRINTF(Commit, "Interrupt detected.\n");
742
743        // Clear the interrupt now that it's going to be handled
744        toIEW->commitInfo[0].clearInterrupt = true;
745
746        assert(!thread[0]->noSquashFromTC);
747        thread[0]->noSquashFromTC = true;
748
749        if (cpu->checker) {
750            cpu->checker->handlePendingInt();
751        }
752
753        // CPU will handle interrupt.
754        cpu->processInterrupts(interrupt);
755
756        thread[0]->noSquashFromTC = false;
757
758        commitStatus[0] = TrapPending;
759
760        // Generate trap squash event.
761        generateTrapEvent(0);
762
763        interrupt = NoFault;
764        avoidQuiesceLiveLock = false;
765    } else {
766        DPRINTF(Commit, "Interrupt pending: instruction is %sin "
767                "flight, ROB is %sempty\n",
768                canHandleInterrupts ? "not " : "",
769                cpu->instList.empty() ? "" : "not " );
770    }
771}
772
773template <class Impl>
774void
775DefaultCommit<Impl>::propagateInterrupt()
776{
777    if (commitStatus[0] == TrapPending || interrupt || trapSquash[0] ||
778            tcSquash[0])
779        return;
780
781    // Process interrupts if interrupts are enabled, not in PAL
782    // mode, and no other traps or external squashes are currently
783    // pending.
784    // @todo: Allow other threads to handle interrupts.
785
786    // Get any interrupt that happened
787    interrupt = cpu->getInterrupts();
788
789    // Tell fetch that there is an interrupt pending.  This
790    // will make fetch wait until it sees a non PAL-mode PC,
791    // at which point it stops fetching instructions.
792    if (interrupt != NoFault)
793        toIEW->commitInfo[0].interruptPending = true;
794}
795
796template <class Impl>
797void
798DefaultCommit<Impl>::commit()
799{
800    if (FullSystem) {
801        // Check if we have a interrupt and get read to handle it
802        if (cpu->checkInterrupts(cpu->tcBase(0)))
803            propagateInterrupt();
804    }
805
806    ////////////////////////////////////
807    // Check for any possible squashes, handle them first
808    ////////////////////////////////////
809    list<ThreadID>::iterator threads = activeThreads->begin();
810    list<ThreadID>::iterator end = activeThreads->end();
811
812    while (threads != end) {
813        ThreadID tid = *threads++;
814
815        // Not sure which one takes priority.  I think if we have
816        // both, that's a bad sign.
817        if (trapSquash[tid] == true) {
818            assert(!tcSquash[tid]);
819            squashFromTrap(tid);
820        } else if (tcSquash[tid] == true) {
821            assert(commitStatus[tid] != TrapPending);
822            squashFromTC(tid);
823        } else if (commitStatus[tid] == SquashAfterPending) {
824            // A squash from the previous cycle of the commit stage (i.e.,
825            // commitInsts() called squashAfter) is pending. Squash the
826            // thread now.
827            squashFromSquashAfter(tid);
828        }
829
830        // Squashed sequence number must be older than youngest valid
831        // instruction in the ROB. This prevents squashes from younger
832        // instructions overriding squashes from older instructions.
833        if (fromIEW->squash[tid] &&
834            commitStatus[tid] != TrapPending &&
835            fromIEW->squashedSeqNum[tid] <= youngestSeqNum[tid]) {
836
837            if (fromIEW->mispredictInst[tid]) {
838                DPRINTF(Commit,
839                    "[tid:%i]: Squashing due to branch mispred PC:%#x [sn:%i]\n",
840                    tid,
841                    fromIEW->mispredictInst[tid]->instAddr(),
842                    fromIEW->squashedSeqNum[tid]);
843            } else {
844                DPRINTF(Commit,
845                    "[tid:%i]: Squashing due to order violation [sn:%i]\n",
846                    tid, fromIEW->squashedSeqNum[tid]);
847            }
848
849            DPRINTF(Commit, "[tid:%i]: Redirecting to PC %#x\n",
850                    tid,
851                    fromIEW->pc[tid].nextInstAddr());
852
853            commitStatus[tid] = ROBSquashing;
854
855            // If we want to include the squashing instruction in the squash,
856            // then use one older sequence number.
857            InstSeqNum squashed_inst = fromIEW->squashedSeqNum[tid];
858
859            if (fromIEW->includeSquashInst[tid] == true) {
860                squashed_inst--;
861            }
862
863            // All younger instructions will be squashed. Set the sequence
864            // number as the youngest instruction in the ROB.
865            youngestSeqNum[tid] = squashed_inst;
866
867            rob->squash(squashed_inst, tid);
868            changedROBNumEntries[tid] = true;
869
870            toIEW->commitInfo[tid].doneSeqNum = squashed_inst;
871
872            toIEW->commitInfo[tid].squash = true;
873
874            // Send back the rob squashing signal so other stages know that
875            // the ROB is in the process of squashing.
876            toIEW->commitInfo[tid].robSquashing = true;
877
878            toIEW->commitInfo[tid].mispredictInst =
879                fromIEW->mispredictInst[tid];
880            toIEW->commitInfo[tid].branchTaken =
881                fromIEW->branchTaken[tid];
882            toIEW->commitInfo[tid].squashInst =
883                                    rob->findInst(tid, squashed_inst);
884            if (toIEW->commitInfo[tid].mispredictInst) {
885                if (toIEW->commitInfo[tid].mispredictInst->isUncondCtrl()) {
886                     toIEW->commitInfo[tid].branchTaken = true;
887                }
888            }
889
890            toIEW->commitInfo[tid].pc = fromIEW->pc[tid];
891
892            if (toIEW->commitInfo[tid].mispredictInst) {
893                ++branchMispredicts;
894            }
895        }
896
897    }
898
899    setNextStatus();
900
901    if (squashCounter != numThreads) {
902        // If we're not currently squashing, then get instructions.
903        getInsts();
904
905        // Try to commit any instructions.
906        commitInsts();
907    }
908
909    //Check for any activity
910    threads = activeThreads->begin();
911
912    while (threads != end) {
913        ThreadID tid = *threads++;
914
915        if (changedROBNumEntries[tid]) {
916            toIEW->commitInfo[tid].usedROB = true;
917            toIEW->commitInfo[tid].freeROBEntries = rob->numFreeEntries(tid);
918
919            wroteToTimeBuffer = true;
920            changedROBNumEntries[tid] = false;
921            if (rob->isEmpty(tid))
922                checkEmptyROB[tid] = true;
923        }
924
925        // ROB is only considered "empty" for previous stages if: a)
926        // ROB is empty, b) there are no outstanding stores, c) IEW
927        // stage has received any information regarding stores that
928        // committed.
929        // c) is checked by making sure to not consider the ROB empty
930        // on the same cycle as when stores have been committed.
931        // @todo: Make this handle multi-cycle communication between
932        // commit and IEW.
933        if (checkEmptyROB[tid] && rob->isEmpty(tid) &&
934            !iewStage->hasStoresToWB(tid) && !committedStores[tid]) {
935            checkEmptyROB[tid] = false;
936            toIEW->commitInfo[tid].usedROB = true;
937            toIEW->commitInfo[tid].emptyROB = true;
938            toIEW->commitInfo[tid].freeROBEntries = rob->numFreeEntries(tid);
939            wroteToTimeBuffer = true;
940        }
941
942    }
943}
944
945template <class Impl>
946void
947DefaultCommit<Impl>::commitInsts()
948{
949    ////////////////////////////////////
950    // Handle commit
951    // Note that commit will be handled prior to putting new
952    // instructions in the ROB so that the ROB only tries to commit
953    // instructions it has in this current cycle, and not instructions
954    // it is writing in during this cycle.  Can't commit and squash
955    // things at the same time...
956    ////////////////////////////////////
957
958    DPRINTF(Commit, "Trying to commit instructions in the ROB.\n");
959
960    unsigned num_committed = 0;
961
962    DynInstPtr head_inst;
963
964    // Commit as many instructions as possible until the commit bandwidth
965    // limit is reached, or it becomes impossible to commit any more.
966    while (num_committed < commitWidth) {
967        // Check for any interrupt that we've already squashed for
968        // and start processing it.
969        if (interrupt != NoFault)
970            handleInterrupt();
971
972        int commit_thread = getCommittingThread();
973
974        if (commit_thread == -1 || !rob->isHeadReady(commit_thread))
975            break;
976
977        head_inst = rob->readHeadInst(commit_thread);
978
979        ThreadID tid = head_inst->threadNumber;
980
981        assert(tid == commit_thread);
982
983        DPRINTF(Commit, "Trying to commit head instruction, [sn:%i] [tid:%i]\n",
984                head_inst->seqNum, tid);
985
986        // If the head instruction is squashed, it is ready to retire
987        // (be removed from the ROB) at any time.
988        if (head_inst->isSquashed()) {
989
990            DPRINTF(Commit, "Retiring squashed instruction from "
991                    "ROB.\n");
992
993            rob->retireHead(commit_thread);
994
995            ++commitSquashedInsts;
996
997            // Record that the number of ROB entries has changed.
998            changedROBNumEntries[tid] = true;
999        } else {
1000            pc[tid] = head_inst->pcState();
1001
1002            // Increment the total number of non-speculative instructions
1003            // executed.
1004            // Hack for now: it really shouldn't happen until after the
1005            // commit is deemed to be successful, but this count is needed
1006            // for syscalls.
1007            thread[tid]->funcExeInst++;
1008
1009            // Try to commit the head instruction.
1010            bool commit_success = commitHead(head_inst, num_committed);
1011
1012            if (commit_success) {
1013                ++num_committed;
1014
1015                changedROBNumEntries[tid] = true;
1016
1017                // Set the doneSeqNum to the youngest committed instruction.
1018                toIEW->commitInfo[tid].doneSeqNum = head_inst->seqNum;
1019
1020                if (tid == 0) {
1021                    canHandleInterrupts =  (!head_inst->isDelayedCommit()) &&
1022                                           ((THE_ISA != ALPHA_ISA) ||
1023                                             (!(pc[0].instAddr() & 0x3)));
1024                }
1025
1026                // Updates misc. registers.
1027                head_inst->updateMiscRegs();
1028
1029                cpu->traceFunctions(pc[tid].instAddr());
1030
1031                TheISA::advancePC(pc[tid], head_inst->staticInst);
1032
1033                // Keep track of the last sequence number commited
1034                lastCommitedSeqNum[tid] = head_inst->seqNum;
1035
1036                // If this is an instruction that doesn't play nicely with
1037                // others squash everything and restart fetch
1038                if (head_inst->isSquashAfter())
1039                    squashAfter(tid, head_inst);
1040
1041                if (drainPending) {
1042                    DPRINTF(Drain, "Draining: %i:%s\n", tid, pc[tid]);
1043                    if (pc[tid].microPC() == 0 && interrupt == NoFault) {
1044                        squashAfter(tid, head_inst);
1045                        cpu->commitDrained(tid);
1046                    }
1047                }
1048
1049                int count = 0;
1050                Addr oldpc;
1051                // Debug statement.  Checks to make sure we're not
1052                // currently updating state while handling PC events.
1053                assert(!thread[tid]->noSquashFromTC && !thread[tid]->trapPending);
1054                do {
1055                    oldpc = pc[tid].instAddr();
1056                    cpu->system->pcEventQueue.service(thread[tid]->getTC());
1057                    count++;
1058                } while (oldpc != pc[tid].instAddr());
1059                if (count > 1) {
1060                    DPRINTF(Commit,
1061                            "PC skip function event, stopping commit\n");
1062                    break;
1063                }
1064
1065                // Check if an instruction just enabled interrupts and we've
1066                // previously had an interrupt pending that was not handled
1067                // because interrupts were subsequently disabled before the
1068                // pipeline reached a place to handle the interrupt. In that
1069                // case squash now to make sure the interrupt is handled.
1070                //
1071                // If we don't do this, we might end up in a live lock situation
1072                if (!interrupt  && avoidQuiesceLiveLock &&
1073                   (!head_inst->isMicroop() || head_inst->isLastMicroop()) &&
1074                   cpu->checkInterrupts(cpu->tcBase(0)))
1075                    squashAfter(tid, head_inst);
1076            } else {
1077                DPRINTF(Commit, "Unable to commit head instruction PC:%s "
1078                        "[tid:%i] [sn:%i].\n",
1079                        head_inst->pcState(), tid ,head_inst->seqNum);
1080                break;
1081            }
1082        }
1083    }
1084
1085    DPRINTF(CommitRate, "%i\n", num_committed);
1086    numCommittedDist.sample(num_committed);
1087
1088    if (num_committed == commitWidth) {
1089        commitEligibleSamples++;
1090    }
1091}
1092
1093template <class Impl>
1094bool
1095DefaultCommit<Impl>::commitHead(DynInstPtr &head_inst, unsigned inst_num)
1096{
1097    assert(head_inst);
1098
1099    ThreadID tid = head_inst->threadNumber;
1100
1101    // If the instruction is not executed yet, then it will need extra
1102    // handling.  Signal backwards that it should be executed.
1103    if (!head_inst->isExecuted()) {
1104        // Keep this number correct.  We have not yet actually executed
1105        // and committed this instruction.
1106        thread[tid]->funcExeInst--;
1107
1108        if (head_inst->isNonSpeculative() ||
1109            head_inst->isStoreConditional() ||
1110            head_inst->isMemBarrier() ||
1111            head_inst->isWriteBarrier()) {
1112
1113            DPRINTF(Commit, "Encountered a barrier or non-speculative "
1114                    "instruction [sn:%lli] at the head of the ROB, PC %s.\n",
1115                    head_inst->seqNum, head_inst->pcState());
1116
1117            if (inst_num > 0 || iewStage->hasStoresToWB(tid)) {
1118                DPRINTF(Commit, "Waiting for all stores to writeback.\n");
1119                return false;
1120            }
1121
1122            toIEW->commitInfo[tid].nonSpecSeqNum = head_inst->seqNum;
1123
1124            // Change the instruction so it won't try to commit again until
1125            // it is executed.
1126            head_inst->clearCanCommit();
1127
1128            ++commitNonSpecStalls;
1129
1130            return false;
1131        } else if (head_inst->isLoad()) {
1132            if (inst_num > 0 || iewStage->hasStoresToWB(tid)) {
1133                DPRINTF(Commit, "Waiting for all stores to writeback.\n");
1134                return false;
1135            }
1136
1137            assert(head_inst->uncacheable());
1138            DPRINTF(Commit, "[sn:%lli]: Uncached load, PC %s.\n",
1139                    head_inst->seqNum, head_inst->pcState());
1140
1141            // Send back the non-speculative instruction's sequence
1142            // number.  Tell the lsq to re-execute the load.
1143            toIEW->commitInfo[tid].nonSpecSeqNum = head_inst->seqNum;
1144            toIEW->commitInfo[tid].uncached = true;
1145            toIEW->commitInfo[tid].uncachedLoad = head_inst;
1146
1147            head_inst->clearCanCommit();
1148
1149            return false;
1150        } else {
1151            panic("Trying to commit un-executed instruction "
1152                  "of unknown type!\n");
1153        }
1154    }
1155
1156    if (head_inst->isThreadSync()) {
1157        // Not handled for now.
1158        panic("Thread sync instructions are not handled yet.\n");
1159    }
1160
1161    // Check if the instruction caused a fault.  If so, trap.
1162    Fault inst_fault = head_inst->getFault();
1163
1164    // Stores mark themselves as completed.
1165    if (!head_inst->isStore() && inst_fault == NoFault) {
1166        head_inst->setCompleted();
1167    }
1168
1169    // Use checker prior to updating anything due to traps or PC
1170    // based events.
1171    if (cpu->checker) {
1172        cpu->checker->verify(head_inst);
1173    }
1174
1175    if (inst_fault != NoFault) {
1176        DPRINTF(Commit, "Inst [sn:%lli] PC %s has a fault\n",
1177                head_inst->seqNum, head_inst->pcState());
1178
1179        if (iewStage->hasStoresToWB(tid) || inst_num > 0) {
1180            DPRINTF(Commit, "Stores outstanding, fault must wait.\n");
1181            return false;
1182        }
1183
1184        head_inst->setCompleted();
1185
1186        if (cpu->checker) {
1187            // Need to check the instruction before its fault is processed
1188            cpu->checker->verify(head_inst);
1189        }
1190
1191        assert(!thread[tid]->noSquashFromTC);
1192
1193        // Mark that we're in state update mode so that the trap's
1194        // execution doesn't generate extra squashes.
1195        thread[tid]->noSquashFromTC = true;
1196
1197        // Execute the trap.  Although it's slightly unrealistic in
1198        // terms of timing (as it doesn't wait for the full timing of
1199        // the trap event to complete before updating state), it's
1200        // needed to update the state as soon as possible.  This
1201        // prevents external agents from changing any specific state
1202        // that the trap need.
1203        cpu->trap(inst_fault, tid, head_inst->staticInst);
1204
1205        // Exit state update mode to avoid accidental updating.
1206        thread[tid]->noSquashFromTC = false;
1207
1208        commitStatus[tid] = TrapPending;
1209
1210        DPRINTF(Commit, "Committing instruction with fault [sn:%lli]\n",
1211            head_inst->seqNum);
1212        if (head_inst->traceData) {
1213            if (DTRACE(ExecFaulting)) {
1214                head_inst->traceData->setFetchSeq(head_inst->seqNum);
1215                head_inst->traceData->setCPSeq(thread[tid]->numOp);
1216                head_inst->traceData->dump();
1217            }
1218            delete head_inst->traceData;
1219            head_inst->traceData = NULL;
1220        }
1221
1222        // Generate trap squash event.
1223        generateTrapEvent(tid);
1224        return false;
1225    }
1226
1227    updateComInstStats(head_inst);
1228
1229    if (FullSystem) {
1230        if (thread[tid]->profile) {
1231            thread[tid]->profilePC = head_inst->instAddr();
1232            ProfileNode *node = thread[tid]->profile->consume(
1233                    thread[tid]->getTC(), head_inst->staticInst);
1234
1235            if (node)
1236                thread[tid]->profileNode = node;
1237        }
1238        if (CPA::available()) {
1239            if (head_inst->isControl()) {
1240                ThreadContext *tc = thread[tid]->getTC();
1241                CPA::cpa()->swAutoBegin(tc, head_inst->nextInstAddr());
1242            }
1243        }
1244    }
1245    DPRINTF(Commit, "Committing instruction with [sn:%lli] PC %s\n",
1246            head_inst->seqNum, head_inst->pcState());
1247    if (head_inst->traceData) {
1248        head_inst->traceData->setFetchSeq(head_inst->seqNum);
1249        head_inst->traceData->setCPSeq(thread[tid]->numOp);
1250        head_inst->traceData->dump();
1251        delete head_inst->traceData;
1252        head_inst->traceData = NULL;
1253    }
1254    if (head_inst->isReturn()) {
1255        DPRINTF(Commit,"Return Instruction Committed [sn:%lli] PC %s \n",
1256                        head_inst->seqNum, head_inst->pcState());
1257    }
1258
1259    // Update the commit rename map
1260    for (int i = 0; i < head_inst->numDestRegs(); i++) {
1261        renameMap[tid]->setEntry(head_inst->flattenedDestRegIdx(i),
1262                                 head_inst->renamedDestRegIdx(i));
1263    }
1264
1265    // Finally clear the head ROB entry.
1266    rob->retireHead(tid);
1267
1268#if TRACING_ON
1269    head_inst->commitTick = curTick() - head_inst->fetchTick;
1270#endif
1271
1272    // If this was a store, record it for this cycle.
1273    if (head_inst->isStore())
1274        committedStores[tid] = true;
1275
1276    // Return true to indicate that we have committed an instruction.
1277    return true;
1278}
1279
1280template <class Impl>
1281void
1282DefaultCommit<Impl>::getInsts()
1283{
1284    DPRINTF(Commit, "Getting instructions from Rename stage.\n");
1285
1286    // Read any renamed instructions and place them into the ROB.
1287    int insts_to_process = std::min((int)renameWidth, fromRename->size);
1288
1289    for (int inst_num = 0; inst_num < insts_to_process; ++inst_num) {
1290        DynInstPtr inst;
1291
1292        inst = fromRename->insts[inst_num];
1293        ThreadID tid = inst->threadNumber;
1294
1295        if (!inst->isSquashed() &&
1296            commitStatus[tid] != ROBSquashing &&
1297            commitStatus[tid] != TrapPending) {
1298            changedROBNumEntries[tid] = true;
1299
1300            DPRINTF(Commit, "Inserting PC %s [sn:%i] [tid:%i] into ROB.\n",
1301                    inst->pcState(), inst->seqNum, tid);
1302
1303            rob->insertInst(inst);
1304
1305            assert(rob->getThreadEntries(tid) <= rob->getMaxEntries(tid));
1306
1307            youngestSeqNum[tid] = inst->seqNum;
1308        } else {
1309            DPRINTF(Commit, "Instruction PC %s [sn:%i] [tid:%i] was "
1310                    "squashed, skipping.\n",
1311                    inst->pcState(), inst->seqNum, tid);
1312        }
1313    }
1314}
1315
1316template <class Impl>
1317void
1318DefaultCommit<Impl>::skidInsert()
1319{
1320    DPRINTF(Commit, "Attempting to any instructions from rename into "
1321            "skidBuffer.\n");
1322
1323    for (int inst_num = 0; inst_num < fromRename->size; ++inst_num) {
1324        DynInstPtr inst = fromRename->insts[inst_num];
1325
1326        if (!inst->isSquashed()) {
1327            DPRINTF(Commit, "Inserting PC %s [sn:%i] [tid:%i] into ",
1328                    "skidBuffer.\n", inst->pcState(), inst->seqNum,
1329                    inst->threadNumber);
1330            skidBuffer.push(inst);
1331        } else {
1332            DPRINTF(Commit, "Instruction PC %s [sn:%i] [tid:%i] was "
1333                    "squashed, skipping.\n",
1334                    inst->pcState(), inst->seqNum, inst->threadNumber);
1335        }
1336    }
1337}
1338
1339template <class Impl>
1340void
1341DefaultCommit<Impl>::markCompletedInsts()
1342{
1343    // Grab completed insts out of the IEW instruction queue, and mark
1344    // instructions completed within the ROB.
1345    for (int inst_num = 0;
1346         inst_num < fromIEW->size && fromIEW->insts[inst_num];
1347         ++inst_num)
1348    {
1349        if (!fromIEW->insts[inst_num]->isSquashed()) {
1350            DPRINTF(Commit, "[tid:%i]: Marking PC %s, [sn:%lli] ready "
1351                    "within ROB.\n",
1352                    fromIEW->insts[inst_num]->threadNumber,
1353                    fromIEW->insts[inst_num]->pcState(),
1354                    fromIEW->insts[inst_num]->seqNum);
1355
1356            // Mark the instruction as ready to commit.
1357            fromIEW->insts[inst_num]->setCanCommit();
1358        }
1359    }
1360}
1361
1362template <class Impl>
1363bool
1364DefaultCommit<Impl>::robDoneSquashing()
1365{
1366    list<ThreadID>::iterator threads = activeThreads->begin();
1367    list<ThreadID>::iterator end = activeThreads->end();
1368
1369    while (threads != end) {
1370        ThreadID tid = *threads++;
1371
1372        if (!rob->isDoneSquashing(tid))
1373            return false;
1374    }
1375
1376    return true;
1377}
1378
1379template <class Impl>
1380void
1381DefaultCommit<Impl>::updateComInstStats(DynInstPtr &inst)
1382{
1383    ThreadID tid = inst->threadNumber;
1384
1385    if (!inst->isMicroop() || inst->isLastMicroop())
1386        instsCommitted[tid]++;
1387    opsCommitted[tid]++;
1388
1389    // To match the old model, don't count nops and instruction
1390    // prefetches towards the total commit count.
1391    if (!inst->isNop() && !inst->isInstPrefetch()) {
1392        cpu->instDone(tid, inst);
1393    }
1394
1395    //
1396    //  Control Instructions
1397    //
1398    if (inst->isControl())
1399        statComBranches[tid]++;
1400
1401    //
1402    //  Memory references
1403    //
1404    if (inst->isMemRef()) {
1405        statComRefs[tid]++;
1406
1407        if (inst->isLoad()) {
1408            statComLoads[tid]++;
1409        }
1410    }
1411
1412    if (inst->isMemBarrier()) {
1413        statComMembars[tid]++;
1414    }
1415
1416    // Integer Instruction
1417    if (inst->isInteger())
1418        statComInteger[tid]++;
1419
1420    // Floating Point Instruction
1421    if (inst->isFloating())
1422        statComFloating[tid]++;
1423
1424    // Function Calls
1425    if (inst->isCall())
1426        statComFunctionCalls[tid]++;
1427
1428}
1429
1430////////////////////////////////////////
1431//                                    //
1432//  SMT COMMIT POLICY MAINTAINED HERE //
1433//                                    //
1434////////////////////////////////////////
1435template <class Impl>
1436ThreadID
1437DefaultCommit<Impl>::getCommittingThread()
1438{
1439    if (numThreads > 1) {
1440        switch (commitPolicy) {
1441
1442          case Aggressive:
1443            //If Policy is Aggressive, commit will call
1444            //this function multiple times per
1445            //cycle
1446            return oldestReady();
1447
1448          case RoundRobin:
1449            return roundRobin();
1450
1451          case OldestReady:
1452            return oldestReady();
1453
1454          default:
1455            return InvalidThreadID;
1456        }
1457    } else {
1458        assert(!activeThreads->empty());
1459        ThreadID tid = activeThreads->front();
1460
1461        if (commitStatus[tid] == Running ||
1462            commitStatus[tid] == Idle ||
1463            commitStatus[tid] == FetchTrapPending) {
1464            return tid;
1465        } else {
1466            return InvalidThreadID;
1467        }
1468    }
1469}
1470
1471template<class Impl>
1472ThreadID
1473DefaultCommit<Impl>::roundRobin()
1474{
1475    list<ThreadID>::iterator pri_iter = priority_list.begin();
1476    list<ThreadID>::iterator end      = priority_list.end();
1477
1478    while (pri_iter != end) {
1479        ThreadID tid = *pri_iter;
1480
1481        if (commitStatus[tid] == Running ||
1482            commitStatus[tid] == Idle ||
1483            commitStatus[tid] == FetchTrapPending) {
1484
1485            if (rob->isHeadReady(tid)) {
1486                priority_list.erase(pri_iter);
1487                priority_list.push_back(tid);
1488
1489                return tid;
1490            }
1491        }
1492
1493        pri_iter++;
1494    }
1495
1496    return InvalidThreadID;
1497}
1498
1499template<class Impl>
1500ThreadID
1501DefaultCommit<Impl>::oldestReady()
1502{
1503    unsigned oldest = 0;
1504    bool first = true;
1505
1506    list<ThreadID>::iterator threads = activeThreads->begin();
1507    list<ThreadID>::iterator end = activeThreads->end();
1508
1509    while (threads != end) {
1510        ThreadID tid = *threads++;
1511
1512        if (!rob->isEmpty(tid) &&
1513            (commitStatus[tid] == Running ||
1514             commitStatus[tid] == Idle ||
1515             commitStatus[tid] == FetchTrapPending)) {
1516
1517            if (rob->isHeadReady(tid)) {
1518
1519                DynInstPtr head_inst = rob->readHeadInst(tid);
1520
1521                if (first) {
1522                    oldest = tid;
1523                    first = false;
1524                } else if (head_inst->seqNum < oldest) {
1525                    oldest = tid;
1526                }
1527            }
1528        }
1529    }
1530
1531    if (!first) {
1532        return oldest;
1533    } else {
1534        return InvalidThreadID;
1535    }
1536}
1537