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