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