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