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