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