commit_impl.hh revision 2875:9b6f6b75b187
1/*
2 * Copyright (c) 2004-2006 The Regents of The University of Michigan
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met: redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer;
9 * redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution;
12 * neither the name of the copyright holders nor the names of its
13 * contributors may be used to endorse or promote products derived from
14 * this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 *
28 * Authors: Kevin Lim
29 */
30
31#include "config/full_system.hh"
32#include "config/use_checker.hh"
33
34#include <algorithm>
35#include <string>
36
37#include "base/loader/symtab.hh"
38#include "base/timebuf.hh"
39#include "cpu/exetrace.hh"
40#include "cpu/o3/commit.hh"
41#include "cpu/o3/thread_state.hh"
42
43#if USE_CHECKER
44#include "cpu/checker/cpu.hh"
45#endif
46
47using namespace std;
48
49template <class Impl>
50DefaultCommit<Impl>::TrapEvent::TrapEvent(DefaultCommit<Impl> *_commit,
51                                          unsigned _tid)
52    : Event(&mainEventQueue, CPU_Tick_Pri), commit(_commit), tid(_tid)
53{
54    this->setFlags(Event::AutoDelete);
55}
56
57template <class Impl>
58void
59DefaultCommit<Impl>::TrapEvent::process()
60{
61    // This will get reset by commit if it was switched out at the
62    // time of this event processing.
63    commit->trapSquash[tid] = true;
64}
65
66template <class Impl>
67const char *
68DefaultCommit<Impl>::TrapEvent::description()
69{
70    return "Trap event";
71}
72
73template <class Impl>
74DefaultCommit<Impl>::DefaultCommit(Params *params)
75    : squashCounter(0),
76      iewToCommitDelay(params->iewToCommitDelay),
77      commitToIEWDelay(params->commitToIEWDelay),
78      renameToROBDelay(params->renameToROBDelay),
79      fetchToCommitDelay(params->commitToFetchDelay),
80      renameWidth(params->renameWidth),
81      commitWidth(params->commitWidth),
82      numThreads(params->numberOfThreads),
83      switchPending(false),
84      switchedOut(false),
85      trapLatency(params->trapLatency),
86      fetchTrapLatency(params->fetchTrapLatency)
87{
88    _status = Active;
89    _nextStatus = Inactive;
90    string policy = params->smtCommitPolicy;
91
92    //Convert string to lowercase
93    std::transform(policy.begin(), policy.end(), policy.begin(),
94                   (int(*)(int)) tolower);
95
96    //Assign commit policy
97    if (policy == "aggressive"){
98        commitPolicy = Aggressive;
99
100        DPRINTF(Commit,"Commit Policy set to Aggressive.");
101    } else if (policy == "roundrobin"){
102        commitPolicy = RoundRobin;
103
104        //Set-Up Priority List
105        for (int tid=0; tid < numThreads; tid++) {
106            priority_list.push_back(tid);
107        }
108
109        DPRINTF(Commit,"Commit Policy set to Round Robin.");
110    } else if (policy == "oldestready"){
111        commitPolicy = OldestReady;
112
113        DPRINTF(Commit,"Commit Policy set to Oldest Ready.");
114    } else {
115        assert(0 && "Invalid SMT Commit Policy. Options Are: {Aggressive,"
116               "RoundRobin,OldestReady}");
117    }
118
119    for (int i=0; i < numThreads; i++) {
120        commitStatus[i] = Idle;
121        changedROBNumEntries[i] = false;
122        trapSquash[i] = false;
123        tcSquash[i] = false;
124        PC[i] = nextPC[i] = 0;
125    }
126
127    fetchFaultTick = 0;
128    fetchTrapWait = 0;
129}
130
131template <class Impl>
132std::string
133DefaultCommit<Impl>::name() const
134{
135    return cpu->name() + ".commit";
136}
137
138template <class Impl>
139void
140DefaultCommit<Impl>::regStats()
141{
142    using namespace Stats;
143    commitCommittedInsts
144        .name(name() + ".commitCommittedInsts")
145        .desc("The number of committed instructions")
146        .prereq(commitCommittedInsts);
147    commitSquashedInsts
148        .name(name() + ".commitSquashedInsts")
149        .desc("The number of squashed insts skipped by commit")
150        .prereq(commitSquashedInsts);
151    commitSquashEvents
152        .name(name() + ".commitSquashEvents")
153        .desc("The number of times commit is told to squash")
154        .prereq(commitSquashEvents);
155    commitNonSpecStalls
156        .name(name() + ".commitNonSpecStalls")
157        .desc("The number of times commit has been forced to stall to "
158              "communicate backwards")
159        .prereq(commitNonSpecStalls);
160    branchMispredicts
161        .name(name() + ".branchMispredicts")
162        .desc("The number of times a branch was mispredicted")
163        .prereq(branchMispredicts);
164    numCommittedDist
165        .init(0,commitWidth,1)
166        .name(name() + ".COM:committed_per_cycle")
167        .desc("Number of insts commited each cycle")
168        .flags(Stats::pdf)
169        ;
170
171    statComInst
172        .init(cpu->number_of_threads)
173        .name(name() + ".COM:count")
174        .desc("Number of instructions committed")
175        .flags(total)
176        ;
177
178    statComSwp
179        .init(cpu->number_of_threads)
180        .name(name() + ".COM:swp_count")
181        .desc("Number of s/w prefetches committed")
182        .flags(total)
183        ;
184
185    statComRefs
186        .init(cpu->number_of_threads)
187        .name(name() +  ".COM:refs")
188        .desc("Number of memory references committed")
189        .flags(total)
190        ;
191
192    statComLoads
193        .init(cpu->number_of_threads)
194        .name(name() +  ".COM:loads")
195        .desc("Number of loads committed")
196        .flags(total)
197        ;
198
199    statComMembars
200        .init(cpu->number_of_threads)
201        .name(name() +  ".COM:membars")
202        .desc("Number of memory barriers committed")
203        .flags(total)
204        ;
205
206    statComBranches
207        .init(cpu->number_of_threads)
208        .name(name() + ".COM:branches")
209        .desc("Number of branches committed")
210        .flags(total)
211        ;
212
213    commitEligible
214        .init(cpu->number_of_threads)
215        .name(name() + ".COM:bw_limited")
216        .desc("number of insts not committed due to BW limits")
217        .flags(total)
218        ;
219
220    commitEligibleSamples
221        .name(name() + ".COM:bw_lim_events")
222        .desc("number cycles where commit BW limit reached")
223        ;
224}
225
226template <class Impl>
227void
228DefaultCommit<Impl>::setCPU(O3CPU *cpu_ptr)
229{
230    DPRINTF(Commit, "Commit: Setting CPU pointer.\n");
231    cpu = cpu_ptr;
232
233    // Commit must broadcast the number of free entries it has at the start of
234    // the simulation, so it starts as active.
235    cpu->activateStage(O3CPU::CommitIdx);
236
237    trapLatency = cpu->cycles(trapLatency);
238    fetchTrapLatency = cpu->cycles(fetchTrapLatency);
239}
240
241template <class Impl>
242void
243DefaultCommit<Impl>::setThreads(vector<Thread *> &threads)
244{
245    thread = threads;
246}
247
248template <class Impl>
249void
250DefaultCommit<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *tb_ptr)
251{
252    DPRINTF(Commit, "Commit: Setting time buffer pointer.\n");
253    timeBuffer = tb_ptr;
254
255    // Setup wire to send information back to IEW.
256    toIEW = timeBuffer->getWire(0);
257
258    // Setup wire to read data from IEW (for the ROB).
259    robInfoFromIEW = timeBuffer->getWire(-iewToCommitDelay);
260}
261
262template <class Impl>
263void
264DefaultCommit<Impl>::setFetchQueue(TimeBuffer<FetchStruct> *fq_ptr)
265{
266    DPRINTF(Commit, "Commit: Setting fetch queue pointer.\n");
267    fetchQueue = fq_ptr;
268
269    // Setup wire to get instructions from rename (for the ROB).
270    fromFetch = fetchQueue->getWire(-fetchToCommitDelay);
271}
272
273template <class Impl>
274void
275DefaultCommit<Impl>::setRenameQueue(TimeBuffer<RenameStruct> *rq_ptr)
276{
277    DPRINTF(Commit, "Commit: Setting rename queue pointer.\n");
278    renameQueue = rq_ptr;
279
280    // Setup wire to get instructions from rename (for the ROB).
281    fromRename = renameQueue->getWire(-renameToROBDelay);
282}
283
284template <class Impl>
285void
286DefaultCommit<Impl>::setIEWQueue(TimeBuffer<IEWStruct> *iq_ptr)
287{
288    DPRINTF(Commit, "Commit: Setting IEW queue pointer.\n");
289    iewQueue = iq_ptr;
290
291    // Setup wire to get instructions from IEW.
292    fromIEW = iewQueue->getWire(-iewToCommitDelay);
293}
294
295template <class Impl>
296void
297DefaultCommit<Impl>::setFetchStage(Fetch *fetch_stage)
298{
299    fetchStage = fetch_stage;
300}
301
302template <class Impl>
303void
304DefaultCommit<Impl>::setIEWStage(IEW *iew_stage)
305{
306    iewStage = iew_stage;
307}
308
309template<class Impl>
310void
311DefaultCommit<Impl>::setActiveThreads(list<unsigned> *at_ptr)
312{
313    DPRINTF(Commit, "Commit: Setting active threads list pointer.\n");
314    activeThreads = at_ptr;
315}
316
317template <class Impl>
318void
319DefaultCommit<Impl>::setRenameMap(RenameMap rm_ptr[])
320{
321    DPRINTF(Commit, "Setting rename map pointers.\n");
322
323    for (int i=0; i < numThreads; i++) {
324        renameMap[i] = &rm_ptr[i];
325    }
326}
327
328template <class Impl>
329void
330DefaultCommit<Impl>::setROB(ROB *rob_ptr)
331{
332    DPRINTF(Commit, "Commit: Setting ROB pointer.\n");
333    rob = rob_ptr;
334}
335
336template <class Impl>
337void
338DefaultCommit<Impl>::initStage()
339{
340    rob->setActiveThreads(activeThreads);
341    rob->resetEntries();
342
343    // Broadcast the number of free entries.
344    for (int i=0; i < numThreads; i++) {
345        toIEW->commitInfo[i].usedROB = true;
346        toIEW->commitInfo[i].freeROBEntries = rob->numFreeEntries(i);
347    }
348
349    cpu->activityThisCycle();
350}
351
352template <class Impl>
353void
354DefaultCommit<Impl>::switchOut()
355{
356    switchPending = true;
357}
358
359template <class Impl>
360void
361DefaultCommit<Impl>::doSwitchOut()
362{
363    switchedOut = true;
364    switchPending = false;
365    rob->switchOut();
366}
367
368template <class Impl>
369void
370DefaultCommit<Impl>::takeOverFrom()
371{
372    switchedOut = false;
373    _status = Active;
374    _nextStatus = Inactive;
375    for (int i=0; i < numThreads; i++) {
376        commitStatus[i] = Idle;
377        changedROBNumEntries[i] = false;
378        trapSquash[i] = false;
379        tcSquash[i] = false;
380    }
381    squashCounter = 0;
382    rob->takeOverFrom();
383}
384
385template <class Impl>
386void
387DefaultCommit<Impl>::updateStatus()
388{
389    // reset ROB changed variable
390    list<unsigned>::iterator threads = (*activeThreads).begin();
391    while (threads != (*activeThreads).end()) {
392        unsigned tid = *threads++;
393        changedROBNumEntries[tid] = false;
394
395        // Also check if any of the threads has a trap pending
396        if (commitStatus[tid] == TrapPending ||
397            commitStatus[tid] == FetchTrapPending) {
398            _nextStatus = Active;
399        }
400    }
401
402    if (_nextStatus == Inactive && _status == Active) {
403        DPRINTF(Activity, "Deactivating stage.\n");
404        cpu->deactivateStage(O3CPU::CommitIdx);
405    } else if (_nextStatus == Active && _status == Inactive) {
406        DPRINTF(Activity, "Activating stage.\n");
407        cpu->activateStage(O3CPU::CommitIdx);
408    }
409
410    _status = _nextStatus;
411}
412
413template <class Impl>
414void
415DefaultCommit<Impl>::setNextStatus()
416{
417    int squashes = 0;
418
419    list<unsigned>::iterator threads = (*activeThreads).begin();
420
421    while (threads != (*activeThreads).end()) {
422        unsigned tid = *threads++;
423
424        if (commitStatus[tid] == ROBSquashing) {
425            squashes++;
426        }
427    }
428
429    squashCounter = squashes;
430
431    // If commit is currently squashing, then it will have activity for the
432    // next cycle. Set its next status as active.
433    if (squashCounter) {
434        _nextStatus = Active;
435    }
436}
437
438template <class Impl>
439bool
440DefaultCommit<Impl>::changedROBEntries()
441{
442    list<unsigned>::iterator threads = (*activeThreads).begin();
443
444    while (threads != (*activeThreads).end()) {
445        unsigned tid = *threads++;
446
447        if (changedROBNumEntries[tid]) {
448            return true;
449        }
450    }
451
452    return false;
453}
454
455template <class Impl>
456unsigned
457DefaultCommit<Impl>::numROBFreeEntries(unsigned tid)
458{
459    return rob->numFreeEntries(tid);
460}
461
462template <class Impl>
463void
464DefaultCommit<Impl>::generateTrapEvent(unsigned tid)
465{
466    DPRINTF(Commit, "Generating trap event for [tid:%i]\n", tid);
467
468    TrapEvent *trap = new TrapEvent(this, tid);
469
470    trap->schedule(curTick + trapLatency);
471
472    thread[tid]->trapPending = true;
473}
474
475template <class Impl>
476void
477DefaultCommit<Impl>::generateTCEvent(unsigned tid)
478{
479    DPRINTF(Commit, "Generating TC squash event for [tid:%i]\n", tid);
480
481    tcSquash[tid] = true;
482}
483
484template <class Impl>
485void
486DefaultCommit<Impl>::squashAll(unsigned tid)
487{
488    // If we want to include the squashing instruction in the squash,
489    // then use one older sequence number.
490    // Hopefully this doesn't mess things up.  Basically I want to squash
491    // all instructions of this thread.
492    InstSeqNum squashed_inst = rob->isEmpty() ?
493        0 : rob->readHeadInst(tid)->seqNum - 1;;
494
495    // All younger instructions will be squashed. Set the sequence
496    // number as the youngest instruction in the ROB (0 in this case.
497    // Hopefully nothing breaks.)
498    youngestSeqNum[tid] = 0;
499
500    rob->squash(squashed_inst, tid);
501    changedROBNumEntries[tid] = true;
502
503    // Send back the sequence number of the squashed instruction.
504    toIEW->commitInfo[tid].doneSeqNum = squashed_inst;
505
506    // Send back the squash signal to tell stages that they should
507    // squash.
508    toIEW->commitInfo[tid].squash = true;
509
510    // Send back the rob squashing signal so other stages know that
511    // the ROB is in the process of squashing.
512    toIEW->commitInfo[tid].robSquashing = true;
513
514    toIEW->commitInfo[tid].branchMispredict = false;
515
516    toIEW->commitInfo[tid].nextPC = PC[tid];
517}
518
519template <class Impl>
520void
521DefaultCommit<Impl>::squashFromTrap(unsigned tid)
522{
523    squashAll(tid);
524
525    DPRINTF(Commit, "Squashing from trap, restarting at PC %#x\n", PC[tid]);
526
527    thread[tid]->trapPending = false;
528    thread[tid]->inSyscall = false;
529
530    trapSquash[tid] = false;
531
532    commitStatus[tid] = ROBSquashing;
533    cpu->activityThisCycle();
534}
535
536template <class Impl>
537void
538DefaultCommit<Impl>::squashFromTC(unsigned tid)
539{
540    squashAll(tid);
541
542    DPRINTF(Commit, "Squashing from TC, restarting at PC %#x\n", PC[tid]);
543
544    thread[tid]->inSyscall = false;
545    assert(!thread[tid]->trapPending);
546
547    commitStatus[tid] = ROBSquashing;
548    cpu->activityThisCycle();
549
550    tcSquash[tid] = false;
551}
552
553template <class Impl>
554void
555DefaultCommit<Impl>::tick()
556{
557    wroteToTimeBuffer = false;
558    _nextStatus = Inactive;
559
560    if (switchPending && rob->isEmpty() && !iewStage->hasStoresToWB()) {
561        cpu->signalSwitched();
562        return;
563    }
564
565    if ((*activeThreads).size() <= 0)
566        return;
567
568    list<unsigned>::iterator threads = (*activeThreads).begin();
569
570    // Check if any of the threads are done squashing.  Change the
571    // status if they are done.
572    while (threads != (*activeThreads).end()) {
573        unsigned tid = *threads++;
574
575        if (commitStatus[tid] == ROBSquashing) {
576
577            if (rob->isDoneSquashing(tid)) {
578                commitStatus[tid] = Running;
579            } else {
580                DPRINTF(Commit,"[tid:%u]: Still Squashing, cannot commit any"
581                        "insts this cycle.\n", tid);
582                rob->doSquash(tid);
583                toIEW->commitInfo[tid].robSquashing = true;
584                wroteToTimeBuffer = true;
585            }
586        }
587    }
588
589    commit();
590
591    markCompletedInsts();
592
593    threads = (*activeThreads).begin();
594
595    while (threads != (*activeThreads).end()) {
596        unsigned tid = *threads++;
597
598        if (!rob->isEmpty(tid) && rob->readHeadInst(tid)->readyToCommit()) {
599            // The ROB has more instructions it can commit. Its next status
600            // will be active.
601            _nextStatus = Active;
602
603            DynInstPtr inst = rob->readHeadInst(tid);
604
605            DPRINTF(Commit,"[tid:%i]: Instruction [sn:%lli] PC %#x is head of"
606                    " ROB and ready to commit\n",
607                    tid, inst->seqNum, inst->readPC());
608
609        } else if (!rob->isEmpty(tid)) {
610            DynInstPtr inst = rob->readHeadInst(tid);
611
612            DPRINTF(Commit,"[tid:%i]: Can't commit, Instruction [sn:%lli] PC "
613                    "%#x is head of ROB and not ready\n",
614                    tid, inst->seqNum, inst->readPC());
615        }
616
617        DPRINTF(Commit, "[tid:%i]: ROB has %d insts & %d free entries.\n",
618                tid, rob->countInsts(tid), rob->numFreeEntries(tid));
619    }
620
621
622    if (wroteToTimeBuffer) {
623        DPRINTF(Activity, "Activity This Cycle.\n");
624        cpu->activityThisCycle();
625    }
626
627    updateStatus();
628}
629
630template <class Impl>
631void
632DefaultCommit<Impl>::commit()
633{
634
635    //////////////////////////////////////
636    // Check for interrupts
637    //////////////////////////////////////
638
639#if FULL_SYSTEM
640    // Process interrupts if interrupts are enabled, not in PAL mode,
641    // and no other traps or external squashes are currently pending.
642    // @todo: Allow other threads to handle interrupts.
643    if (cpu->checkInterrupts &&
644        cpu->check_interrupts() &&
645        !cpu->inPalMode(readPC()) &&
646        !trapSquash[0] &&
647        !tcSquash[0]) {
648        // Tell fetch that there is an interrupt pending.  This will
649        // make fetch wait until it sees a non PAL-mode PC, at which
650        // point it stops fetching instructions.
651        toIEW->commitInfo[0].interruptPending = true;
652
653        // Wait until the ROB is empty and all stores have drained in
654        // order to enter the interrupt.
655        if (rob->isEmpty() && !iewStage->hasStoresToWB()) {
656            // Not sure which thread should be the one to interrupt.  For now
657            // always do thread 0.
658            assert(!thread[0]->inSyscall);
659            thread[0]->inSyscall = true;
660
661            // CPU will handle implementation of the interrupt.
662            cpu->processInterrupts();
663
664            // Now squash or record that I need to squash this cycle.
665            commitStatus[0] = TrapPending;
666
667            // Exit state update mode to avoid accidental updating.
668            thread[0]->inSyscall = false;
669
670            // Generate trap squash event.
671            generateTrapEvent(0);
672
673            toIEW->commitInfo[0].clearInterrupt = true;
674
675            DPRINTF(Commit, "Interrupt detected.\n");
676        } else {
677            DPRINTF(Commit, "Interrupt pending, waiting for ROB to empty.\n");
678        }
679    }
680#endif // FULL_SYSTEM
681
682    ////////////////////////////////////
683    // Check for any possible squashes, handle them first
684    ////////////////////////////////////
685
686    list<unsigned>::iterator threads = (*activeThreads).begin();
687
688    while (threads != (*activeThreads).end()) {
689        unsigned tid = *threads++;
690
691        // Not sure which one takes priority.  I think if we have
692        // both, that's a bad sign.
693        if (trapSquash[tid] == true) {
694            assert(!tcSquash[tid]);
695            squashFromTrap(tid);
696        } else if (tcSquash[tid] == true) {
697            squashFromTC(tid);
698        }
699
700        // Squashed sequence number must be older than youngest valid
701        // instruction in the ROB. This prevents squashes from younger
702        // instructions overriding squashes from older instructions.
703        if (fromIEW->squash[tid] &&
704            commitStatus[tid] != TrapPending &&
705            fromIEW->squashedSeqNum[tid] <= youngestSeqNum[tid]) {
706
707            DPRINTF(Commit, "[tid:%i]: Squashing due to PC %#x [sn:%i]\n",
708                    tid,
709                    fromIEW->mispredPC[tid],
710                    fromIEW->squashedSeqNum[tid]);
711
712            DPRINTF(Commit, "[tid:%i]: Redirecting to PC %#x\n",
713                    tid,
714                    fromIEW->nextPC[tid]);
715
716            commitStatus[tid] = ROBSquashing;
717
718            // If we want to include the squashing instruction in the squash,
719            // then use one older sequence number.
720            InstSeqNum squashed_inst = fromIEW->squashedSeqNum[tid];
721
722            if (fromIEW->includeSquashInst[tid] == true)
723                squashed_inst--;
724
725            // All younger instructions will be squashed. Set the sequence
726            // number as the youngest instruction in the ROB.
727            youngestSeqNum[tid] = squashed_inst;
728
729            rob->squash(squashed_inst, tid);
730            changedROBNumEntries[tid] = true;
731
732            toIEW->commitInfo[tid].doneSeqNum = squashed_inst;
733
734            toIEW->commitInfo[tid].squash = true;
735
736            // Send back the rob squashing signal so other stages know that
737            // the ROB is in the process of squashing.
738            toIEW->commitInfo[tid].robSquashing = true;
739
740            toIEW->commitInfo[tid].branchMispredict =
741                fromIEW->branchMispredict[tid];
742
743            toIEW->commitInfo[tid].branchTaken =
744                fromIEW->branchTaken[tid];
745
746            toIEW->commitInfo[tid].nextPC = fromIEW->nextPC[tid];
747
748            toIEW->commitInfo[tid].mispredPC = fromIEW->mispredPC[tid];
749
750            if (toIEW->commitInfo[tid].branchMispredict) {
751                ++branchMispredicts;
752            }
753        }
754
755    }
756
757    setNextStatus();
758
759    if (squashCounter != numThreads) {
760        // If we're not currently squashing, then get instructions.
761        getInsts();
762
763        // Try to commit any instructions.
764        commitInsts();
765    }
766
767    //Check for any activity
768    threads = (*activeThreads).begin();
769
770    while (threads != (*activeThreads).end()) {
771        unsigned tid = *threads++;
772
773        if (changedROBNumEntries[tid]) {
774            toIEW->commitInfo[tid].usedROB = true;
775            toIEW->commitInfo[tid].freeROBEntries = rob->numFreeEntries(tid);
776
777            if (rob->isEmpty(tid)) {
778                toIEW->commitInfo[tid].emptyROB = true;
779            }
780
781            wroteToTimeBuffer = true;
782            changedROBNumEntries[tid] = false;
783        }
784    }
785}
786
787template <class Impl>
788void
789DefaultCommit<Impl>::commitInsts()
790{
791    ////////////////////////////////////
792    // Handle commit
793    // Note that commit will be handled prior to putting new
794    // instructions in the ROB so that the ROB only tries to commit
795    // instructions it has in this current cycle, and not instructions
796    // it is writing in during this cycle.  Can't commit and squash
797    // things at the same time...
798    ////////////////////////////////////
799
800    DPRINTF(Commit, "Trying to commit instructions in the ROB.\n");
801
802    unsigned num_committed = 0;
803
804    DynInstPtr head_inst;
805
806    // Commit as many instructions as possible until the commit bandwidth
807    // limit is reached, or it becomes impossible to commit any more.
808    while (num_committed < commitWidth) {
809        int commit_thread = getCommittingThread();
810
811        if (commit_thread == -1 || !rob->isHeadReady(commit_thread))
812            break;
813
814        head_inst = rob->readHeadInst(commit_thread);
815
816        int tid = head_inst->threadNumber;
817
818        assert(tid == commit_thread);
819
820        DPRINTF(Commit, "Trying to commit head instruction, [sn:%i] [tid:%i]\n",
821                head_inst->seqNum, tid);
822
823        // If the head instruction is squashed, it is ready to retire
824        // (be removed from the ROB) at any time.
825        if (head_inst->isSquashed()) {
826
827            DPRINTF(Commit, "Retiring squashed instruction from "
828                    "ROB.\n");
829
830            rob->retireHead(commit_thread);
831
832            ++commitSquashedInsts;
833
834            // Record that the number of ROB entries has changed.
835            changedROBNumEntries[tid] = true;
836        } else {
837            PC[tid] = head_inst->readPC();
838            nextPC[tid] = head_inst->readNextPC();
839
840            // Increment the total number of non-speculative instructions
841            // executed.
842            // Hack for now: it really shouldn't happen until after the
843            // commit is deemed to be successful, but this count is needed
844            // for syscalls.
845            thread[tid]->funcExeInst++;
846
847            // Try to commit the head instruction.
848            bool commit_success = commitHead(head_inst, num_committed);
849
850            if (commit_success) {
851                ++num_committed;
852
853                changedROBNumEntries[tid] = true;
854
855                // Set the doneSeqNum to the youngest committed instruction.
856                toIEW->commitInfo[tid].doneSeqNum = head_inst->seqNum;
857
858                ++commitCommittedInsts;
859
860                // To match the old model, don't count nops and instruction
861                // prefetches towards the total commit count.
862                if (!head_inst->isNop() && !head_inst->isInstPrefetch()) {
863                    cpu->instDone(tid);
864                }
865
866                PC[tid] = nextPC[tid];
867                nextPC[tid] = nextPC[tid] + sizeof(TheISA::MachInst);
868#if FULL_SYSTEM
869                int count = 0;
870                Addr oldpc;
871                do {
872                    // Debug statement.  Checks to make sure we're not
873                    // currently updating state while handling PC events.
874                    if (count == 0)
875                        assert(!thread[tid]->inSyscall &&
876                               !thread[tid]->trapPending);
877                    oldpc = PC[tid];
878                    cpu->system->pcEventQueue.service(
879                        thread[tid]->getTC());
880                    count++;
881                } while (oldpc != PC[tid]);
882                if (count > 1) {
883                    DPRINTF(Commit, "PC skip function event, stopping commit\n");
884                    break;
885                }
886#endif
887            } else {
888                DPRINTF(Commit, "Unable to commit head instruction PC:%#x "
889                        "[tid:%i] [sn:%i].\n",
890                        head_inst->readPC(), tid ,head_inst->seqNum);
891                break;
892            }
893        }
894    }
895
896    DPRINTF(CommitRate, "%i\n", num_committed);
897    numCommittedDist.sample(num_committed);
898
899    if (num_committed == commitWidth) {
900        commitEligibleSamples++;
901    }
902}
903
904template <class Impl>
905bool
906DefaultCommit<Impl>::commitHead(DynInstPtr &head_inst, unsigned inst_num)
907{
908    assert(head_inst);
909
910    int tid = head_inst->threadNumber;
911
912    // If the instruction is not executed yet, then it will need extra
913    // handling.  Signal backwards that it should be executed.
914    if (!head_inst->isExecuted()) {
915        // Keep this number correct.  We have not yet actually executed
916        // and committed this instruction.
917        thread[tid]->funcExeInst--;
918
919        head_inst->setAtCommit();
920
921        if (head_inst->isNonSpeculative() ||
922            head_inst->isStoreConditional() ||
923            head_inst->isMemBarrier() ||
924            head_inst->isWriteBarrier()) {
925
926            DPRINTF(Commit, "Encountered a barrier or non-speculative "
927                    "instruction [sn:%lli] at the head of the ROB, PC %#x.\n",
928                    head_inst->seqNum, head_inst->readPC());
929
930#if !FULL_SYSTEM
931            // Hack to make sure syscalls/memory barriers/quiesces
932            // aren't executed until all stores write back their data.
933            // This direct communication shouldn't be used for
934            // anything other than this.
935            if (inst_num > 0 || iewStage->hasStoresToWB())
936#else
937            if ((head_inst->isMemBarrier() || head_inst->isWriteBarrier() ||
938                    head_inst->isQuiesce()) &&
939                iewStage->hasStoresToWB())
940#endif
941            {
942                DPRINTF(Commit, "Waiting for all stores to writeback.\n");
943                return false;
944            }
945
946            toIEW->commitInfo[tid].nonSpecSeqNum = head_inst->seqNum;
947
948            // Change the instruction so it won't try to commit again until
949            // it is executed.
950            head_inst->clearCanCommit();
951
952            ++commitNonSpecStalls;
953
954            return false;
955        } else if (head_inst->isLoad()) {
956            DPRINTF(Commit, "[sn:%lli]: Uncached load, PC %#x.\n",
957                    head_inst->seqNum, head_inst->readPC());
958
959            // Send back the non-speculative instruction's sequence
960            // number.  Tell the lsq to re-execute the load.
961            toIEW->commitInfo[tid].nonSpecSeqNum = head_inst->seqNum;
962            toIEW->commitInfo[tid].uncached = true;
963            toIEW->commitInfo[tid].uncachedLoad = head_inst;
964
965            head_inst->clearCanCommit();
966
967            return false;
968        } else {
969            panic("Trying to commit un-executed instruction "
970                  "of unknown type!\n");
971        }
972    }
973
974    if (head_inst->isThreadSync()) {
975        // Not handled for now.
976        panic("Thread sync instructions are not handled yet.\n");
977    }
978
979    // Stores mark themselves as completed.
980    if (!head_inst->isStore()) {
981        head_inst->setCompleted();
982    }
983
984#if USE_CHECKER
985    // Use checker prior to updating anything due to traps or PC
986    // based events.
987    if (cpu->checker) {
988        cpu->checker->verify(head_inst);
989    }
990#endif
991
992    // Check if the instruction caused a fault.  If so, trap.
993    Fault inst_fault = head_inst->getFault();
994
995    if (inst_fault != NoFault) {
996        head_inst->setCompleted();
997        DPRINTF(Commit, "Inst [sn:%lli] PC %#x has a fault\n",
998                head_inst->seqNum, head_inst->readPC());
999
1000        if (iewStage->hasStoresToWB() || inst_num > 0) {
1001            DPRINTF(Commit, "Stores outstanding, fault must wait.\n");
1002            return false;
1003        }
1004
1005#if USE_CHECKER
1006        if (cpu->checker && head_inst->isStore()) {
1007            cpu->checker->verify(head_inst);
1008        }
1009#endif
1010
1011        assert(!thread[tid]->inSyscall);
1012
1013        // Mark that we're in state update mode so that the trap's
1014        // execution doesn't generate extra squashes.
1015        thread[tid]->inSyscall = true;
1016
1017        // DTB will sometimes need the machine instruction for when
1018        // faults happen.  So we will set it here, prior to the DTB
1019        // possibly needing it for its fault.
1020        thread[tid]->setInst(
1021            static_cast<TheISA::MachInst>(head_inst->staticInst->machInst));
1022
1023        // Execute the trap.  Although it's slightly unrealistic in
1024        // terms of timing (as it doesn't wait for the full timing of
1025        // the trap event to complete before updating state), it's
1026        // needed to update the state as soon as possible.  This
1027        // prevents external agents from changing any specific state
1028        // that the trap need.
1029        cpu->trap(inst_fault, tid);
1030
1031        // Exit state update mode to avoid accidental updating.
1032        thread[tid]->inSyscall = false;
1033
1034        commitStatus[tid] = TrapPending;
1035
1036        // Generate trap squash event.
1037        generateTrapEvent(tid);
1038
1039        return false;
1040    }
1041
1042    updateComInstStats(head_inst);
1043
1044    if (head_inst->traceData) {
1045        head_inst->traceData->setFetchSeq(head_inst->seqNum);
1046        head_inst->traceData->setCPSeq(thread[tid]->numInst);
1047        head_inst->traceData->finalize();
1048        head_inst->traceData = NULL;
1049    }
1050
1051    // Update the commit rename map
1052    for (int i = 0; i < head_inst->numDestRegs(); i++) {
1053        renameMap[tid]->setEntry(head_inst->destRegIdx(i),
1054                                 head_inst->renamedDestRegIdx(i));
1055    }
1056
1057    // Finally clear the head ROB entry.
1058    rob->retireHead(tid);
1059
1060    // Return true to indicate that we have committed an instruction.
1061    return true;
1062}
1063
1064template <class Impl>
1065void
1066DefaultCommit<Impl>::getInsts()
1067{
1068    // Read any renamed instructions and place them into the ROB.
1069    int insts_to_process = min((int)renameWidth, fromRename->size);
1070
1071    for (int inst_num = 0; inst_num < insts_to_process; ++inst_num)
1072    {
1073        DynInstPtr inst = fromRename->insts[inst_num];
1074        int tid = inst->threadNumber;
1075
1076        if (!inst->isSquashed() &&
1077            commitStatus[tid] != ROBSquashing) {
1078            changedROBNumEntries[tid] = true;
1079
1080            DPRINTF(Commit, "Inserting PC %#x [sn:%i] [tid:%i] into ROB.\n",
1081                    inst->readPC(), inst->seqNum, tid);
1082
1083            rob->insertInst(inst);
1084
1085            assert(rob->getThreadEntries(tid) <= rob->getMaxEntries(tid));
1086
1087            youngestSeqNum[tid] = inst->seqNum;
1088        } else {
1089            DPRINTF(Commit, "Instruction PC %#x [sn:%i] [tid:%i] was "
1090                    "squashed, skipping.\n",
1091                    inst->readPC(), inst->seqNum, tid);
1092        }
1093    }
1094}
1095
1096template <class Impl>
1097void
1098DefaultCommit<Impl>::markCompletedInsts()
1099{
1100    // Grab completed insts out of the IEW instruction queue, and mark
1101    // instructions completed within the ROB.
1102    for (int inst_num = 0;
1103         inst_num < fromIEW->size && fromIEW->insts[inst_num];
1104         ++inst_num)
1105    {
1106        if (!fromIEW->insts[inst_num]->isSquashed()) {
1107            DPRINTF(Commit, "[tid:%i]: Marking PC %#x, [sn:%lli] ready "
1108                    "within ROB.\n",
1109                    fromIEW->insts[inst_num]->threadNumber,
1110                    fromIEW->insts[inst_num]->readPC(),
1111                    fromIEW->insts[inst_num]->seqNum);
1112
1113            // Mark the instruction as ready to commit.
1114            fromIEW->insts[inst_num]->setCanCommit();
1115        }
1116    }
1117}
1118
1119template <class Impl>
1120bool
1121DefaultCommit<Impl>::robDoneSquashing()
1122{
1123    list<unsigned>::iterator threads = (*activeThreads).begin();
1124
1125    while (threads != (*activeThreads).end()) {
1126        unsigned tid = *threads++;
1127
1128        if (!rob->isDoneSquashing(tid))
1129            return false;
1130    }
1131
1132    return true;
1133}
1134
1135template <class Impl>
1136void
1137DefaultCommit<Impl>::updateComInstStats(DynInstPtr &inst)
1138{
1139    unsigned thread = inst->threadNumber;
1140
1141    //
1142    //  Pick off the software prefetches
1143    //
1144#ifdef TARGET_ALPHA
1145    if (inst->isDataPrefetch()) {
1146        statComSwp[thread]++;
1147    } else {
1148        statComInst[thread]++;
1149    }
1150#else
1151    statComInst[thread]++;
1152#endif
1153
1154    //
1155    //  Control Instructions
1156    //
1157    if (inst->isControl())
1158        statComBranches[thread]++;
1159
1160    //
1161    //  Memory references
1162    //
1163    if (inst->isMemRef()) {
1164        statComRefs[thread]++;
1165
1166        if (inst->isLoad()) {
1167            statComLoads[thread]++;
1168        }
1169    }
1170
1171    if (inst->isMemBarrier()) {
1172        statComMembars[thread]++;
1173    }
1174}
1175
1176////////////////////////////////////////
1177//                                    //
1178//  SMT COMMIT POLICY MAINTAINED HERE //
1179//                                    //
1180////////////////////////////////////////
1181template <class Impl>
1182int
1183DefaultCommit<Impl>::getCommittingThread()
1184{
1185    if (numThreads > 1) {
1186        switch (commitPolicy) {
1187
1188          case Aggressive:
1189            //If Policy is Aggressive, commit will call
1190            //this function multiple times per
1191            //cycle
1192            return oldestReady();
1193
1194          case RoundRobin:
1195            return roundRobin();
1196
1197          case OldestReady:
1198            return oldestReady();
1199
1200          default:
1201            return -1;
1202        }
1203    } else {
1204        int tid = (*activeThreads).front();
1205
1206        if (commitStatus[tid] == Running ||
1207            commitStatus[tid] == Idle ||
1208            commitStatus[tid] == FetchTrapPending) {
1209            return tid;
1210        } else {
1211            return -1;
1212        }
1213    }
1214}
1215
1216template<class Impl>
1217int
1218DefaultCommit<Impl>::roundRobin()
1219{
1220    list<unsigned>::iterator pri_iter = priority_list.begin();
1221    list<unsigned>::iterator end      = priority_list.end();
1222
1223    while (pri_iter != end) {
1224        unsigned tid = *pri_iter;
1225
1226        if (commitStatus[tid] == Running ||
1227            commitStatus[tid] == Idle ||
1228            commitStatus[tid] == FetchTrapPending) {
1229
1230            if (rob->isHeadReady(tid)) {
1231                priority_list.erase(pri_iter);
1232                priority_list.push_back(tid);
1233
1234                return tid;
1235            }
1236        }
1237
1238        pri_iter++;
1239    }
1240
1241    return -1;
1242}
1243
1244template<class Impl>
1245int
1246DefaultCommit<Impl>::oldestReady()
1247{
1248    unsigned oldest = 0;
1249    bool first = true;
1250
1251    list<unsigned>::iterator threads = (*activeThreads).begin();
1252
1253    while (threads != (*activeThreads).end()) {
1254        unsigned tid = *threads++;
1255
1256        if (!rob->isEmpty(tid) &&
1257            (commitStatus[tid] == Running ||
1258             commitStatus[tid] == Idle ||
1259             commitStatus[tid] == FetchTrapPending)) {
1260
1261            if (rob->isHeadReady(tid)) {
1262
1263                DynInstPtr head_inst = rob->readHeadInst(tid);
1264
1265                if (first) {
1266                    oldest = tid;
1267                    first = false;
1268                } else if (head_inst->seqNum < oldest) {
1269                    oldest = tid;
1270                }
1271            }
1272        }
1273    }
1274
1275    if (!first) {
1276        return oldest;
1277    } else {
1278        return -1;
1279    }
1280}
1281