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