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