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