commit_impl.hh revision 3708:b174ae14f007
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 *          Korey Sewell
30 */
31
32#include "config/full_system.hh"
33#include "config/use_checker.hh"
34
35#include <algorithm>
36#include <string>
37
38#include "arch/utility.hh"
39#include "base/loader/symtab.hh"
40#include "base/timebuf.hh"
41#include "cpu/exetrace.hh"
42#include "cpu/o3/commit.hh"
43#include "cpu/o3/thread_state.hh"
44
45#if USE_CHECKER
46#include "cpu/checker/cpu.hh"
47#endif
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      drainPending(false),
84      switchedOut(false),
85      trapLatency(params->trapLatency)
86{
87    _status = Active;
88    _nextStatus = Inactive;
89    std::string policy = params->smtCommitPolicy;
90
91    //Convert string to lowercase
92    std::transform(policy.begin(), policy.end(), policy.begin(),
93                   (int(*)(int)) tolower);
94
95    //Assign commit policy
96    if (policy == "aggressive"){
97        commitPolicy = Aggressive;
98
99        DPRINTF(Commit,"Commit Policy set to Aggressive.");
100    } else if (policy == "roundrobin"){
101        commitPolicy = RoundRobin;
102
103        //Set-Up Priority List
104        for (int tid=0; tid < numThreads; tid++) {
105            priority_list.push_back(tid);
106        }
107
108        DPRINTF(Commit,"Commit Policy set to Round Robin.");
109    } else if (policy == "oldestready"){
110        commitPolicy = OldestReady;
111
112        DPRINTF(Commit,"Commit Policy set to Oldest Ready.");
113    } else {
114        assert(0 && "Invalid SMT Commit Policy. Options Are: {Aggressive,"
115               "RoundRobin,OldestReady}");
116    }
117
118    for (int i=0; i < numThreads; i++) {
119        commitStatus[i] = Idle;
120        changedROBNumEntries[i] = false;
121        trapSquash[i] = false;
122        tcSquash[i] = false;
123        PC[i] = nextPC[i] = nextNPC[i] = 0;
124    }
125#if FULL_SYSTEM
126    interrupt = NoFault;
127#endif
128}
129
130template <class Impl>
131std::string
132DefaultCommit<Impl>::name() const
133{
134    return cpu->name() + ".commit";
135}
136
137template <class Impl>
138void
139DefaultCommit<Impl>::regStats()
140{
141    using namespace Stats;
142    commitCommittedInsts
143        .name(name() + ".commitCommittedInsts")
144        .desc("The number of committed instructions")
145        .prereq(commitCommittedInsts);
146    commitSquashedInsts
147        .name(name() + ".commitSquashedInsts")
148        .desc("The number of squashed insts skipped by commit")
149        .prereq(commitSquashedInsts);
150    commitSquashEvents
151        .name(name() + ".commitSquashEvents")
152        .desc("The number of times commit is told to squash")
153        .prereq(commitSquashEvents);
154    commitNonSpecStalls
155        .name(name() + ".commitNonSpecStalls")
156        .desc("The number of times commit has been forced to stall to "
157              "communicate backwards")
158        .prereq(commitNonSpecStalls);
159    branchMispredicts
160        .name(name() + ".branchMispredicts")
161        .desc("The number of times a branch was mispredicted")
162        .prereq(branchMispredicts);
163    numCommittedDist
164        .init(0,commitWidth,1)
165        .name(name() + ".COM:committed_per_cycle")
166        .desc("Number of insts commited each cycle")
167        .flags(Stats::pdf)
168        ;
169
170    statComInst
171        .init(cpu->number_of_threads)
172        .name(name() + ".COM:count")
173        .desc("Number of instructions committed")
174        .flags(total)
175        ;
176
177    statComSwp
178        .init(cpu->number_of_threads)
179        .name(name() + ".COM:swp_count")
180        .desc("Number of s/w prefetches committed")
181        .flags(total)
182        ;
183
184    statComRefs
185        .init(cpu->number_of_threads)
186        .name(name() +  ".COM:refs")
187        .desc("Number of memory references committed")
188        .flags(total)
189        ;
190
191    statComLoads
192        .init(cpu->number_of_threads)
193        .name(name() +  ".COM:loads")
194        .desc("Number of loads committed")
195        .flags(total)
196        ;
197
198    statComMembars
199        .init(cpu->number_of_threads)
200        .name(name() +  ".COM:membars")
201        .desc("Number of memory barriers committed")
202        .flags(total)
203        ;
204
205    statComBranches
206        .init(cpu->number_of_threads)
207        .name(name() + ".COM:branches")
208        .desc("Number of branches committed")
209        .flags(total)
210        ;
211
212    commitEligible
213        .init(cpu->number_of_threads)
214        .name(name() + ".COM:bw_limited")
215        .desc("number of insts not committed due to BW limits")
216        .flags(total)
217        ;
218
219    commitEligibleSamples
220        .name(name() + ".COM:bw_lim_events")
221        .desc("number cycles where commit BW limit reached")
222        ;
223}
224
225template <class Impl>
226void
227DefaultCommit<Impl>::setCPU(O3CPU *cpu_ptr)
228{
229    DPRINTF(Commit, "Commit: Setting CPU pointer.\n");
230    cpu = cpu_ptr;
231
232    // Commit must broadcast the number of free entries it has at the start of
233    // the simulation, so it starts as active.
234    cpu->activateStage(O3CPU::CommitIdx);
235
236    trapLatency = cpu->cycles(trapLatency);
237}
238
239template <class Impl>
240void
241DefaultCommit<Impl>::setThreads(std::vector<Thread *> &threads)
242{
243    thread = threads;
244}
245
246template <class Impl>
247void
248DefaultCommit<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *tb_ptr)
249{
250    DPRINTF(Commit, "Commit: Setting time buffer pointer.\n");
251    timeBuffer = tb_ptr;
252
253    // Setup wire to send information back to IEW.
254    toIEW = timeBuffer->getWire(0);
255
256    // Setup wire to read data from IEW (for the ROB).
257    robInfoFromIEW = timeBuffer->getWire(-iewToCommitDelay);
258}
259
260template <class Impl>
261void
262DefaultCommit<Impl>::setFetchQueue(TimeBuffer<FetchStruct> *fq_ptr)
263{
264    DPRINTF(Commit, "Commit: Setting fetch queue pointer.\n");
265    fetchQueue = fq_ptr;
266
267    // Setup wire to get instructions from rename (for the ROB).
268    fromFetch = fetchQueue->getWire(-fetchToCommitDelay);
269}
270
271template <class Impl>
272void
273DefaultCommit<Impl>::setRenameQueue(TimeBuffer<RenameStruct> *rq_ptr)
274{
275    DPRINTF(Commit, "Commit: Setting rename queue pointer.\n");
276    renameQueue = rq_ptr;
277
278    // Setup wire to get instructions from rename (for the ROB).
279    fromRename = renameQueue->getWire(-renameToROBDelay);
280}
281
282template <class Impl>
283void
284DefaultCommit<Impl>::setIEWQueue(TimeBuffer<IEWStruct> *iq_ptr)
285{
286    DPRINTF(Commit, "Commit: Setting IEW queue pointer.\n");
287    iewQueue = iq_ptr;
288
289    // Setup wire to get instructions from IEW.
290    fromIEW = iewQueue->getWire(-iewToCommitDelay);
291}
292
293template <class Impl>
294void
295DefaultCommit<Impl>::setIEWStage(IEW *iew_stage)
296{
297    iewStage = iew_stage;
298}
299
300template<class Impl>
301void
302DefaultCommit<Impl>::setActiveThreads(std::list<unsigned> *at_ptr)
303{
304    DPRINTF(Commit, "Commit: Setting active threads list pointer.\n");
305    activeThreads = at_ptr;
306}
307
308template <class Impl>
309void
310DefaultCommit<Impl>::setRenameMap(RenameMap rm_ptr[])
311{
312    DPRINTF(Commit, "Setting rename map pointers.\n");
313
314    for (int i=0; i < numThreads; i++) {
315        renameMap[i] = &rm_ptr[i];
316    }
317}
318
319template <class Impl>
320void
321DefaultCommit<Impl>::setROB(ROB *rob_ptr)
322{
323    DPRINTF(Commit, "Commit: Setting ROB pointer.\n");
324    rob = rob_ptr;
325}
326
327template <class Impl>
328void
329DefaultCommit<Impl>::initStage()
330{
331    rob->setActiveThreads(activeThreads);
332    rob->resetEntries();
333
334    // Broadcast the number of free entries.
335    for (int i=0; i < numThreads; i++) {
336        toIEW->commitInfo[i].usedROB = true;
337        toIEW->commitInfo[i].freeROBEntries = rob->numFreeEntries(i);
338    }
339
340    cpu->activityThisCycle();
341}
342
343template <class Impl>
344bool
345DefaultCommit<Impl>::drain()
346{
347    drainPending = true;
348
349    return false;
350}
351
352template <class Impl>
353void
354DefaultCommit<Impl>::switchOut()
355{
356    switchedOut = true;
357    drainPending = false;
358    rob->switchOut();
359}
360
361template <class Impl>
362void
363DefaultCommit<Impl>::resume()
364{
365    drainPending = false;
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    std::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    std::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    std::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 (drainPending && rob->isEmpty() && !iewStage->hasStoresToWB()) {
561        cpu->signalDrained();
562        drainPending = false;
563        return;
564    }
565
566    if ((*activeThreads).size() <= 0)
567        return;
568
569    std::list<unsigned>::iterator threads = (*activeThreads).begin();
570
571    // Check if any of the threads are done squashing.  Change the
572    // status if they are done.
573    while (threads != (*activeThreads).end()) {
574        unsigned tid = *threads++;
575
576        if (commitStatus[tid] == ROBSquashing) {
577
578            if (rob->isDoneSquashing(tid)) {
579                commitStatus[tid] = Running;
580            } else {
581                DPRINTF(Commit,"[tid:%u]: Still Squashing, cannot commit any"
582                        " insts this cycle.\n", tid);
583                rob->doSquash(tid);
584                toIEW->commitInfo[tid].robSquashing = true;
585                wroteToTimeBuffer = true;
586            }
587        }
588    }
589
590    commit();
591
592    markCompletedInsts();
593
594    threads = (*activeThreads).begin();
595
596    while (threads != (*activeThreads).end()) {
597        unsigned tid = *threads++;
598
599        if (!rob->isEmpty(tid) && rob->readHeadInst(tid)->readyToCommit()) {
600            // The ROB has more instructions it can commit. Its next status
601            // will be active.
602            _nextStatus = Active;
603
604            DynInstPtr inst = rob->readHeadInst(tid);
605
606            DPRINTF(Commit,"[tid:%i]: Instruction [sn:%lli] PC %#x is head of"
607                    " ROB and ready to commit\n",
608                    tid, inst->seqNum, inst->readPC());
609
610        } else if (!rob->isEmpty(tid)) {
611            DynInstPtr inst = rob->readHeadInst(tid);
612
613            DPRINTF(Commit,"[tid:%i]: Can't commit, Instruction [sn:%lli] PC "
614                    "%#x is head of ROB and not ready\n",
615                    tid, inst->seqNum, inst->readPC());
616        }
617
618        DPRINTF(Commit, "[tid:%i]: ROB has %d insts & %d free entries.\n",
619                tid, rob->countInsts(tid), rob->numFreeEntries(tid));
620    }
621
622
623    if (wroteToTimeBuffer) {
624        DPRINTF(Activity, "Activity This Cycle.\n");
625        cpu->activityThisCycle();
626    }
627
628    updateStatus();
629}
630
631template <class Impl>
632void
633DefaultCommit<Impl>::commit()
634{
635
636    //////////////////////////////////////
637    // Check for interrupts
638    //////////////////////////////////////
639
640#if FULL_SYSTEM
641    if (interrupt != NoFault) {
642        // Wait until the ROB is empty and all stores have drained in
643        // order to enter the interrupt.
644        if (rob->isEmpty() && !iewStage->hasStoresToWB()) {
645            // Squash or record that I need to squash this cycle if
646            // an interrupt needed to be handled.
647            DPRINTF(Commit, "Interrupt detected.\n");
648
649            assert(!thread[0]->inSyscall);
650            thread[0]->inSyscall = true;
651
652            // CPU will handle interrupt.
653            cpu->processInterrupts(interrupt);
654
655            thread[0]->inSyscall = false;
656
657            commitStatus[0] = TrapPending;
658
659            // Generate trap squash event.
660            generateTrapEvent(0);
661
662            // Clear the interrupt now that it's been handled
663            toIEW->commitInfo[0].clearInterrupt = true;
664            interrupt = NoFault;
665        } else {
666            DPRINTF(Commit, "Interrupt pending, waiting for ROB to empty.\n");
667        }
668    } else if (cpu->checkInterrupts &&
669        cpu->check_interrupts(cpu->tcBase(0)) &&
670        commitStatus[0] != TrapPending &&
671        !trapSquash[0] &&
672        !tcSquash[0]) {
673        // Process interrupts if interrupts are enabled, not in PAL
674        // mode, and no other traps or external squashes are currently
675        // pending.
676        // @todo: Allow other threads to handle interrupts.
677
678        // Get any interrupt that happened
679        interrupt = cpu->getInterrupts();
680
681        if (interrupt != NoFault) {
682            // Tell fetch that there is an interrupt pending.  This
683            // will make fetch wait until it sees a non PAL-mode PC,
684            // at which point it stops fetching instructions.
685            toIEW->commitInfo[0].interruptPending = true;
686        }
687    }
688
689#endif // FULL_SYSTEM
690
691    ////////////////////////////////////
692    // Check for any possible squashes, handle them first
693    ////////////////////////////////////
694    std::list<unsigned>::iterator threads = (*activeThreads).begin();
695
696    while (threads != (*activeThreads).end()) {
697        unsigned tid = *threads++;
698
699        // Not sure which one takes priority.  I think if we have
700        // both, that's a bad sign.
701        if (trapSquash[tid] == true) {
702            assert(!tcSquash[tid]);
703            squashFromTrap(tid);
704        } else if (tcSquash[tid] == true) {
705            squashFromTC(tid);
706        }
707
708        // Squashed sequence number must be older than youngest valid
709        // instruction in the ROB. This prevents squashes from younger
710        // instructions overriding squashes from older instructions.
711        if (fromIEW->squash[tid] &&
712            commitStatus[tid] != TrapPending &&
713            fromIEW->squashedSeqNum[tid] <= youngestSeqNum[tid]) {
714
715            DPRINTF(Commit, "[tid:%i]: Squashing due to PC %#x [sn:%i]\n",
716                    tid,
717                    fromIEW->mispredPC[tid],
718                    fromIEW->squashedSeqNum[tid]);
719
720            DPRINTF(Commit, "[tid:%i]: Redirecting to PC %#x\n",
721                    tid,
722                    fromIEW->nextPC[tid]);
723
724            commitStatus[tid] = ROBSquashing;
725
726            // If we want to include the squashing instruction in the squash,
727            // then use one older sequence number.
728            InstSeqNum squashed_inst = fromIEW->squashedSeqNum[tid];
729
730#if ISA_HAS_DELAY_SLOT
731            InstSeqNum bdelay_done_seq_num;
732            bool squash_bdelay_slot;
733
734            if (fromIEW->branchMispredict[tid]) {
735                if (fromIEW->branchTaken[tid] &&
736                    fromIEW->condDelaySlotBranch[tid]) {
737                    DPRINTF(Commit, "[tid:%i]: Cond. delay slot branch"
738                            "mispredicted as taken. Squashing after previous "
739                            "inst, [sn:%i]\n",
740                            tid, squashed_inst);
741                     bdelay_done_seq_num = squashed_inst;
742                     squash_bdelay_slot = true;
743                } else {
744                    DPRINTF(Commit, "[tid:%i]: Branch Mispredict. Squashing "
745                            "after delay slot [sn:%i]\n", tid, squashed_inst+1);
746                    bdelay_done_seq_num = squashed_inst + 1;
747                    squash_bdelay_slot = false;
748                }
749            } else {
750                bdelay_done_seq_num = squashed_inst;
751                squash_bdelay_slot = true;
752            }
753#endif
754
755            if (fromIEW->includeSquashInst[tid] == true) {
756                squashed_inst--;
757#if ISA_HAS_DELAY_SLOT
758                bdelay_done_seq_num--;
759#endif
760            }
761            // All younger instructions will be squashed. Set the sequence
762            // number as the youngest instruction in the ROB.
763            youngestSeqNum[tid] = squashed_inst;
764
765#if ISA_HAS_DELAY_SLOT
766            rob->squash(bdelay_done_seq_num, tid);
767            toIEW->commitInfo[tid].squashDelaySlot = squash_bdelay_slot;
768            toIEW->commitInfo[tid].bdelayDoneSeqNum = bdelay_done_seq_num;
769#else
770            rob->squash(squashed_inst, tid);
771            toIEW->commitInfo[tid].squashDelaySlot = true;
772#endif
773            changedROBNumEntries[tid] = true;
774
775            toIEW->commitInfo[tid].doneSeqNum = squashed_inst;
776
777            toIEW->commitInfo[tid].squash = true;
778
779            // Send back the rob squashing signal so other stages know that
780            // the ROB is in the process of squashing.
781            toIEW->commitInfo[tid].robSquashing = true;
782
783            toIEW->commitInfo[tid].branchMispredict =
784                fromIEW->branchMispredict[tid];
785
786            toIEW->commitInfo[tid].branchTaken =
787                fromIEW->branchTaken[tid];
788
789            toIEW->commitInfo[tid].nextPC = fromIEW->nextPC[tid];
790
791            toIEW->commitInfo[tid].mispredPC = fromIEW->mispredPC[tid];
792
793            if (toIEW->commitInfo[tid].branchMispredict) {
794                ++branchMispredicts;
795            }
796        }
797
798    }
799
800    setNextStatus();
801
802    if (squashCounter != numThreads) {
803        // If we're not currently squashing, then get instructions.
804        getInsts();
805
806        // Try to commit any instructions.
807        commitInsts();
808    } else {
809#if ISA_HAS_DELAY_SLOT
810        skidInsert();
811#endif
812    }
813
814    //Check for any activity
815    threads = (*activeThreads).begin();
816
817    while (threads != (*activeThreads).end()) {
818        unsigned tid = *threads++;
819
820        if (changedROBNumEntries[tid]) {
821            toIEW->commitInfo[tid].usedROB = true;
822            toIEW->commitInfo[tid].freeROBEntries = rob->numFreeEntries(tid);
823
824            if (rob->isEmpty(tid)) {
825                toIEW->commitInfo[tid].emptyROB = true;
826            }
827
828            wroteToTimeBuffer = true;
829            changedROBNumEntries[tid] = false;
830        }
831    }
832}
833
834template <class Impl>
835void
836DefaultCommit<Impl>::commitInsts()
837{
838    ////////////////////////////////////
839    // Handle commit
840    // Note that commit will be handled prior to putting new
841    // instructions in the ROB so that the ROB only tries to commit
842    // instructions it has in this current cycle, and not instructions
843    // it is writing in during this cycle.  Can't commit and squash
844    // things at the same time...
845    ////////////////////////////////////
846
847    DPRINTF(Commit, "Trying to commit instructions in the ROB.\n");
848
849    unsigned num_committed = 0;
850
851    DynInstPtr head_inst;
852
853    // Commit as many instructions as possible until the commit bandwidth
854    // limit is reached, or it becomes impossible to commit any more.
855    while (num_committed < commitWidth) {
856        int commit_thread = getCommittingThread();
857
858        if (commit_thread == -1 || !rob->isHeadReady(commit_thread))
859            break;
860
861        head_inst = rob->readHeadInst(commit_thread);
862
863        int tid = head_inst->threadNumber;
864
865        assert(tid == commit_thread);
866
867        DPRINTF(Commit, "Trying to commit head instruction, [sn:%i] [tid:%i]\n",
868                head_inst->seqNum, tid);
869
870        // If the head instruction is squashed, it is ready to retire
871        // (be removed from the ROB) at any time.
872        if (head_inst->isSquashed()) {
873
874            DPRINTF(Commit, "Retiring squashed instruction from "
875                    "ROB.\n");
876
877            rob->retireHead(commit_thread);
878
879            ++commitSquashedInsts;
880
881            // Record that the number of ROB entries has changed.
882            changedROBNumEntries[tid] = true;
883        } else {
884            PC[tid] = head_inst->readPC();
885            nextPC[tid] = head_inst->readNextPC();
886            nextNPC[tid] = head_inst->readNextNPC();
887
888            // Increment the total number of non-speculative instructions
889            // executed.
890            // Hack for now: it really shouldn't happen until after the
891            // commit is deemed to be successful, but this count is needed
892            // for syscalls.
893            thread[tid]->funcExeInst++;
894
895            // Try to commit the head instruction.
896            bool commit_success = commitHead(head_inst, num_committed);
897
898            if (commit_success) {
899                ++num_committed;
900
901                changedROBNumEntries[tid] = true;
902
903                // Set the doneSeqNum to the youngest committed instruction.
904                toIEW->commitInfo[tid].doneSeqNum = head_inst->seqNum;
905
906                ++commitCommittedInsts;
907
908                // To match the old model, don't count nops and instruction
909                // prefetches towards the total commit count.
910                if (!head_inst->isNop() && !head_inst->isInstPrefetch()) {
911                    cpu->instDone(tid);
912                }
913
914                PC[tid] = nextPC[tid];
915#if ISA_HAS_DELAY_SLOT
916                nextPC[tid] = nextNPC[tid];
917                nextNPC[tid] = nextNPC[tid] + sizeof(TheISA::MachInst);
918#else
919                nextPC[tid] = nextPC[tid] + sizeof(TheISA::MachInst);
920#endif
921
922#if FULL_SYSTEM
923                int count = 0;
924                Addr oldpc;
925                do {
926                    // Debug statement.  Checks to make sure we're not
927                    // currently updating state while handling PC events.
928                    if (count == 0)
929                        assert(!thread[tid]->inSyscall &&
930                               !thread[tid]->trapPending);
931                    oldpc = PC[tid];
932                    cpu->system->pcEventQueue.service(
933                        thread[tid]->getTC());
934                    count++;
935                } while (oldpc != PC[tid]);
936                if (count > 1) {
937                    DPRINTF(Commit, "PC skip function event, stopping commit\n");
938                    break;
939                }
940#endif
941            } else {
942                DPRINTF(Commit, "Unable to commit head instruction PC:%#x "
943                        "[tid:%i] [sn:%i].\n",
944                        head_inst->readPC(), tid ,head_inst->seqNum);
945                break;
946            }
947        }
948    }
949
950    DPRINTF(CommitRate, "%i\n", num_committed);
951    numCommittedDist.sample(num_committed);
952
953    if (num_committed == commitWidth) {
954        commitEligibleSamples++;
955    }
956}
957
958template <class Impl>
959bool
960DefaultCommit<Impl>::commitHead(DynInstPtr &head_inst, unsigned inst_num)
961{
962    assert(head_inst);
963
964    int tid = head_inst->threadNumber;
965
966    // If the instruction is not executed yet, then it will need extra
967    // handling.  Signal backwards that it should be executed.
968    if (!head_inst->isExecuted()) {
969        // Keep this number correct.  We have not yet actually executed
970        // and committed this instruction.
971        thread[tid]->funcExeInst--;
972
973        head_inst->setAtCommit();
974
975        if (head_inst->isNonSpeculative() ||
976            head_inst->isStoreConditional() ||
977            head_inst->isMemBarrier() ||
978            head_inst->isWriteBarrier()) {
979
980            DPRINTF(Commit, "Encountered a barrier or non-speculative "
981                    "instruction [sn:%lli] at the head of the ROB, PC %#x.\n",
982                    head_inst->seqNum, head_inst->readPC());
983
984#if !FULL_SYSTEM
985            // Hack to make sure syscalls/memory barriers/quiesces
986            // aren't executed until all stores write back their data.
987            // This direct communication shouldn't be used for
988            // anything other than this.
989            if (inst_num > 0 || iewStage->hasStoresToWB())
990#else
991            if ((head_inst->isMemBarrier() || head_inst->isWriteBarrier() ||
992                    head_inst->isQuiesce()) &&
993                iewStage->hasStoresToWB())
994#endif
995            {
996                DPRINTF(Commit, "Waiting for all stores to writeback.\n");
997                return false;
998            }
999
1000            toIEW->commitInfo[tid].nonSpecSeqNum = head_inst->seqNum;
1001
1002            // Change the instruction so it won't try to commit again until
1003            // it is executed.
1004            head_inst->clearCanCommit();
1005
1006            ++commitNonSpecStalls;
1007
1008            return false;
1009        } else if (head_inst->isLoad()) {
1010            DPRINTF(Commit, "[sn:%lli]: Uncached load, PC %#x.\n",
1011                    head_inst->seqNum, head_inst->readPC());
1012
1013            // Send back the non-speculative instruction's sequence
1014            // number.  Tell the lsq to re-execute the load.
1015            toIEW->commitInfo[tid].nonSpecSeqNum = head_inst->seqNum;
1016            toIEW->commitInfo[tid].uncached = true;
1017            toIEW->commitInfo[tid].uncachedLoad = head_inst;
1018
1019            head_inst->clearCanCommit();
1020
1021            return false;
1022        } else {
1023            panic("Trying to commit un-executed instruction "
1024                  "of unknown type!\n");
1025        }
1026    }
1027
1028    if (head_inst->isThreadSync()) {
1029        // Not handled for now.
1030        panic("Thread sync instructions are not handled yet.\n");
1031    }
1032
1033    // Stores mark themselves as completed.
1034    if (!head_inst->isStore()) {
1035        head_inst->setCompleted();
1036    }
1037
1038#if USE_CHECKER
1039    // Use checker prior to updating anything due to traps or PC
1040    // based events.
1041    if (cpu->checker) {
1042        cpu->checker->verify(head_inst);
1043    }
1044#endif
1045
1046    // Check if the instruction caused a fault.  If so, trap.
1047    Fault inst_fault = head_inst->getFault();
1048
1049    // DTB will sometimes need the machine instruction for when
1050    // faults happen.  So we will set it here, prior to the DTB
1051    // possibly needing it for its fault.
1052    thread[tid]->setInst(
1053        static_cast<TheISA::MachInst>(head_inst->staticInst->machInst));
1054
1055    if (inst_fault != NoFault) {
1056        head_inst->setCompleted();
1057        DPRINTF(Commit, "Inst [sn:%lli] PC %#x has a fault\n",
1058                head_inst->seqNum, head_inst->readPC());
1059
1060        if (iewStage->hasStoresToWB() || inst_num > 0) {
1061            DPRINTF(Commit, "Stores outstanding, fault must wait.\n");
1062            return false;
1063        }
1064
1065#if USE_CHECKER
1066        if (cpu->checker && head_inst->isStore()) {
1067            cpu->checker->verify(head_inst);
1068        }
1069#endif
1070
1071        assert(!thread[tid]->inSyscall);
1072
1073        // Mark that we're in state update mode so that the trap's
1074        // execution doesn't generate extra squashes.
1075        thread[tid]->inSyscall = true;
1076
1077        // Execute the trap.  Although it's slightly unrealistic in
1078        // terms of timing (as it doesn't wait for the full timing of
1079        // the trap event to complete before updating state), it's
1080        // needed to update the state as soon as possible.  This
1081        // prevents external agents from changing any specific state
1082        // that the trap need.
1083        cpu->trap(inst_fault, tid);
1084
1085        // Exit state update mode to avoid accidental updating.
1086        thread[tid]->inSyscall = false;
1087
1088        commitStatus[tid] = TrapPending;
1089
1090        // Generate trap squash event.
1091        generateTrapEvent(tid);
1092//        warn("%lli fault (%d) handled @ PC %08p", curTick, inst_fault->name(), head_inst->readPC());
1093        return false;
1094    }
1095
1096    updateComInstStats(head_inst);
1097
1098#if FULL_SYSTEM
1099    if (thread[tid]->profile) {
1100//        bool usermode = TheISA::inUserMode(thread[tid]->getTC());
1101//        thread[tid]->profilePC = usermode ? 1 : head_inst->readPC();
1102        thread[tid]->profilePC = head_inst->readPC();
1103        ProfileNode *node = thread[tid]->profile->consume(thread[tid]->getTC(),
1104                                                          head_inst->staticInst);
1105
1106        if (node)
1107            thread[tid]->profileNode = node;
1108    }
1109#endif
1110
1111    if (head_inst->traceData) {
1112        head_inst->traceData->setFetchSeq(head_inst->seqNum);
1113        head_inst->traceData->setCPSeq(thread[tid]->numInst);
1114        head_inst->traceData->finalize();
1115        head_inst->traceData = NULL;
1116    }
1117
1118    // Update the commit rename map
1119    for (int i = 0; i < head_inst->numDestRegs(); i++) {
1120        renameMap[tid]->setEntry(head_inst->destRegIdx(i),
1121                                 head_inst->renamedDestRegIdx(i));
1122    }
1123
1124    if (head_inst->isCopy())
1125        panic("Should not commit any copy instructions!");
1126
1127    // Finally clear the head ROB entry.
1128    rob->retireHead(tid);
1129
1130    // Return true to indicate that we have committed an instruction.
1131    return true;
1132}
1133
1134template <class Impl>
1135void
1136DefaultCommit<Impl>::getInsts()
1137{
1138    DPRINTF(Commit, "Getting instructions from Rename stage.\n");
1139
1140#if ISA_HAS_DELAY_SLOT
1141    // Read any renamed instructions and place them into the ROB.
1142    int insts_to_process = std::min((int)renameWidth,
1143                               (int)(fromRename->size + skidBuffer.size()));
1144    int rename_idx = 0;
1145
1146    DPRINTF(Commit, "%i insts available to process. Rename Insts:%i "
1147            "SkidBuffer Insts:%i\n", insts_to_process, fromRename->size,
1148            skidBuffer.size());
1149#else
1150    // Read any renamed instructions and place them into the ROB.
1151    int insts_to_process = std::min((int)renameWidth, fromRename->size);
1152#endif
1153
1154
1155    for (int inst_num = 0; inst_num < insts_to_process; ++inst_num) {
1156        DynInstPtr inst;
1157
1158#if ISA_HAS_DELAY_SLOT
1159        // Get insts from skidBuffer or from Rename
1160        if (skidBuffer.size() > 0) {
1161            DPRINTF(Commit, "Grabbing skidbuffer inst.\n");
1162            inst = skidBuffer.front();
1163            skidBuffer.pop();
1164        } else {
1165            DPRINTF(Commit, "Grabbing rename inst.\n");
1166            inst = fromRename->insts[rename_idx++];
1167        }
1168#else
1169        inst = fromRename->insts[inst_num];
1170#endif
1171        int tid = inst->threadNumber;
1172
1173        if (!inst->isSquashed() &&
1174            commitStatus[tid] != ROBSquashing) {
1175            changedROBNumEntries[tid] = true;
1176
1177            DPRINTF(Commit, "Inserting PC %#x [sn:%i] [tid:%i] into ROB.\n",
1178                    inst->readPC(), inst->seqNum, tid);
1179
1180            rob->insertInst(inst);
1181
1182            assert(rob->getThreadEntries(tid) <= rob->getMaxEntries(tid));
1183
1184            youngestSeqNum[tid] = inst->seqNum;
1185        } else {
1186            DPRINTF(Commit, "Instruction PC %#x [sn:%i] [tid:%i] was "
1187                    "squashed, skipping.\n",
1188                    inst->readPC(), inst->seqNum, tid);
1189        }
1190    }
1191
1192#if ISA_HAS_DELAY_SLOT
1193    if (rename_idx < fromRename->size) {
1194        DPRINTF(Commit,"Placing Rename Insts into skidBuffer.\n");
1195
1196        for (;
1197             rename_idx < fromRename->size;
1198             rename_idx++) {
1199            DynInstPtr inst = fromRename->insts[rename_idx];
1200
1201            if (!inst->isSquashed()) {
1202                DPRINTF(Commit, "Inserting PC %#x [sn:%i] [tid:%i] into ",
1203                        "skidBuffer.\n", inst->readPC(), inst->seqNum,
1204                        inst->threadNumber);
1205                skidBuffer.push(inst);
1206            } else {
1207                DPRINTF(Commit, "Instruction PC %#x [sn:%i] [tid:%i] was "
1208                        "squashed, skipping.\n",
1209                        inst->readPC(), inst->seqNum, inst->threadNumber);
1210            }
1211        }
1212    }
1213#endif
1214
1215}
1216
1217template <class Impl>
1218void
1219DefaultCommit<Impl>::skidInsert()
1220{
1221    DPRINTF(Commit, "Attempting to any instructions from rename into "
1222            "skidBuffer.\n");
1223
1224    for (int inst_num = 0; inst_num < fromRename->size; ++inst_num) {
1225        DynInstPtr inst = fromRename->insts[inst_num];
1226
1227        if (!inst->isSquashed()) {
1228            DPRINTF(Commit, "Inserting PC %#x [sn:%i] [tid:%i] into ",
1229                    "skidBuffer.\n", inst->readPC(), inst->seqNum,
1230                    inst->threadNumber);
1231            skidBuffer.push(inst);
1232        } else {
1233            DPRINTF(Commit, "Instruction PC %#x [sn:%i] [tid:%i] was "
1234                    "squashed, skipping.\n",
1235                    inst->readPC(), inst->seqNum, inst->threadNumber);
1236        }
1237    }
1238}
1239
1240template <class Impl>
1241void
1242DefaultCommit<Impl>::markCompletedInsts()
1243{
1244    // Grab completed insts out of the IEW instruction queue, and mark
1245    // instructions completed within the ROB.
1246    for (int inst_num = 0;
1247         inst_num < fromIEW->size && fromIEW->insts[inst_num];
1248         ++inst_num)
1249    {
1250        if (!fromIEW->insts[inst_num]->isSquashed()) {
1251            DPRINTF(Commit, "[tid:%i]: Marking PC %#x, [sn:%lli] ready "
1252                    "within ROB.\n",
1253                    fromIEW->insts[inst_num]->threadNumber,
1254                    fromIEW->insts[inst_num]->readPC(),
1255                    fromIEW->insts[inst_num]->seqNum);
1256
1257            // Mark the instruction as ready to commit.
1258            fromIEW->insts[inst_num]->setCanCommit();
1259        }
1260    }
1261}
1262
1263template <class Impl>
1264bool
1265DefaultCommit<Impl>::robDoneSquashing()
1266{
1267    std::list<unsigned>::iterator threads = (*activeThreads).begin();
1268
1269    while (threads != (*activeThreads).end()) {
1270        unsigned tid = *threads++;
1271
1272        if (!rob->isDoneSquashing(tid))
1273            return false;
1274    }
1275
1276    return true;
1277}
1278
1279template <class Impl>
1280void
1281DefaultCommit<Impl>::updateComInstStats(DynInstPtr &inst)
1282{
1283    unsigned thread = inst->threadNumber;
1284
1285    //
1286    //  Pick off the software prefetches
1287    //
1288#ifdef TARGET_ALPHA
1289    if (inst->isDataPrefetch()) {
1290        statComSwp[thread]++;
1291    } else {
1292        statComInst[thread]++;
1293    }
1294#else
1295    statComInst[thread]++;
1296#endif
1297
1298    //
1299    //  Control Instructions
1300    //
1301    if (inst->isControl())
1302        statComBranches[thread]++;
1303
1304    //
1305    //  Memory references
1306    //
1307    if (inst->isMemRef()) {
1308        statComRefs[thread]++;
1309
1310        if (inst->isLoad()) {
1311            statComLoads[thread]++;
1312        }
1313    }
1314
1315    if (inst->isMemBarrier()) {
1316        statComMembars[thread]++;
1317    }
1318}
1319
1320////////////////////////////////////////
1321//                                    //
1322//  SMT COMMIT POLICY MAINTAINED HERE //
1323//                                    //
1324////////////////////////////////////////
1325template <class Impl>
1326int
1327DefaultCommit<Impl>::getCommittingThread()
1328{
1329    if (numThreads > 1) {
1330        switch (commitPolicy) {
1331
1332          case Aggressive:
1333            //If Policy is Aggressive, commit will call
1334            //this function multiple times per
1335            //cycle
1336            return oldestReady();
1337
1338          case RoundRobin:
1339            return roundRobin();
1340
1341          case OldestReady:
1342            return oldestReady();
1343
1344          default:
1345            return -1;
1346        }
1347    } else {
1348        int tid = (*activeThreads).front();
1349
1350        if (commitStatus[tid] == Running ||
1351            commitStatus[tid] == Idle ||
1352            commitStatus[tid] == FetchTrapPending) {
1353            return tid;
1354        } else {
1355            return -1;
1356        }
1357    }
1358}
1359
1360template<class Impl>
1361int
1362DefaultCommit<Impl>::roundRobin()
1363{
1364    std::list<unsigned>::iterator pri_iter = priority_list.begin();
1365    std::list<unsigned>::iterator end      = priority_list.end();
1366
1367    while (pri_iter != end) {
1368        unsigned tid = *pri_iter;
1369
1370        if (commitStatus[tid] == Running ||
1371            commitStatus[tid] == Idle ||
1372            commitStatus[tid] == FetchTrapPending) {
1373
1374            if (rob->isHeadReady(tid)) {
1375                priority_list.erase(pri_iter);
1376                priority_list.push_back(tid);
1377
1378                return tid;
1379            }
1380        }
1381
1382        pri_iter++;
1383    }
1384
1385    return -1;
1386}
1387
1388template<class Impl>
1389int
1390DefaultCommit<Impl>::oldestReady()
1391{
1392    unsigned oldest = 0;
1393    bool first = true;
1394
1395    std::list<unsigned>::iterator threads = (*activeThreads).begin();
1396
1397    while (threads != (*activeThreads).end()) {
1398        unsigned tid = *threads++;
1399
1400        if (!rob->isEmpty(tid) &&
1401            (commitStatus[tid] == Running ||
1402             commitStatus[tid] == Idle ||
1403             commitStatus[tid] == FetchTrapPending)) {
1404
1405            if (rob->isHeadReady(tid)) {
1406
1407                DynInstPtr head_inst = rob->readHeadInst(tid);
1408
1409                if (first) {
1410                    oldest = tid;
1411                    first = false;
1412                } else if (head_inst->seqNum < oldest) {
1413                    oldest = tid;
1414                }
1415            }
1416        }
1417    }
1418
1419    if (!first) {
1420        return oldest;
1421    } else {
1422        return -1;
1423    }
1424}
1425