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