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