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