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