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