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