commit_impl.hh revision 13453:4a7a060ea26e
15222Sksewell@umich.edu/*
25254Sksewell@umich.edu * Copyright 2014 Google, Inc.
35254Sksewell@umich.edu * Copyright (c) 2010-2014, 2017 ARM Limited
45222Sksewell@umich.edu * All rights reserved
55254Sksewell@umich.edu *
65254Sksewell@umich.edu * The license below extends only to copyright in the software and shall
75254Sksewell@umich.edu * not be construed as granting a license to any other intellectual
85254Sksewell@umich.edu * property including but not limited to intellectual property relating
95254Sksewell@umich.edu * to a hardware implementation of the functionality of the software
105254Sksewell@umich.edu * licensed hereunder.  You may use the software subject to the license
115254Sksewell@umich.edu * terms below provided that you ensure that this notice is replicated
125254Sksewell@umich.edu * unmodified and in its entirety in all distributions of the software,
135254Sksewell@umich.edu * modified or unmodified, in source code or in binary form.
145254Sksewell@umich.edu *
155222Sksewell@umich.edu * Copyright (c) 2004-2006 The Regents of The University of Michigan
165254Sksewell@umich.edu * All rights reserved.
175254Sksewell@umich.edu *
185254Sksewell@umich.edu * Redistribution and use in source and binary forms, with or without
195254Sksewell@umich.edu * modification, are permitted provided that the following conditions are
205254Sksewell@umich.edu * met: redistributions of source code must retain the above copyright
215254Sksewell@umich.edu * notice, this list of conditions and the following disclaimer;
225254Sksewell@umich.edu * redistributions in binary form must reproduce the above copyright
235254Sksewell@umich.edu * notice, this list of conditions and the following disclaimer in the
245254Sksewell@umich.edu * documentation and/or other materials provided with the distribution;
255254Sksewell@umich.edu * neither the name of the copyright holders nor the names of its
265254Sksewell@umich.edu * contributors may be used to endorse or promote products derived from
275222Sksewell@umich.edu * this software without specific prior written permission.
285254Sksewell@umich.edu *
295222Sksewell@umich.edu * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
305222Sksewell@umich.edu * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
3111793Sbrandon.potter@amd.com * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
3211793Sbrandon.potter@amd.com * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
335222Sksewell@umich.edu * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
345222Sksewell@umich.edu * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
355222Sksewell@umich.edu * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
365222Sksewell@umich.edu * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
375222Sksewell@umich.edu * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
385222Sksewell@umich.edu * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
395222Sksewell@umich.edu * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
405222Sksewell@umich.edu *
418799Sgblack@eecs.umich.edu * Authors: Kevin Lim
425222Sksewell@umich.edu *          Korey Sewell
435222Sksewell@umich.edu */
445222Sksewell@umich.edu#ifndef __CPU_O3_COMMIT_IMPL_HH__
455222Sksewell@umich.edu#define __CPU_O3_COMMIT_IMPL_HH__
466378Sgblack@eecs.umich.edu
476378Sgblack@eecs.umich.edu#include <algorithm>
485222Sksewell@umich.edu#include <set>
495222Sksewell@umich.edu#include <string>
505222Sksewell@umich.edu
515222Sksewell@umich.edu#include "arch/utility.hh"
525222Sksewell@umich.edu#include "base/cp_annotate.hh"
535222Sksewell@umich.edu#include "base/loader/symtab.hh"
545222Sksewell@umich.edu#include "base/logging.hh"
555222Sksewell@umich.edu#include "config/the_isa.hh"
565222Sksewell@umich.edu#include "cpu/checker/cpu.hh"
575222Sksewell@umich.edu#include "cpu/o3/commit.hh"
588852Sandreas.hansson@arm.com#include "cpu/o3/thread_state.hh"
5913893Sgabeblack@google.com#include "cpu/base.hh"
605222Sksewell@umich.edu#include "cpu/exetrace.hh"
615222Sksewell@umich.edu#include "cpu/timebuf.hh"
625222Sksewell@umich.edu#include "debug/Activity.hh"
635222Sksewell@umich.edu#include "debug/Commit.hh"
645222Sksewell@umich.edu#include "debug/CommitRate.hh"
655222Sksewell@umich.edu#include "debug/Drain.hh"
665222Sksewell@umich.edu#include "debug/ExecFaulting.hh"
675222Sksewell@umich.edu#include "debug/O3PipeView.hh"
685222Sksewell@umich.edu#include "params/DerivO3CPU.hh"
695222Sksewell@umich.edu#include "sim/faults.hh"
705222Sksewell@umich.edu#include "sim/full_system.hh"
715222Sksewell@umich.edu
725222Sksewell@umich.eduusing namespace std;
738852Sandreas.hansson@arm.com
7413893Sgabeblack@google.comtemplate <class Impl>
755222Sksewell@umich.eduvoid
765222Sksewell@umich.eduDefaultCommit<Impl>::processTrapEvent(ThreadID tid)
775222Sksewell@umich.edu{
785222Sksewell@umich.edu    // This will get reset by commit if it was switched out at the
7913893Sgabeblack@google.com    // time of this event processing.
805222Sksewell@umich.edu    trapSquash[tid] = true;
815222Sksewell@umich.edu}
825222Sksewell@umich.edu
835222Sksewell@umich.edutemplate <class Impl>
845222Sksewell@umich.eduDefaultCommit<Impl>::DefaultCommit(O3CPU *_cpu, DerivO3CPUParams *params)
855222Sksewell@umich.edu    : cpu(_cpu),
865222Sksewell@umich.edu      iewToCommitDelay(params->iewToCommitDelay),
8714018Sgabeblack@google.com      commitToIEWDelay(params->commitToIEWDelay),
885222Sksewell@umich.edu      renameToROBDelay(params->renameToROBDelay),
895222Sksewell@umich.edu      fetchToCommitDelay(params->commitToFetchDelay),
905222Sksewell@umich.edu      renameWidth(params->renameWidth),
915222Sksewell@umich.edu      commitWidth(params->commitWidth),
925222Sksewell@umich.edu      numThreads(params->numThreads),
935222Sksewell@umich.edu      drainPending(false),
945222Sksewell@umich.edu      drainImminent(false),
955222Sksewell@umich.edu      trapLatency(params->trapLatency),
965222Sksewell@umich.edu      canHandleInterrupts(true),
975222Sksewell@umich.edu      avoidQuiesceLiveLock(false)
985222Sksewell@umich.edu{
9910417Sandreas.hansson@arm.com    if (commitWidth > Impl::MaxWidth)
1005222Sksewell@umich.edu        fatal("commitWidth (%d) is larger than compiled limit (%d),\n"
1015222Sksewell@umich.edu             "\tincrease MaxWidth in src/cpu/o3/impl.hh\n",
1025222Sksewell@umich.edu             commitWidth, static_cast<int>(Impl::MaxWidth));
1035222Sksewell@umich.edu
1045222Sksewell@umich.edu    _status = Active;
1055222Sksewell@umich.edu    _nextStatus = Inactive;
1065222Sksewell@umich.edu    std::string policy = params->smtCommitPolicy;
1075222Sksewell@umich.edu
1085222Sksewell@umich.edu    //Convert string to lowercase
1095222Sksewell@umich.edu    std::transform(policy.begin(), policy.end(), policy.begin(),
1105222Sksewell@umich.edu                   (int(*)(int)) tolower);
1115222Sksewell@umich.edu
1125222Sksewell@umich.edu    //Assign commit policy
1135222Sksewell@umich.edu    if (policy == "aggressive"){
1145222Sksewell@umich.edu        commitPolicy = Aggressive;
1155222Sksewell@umich.edu
1165222Sksewell@umich.edu        DPRINTF(Commit,"Commit Policy set to Aggressive.\n");
1175222Sksewell@umich.edu    } else if (policy == "roundrobin"){
1185222Sksewell@umich.edu        commitPolicy = RoundRobin;
1195222Sksewell@umich.edu
1205222Sksewell@umich.edu        //Set-Up Priority List
1215222Sksewell@umich.edu        for (ThreadID tid = 0; tid < numThreads; tid++) {
1225222Sksewell@umich.edu            priority_list.push_back(tid);
1235222Sksewell@umich.edu        }
1245222Sksewell@umich.edu
1255222Sksewell@umich.edu        DPRINTF(Commit,"Commit Policy set to Round Robin.\n");
1265222Sksewell@umich.edu    } else if (policy == "oldestready"){
1275222Sksewell@umich.edu        commitPolicy = OldestReady;
1285222Sksewell@umich.edu
1295222Sksewell@umich.edu        DPRINTF(Commit,"Commit Policy set to Oldest Ready.");
1305222Sksewell@umich.edu    } else {
1315222Sksewell@umich.edu        panic("Invalid SMT commit policy. Options are: Aggressive, "
1325222Sksewell@umich.edu               "RoundRobin, OldestReady");
1335222Sksewell@umich.edu    }
1345222Sksewell@umich.edu
1355222Sksewell@umich.edu    for (ThreadID tid = 0; tid < Impl::MaxThreads; tid++) {
1365222Sksewell@umich.edu        commitStatus[tid] = Idle;
1375222Sksewell@umich.edu        changedROBNumEntries[tid] = false;
1385222Sksewell@umich.edu        trapSquash[tid] = false;
1395222Sksewell@umich.edu        tcSquash[tid] = false;
1405222Sksewell@umich.edu        squashAfterInst[tid] = nullptr;
1415222Sksewell@umich.edu        pc[tid].set(0);
1425222Sksewell@umich.edu        youngestSeqNum[tid] = 0;
1435222Sksewell@umich.edu        lastCommitedSeqNum[tid] = 0;
1445222Sksewell@umich.edu        trapInFlight[tid] = false;
1455222Sksewell@umich.edu        committedStores[tid] = false;
1465222Sksewell@umich.edu        checkEmptyROB[tid] = false;
1475222Sksewell@umich.edu        renameMap[tid] = nullptr;
1485222Sksewell@umich.edu    }
1495222Sksewell@umich.edu    interrupt = NoFault;
1505222Sksewell@umich.edu}
1515222Sksewell@umich.edu
1525222Sksewell@umich.edutemplate <class Impl>
1535222Sksewell@umich.edustd::string
1545222Sksewell@umich.eduDefaultCommit<Impl>::name() const
1555222Sksewell@umich.edu{
1565222Sksewell@umich.edu    return cpu->name() + ".commit";
1575222Sksewell@umich.edu}
1585222Sksewell@umich.edu
1595222Sksewell@umich.edutemplate <class Impl>
1605222Sksewell@umich.eduvoid
1615222Sksewell@umich.eduDefaultCommit<Impl>::regProbePoints()
1625222Sksewell@umich.edu{
1635222Sksewell@umich.edu    ppCommit = new ProbePointArg<DynInstPtr>(cpu->getProbeManager(), "Commit");
1645222Sksewell@umich.edu    ppCommitStall = new ProbePointArg<DynInstPtr>(cpu->getProbeManager(), "CommitStall");
1655222Sksewell@umich.edu    ppSquash = new ProbePointArg<DynInstPtr>(cpu->getProbeManager(), "Squash");
1665222Sksewell@umich.edu}
1675222Sksewell@umich.edu
1685222Sksewell@umich.edutemplate <class Impl>
1695222Sksewell@umich.eduvoid
1705222Sksewell@umich.eduDefaultCommit<Impl>::regStats()
1715222Sksewell@umich.edu{
1725222Sksewell@umich.edu    using namespace Stats;
1735222Sksewell@umich.edu    commitSquashedInsts
1745222Sksewell@umich.edu        .name(name() + ".commitSquashedInsts")
1755222Sksewell@umich.edu        .desc("The number of squashed insts skipped by commit")
1765222Sksewell@umich.edu        .prereq(commitSquashedInsts);
1775222Sksewell@umich.edu
1785222Sksewell@umich.edu    commitNonSpecStalls
1795222Sksewell@umich.edu        .name(name() + ".commitNonSpecStalls")
1805222Sksewell@umich.edu        .desc("The number of times commit has been forced to stall to "
1815222Sksewell@umich.edu              "communicate backwards")
1825222Sksewell@umich.edu        .prereq(commitNonSpecStalls);
1835222Sksewell@umich.edu
1845222Sksewell@umich.edu    branchMispredicts
1855222Sksewell@umich.edu        .name(name() + ".branchMispredicts")
1865222Sksewell@umich.edu        .desc("The number of times a branch was mispredicted")
1875222Sksewell@umich.edu        .prereq(branchMispredicts);
1885222Sksewell@umich.edu
1895222Sksewell@umich.edu    numCommittedDist
1905222Sksewell@umich.edu        .init(0,commitWidth,1)
1915222Sksewell@umich.edu        .name(name() + ".committed_per_cycle")
1925222Sksewell@umich.edu        .desc("Number of insts commited each cycle")
1935222Sksewell@umich.edu        .flags(Stats::pdf)
1945222Sksewell@umich.edu        ;
1955222Sksewell@umich.edu
1965222Sksewell@umich.edu    instsCommitted
1975222Sksewell@umich.edu        .init(cpu->numThreads)
1985222Sksewell@umich.edu        .name(name() + ".committedInsts")
1995222Sksewell@umich.edu        .desc("Number of instructions committed")
2005222Sksewell@umich.edu        .flags(total)
2015222Sksewell@umich.edu        ;
2025222Sksewell@umich.edu
2035222Sksewell@umich.edu    opsCommitted
2045222Sksewell@umich.edu        .init(cpu->numThreads)
20514018Sgabeblack@google.com        .name(name() + ".committedOps")
2065222Sksewell@umich.edu        .desc("Number of ops (including micro ops) committed")
2075222Sksewell@umich.edu        .flags(total)
2085222Sksewell@umich.edu        ;
2095222Sksewell@umich.edu
2105222Sksewell@umich.edu    statComSwp
2115222Sksewell@umich.edu        .init(cpu->numThreads)
2125222Sksewell@umich.edu        .name(name() + ".swp_count")
2135222Sksewell@umich.edu        .desc("Number of s/w prefetches committed")
2145222Sksewell@umich.edu        .flags(total)
21514018Sgabeblack@google.com        ;
2165222Sksewell@umich.edu
2175222Sksewell@umich.edu    statComRefs
2185222Sksewell@umich.edu        .init(cpu->numThreads)
2195222Sksewell@umich.edu        .name(name() +  ".refs")
2205222Sksewell@umich.edu        .desc("Number of memory references committed")
2215222Sksewell@umich.edu        .flags(total)
2225222Sksewell@umich.edu        ;
2235222Sksewell@umich.edu
2245222Sksewell@umich.edu    statComLoads
2255222Sksewell@umich.edu        .init(cpu->numThreads)
2265222Sksewell@umich.edu        .name(name() +  ".loads")
2275222Sksewell@umich.edu        .desc("Number of loads committed")
2285222Sksewell@umich.edu        .flags(total)
2295222Sksewell@umich.edu        ;
2306378Sgblack@eecs.umich.edu
2315222Sksewell@umich.edu    statComMembars
2325222Sksewell@umich.edu        .init(cpu->numThreads)
233        .name(name() +  ".membars")
234        .desc("Number of memory barriers committed")
235        .flags(total)
236        ;
237
238    statComBranches
239        .init(cpu->numThreads)
240        .name(name() + ".branches")
241        .desc("Number of branches committed")
242        .flags(total)
243        ;
244
245    statComFloating
246        .init(cpu->numThreads)
247        .name(name() + ".fp_insts")
248        .desc("Number of committed floating point instructions.")
249        .flags(total)
250        ;
251
252    statComVector
253        .init(cpu->numThreads)
254        .name(name() + ".vec_insts")
255        .desc("Number of committed Vector instructions.")
256        .flags(total)
257        ;
258
259    statComInteger
260        .init(cpu->numThreads)
261        .name(name()+".int_insts")
262        .desc("Number of committed integer instructions.")
263        .flags(total)
264        ;
265
266    statComFunctionCalls
267        .init(cpu->numThreads)
268        .name(name()+".function_calls")
269        .desc("Number of function calls committed.")
270        .flags(total)
271        ;
272
273    statCommittedInstType
274        .init(numThreads,Enums::Num_OpClass)
275        .name(name() + ".op_class")
276        .desc("Class of committed instruction")
277        .flags(total | pdf | dist)
278        ;
279    statCommittedInstType.ysubnames(Enums::OpClassStrings);
280
281    commitEligibleSamples
282        .name(name() + ".bw_lim_events")
283        .desc("number cycles where commit BW limit reached")
284        ;
285}
286
287template <class Impl>
288void
289DefaultCommit<Impl>::setThreads(std::vector<Thread *> &threads)
290{
291    thread = threads;
292}
293
294template <class Impl>
295void
296DefaultCommit<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *tb_ptr)
297{
298    timeBuffer = tb_ptr;
299
300    // Setup wire to send information back to IEW.
301    toIEW = timeBuffer->getWire(0);
302
303    // Setup wire to read data from IEW (for the ROB).
304    robInfoFromIEW = timeBuffer->getWire(-iewToCommitDelay);
305}
306
307template <class Impl>
308void
309DefaultCommit<Impl>::setFetchQueue(TimeBuffer<FetchStruct> *fq_ptr)
310{
311    fetchQueue = fq_ptr;
312
313    // Setup wire to get instructions from rename (for the ROB).
314    fromFetch = fetchQueue->getWire(-fetchToCommitDelay);
315}
316
317template <class Impl>
318void
319DefaultCommit<Impl>::setRenameQueue(TimeBuffer<RenameStruct> *rq_ptr)
320{
321    renameQueue = rq_ptr;
322
323    // Setup wire to get instructions from rename (for the ROB).
324    fromRename = renameQueue->getWire(-renameToROBDelay);
325}
326
327template <class Impl>
328void
329DefaultCommit<Impl>::setIEWQueue(TimeBuffer<IEWStruct> *iq_ptr)
330{
331    iewQueue = iq_ptr;
332
333    // Setup wire to get instructions from IEW.
334    fromIEW = iewQueue->getWire(-iewToCommitDelay);
335}
336
337template <class Impl>
338void
339DefaultCommit<Impl>::setIEWStage(IEW *iew_stage)
340{
341    iewStage = iew_stage;
342}
343
344template<class Impl>
345void
346DefaultCommit<Impl>::setActiveThreads(list<ThreadID> *at_ptr)
347{
348    activeThreads = at_ptr;
349}
350
351template <class Impl>
352void
353DefaultCommit<Impl>::setRenameMap(RenameMap rm_ptr[])
354{
355    for (ThreadID tid = 0; tid < numThreads; tid++)
356        renameMap[tid] = &rm_ptr[tid];
357}
358
359template <class Impl>
360void
361DefaultCommit<Impl>::setROB(ROB *rob_ptr)
362{
363    rob = rob_ptr;
364}
365
366template <class Impl>
367void
368DefaultCommit<Impl>::startupStage()
369{
370    rob->setActiveThreads(activeThreads);
371    rob->resetEntries();
372
373    // Broadcast the number of free entries.
374    for (ThreadID tid = 0; tid < numThreads; tid++) {
375        toIEW->commitInfo[tid].usedROB = true;
376        toIEW->commitInfo[tid].freeROBEntries = rob->numFreeEntries(tid);
377        toIEW->commitInfo[tid].emptyROB = true;
378    }
379
380    // Commit must broadcast the number of free entries it has at the
381    // start of the simulation, so it starts as active.
382    cpu->activateStage(O3CPU::CommitIdx);
383
384    cpu->activityThisCycle();
385}
386
387template <class Impl>
388void
389DefaultCommit<Impl>::drain()
390{
391    drainPending = true;
392}
393
394template <class Impl>
395void
396DefaultCommit<Impl>::drainResume()
397{
398    drainPending = false;
399    drainImminent = false;
400}
401
402template <class Impl>
403void
404DefaultCommit<Impl>::drainSanityCheck() const
405{
406    assert(isDrained());
407    rob->drainSanityCheck();
408}
409
410template <class Impl>
411bool
412DefaultCommit<Impl>::isDrained() const
413{
414    /* Make sure no one is executing microcode. There are two reasons
415     * for this:
416     * - Hardware virtualized CPUs can't switch into the middle of a
417     *   microcode sequence.
418     * - The current fetch implementation will most likely get very
419     *   confused if it tries to start fetching an instruction that
420     *   is executing in the middle of a ucode sequence that changes
421     *   address mappings. This can happen on for example x86.
422     */
423    for (ThreadID tid = 0; tid < numThreads; tid++) {
424        if (pc[tid].microPC() != 0)
425            return false;
426    }
427
428    /* Make sure that all instructions have finished committing before
429     * declaring the system as drained. We want the pipeline to be
430     * completely empty when we declare the CPU to be drained. This
431     * makes debugging easier since CPU handover and restoring from a
432     * checkpoint with a different CPU should have the same timing.
433     */
434    return rob->isEmpty() &&
435        interrupt == NoFault;
436}
437
438template <class Impl>
439void
440DefaultCommit<Impl>::takeOverFrom()
441{
442    _status = Active;
443    _nextStatus = Inactive;
444    for (ThreadID tid = 0; tid < numThreads; tid++) {
445        commitStatus[tid] = Idle;
446        changedROBNumEntries[tid] = false;
447        trapSquash[tid] = false;
448        tcSquash[tid] = false;
449        squashAfterInst[tid] = NULL;
450    }
451    rob->takeOverFrom();
452}
453
454template <class Impl>
455void
456DefaultCommit<Impl>::deactivateThread(ThreadID tid)
457{
458    list<ThreadID>::iterator thread_it = std::find(priority_list.begin(),
459            priority_list.end(), tid);
460
461    if (thread_it != priority_list.end()) {
462        priority_list.erase(thread_it);
463    }
464}
465
466
467template <class Impl>
468void
469DefaultCommit<Impl>::updateStatus()
470{
471    // reset ROB changed variable
472    list<ThreadID>::iterator threads = activeThreads->begin();
473    list<ThreadID>::iterator end = activeThreads->end();
474
475    while (threads != end) {
476        ThreadID tid = *threads++;
477
478        changedROBNumEntries[tid] = false;
479
480        // Also check if any of the threads has a trap pending
481        if (commitStatus[tid] == TrapPending ||
482            commitStatus[tid] == FetchTrapPending) {
483            _nextStatus = Active;
484        }
485    }
486
487    if (_nextStatus == Inactive && _status == Active) {
488        DPRINTF(Activity, "Deactivating stage.\n");
489        cpu->deactivateStage(O3CPU::CommitIdx);
490    } else if (_nextStatus == Active && _status == Inactive) {
491        DPRINTF(Activity, "Activating stage.\n");
492        cpu->activateStage(O3CPU::CommitIdx);
493    }
494
495    _status = _nextStatus;
496}
497
498template <class Impl>
499bool
500DefaultCommit<Impl>::changedROBEntries()
501{
502    list<ThreadID>::iterator threads = activeThreads->begin();
503    list<ThreadID>::iterator end = activeThreads->end();
504
505    while (threads != end) {
506        ThreadID tid = *threads++;
507
508        if (changedROBNumEntries[tid]) {
509            return true;
510        }
511    }
512
513    return false;
514}
515
516template <class Impl>
517size_t
518DefaultCommit<Impl>::numROBFreeEntries(ThreadID tid)
519{
520    return rob->numFreeEntries(tid);
521}
522
523template <class Impl>
524void
525DefaultCommit<Impl>::generateTrapEvent(ThreadID tid, Fault inst_fault)
526{
527    DPRINTF(Commit, "Generating trap event for [tid:%i]\n", tid);
528
529    EventFunctionWrapper *trap = new EventFunctionWrapper(
530        [this, tid]{ processTrapEvent(tid); },
531        "Trap", true, Event::CPU_Tick_Pri);
532
533    Cycles latency = dynamic_pointer_cast<SyscallRetryFault>(inst_fault) ?
534                     cpu->syscallRetryLatency : trapLatency;
535
536    cpu->schedule(trap, cpu->clockEdge(latency));
537    trapInFlight[tid] = true;
538    thread[tid]->trapPending = true;
539}
540
541template <class Impl>
542void
543DefaultCommit<Impl>::generateTCEvent(ThreadID tid)
544{
545    assert(!trapInFlight[tid]);
546    DPRINTF(Commit, "Generating TC squash event for [tid:%i]\n", tid);
547
548    tcSquash[tid] = true;
549}
550
551template <class Impl>
552void
553DefaultCommit<Impl>::squashAll(ThreadID tid)
554{
555    // If we want to include the squashing instruction in the squash,
556    // then use one older sequence number.
557    // Hopefully this doesn't mess things up.  Basically I want to squash
558    // all instructions of this thread.
559    InstSeqNum squashed_inst = rob->isEmpty(tid) ?
560        lastCommitedSeqNum[tid] : rob->readHeadInst(tid)->seqNum - 1;
561
562    // All younger instructions will be squashed. Set the sequence
563    // number as the youngest instruction in the ROB (0 in this case.
564    // Hopefully nothing breaks.)
565    youngestSeqNum[tid] = lastCommitedSeqNum[tid];
566
567    rob->squash(squashed_inst, tid);
568    changedROBNumEntries[tid] = true;
569
570    // Send back the sequence number of the squashed instruction.
571    toIEW->commitInfo[tid].doneSeqNum = squashed_inst;
572
573    // Send back the squash signal to tell stages that they should
574    // 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].mispredictInst = NULL;
582    toIEW->commitInfo[tid].squashInst = NULL;
583
584    toIEW->commitInfo[tid].pc = pc[tid];
585}
586
587template <class Impl>
588void
589DefaultCommit<Impl>::squashFromTrap(ThreadID tid)
590{
591    squashAll(tid);
592
593    DPRINTF(Commit, "Squashing from trap, restarting at PC %s\n", pc[tid]);
594
595    thread[tid]->trapPending = false;
596    thread[tid]->noSquashFromTC = false;
597    trapInFlight[tid] = false;
598
599    trapSquash[tid] = false;
600
601    commitStatus[tid] = ROBSquashing;
602    cpu->activityThisCycle();
603}
604
605template <class Impl>
606void
607DefaultCommit<Impl>::squashFromTC(ThreadID tid)
608{
609    squashAll(tid);
610
611    DPRINTF(Commit, "Squashing from TC, restarting at PC %s\n", pc[tid]);
612
613    thread[tid]->noSquashFromTC = false;
614    assert(!thread[tid]->trapPending);
615
616    commitStatus[tid] = ROBSquashing;
617    cpu->activityThisCycle();
618
619    tcSquash[tid] = false;
620}
621
622template <class Impl>
623void
624DefaultCommit<Impl>::squashFromSquashAfter(ThreadID tid)
625{
626    DPRINTF(Commit, "Squashing after squash after request, "
627            "restarting at PC %s\n", pc[tid]);
628
629    squashAll(tid);
630    // Make sure to inform the fetch stage of which instruction caused
631    // the squash. It'll try to re-fetch an instruction executing in
632    // microcode unless this is set.
633    toIEW->commitInfo[tid].squashInst = squashAfterInst[tid];
634    squashAfterInst[tid] = NULL;
635
636    commitStatus[tid] = ROBSquashing;
637    cpu->activityThisCycle();
638}
639
640template <class Impl>
641void
642DefaultCommit<Impl>::squashAfter(ThreadID tid, const DynInstPtr &head_inst)
643{
644    DPRINTF(Commit, "Executing squash after for [tid:%i] inst [sn:%lli]\n",
645            tid, head_inst->seqNum);
646
647    assert(!squashAfterInst[tid] || squashAfterInst[tid] == head_inst);
648    commitStatus[tid] = SquashAfterPending;
649    squashAfterInst[tid] = head_inst;
650}
651
652template <class Impl>
653void
654DefaultCommit<Impl>::tick()
655{
656    wroteToTimeBuffer = false;
657    _nextStatus = Inactive;
658
659    if (activeThreads->empty())
660        return;
661
662    list<ThreadID>::iterator threads = activeThreads->begin();
663    list<ThreadID>::iterator end = activeThreads->end();
664
665    // Check if any of the threads are done squashing.  Change the
666    // status if they are done.
667    while (threads != end) {
668        ThreadID tid = *threads++;
669
670        // Clear the bit saying if the thread has committed stores
671        // this cycle.
672        committedStores[tid] = false;
673
674        if (commitStatus[tid] == ROBSquashing) {
675
676            if (rob->isDoneSquashing(tid)) {
677                commitStatus[tid] = Running;
678            } else {
679                DPRINTF(Commit,"[tid:%u]: Still Squashing, cannot commit any"
680                        " insts this cycle.\n", tid);
681                rob->doSquash(tid);
682                toIEW->commitInfo[tid].robSquashing = true;
683                wroteToTimeBuffer = true;
684            }
685        }
686    }
687
688    commit();
689
690    markCompletedInsts();
691
692    threads = activeThreads->begin();
693
694    while (threads != end) {
695        ThreadID tid = *threads++;
696
697        if (!rob->isEmpty(tid) && rob->readHeadInst(tid)->readyToCommit()) {
698            // The ROB has more instructions it can commit. Its next status
699            // will be active.
700            _nextStatus = Active;
701
702            const DynInstPtr &inst M5_VAR_USED = rob->readHeadInst(tid);
703
704            DPRINTF(Commit,"[tid:%i]: Instruction [sn:%lli] PC %s is head of"
705                    " ROB and ready to commit\n",
706                    tid, inst->seqNum, inst->pcState());
707
708        } else if (!rob->isEmpty(tid)) {
709            const DynInstPtr &inst = rob->readHeadInst(tid);
710
711            ppCommitStall->notify(inst);
712
713            DPRINTF(Commit,"[tid:%i]: Can't commit, Instruction [sn:%lli] PC "
714                    "%s is head of ROB and not ready\n",
715                    tid, inst->seqNum, inst->pcState());
716        }
717
718        DPRINTF(Commit, "[tid:%i]: ROB has %d insts & %d free entries.\n",
719                tid, rob->countInsts(tid), rob->numFreeEntries(tid));
720    }
721
722
723    if (wroteToTimeBuffer) {
724        DPRINTF(Activity, "Activity This Cycle.\n");
725        cpu->activityThisCycle();
726    }
727
728    updateStatus();
729}
730
731template <class Impl>
732void
733DefaultCommit<Impl>::handleInterrupt()
734{
735    // Verify that we still have an interrupt to handle
736    if (!cpu->checkInterrupts(cpu->tcBase(0))) {
737        DPRINTF(Commit, "Pending interrupt is cleared by master before "
738                "it got handled. Restart fetching from the orig path.\n");
739        toIEW->commitInfo[0].clearInterrupt = true;
740        interrupt = NoFault;
741        avoidQuiesceLiveLock = true;
742        return;
743    }
744
745    // Wait until all in flight instructions are finished before enterring
746    // the interrupt.
747    if (canHandleInterrupts && cpu->instList.empty()) {
748        // Squash or record that I need to squash this cycle if
749        // an interrupt needed to be handled.
750        DPRINTF(Commit, "Interrupt detected.\n");
751
752        // Clear the interrupt now that it's going to be handled
753        toIEW->commitInfo[0].clearInterrupt = true;
754
755        assert(!thread[0]->noSquashFromTC);
756        thread[0]->noSquashFromTC = true;
757
758        if (cpu->checker) {
759            cpu->checker->handlePendingInt();
760        }
761
762        // CPU will handle interrupt. Note that we ignore the local copy of
763        // interrupt. This is because the local copy may no longer be the
764        // interrupt that the interrupt controller thinks is being handled.
765        cpu->processInterrupts(cpu->getInterrupts());
766
767        thread[0]->noSquashFromTC = false;
768
769        commitStatus[0] = TrapPending;
770
771        interrupt = NoFault;
772
773        // Generate trap squash event.
774        generateTrapEvent(0, interrupt);
775
776        avoidQuiesceLiveLock = false;
777    } else {
778        DPRINTF(Commit, "Interrupt pending: instruction is %sin "
779                "flight, ROB is %sempty\n",
780                canHandleInterrupts ? "not " : "",
781                cpu->instList.empty() ? "" : "not " );
782    }
783}
784
785template <class Impl>
786void
787DefaultCommit<Impl>::propagateInterrupt()
788{
789    // Don't propagate intterupts if we are currently handling a trap or
790    // in draining and the last observable instruction has been committed.
791    if (commitStatus[0] == TrapPending || interrupt || trapSquash[0] ||
792            tcSquash[0] || drainImminent)
793        return;
794
795    // Process interrupts if interrupts are enabled, not in PAL
796    // mode, and no other traps or external squashes are currently
797    // pending.
798    // @todo: Allow other threads to handle interrupts.
799
800    // Get any interrupt that happened
801    interrupt = cpu->getInterrupts();
802
803    // Tell fetch that there is an interrupt pending.  This
804    // will make fetch wait until it sees a non PAL-mode PC,
805    // at which point it stops fetching instructions.
806    if (interrupt != NoFault)
807        toIEW->commitInfo[0].interruptPending = true;
808}
809
810template <class Impl>
811void
812DefaultCommit<Impl>::commit()
813{
814    if (FullSystem) {
815        // Check if we have a interrupt and get read to handle it
816        if (cpu->checkInterrupts(cpu->tcBase(0)))
817            propagateInterrupt();
818    }
819
820    ////////////////////////////////////
821    // Check for any possible squashes, handle them first
822    ////////////////////////////////////
823    list<ThreadID>::iterator threads = activeThreads->begin();
824    list<ThreadID>::iterator end = activeThreads->end();
825
826    int num_squashing_threads = 0;
827
828    while (threads != end) {
829        ThreadID tid = *threads++;
830
831        // Not sure which one takes priority.  I think if we have
832        // both, that's a bad sign.
833        if (trapSquash[tid]) {
834            assert(!tcSquash[tid]);
835            squashFromTrap(tid);
836        } else if (tcSquash[tid]) {
837            assert(commitStatus[tid] != TrapPending);
838            squashFromTC(tid);
839        } else if (commitStatus[tid] == SquashAfterPending) {
840            // A squash from the previous cycle of the commit stage (i.e.,
841            // commitInsts() called squashAfter) is pending. Squash the
842            // thread now.
843            squashFromSquashAfter(tid);
844        }
845
846        // Squashed sequence number must be older than youngest valid
847        // instruction in the ROB. This prevents squashes from younger
848        // instructions overriding squashes from older instructions.
849        if (fromIEW->squash[tid] &&
850            commitStatus[tid] != TrapPending &&
851            fromIEW->squashedSeqNum[tid] <= youngestSeqNum[tid]) {
852
853            if (fromIEW->mispredictInst[tid]) {
854                DPRINTF(Commit,
855                    "[tid:%i]: Squashing due to branch mispred PC:%#x [sn:%i]\n",
856                    tid,
857                    fromIEW->mispredictInst[tid]->instAddr(),
858                    fromIEW->squashedSeqNum[tid]);
859            } else {
860                DPRINTF(Commit,
861                    "[tid:%i]: Squashing due to order violation [sn:%i]\n",
862                    tid, fromIEW->squashedSeqNum[tid]);
863            }
864
865            DPRINTF(Commit, "[tid:%i]: Redirecting to PC %#x\n",
866                    tid,
867                    fromIEW->pc[tid].nextInstAddr());
868
869            commitStatus[tid] = ROBSquashing;
870
871            // If we want to include the squashing instruction in the squash,
872            // then use one older sequence number.
873            InstSeqNum squashed_inst = fromIEW->squashedSeqNum[tid];
874
875            if (fromIEW->includeSquashInst[tid]) {
876                squashed_inst--;
877            }
878
879            // All younger instructions will be squashed. Set the sequence
880            // number as the youngest instruction in the ROB.
881            youngestSeqNum[tid] = squashed_inst;
882
883            rob->squash(squashed_inst, tid);
884            changedROBNumEntries[tid] = true;
885
886            toIEW->commitInfo[tid].doneSeqNum = squashed_inst;
887
888            toIEW->commitInfo[tid].squash = true;
889
890            // Send back the rob squashing signal so other stages know that
891            // the ROB is in the process of squashing.
892            toIEW->commitInfo[tid].robSquashing = true;
893
894            toIEW->commitInfo[tid].mispredictInst =
895                fromIEW->mispredictInst[tid];
896            toIEW->commitInfo[tid].branchTaken =
897                fromIEW->branchTaken[tid];
898            toIEW->commitInfo[tid].squashInst =
899                                    rob->findInst(tid, squashed_inst);
900            if (toIEW->commitInfo[tid].mispredictInst) {
901                if (toIEW->commitInfo[tid].mispredictInst->isUncondCtrl()) {
902                     toIEW->commitInfo[tid].branchTaken = true;
903                }
904                ++branchMispredicts;
905            }
906
907            toIEW->commitInfo[tid].pc = fromIEW->pc[tid];
908        }
909
910        if (commitStatus[tid] == ROBSquashing) {
911            num_squashing_threads++;
912        }
913    }
914
915    // If commit is currently squashing, then it will have activity for the
916    // next cycle. Set its next status as active.
917    if (num_squashing_threads) {
918        _nextStatus = Active;
919    }
920
921    if (num_squashing_threads != numThreads) {
922        // If we're not currently squashing, then get instructions.
923        getInsts();
924
925        // Try to commit any instructions.
926        commitInsts();
927    }
928
929    //Check for any activity
930    threads = activeThreads->begin();
931
932    while (threads != end) {
933        ThreadID tid = *threads++;
934
935        if (changedROBNumEntries[tid]) {
936            toIEW->commitInfo[tid].usedROB = true;
937            toIEW->commitInfo[tid].freeROBEntries = rob->numFreeEntries(tid);
938
939            wroteToTimeBuffer = true;
940            changedROBNumEntries[tid] = false;
941            if (rob->isEmpty(tid))
942                checkEmptyROB[tid] = true;
943        }
944
945        // ROB is only considered "empty" for previous stages if: a)
946        // ROB is empty, b) there are no outstanding stores, c) IEW
947        // stage has received any information regarding stores that
948        // committed.
949        // c) is checked by making sure to not consider the ROB empty
950        // on the same cycle as when stores have been committed.
951        // @todo: Make this handle multi-cycle communication between
952        // commit and IEW.
953        if (checkEmptyROB[tid] && rob->isEmpty(tid) &&
954            !iewStage->hasStoresToWB(tid) && !committedStores[tid]) {
955            checkEmptyROB[tid] = false;
956            toIEW->commitInfo[tid].usedROB = true;
957            toIEW->commitInfo[tid].emptyROB = true;
958            toIEW->commitInfo[tid].freeROBEntries = rob->numFreeEntries(tid);
959            wroteToTimeBuffer = true;
960        }
961
962    }
963}
964
965template <class Impl>
966void
967DefaultCommit<Impl>::commitInsts()
968{
969    ////////////////////////////////////
970    // Handle commit
971    // Note that commit will be handled prior to putting new
972    // instructions in the ROB so that the ROB only tries to commit
973    // instructions it has in this current cycle, and not instructions
974    // it is writing in during this cycle.  Can't commit and squash
975    // things at the same time...
976    ////////////////////////////////////
977
978    DPRINTF(Commit, "Trying to commit instructions in the ROB.\n");
979
980    unsigned num_committed = 0;
981
982    DynInstPtr head_inst;
983
984    // Commit as many instructions as possible until the commit bandwidth
985    // limit is reached, or it becomes impossible to commit any more.
986    while (num_committed < commitWidth) {
987        // Check for any interrupt that we've already squashed for
988        // and start processing it.
989        if (interrupt != NoFault)
990            handleInterrupt();
991
992        ThreadID commit_thread = getCommittingThread();
993
994        if (commit_thread == -1 || !rob->isHeadReady(commit_thread))
995            break;
996
997        head_inst = rob->readHeadInst(commit_thread);
998
999        ThreadID tid = head_inst->threadNumber;
1000
1001        assert(tid == commit_thread);
1002
1003        DPRINTF(Commit, "Trying to commit head instruction, [sn:%i] [tid:%i]\n",
1004                head_inst->seqNum, tid);
1005
1006        // If the head instruction is squashed, it is ready to retire
1007        // (be removed from the ROB) at any time.
1008        if (head_inst->isSquashed()) {
1009
1010            DPRINTF(Commit, "Retiring squashed instruction from "
1011                    "ROB.\n");
1012
1013            rob->retireHead(commit_thread);
1014
1015            ++commitSquashedInsts;
1016            // Notify potential listeners that this instruction is squashed
1017            ppSquash->notify(head_inst);
1018
1019            // Record that the number of ROB entries has changed.
1020            changedROBNumEntries[tid] = true;
1021        } else {
1022            pc[tid] = head_inst->pcState();
1023
1024            // Increment the total number of non-speculative instructions
1025            // executed.
1026            // Hack for now: it really shouldn't happen until after the
1027            // commit is deemed to be successful, but this count is needed
1028            // for syscalls.
1029            thread[tid]->funcExeInst++;
1030
1031            // Try to commit the head instruction.
1032            bool commit_success = commitHead(head_inst, num_committed);
1033
1034            if (commit_success) {
1035                ++num_committed;
1036                statCommittedInstType[tid][head_inst->opClass()]++;
1037                ppCommit->notify(head_inst);
1038
1039                changedROBNumEntries[tid] = true;
1040
1041                // Set the doneSeqNum to the youngest committed instruction.
1042                toIEW->commitInfo[tid].doneSeqNum = head_inst->seqNum;
1043
1044                if (tid == 0) {
1045                    canHandleInterrupts =  (!head_inst->isDelayedCommit()) &&
1046                                           ((THE_ISA != ALPHA_ISA) ||
1047                                             (!(pc[0].instAddr() & 0x3)));
1048                }
1049
1050                // at this point store conditionals should either have
1051                // been completed or predicated false
1052                assert(!head_inst->isStoreConditional() ||
1053                       head_inst->isCompleted() ||
1054                       !head_inst->readPredicate());
1055
1056                // Updates misc. registers.
1057                head_inst->updateMiscRegs();
1058
1059                // Check instruction execution if it successfully commits and
1060                // is not carrying a fault.
1061                if (cpu->checker) {
1062                    cpu->checker->verify(head_inst);
1063                }
1064
1065                cpu->traceFunctions(pc[tid].instAddr());
1066
1067                TheISA::advancePC(pc[tid], head_inst->staticInst);
1068
1069                // Keep track of the last sequence number commited
1070                lastCommitedSeqNum[tid] = head_inst->seqNum;
1071
1072                // If this is an instruction that doesn't play nicely with
1073                // others squash everything and restart fetch
1074                if (head_inst->isSquashAfter())
1075                    squashAfter(tid, head_inst);
1076
1077                if (drainPending) {
1078                    if (pc[tid].microPC() == 0 && interrupt == NoFault &&
1079                        !thread[tid]->trapPending) {
1080                        // Last architectually committed instruction.
1081                        // Squash the pipeline, stall fetch, and use
1082                        // drainImminent to disable interrupts
1083                        DPRINTF(Drain, "Draining: %i:%s\n", tid, pc[tid]);
1084                        squashAfter(tid, head_inst);
1085                        cpu->commitDrained(tid);
1086                        drainImminent = true;
1087                    }
1088                }
1089
1090                bool onInstBoundary = !head_inst->isMicroop() ||
1091                                      head_inst->isLastMicroop() ||
1092                                      !head_inst->isDelayedCommit();
1093
1094                if (onInstBoundary) {
1095                    int count = 0;
1096                    Addr oldpc;
1097                    // Make sure we're not currently updating state while
1098                    // handling PC events.
1099                    assert(!thread[tid]->noSquashFromTC &&
1100                           !thread[tid]->trapPending);
1101                    do {
1102                        oldpc = pc[tid].instAddr();
1103                        cpu->system->pcEventQueue.service(thread[tid]->getTC());
1104                        count++;
1105                    } while (oldpc != pc[tid].instAddr());
1106                    if (count > 1) {
1107                        DPRINTF(Commit,
1108                                "PC skip function event, stopping commit\n");
1109                        break;
1110                    }
1111                }
1112
1113                // Check if an instruction just enabled interrupts and we've
1114                // previously had an interrupt pending that was not handled
1115                // because interrupts were subsequently disabled before the
1116                // pipeline reached a place to handle the interrupt. In that
1117                // case squash now to make sure the interrupt is handled.
1118                //
1119                // If we don't do this, we might end up in a live lock situation
1120                if (!interrupt && avoidQuiesceLiveLock &&
1121                    onInstBoundary && cpu->checkInterrupts(cpu->tcBase(0)))
1122                    squashAfter(tid, head_inst);
1123            } else {
1124                DPRINTF(Commit, "Unable to commit head instruction PC:%s "
1125                        "[tid:%i] [sn:%i].\n",
1126                        head_inst->pcState(), tid ,head_inst->seqNum);
1127                break;
1128            }
1129        }
1130    }
1131
1132    DPRINTF(CommitRate, "%i\n", num_committed);
1133    numCommittedDist.sample(num_committed);
1134
1135    if (num_committed == commitWidth) {
1136        commitEligibleSamples++;
1137    }
1138}
1139
1140template <class Impl>
1141bool
1142DefaultCommit<Impl>::commitHead(const DynInstPtr &head_inst, unsigned inst_num)
1143{
1144    assert(head_inst);
1145
1146    ThreadID tid = head_inst->threadNumber;
1147
1148    // If the instruction is not executed yet, then it will need extra
1149    // handling.  Signal backwards that it should be executed.
1150    if (!head_inst->isExecuted()) {
1151        // Keep this number correct.  We have not yet actually executed
1152        // and committed this instruction.
1153        thread[tid]->funcExeInst--;
1154
1155        // Make sure we are only trying to commit un-executed instructions we
1156        // think are possible.
1157        assert(head_inst->isNonSpeculative() || head_inst->isStoreConditional()
1158               || head_inst->isMemBarrier() || head_inst->isWriteBarrier() ||
1159               (head_inst->isLoad() && head_inst->strictlyOrdered()));
1160
1161        DPRINTF(Commit, "Encountered a barrier or non-speculative "
1162                "instruction [sn:%lli] at the head of the ROB, PC %s.\n",
1163                head_inst->seqNum, head_inst->pcState());
1164
1165        if (inst_num > 0 || iewStage->hasStoresToWB(tid)) {
1166            DPRINTF(Commit, "Waiting for all stores to writeback.\n");
1167            return false;
1168        }
1169
1170        toIEW->commitInfo[tid].nonSpecSeqNum = head_inst->seqNum;
1171
1172        // Change the instruction so it won't try to commit again until
1173        // it is executed.
1174        head_inst->clearCanCommit();
1175
1176        if (head_inst->isLoad() && head_inst->strictlyOrdered()) {
1177            DPRINTF(Commit, "[sn:%lli]: Strictly ordered load, PC %s.\n",
1178                    head_inst->seqNum, head_inst->pcState());
1179            toIEW->commitInfo[tid].strictlyOrdered = true;
1180            toIEW->commitInfo[tid].strictlyOrderedLoad = head_inst;
1181        } else {
1182            ++commitNonSpecStalls;
1183        }
1184
1185        return false;
1186    }
1187
1188    if (head_inst->isThreadSync()) {
1189        // Not handled for now.
1190        panic("Thread sync instructions are not handled yet.\n");
1191    }
1192
1193    // Check if the instruction caused a fault.  If so, trap.
1194    Fault inst_fault = head_inst->getFault();
1195
1196    // Stores mark themselves as completed.
1197    if (!head_inst->isStore() && inst_fault == NoFault) {
1198        head_inst->setCompleted();
1199    }
1200
1201    if (inst_fault != NoFault) {
1202        DPRINTF(Commit, "Inst [sn:%lli] PC %s has a fault\n",
1203                head_inst->seqNum, head_inst->pcState());
1204
1205        if (iewStage->hasStoresToWB(tid) || inst_num > 0) {
1206            DPRINTF(Commit, "Stores outstanding, fault must wait.\n");
1207            return false;
1208        }
1209
1210        head_inst->setCompleted();
1211
1212        // If instruction has faulted, let the checker execute it and
1213        // check if it sees the same fault and control flow.
1214        if (cpu->checker) {
1215            // Need to check the instruction before its fault is processed
1216            cpu->checker->verify(head_inst);
1217        }
1218
1219        assert(!thread[tid]->noSquashFromTC);
1220
1221        // Mark that we're in state update mode so that the trap's
1222        // execution doesn't generate extra squashes.
1223        thread[tid]->noSquashFromTC = true;
1224
1225        // Execute the trap.  Although it's slightly unrealistic in
1226        // terms of timing (as it doesn't wait for the full timing of
1227        // the trap event to complete before updating state), it's
1228        // needed to update the state as soon as possible.  This
1229        // prevents external agents from changing any specific state
1230        // that the trap need.
1231        cpu->trap(inst_fault, tid,
1232                  head_inst->notAnInst() ?
1233                      StaticInst::nullStaticInstPtr :
1234                      head_inst->staticInst);
1235
1236        // Exit state update mode to avoid accidental updating.
1237        thread[tid]->noSquashFromTC = false;
1238
1239        commitStatus[tid] = TrapPending;
1240
1241        DPRINTF(Commit, "Committing instruction with fault [sn:%lli]\n",
1242            head_inst->seqNum);
1243        if (head_inst->traceData) {
1244            if (DTRACE(ExecFaulting)) {
1245                head_inst->traceData->setFetchSeq(head_inst->seqNum);
1246                head_inst->traceData->setCPSeq(thread[tid]->numOp);
1247                head_inst->traceData->dump();
1248            }
1249            delete head_inst->traceData;
1250            head_inst->traceData = NULL;
1251        }
1252
1253        // Generate trap squash event.
1254        generateTrapEvent(tid, inst_fault);
1255        return false;
1256    }
1257
1258    updateComInstStats(head_inst);
1259
1260    if (FullSystem) {
1261        if (thread[tid]->profile) {
1262            thread[tid]->profilePC = head_inst->instAddr();
1263            ProfileNode *node = thread[tid]->profile->consume(
1264                    thread[tid]->getTC(), head_inst->staticInst);
1265
1266            if (node)
1267                thread[tid]->profileNode = node;
1268        }
1269        if (CPA::available()) {
1270            if (head_inst->isControl()) {
1271                ThreadContext *tc = thread[tid]->getTC();
1272                CPA::cpa()->swAutoBegin(tc, head_inst->nextInstAddr());
1273            }
1274        }
1275    }
1276    DPRINTF(Commit, "Committing instruction with [sn:%lli] PC %s\n",
1277            head_inst->seqNum, head_inst->pcState());
1278    if (head_inst->traceData) {
1279        head_inst->traceData->setFetchSeq(head_inst->seqNum);
1280        head_inst->traceData->setCPSeq(thread[tid]->numOp);
1281        head_inst->traceData->dump();
1282        delete head_inst->traceData;
1283        head_inst->traceData = NULL;
1284    }
1285    if (head_inst->isReturn()) {
1286        DPRINTF(Commit,"Return Instruction Committed [sn:%lli] PC %s \n",
1287                        head_inst->seqNum, head_inst->pcState());
1288    }
1289
1290    // Update the commit rename map
1291    for (int i = 0; i < head_inst->numDestRegs(); i++) {
1292        renameMap[tid]->setEntry(head_inst->flattenedDestRegIdx(i),
1293                                 head_inst->renamedDestRegIdx(i));
1294    }
1295
1296    // Finally clear the head ROB entry.
1297    rob->retireHead(tid);
1298
1299#if TRACING_ON
1300    if (DTRACE(O3PipeView)) {
1301        head_inst->commitTick = curTick() - head_inst->fetchTick;
1302    }
1303#endif
1304
1305    // If this was a store, record it for this cycle.
1306    if (head_inst->isStore())
1307        committedStores[tid] = true;
1308
1309    // Return true to indicate that we have committed an instruction.
1310    return true;
1311}
1312
1313template <class Impl>
1314void
1315DefaultCommit<Impl>::getInsts()
1316{
1317    DPRINTF(Commit, "Getting instructions from Rename stage.\n");
1318
1319    // Read any renamed instructions and place them into the ROB.
1320    int insts_to_process = std::min((int)renameWidth, fromRename->size);
1321
1322    for (int inst_num = 0; inst_num < insts_to_process; ++inst_num) {
1323        const DynInstPtr &inst = fromRename->insts[inst_num];
1324        ThreadID tid = inst->threadNumber;
1325
1326        if (!inst->isSquashed() &&
1327            commitStatus[tid] != ROBSquashing &&
1328            commitStatus[tid] != TrapPending) {
1329            changedROBNumEntries[tid] = true;
1330
1331            DPRINTF(Commit, "Inserting PC %s [sn:%i] [tid:%i] into ROB.\n",
1332                    inst->pcState(), inst->seqNum, tid);
1333
1334            rob->insertInst(inst);
1335
1336            assert(rob->getThreadEntries(tid) <= rob->getMaxEntries(tid));
1337
1338            youngestSeqNum[tid] = inst->seqNum;
1339        } else {
1340            DPRINTF(Commit, "Instruction PC %s [sn:%i] [tid:%i] was "
1341                    "squashed, skipping.\n",
1342                    inst->pcState(), inst->seqNum, tid);
1343        }
1344    }
1345}
1346
1347template <class Impl>
1348void
1349DefaultCommit<Impl>::markCompletedInsts()
1350{
1351    // Grab completed insts out of the IEW instruction queue, and mark
1352    // instructions completed within the ROB.
1353    for (int inst_num = 0; inst_num < fromIEW->size; ++inst_num) {
1354        assert(fromIEW->insts[inst_num]);
1355        if (!fromIEW->insts[inst_num]->isSquashed()) {
1356            DPRINTF(Commit, "[tid:%i]: Marking PC %s, [sn:%lli] ready "
1357                    "within ROB.\n",
1358                    fromIEW->insts[inst_num]->threadNumber,
1359                    fromIEW->insts[inst_num]->pcState(),
1360                    fromIEW->insts[inst_num]->seqNum);
1361
1362            // Mark the instruction as ready to commit.
1363            fromIEW->insts[inst_num]->setCanCommit();
1364        }
1365    }
1366}
1367
1368template <class Impl>
1369void
1370DefaultCommit<Impl>::updateComInstStats(const DynInstPtr &inst)
1371{
1372    ThreadID tid = inst->threadNumber;
1373
1374    if (!inst->isMicroop() || inst->isLastMicroop())
1375        instsCommitted[tid]++;
1376    opsCommitted[tid]++;
1377
1378    // To match the old model, don't count nops and instruction
1379    // prefetches towards the total commit count.
1380    if (!inst->isNop() && !inst->isInstPrefetch()) {
1381        cpu->instDone(tid, inst);
1382    }
1383
1384    //
1385    //  Control Instructions
1386    //
1387    if (inst->isControl())
1388        statComBranches[tid]++;
1389
1390    //
1391    //  Memory references
1392    //
1393    if (inst->isMemRef()) {
1394        statComRefs[tid]++;
1395
1396        if (inst->isLoad()) {
1397            statComLoads[tid]++;
1398        }
1399    }
1400
1401    if (inst->isMemBarrier()) {
1402        statComMembars[tid]++;
1403    }
1404
1405    // Integer Instruction
1406    if (inst->isInteger())
1407        statComInteger[tid]++;
1408
1409    // Floating Point Instruction
1410    if (inst->isFloating())
1411        statComFloating[tid]++;
1412    // Vector Instruction
1413    if (inst->isVector())
1414        statComVector[tid]++;
1415
1416    // Function Calls
1417    if (inst->isCall())
1418        statComFunctionCalls[tid]++;
1419
1420}
1421
1422////////////////////////////////////////
1423//                                    //
1424//  SMT COMMIT POLICY MAINTAINED HERE //
1425//                                    //
1426////////////////////////////////////////
1427template <class Impl>
1428ThreadID
1429DefaultCommit<Impl>::getCommittingThread()
1430{
1431    if (numThreads > 1) {
1432        switch (commitPolicy) {
1433
1434          case Aggressive:
1435            //If Policy is Aggressive, commit will call
1436            //this function multiple times per
1437            //cycle
1438            return oldestReady();
1439
1440          case RoundRobin:
1441            return roundRobin();
1442
1443          case OldestReady:
1444            return oldestReady();
1445
1446          default:
1447            return InvalidThreadID;
1448        }
1449    } else {
1450        assert(!activeThreads->empty());
1451        ThreadID tid = activeThreads->front();
1452
1453        if (commitStatus[tid] == Running ||
1454            commitStatus[tid] == Idle ||
1455            commitStatus[tid] == FetchTrapPending) {
1456            return tid;
1457        } else {
1458            return InvalidThreadID;
1459        }
1460    }
1461}
1462
1463template<class Impl>
1464ThreadID
1465DefaultCommit<Impl>::roundRobin()
1466{
1467    list<ThreadID>::iterator pri_iter = priority_list.begin();
1468    list<ThreadID>::iterator end      = priority_list.end();
1469
1470    while (pri_iter != end) {
1471        ThreadID tid = *pri_iter;
1472
1473        if (commitStatus[tid] == Running ||
1474            commitStatus[tid] == Idle ||
1475            commitStatus[tid] == FetchTrapPending) {
1476
1477            if (rob->isHeadReady(tid)) {
1478                priority_list.erase(pri_iter);
1479                priority_list.push_back(tid);
1480
1481                return tid;
1482            }
1483        }
1484
1485        pri_iter++;
1486    }
1487
1488    return InvalidThreadID;
1489}
1490
1491template<class Impl>
1492ThreadID
1493DefaultCommit<Impl>::oldestReady()
1494{
1495    unsigned oldest = 0;
1496    bool first = true;
1497
1498    list<ThreadID>::iterator threads = activeThreads->begin();
1499    list<ThreadID>::iterator end = activeThreads->end();
1500
1501    while (threads != end) {
1502        ThreadID tid = *threads++;
1503
1504        if (!rob->isEmpty(tid) &&
1505            (commitStatus[tid] == Running ||
1506             commitStatus[tid] == Idle ||
1507             commitStatus[tid] == FetchTrapPending)) {
1508
1509            if (rob->isHeadReady(tid)) {
1510
1511                const DynInstPtr &head_inst = rob->readHeadInst(tid);
1512
1513                if (first) {
1514                    oldest = tid;
1515                    first = false;
1516                } else if (head_inst->seqNum < oldest) {
1517                    oldest = tid;
1518                }
1519            }
1520        }
1521    }
1522
1523    if (!first) {
1524        return oldest;
1525    } else {
1526        return InvalidThreadID;
1527    }
1528}
1529
1530#endif//__CPU_O3_COMMIT_IMPL_HH__
1531