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