commit_impl.hh revision 2348
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
29#include <algorithm>
30#include <string>
31
32#include "base/loader/symtab.hh"
33#include "base/timebuf.hh"
34#include "cpu/checker/cpu.hh"
35#include "cpu/exetrace.hh"
36#include "cpu/o3/commit.hh"
37#include "cpu/o3/thread_state.hh"
38
39using namespace std;
40
41template <class Impl>
42DefaultCommit<Impl>::TrapEvent::TrapEvent(DefaultCommit<Impl> *_commit,
43                                          unsigned _tid)
44    : Event(&mainEventQueue, CPU_Tick_Pri), commit(_commit), tid(_tid)
45{
46    this->setFlags(Event::AutoDelete);
47}
48
49template <class Impl>
50void
51DefaultCommit<Impl>::TrapEvent::process()
52{
53    // This will get reset by commit if it was switched out at the
54    // time of this event processing.
55    commit->trapSquash[tid] = true;
56}
57
58template <class Impl>
59const char *
60DefaultCommit<Impl>::TrapEvent::description()
61{
62    return "Trap event";
63}
64
65template <class Impl>
66DefaultCommit<Impl>::DefaultCommit(Params *params)
67    : dcacheInterface(params->dcacheInterface),
68      squashCounter(0),
69      iewToCommitDelay(params->iewToCommitDelay),
70      commitToIEWDelay(params->commitToIEWDelay),
71      renameToROBDelay(params->renameToROBDelay),
72      fetchToCommitDelay(params->commitToFetchDelay),
73      renameWidth(params->renameWidth),
74      iewWidth(params->executeWidth),
75      commitWidth(params->commitWidth),
76      numThreads(params->numberOfThreads),
77      switchedOut(false),
78      trapLatency(params->trapLatency),
79      fetchTrapLatency(params->fetchTrapLatency)
80{
81    _status = Active;
82    _nextStatus = Inactive;
83    string policy = params->smtCommitPolicy;
84
85    //Convert string to lowercase
86    std::transform(policy.begin(), policy.end(), policy.begin(),
87                   (int(*)(int)) tolower);
88
89    //Assign commit policy
90    if (policy == "aggressive"){
91        commitPolicy = Aggressive;
92
93        DPRINTF(Commit,"Commit Policy set to Aggressive.");
94    } else if (policy == "roundrobin"){
95        commitPolicy = RoundRobin;
96
97        //Set-Up Priority List
98        for (int tid=0; tid < numThreads; tid++) {
99            priority_list.push_back(tid);
100        }
101
102        DPRINTF(Commit,"Commit Policy set to Round Robin.");
103    } else if (policy == "oldestready"){
104        commitPolicy = OldestReady;
105
106        DPRINTF(Commit,"Commit Policy set to Oldest Ready.");
107    } else {
108        assert(0 && "Invalid SMT Commit Policy. Options Are: {Aggressive,"
109               "RoundRobin,OldestReady}");
110    }
111
112    for (int i=0; i < numThreads; i++) {
113        commitStatus[i] = Idle;
114        changedROBNumEntries[i] = false;
115        trapSquash[i] = false;
116        xcSquash[i] = false;
117    }
118
119    fetchFaultTick = 0;
120    fetchTrapWait = 0;
121}
122
123template <class Impl>
124std::string
125DefaultCommit<Impl>::name() const
126{
127    return cpu->name() + ".commit";
128}
129
130template <class Impl>
131void
132DefaultCommit<Impl>::regStats()
133{
134    using namespace Stats;
135    commitCommittedInsts
136        .name(name() + ".commitCommittedInsts")
137        .desc("The number of committed instructions")
138        .prereq(commitCommittedInsts);
139    commitSquashedInsts
140        .name(name() + ".commitSquashedInsts")
141        .desc("The number of squashed insts skipped by commit")
142        .prereq(commitSquashedInsts);
143    commitSquashEvents
144        .name(name() + ".commitSquashEvents")
145        .desc("The number of times commit is told to squash")
146        .prereq(commitSquashEvents);
147    commitNonSpecStalls
148        .name(name() + ".commitNonSpecStalls")
149        .desc("The number of times commit has been forced to stall to "
150              "communicate backwards")
151        .prereq(commitNonSpecStalls);
152    branchMispredicts
153        .name(name() + ".branchMispredicts")
154        .desc("The number of times a branch was mispredicted")
155        .prereq(branchMispredicts);
156    numCommittedDist
157        .init(0,commitWidth,1)
158        .name(name() + ".COM:committed_per_cycle")
159        .desc("Number of insts commited each cycle")
160        .flags(Stats::pdf)
161        ;
162
163    statComInst
164        .init(cpu->number_of_threads)
165        .name(name() + ".COM:count")
166        .desc("Number of instructions committed")
167        .flags(total)
168        ;
169
170    statComSwp
171        .init(cpu->number_of_threads)
172        .name(name() + ".COM:swp_count")
173        .desc("Number of s/w prefetches committed")
174        .flags(total)
175        ;
176
177    statComRefs
178        .init(cpu->number_of_threads)
179        .name(name() +  ".COM:refs")
180        .desc("Number of memory references committed")
181        .flags(total)
182        ;
183
184    statComLoads
185        .init(cpu->number_of_threads)
186        .name(name() +  ".COM:loads")
187        .desc("Number of loads committed")
188        .flags(total)
189        ;
190
191    statComMembars
192        .init(cpu->number_of_threads)
193        .name(name() +  ".COM:membars")
194        .desc("Number of memory barriers committed")
195        .flags(total)
196        ;
197
198    statComBranches
199        .init(cpu->number_of_threads)
200        .name(name() + ".COM:branches")
201        .desc("Number of branches committed")
202        .flags(total)
203        ;
204
205    //
206    //  Commit-Eligible instructions...
207    //
208    //  -> The number of instructions eligible to commit in those
209    //  cycles where we reached our commit BW limit (less the number
210    //  actually committed)
211    //
212    //  -> The average value is computed over ALL CYCLES... not just
213    //  the BW limited cycles
214    //
215    //  -> The standard deviation is computed only over cycles where
216    //  we reached the BW limit
217    //
218    commitEligible
219        .init(cpu->number_of_threads)
220        .name(name() + ".COM:bw_limited")
221        .desc("number of insts not committed due to BW limits")
222        .flags(total)
223        ;
224
225    commitEligibleSamples
226        .name(name() + ".COM:bw_lim_events")
227        .desc("number cycles where commit BW limit reached")
228        ;
229}
230
231template <class Impl>
232void
233DefaultCommit<Impl>::setCPU(FullCPU *cpu_ptr)
234{
235    DPRINTF(Commit, "Commit: Setting CPU pointer.\n");
236    cpu = cpu_ptr;
237
238    // Commit must broadcast the number of free entries it has at the start of
239    // the simulation, so it starts as active.
240    cpu->activateStage(FullCPU::CommitIdx);
241
242    trapLatency = cpu->cycles(trapLatency);
243    fetchTrapLatency = cpu->cycles(fetchTrapLatency);
244}
245
246template <class Impl>
247void
248DefaultCommit<Impl>::setThreads(vector<Thread *> &threads)
249{
250    thread = threads;
251}
252
253template <class Impl>
254void
255DefaultCommit<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *tb_ptr)
256{
257    DPRINTF(Commit, "Commit: Setting time buffer pointer.\n");
258    timeBuffer = tb_ptr;
259
260    // Setup wire to send information back to IEW.
261    toIEW = timeBuffer->getWire(0);
262
263    // Setup wire to read data from IEW (for the ROB).
264    robInfoFromIEW = timeBuffer->getWire(-iewToCommitDelay);
265}
266
267template <class Impl>
268void
269DefaultCommit<Impl>::setFetchQueue(TimeBuffer<FetchStruct> *fq_ptr)
270{
271    DPRINTF(Commit, "Commit: Setting fetch queue pointer.\n");
272    fetchQueue = fq_ptr;
273
274    // Setup wire to get instructions from rename (for the ROB).
275    fromFetch = fetchQueue->getWire(-fetchToCommitDelay);
276}
277
278template <class Impl>
279void
280DefaultCommit<Impl>::setRenameQueue(TimeBuffer<RenameStruct> *rq_ptr)
281{
282    DPRINTF(Commit, "Commit: Setting rename queue pointer.\n");
283    renameQueue = rq_ptr;
284
285    // Setup wire to get instructions from rename (for the ROB).
286    fromRename = renameQueue->getWire(-renameToROBDelay);
287}
288
289template <class Impl>
290void
291DefaultCommit<Impl>::setIEWQueue(TimeBuffer<IEWStruct> *iq_ptr)
292{
293    DPRINTF(Commit, "Commit: Setting IEW queue pointer.\n");
294    iewQueue = iq_ptr;
295
296    // Setup wire to get instructions from IEW.
297    fromIEW = iewQueue->getWire(-iewToCommitDelay);
298}
299
300template <class Impl>
301void
302DefaultCommit<Impl>::setFetchStage(Fetch *fetch_stage)
303{
304    fetchStage = fetch_stage;
305}
306
307template <class Impl>
308void
309DefaultCommit<Impl>::setIEWStage(IEW *iew_stage)
310{
311    iewStage = iew_stage;
312}
313
314template<class Impl>
315void
316DefaultCommit<Impl>::setActiveThreads(list<unsigned> *at_ptr)
317{
318    DPRINTF(Commit, "Commit: Setting active threads list pointer.\n");
319    activeThreads = at_ptr;
320}
321
322template <class Impl>
323void
324DefaultCommit<Impl>::setRenameMap(RenameMap rm_ptr[])
325{
326    DPRINTF(Commit, "Setting rename map pointers.\n");
327
328    for (int i=0; i < numThreads; i++) {
329        renameMap[i] = &rm_ptr[i];
330    }
331}
332
333template <class Impl>
334void
335DefaultCommit<Impl>::setROB(ROB *rob_ptr)
336{
337    DPRINTF(Commit, "Commit: Setting ROB pointer.\n");
338    rob = rob_ptr;
339}
340
341template <class Impl>
342void
343DefaultCommit<Impl>::initStage()
344{
345    rob->setActiveThreads(activeThreads);
346    rob->resetEntries();
347
348    // Broadcast the number of free entries.
349    for (int i=0; i < numThreads; i++) {
350        toIEW->commitInfo[i].usedROB = true;
351        toIEW->commitInfo[i].freeROBEntries = rob->numFreeEntries(i);
352    }
353
354    cpu->activityThisCycle();
355}
356
357template <class Impl>
358void
359DefaultCommit<Impl>::switchOut()
360{
361    switchPending = true;
362}
363
364template <class Impl>
365void
366DefaultCommit<Impl>::doSwitchOut()
367{
368    switchedOut = true;
369    switchPending = false;
370    rob->switchOut();
371}
372
373template <class Impl>
374void
375DefaultCommit<Impl>::takeOverFrom()
376{
377    switchedOut = false;
378    _status = Active;
379    _nextStatus = Inactive;
380    for (int i=0; i < numThreads; i++) {
381        commitStatus[i] = Idle;
382        changedROBNumEntries[i] = false;
383        trapSquash[i] = false;
384        xcSquash[i] = false;
385    }
386    squashCounter = 0;
387    rob->takeOverFrom();
388}
389
390template <class Impl>
391void
392DefaultCommit<Impl>::updateStatus()
393{
394    // reset ROB changed variable
395    list<unsigned>::iterator threads = (*activeThreads).begin();
396    while (threads != (*activeThreads).end()) {
397        unsigned tid = *threads++;
398        changedROBNumEntries[tid] = false;
399
400        // Also check if any of the threads has a trap pending
401        if (commitStatus[tid] == TrapPending ||
402            commitStatus[tid] == FetchTrapPending) {
403            _nextStatus = Active;
404        }
405    }
406
407    if (_nextStatus == Inactive && _status == Active) {
408        DPRINTF(Activity, "Deactivating stage.\n");
409        cpu->deactivateStage(FullCPU::CommitIdx);
410    } else if (_nextStatus == Active && _status == Inactive) {
411        DPRINTF(Activity, "Activating stage.\n");
412        cpu->activateStage(FullCPU::CommitIdx);
413    }
414
415    _status = _nextStatus;
416}
417
418template <class Impl>
419void
420DefaultCommit<Impl>::setNextStatus()
421{
422    int squashes = 0;
423
424    list<unsigned>::iterator threads = (*activeThreads).begin();
425
426    while (threads != (*activeThreads).end()) {
427        unsigned tid = *threads++;
428
429        if (commitStatus[tid] == ROBSquashing) {
430            squashes++;
431        }
432    }
433
434    assert(squashes == squashCounter);
435
436    // If commit is currently squashing, then it will have activity for the
437    // next cycle. Set its next status as active.
438    if (squashCounter) {
439        _nextStatus = Active;
440    }
441}
442
443template <class Impl>
444bool
445DefaultCommit<Impl>::changedROBEntries()
446{
447    list<unsigned>::iterator threads = (*activeThreads).begin();
448
449    while (threads != (*activeThreads).end()) {
450        unsigned tid = *threads++;
451
452        if (changedROBNumEntries[tid]) {
453            return true;
454        }
455    }
456
457    return false;
458}
459
460template <class Impl>
461unsigned
462DefaultCommit<Impl>::numROBFreeEntries(unsigned tid)
463{
464    return rob->numFreeEntries(tid);
465}
466
467template <class Impl>
468void
469DefaultCommit<Impl>::generateTrapEvent(unsigned tid)
470{
471    DPRINTF(Commit, "Generating trap event for [tid:%i]\n", tid);
472
473    TrapEvent *trap = new TrapEvent(this, tid);
474
475    trap->schedule(curTick + trapLatency);
476
477    thread[tid]->trapPending = true;
478}
479
480template <class Impl>
481void
482DefaultCommit<Impl>::generateXCEvent(unsigned tid)
483{
484    DPRINTF(Commit, "Generating XC squash event for [tid:%i]\n", tid);
485
486    xcSquash[tid] = true;
487}
488
489template <class Impl>
490void
491DefaultCommit<Impl>::squashAll(unsigned tid)
492{
493    // If we want to include the squashing instruction in the squash,
494    // then use one older sequence number.
495    // Hopefully this doesn't mess things up.  Basically I want to squash
496    // all instructions of this thread.
497    InstSeqNum squashed_inst = rob->isEmpty() ?
498        0 : rob->readHeadInst(tid)->seqNum - 1;;
499
500    // All younger instructions will be squashed. Set the sequence
501    // number as the youngest instruction in the ROB (0 in this case.
502    // Hopefully nothing breaks.)
503    youngestSeqNum[tid] = 0;
504
505    rob->squash(squashed_inst, tid);
506    changedROBNumEntries[tid] = true;
507
508    // Send back the sequence number of the squashed instruction.
509    toIEW->commitInfo[tid].doneSeqNum = squashed_inst;
510
511    // Send back the squash signal to tell stages that they should
512    // squash.
513    toIEW->commitInfo[tid].squash = true;
514
515    // Send back the rob squashing signal so other stages know that
516    // the ROB is in the process of squashing.
517    toIEW->commitInfo[tid].robSquashing = true;
518
519    toIEW->commitInfo[tid].branchMispredict = false;
520
521    toIEW->commitInfo[tid].nextPC = PC[tid];
522}
523
524template <class Impl>
525void
526DefaultCommit<Impl>::squashFromTrap(unsigned tid)
527{
528    squashAll(tid);
529
530    DPRINTF(Commit, "Squashing from trap, restarting at PC %#x\n", PC[tid]);
531
532    thread[tid]->trapPending = false;
533    thread[tid]->inSyscall = false;
534
535    trapSquash[tid] = false;
536
537    commitStatus[tid] = ROBSquashing;
538    cpu->activityThisCycle();
539
540    ++squashCounter;
541}
542
543template <class Impl>
544void
545DefaultCommit<Impl>::squashFromXC(unsigned tid)
546{
547    squashAll(tid);
548
549    DPRINTF(Commit, "Squashing from XC, restarting at PC %#x\n", PC[tid]);
550
551    thread[tid]->inSyscall = false;
552    assert(!thread[tid]->trapPending);
553
554    commitStatus[tid] = ROBSquashing;
555    cpu->activityThisCycle();
556
557    xcSquash[tid] = false;
558
559    ++squashCounter;
560}
561
562template <class Impl>
563void
564DefaultCommit<Impl>::tick()
565{
566    wroteToTimeBuffer = false;
567    _nextStatus = Inactive;
568
569    if (switchPending && rob->isEmpty() && !iewStage->hasStoresToWB()) {
570        cpu->signalSwitched();
571        return;
572    }
573
574    list<unsigned>::iterator threads = (*activeThreads).begin();
575
576    // Check if any of the threads are done squashing.  Change the
577    // status if they are done.
578    while (threads != (*activeThreads).end()) {
579        unsigned tid = *threads++;
580
581        if (commitStatus[tid] == ROBSquashing) {
582
583            if (rob->isDoneSquashing(tid)) {
584                commitStatus[tid] = Running;
585                --squashCounter;
586            } else {
587                DPRINTF(Commit,"[tid:%u]: Still Squashing, cannot commit any"
588                        "insts this cycle.\n", tid);
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        !xcSquash[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        if (fromFetch->fetchFault && commitStatus[0] != TrapPending) {
696            // Record the fault.  Wait until it's empty in the ROB.
697            // Then handle the trap.  Ignore it if there's already a
698            // trap pending as fetch will be redirected.
699            fetchFault = fromFetch->fetchFault;
700            fetchFaultTick = curTick + fetchTrapLatency;
701            commitStatus[0] = FetchTrapPending;
702            DPRINTF(Commit, "Fault from fetch recorded.  Will trap if the "
703                    "ROB empties without squashing the fault.\n");
704            fetchTrapWait = 0;
705        }
706
707        // Fetch may tell commit to clear the trap if it's been squashed.
708        if (fromFetch->clearFetchFault) {
709            DPRINTF(Commit, "Received clear fetch fault signal\n");
710            fetchTrapWait = 0;
711            if (commitStatus[0] == FetchTrapPending) {
712                DPRINTF(Commit, "Clearing fault from fetch\n");
713                commitStatus[0] = Running;
714            }
715        }
716*/
717        // Not sure which one takes priority.  I think if we have
718        // both, that's a bad sign.
719        if (trapSquash[tid] == true) {
720            assert(!xcSquash[tid]);
721            squashFromTrap(tid);
722        } else if (xcSquash[tid] == true) {
723            squashFromXC(tid);
724        }
725
726        // Squashed sequence number must be older than youngest valid
727        // instruction in the ROB. This prevents squashes from younger
728        // instructions overriding squashes from older instructions.
729        if (fromIEW->squash[tid] &&
730            commitStatus[tid] != TrapPending &&
731            fromIEW->squashedSeqNum[tid] <= youngestSeqNum[tid]) {
732
733            DPRINTF(Commit, "[tid:%i]: Squashing due to PC %#x [sn:%i]\n",
734                    tid,
735                    fromIEW->mispredPC[tid],
736                    fromIEW->squashedSeqNum[tid]);
737
738            DPRINTF(Commit, "[tid:%i]: Redirecting to PC %#x\n",
739                    tid,
740                    fromIEW->nextPC[tid]);
741
742            commitStatus[tid] = ROBSquashing;
743
744            ++squashCounter;
745
746            // If we want to include the squashing instruction in the squash,
747            // then use one older sequence number.
748            InstSeqNum squashed_inst = fromIEW->squashedSeqNum[tid];
749
750            if (fromIEW->includeSquashInst[tid] == true)
751                squashed_inst--;
752
753            // All younger instructions will be squashed. Set the sequence
754            // number as the youngest instruction in the ROB.
755            youngestSeqNum[tid] = squashed_inst;
756
757            rob->squash(squashed_inst, tid);
758            changedROBNumEntries[tid] = true;
759
760            toIEW->commitInfo[tid].doneSeqNum = squashed_inst;
761
762            toIEW->commitInfo[tid].squash = true;
763
764            // Send back the rob squashing signal so other stages know that
765            // the ROB is in the process of squashing.
766            toIEW->commitInfo[tid].robSquashing = true;
767
768            toIEW->commitInfo[tid].branchMispredict =
769                fromIEW->branchMispredict[tid];
770
771            toIEW->commitInfo[tid].branchTaken =
772                fromIEW->branchTaken[tid];
773
774            toIEW->commitInfo[tid].nextPC = fromIEW->nextPC[tid];
775
776            toIEW->commitInfo[tid].mispredPC = fromIEW->mispredPC[tid];
777
778            if (toIEW->commitInfo[tid].branchMispredict) {
779                ++branchMispredicts;
780            }
781        }
782
783    }
784
785    setNextStatus();
786
787    if (squashCounter != numThreads) {
788        // If we're not currently squashing, then get instructions.
789        getInsts();
790
791        // Try to commit any instructions.
792        commitInsts();
793    }
794
795    //Check for any activity
796    threads = (*activeThreads).begin();
797
798    while (threads != (*activeThreads).end()) {
799        unsigned tid = *threads++;
800
801        if (changedROBNumEntries[tid]) {
802            toIEW->commitInfo[tid].usedROB = true;
803            toIEW->commitInfo[tid].freeROBEntries = rob->numFreeEntries(tid);
804
805            if (rob->isEmpty(tid)) {
806                toIEW->commitInfo[tid].emptyROB = true;
807            }
808
809            wroteToTimeBuffer = true;
810            changedROBNumEntries[tid] = false;
811        }
812    }
813}
814
815template <class Impl>
816void
817DefaultCommit<Impl>::commitInsts()
818{
819    ////////////////////////////////////
820    // Handle commit
821    // Note that commit will be handled prior to putting new
822    // instructions in the ROB so that the ROB only tries to commit
823    // instructions it has in this current cycle, and not instructions
824    // it is writing in during this cycle.  Can't commit and squash
825    // things at the same time...
826    ////////////////////////////////////
827
828    DPRINTF(Commit, "Trying to commit instructions in the ROB.\n");
829
830    unsigned num_committed = 0;
831
832    DynInstPtr head_inst;
833
834    // Commit as many instructions as possible until the commit bandwidth
835    // limit is reached, or it becomes impossible to commit any more.
836    while (num_committed < commitWidth) {
837        int commit_thread = getCommittingThread();
838
839        if (commit_thread == -1 || !rob->isHeadReady(commit_thread))
840            break;
841
842        head_inst = rob->readHeadInst(commit_thread);
843
844        int tid = head_inst->threadNumber;
845
846        assert(tid == commit_thread);
847
848        DPRINTF(Commit, "Trying to commit head instruction, [sn:%i] [tid:%i]\n",
849                head_inst->seqNum, tid);
850
851        // If the head instruction is squashed, it is ready to retire
852        // (be removed from the ROB) at any time.
853        if (head_inst->isSquashed()) {
854
855            DPRINTF(Commit, "Retiring squashed instruction from "
856                    "ROB.\n");
857
858            rob->retireHead(commit_thread);
859
860            ++commitSquashedInsts;
861
862            // Record that the number of ROB entries has changed.
863            changedROBNumEntries[tid] = true;
864        } else {
865            PC[tid] = head_inst->readPC();
866            nextPC[tid] = head_inst->readNextPC();
867
868            // Increment the total number of non-speculative instructions
869            // executed.
870            // Hack for now: it really shouldn't happen until after the
871            // commit is deemed to be successful, but this count is needed
872            // for syscalls.
873            thread[tid]->funcExeInst++;
874
875            // Try to commit the head instruction.
876            bool commit_success = commitHead(head_inst, num_committed);
877
878            if (commit_success) {
879                ++num_committed;
880
881                changedROBNumEntries[tid] = true;
882
883                // Set the doneSeqNum to the youngest committed instruction.
884                toIEW->commitInfo[tid].doneSeqNum = head_inst->seqNum;
885
886                ++commitCommittedInsts;
887
888                // To match the old model, don't count nops and instruction
889                // prefetches towards the total commit count.
890                if (!head_inst->isNop() && !head_inst->isInstPrefetch()) {
891                    cpu->instDone(tid);
892                }
893
894                PC[tid] = nextPC[tid];
895                nextPC[tid] = nextPC[tid] + sizeof(TheISA::MachInst);
896#if FULL_SYSTEM
897                int count = 0;
898                Addr oldpc;
899                do {
900                    // Debug statement.  Checks to make sure we're not
901                    // currently updating state while handling PC events.
902                    if (count == 0)
903                        assert(!thread[tid]->inSyscall &&
904                               !thread[tid]->trapPending);
905                    oldpc = PC[tid];
906                    cpu->system->pcEventQueue.service(
907                        thread[tid]->getXCProxy());
908                    count++;
909                } while (oldpc != PC[tid]);
910                if (count > 1) {
911                    DPRINTF(Commit, "PC skip function event, stopping commit\n");
912                    break;
913                }
914#endif
915            } else {
916                DPRINTF(Commit, "Unable to commit head instruction PC:%#x "
917                        "[tid:%i] [sn:%i].\n",
918                        head_inst->readPC(), tid ,head_inst->seqNum);
919                break;
920            }
921        }
922    }
923
924    DPRINTF(CommitRate, "%i\n", num_committed);
925    numCommittedDist.sample(num_committed);
926
927    if (num_committed == commitWidth) {
928        commitEligibleSamples[0]++;
929    }
930}
931
932template <class Impl>
933bool
934DefaultCommit<Impl>::commitHead(DynInstPtr &head_inst, unsigned inst_num)
935{
936    assert(head_inst);
937
938    int tid = head_inst->threadNumber;
939
940    // If the instruction is not executed yet, then it will need extra
941    // handling.  Signal backwards that it should be executed.
942    if (!head_inst->isExecuted()) {
943        // Keep this number correct.  We have not yet actually executed
944        // and committed this instruction.
945        thread[tid]->funcExeInst--;
946
947        head_inst->reachedCommit = true;
948
949        if (head_inst->isNonSpeculative() ||
950            head_inst->isStoreConditional() ||
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