base.cc revision 8850:ed91b534ed04
1/*
2 * Copyright (c) 2011 ARM Limited
3 * All rights reserved
4 *
5 * The license below extends only to copyright in the software and shall
6 * not be construed as granting a license to any other intellectual
7 * property including but not limited to intellectual property relating
8 * to a hardware implementation of the functionality of the software
9 * licensed hereunder.  You may use the software subject to the license
10 * terms below provided that you ensure that this notice is replicated
11 * unmodified and in its entirety in all distributions of the software,
12 * modified or unmodified, in source code or in binary form.
13 *
14 * Copyright (c) 2002-2005 The Regents of The University of Michigan
15 * Copyright (c) 2011 Regents of the University of California
16 * All rights reserved.
17 *
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions are
20 * met: redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer;
22 * redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution;
25 * neither the name of the copyright holders nor the names of its
26 * contributors may be used to endorse or promote products derived from
27 * this software without specific prior written permission.
28 *
29 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
30 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
31 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
32 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
33 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
34 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
35 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
39 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 *
41 * Authors: Steve Reinhardt
42 *          Nathan Binkert
43 *          Rick Strong
44 */
45
46#include <iostream>
47#include <sstream>
48#include <string>
49
50#include "arch/tlb.hh"
51#include "base/loader/symtab.hh"
52#include "base/cprintf.hh"
53#include "base/misc.hh"
54#include "base/output.hh"
55#include "base/trace.hh"
56#include "config/use_checker.hh"
57#include "cpu/base.hh"
58#include "cpu/cpuevent.hh"
59#include "cpu/profile.hh"
60#include "cpu/thread_context.hh"
61#include "debug/SyscallVerbose.hh"
62#include "params/BaseCPU.hh"
63#include "sim/full_system.hh"
64#include "sim/process.hh"
65#include "sim/sim_events.hh"
66#include "sim/sim_exit.hh"
67#include "sim/system.hh"
68
69#if USE_CHECKER
70#include "cpu/checker/cpu.hh"
71#endif
72
73// Hack
74#include "sim/stat_control.hh"
75
76using namespace std;
77
78vector<BaseCPU *> BaseCPU::cpuList;
79
80// This variable reflects the max number of threads in any CPU.  Be
81// careful to only use it once all the CPUs that you care about have
82// been initialized
83int maxThreadsPerCPU = 1;
84
85CPUProgressEvent::CPUProgressEvent(BaseCPU *_cpu, Tick ival)
86    : Event(Event::Progress_Event_Pri), _interval(ival), lastNumInst(0),
87      cpu(_cpu), _repeatEvent(true)
88{
89    if (_interval)
90        cpu->schedule(this, curTick() + _interval);
91}
92
93void
94CPUProgressEvent::process()
95{
96    Counter temp = cpu->totalOps();
97#ifndef NDEBUG
98    double ipc = double(temp - lastNumInst) / (_interval / cpu->ticks(1));
99
100    DPRINTFN("%s progress event, total committed:%i, progress insts committed: "
101             "%lli, IPC: %0.8d\n", cpu->name(), temp, temp - lastNumInst,
102             ipc);
103    ipc = 0.0;
104#else
105    cprintf("%lli: %s progress event, total committed:%i, progress insts "
106            "committed: %lli\n", curTick(), cpu->name(), temp,
107            temp - lastNumInst);
108#endif
109    lastNumInst = temp;
110
111    if (_repeatEvent)
112        cpu->schedule(this, curTick() + _interval);
113}
114
115const char *
116CPUProgressEvent::description() const
117{
118    return "CPU Progress";
119}
120
121BaseCPU::BaseCPU(Params *p)
122    : MemObject(p), clock(p->clock), instCnt(0), _cpuId(p->cpu_id),
123      _instMasterId(p->system->getMasterId(name() + ".inst")),
124      _dataMasterId(p->system->getMasterId(name() + ".data")),
125      interrupts(p->interrupts),
126      numThreads(p->numThreads), system(p->system),
127      phase(p->phase)
128{
129//    currentTick = curTick();
130
131    // if Python did not provide a valid ID, do it here
132    if (_cpuId == -1 ) {
133        _cpuId = cpuList.size();
134    }
135
136    // add self to global list of CPUs
137    cpuList.push_back(this);
138
139    DPRINTF(SyscallVerbose, "Constructing CPU with id %d\n", _cpuId);
140
141    if (numThreads > maxThreadsPerCPU)
142        maxThreadsPerCPU = numThreads;
143
144    // allocate per-thread instruction-based event queues
145    comInstEventQueue = new EventQueue *[numThreads];
146    for (ThreadID tid = 0; tid < numThreads; ++tid)
147        comInstEventQueue[tid] =
148            new EventQueue("instruction-based event queue");
149
150    //
151    // set up instruction-count-based termination events, if any
152    //
153    if (p->max_insts_any_thread != 0) {
154        const char *cause = "a thread reached the max instruction count";
155        for (ThreadID tid = 0; tid < numThreads; ++tid) {
156            Event *event = new SimLoopExitEvent(cause, 0);
157            comInstEventQueue[tid]->schedule(event, p->max_insts_any_thread);
158        }
159    }
160
161    if (p->max_insts_all_threads != 0) {
162        const char *cause = "all threads reached the max instruction count";
163
164        // allocate & initialize shared downcounter: each event will
165        // decrement this when triggered; simulation will terminate
166        // when counter reaches 0
167        int *counter = new int;
168        *counter = numThreads;
169        for (ThreadID tid = 0; tid < numThreads; ++tid) {
170            Event *event = new CountedExitEvent(cause, *counter);
171            comInstEventQueue[tid]->schedule(event, p->max_insts_all_threads);
172        }
173    }
174
175    // allocate per-thread load-based event queues
176    comLoadEventQueue = new EventQueue *[numThreads];
177    for (ThreadID tid = 0; tid < numThreads; ++tid)
178        comLoadEventQueue[tid] = new EventQueue("load-based event queue");
179
180    //
181    // set up instruction-count-based termination events, if any
182    //
183    if (p->max_loads_any_thread != 0) {
184        const char *cause = "a thread reached the max load count";
185        for (ThreadID tid = 0; tid < numThreads; ++tid) {
186            Event *event = new SimLoopExitEvent(cause, 0);
187            comLoadEventQueue[tid]->schedule(event, p->max_loads_any_thread);
188        }
189    }
190
191    if (p->max_loads_all_threads != 0) {
192        const char *cause = "all threads reached the max load count";
193        // allocate & initialize shared downcounter: each event will
194        // decrement this when triggered; simulation will terminate
195        // when counter reaches 0
196        int *counter = new int;
197        *counter = numThreads;
198        for (ThreadID tid = 0; tid < numThreads; ++tid) {
199            Event *event = new CountedExitEvent(cause, *counter);
200            comLoadEventQueue[tid]->schedule(event, p->max_loads_all_threads);
201        }
202    }
203
204    functionTracingEnabled = false;
205    if (p->function_trace) {
206        const string fname = csprintf("ftrace.%s", name());
207        functionTraceStream = simout.find(fname);
208        if (!functionTraceStream)
209            functionTraceStream = simout.create(fname);
210
211        currentFunctionStart = currentFunctionEnd = 0;
212        functionEntryTick = p->function_trace_start;
213
214        if (p->function_trace_start == 0) {
215            functionTracingEnabled = true;
216        } else {
217            typedef EventWrapper<BaseCPU, &BaseCPU::enableFunctionTrace> wrap;
218            Event *event = new wrap(this, true);
219            schedule(event, p->function_trace_start);
220        }
221    }
222    // Check if CPU model has interrupts connected. The CheckerCPU
223    // cannot take interrupts directly for example.
224    if (interrupts)
225        interrupts->setCPU(this);
226
227    if (FullSystem) {
228        profileEvent = NULL;
229        if (params()->profile)
230            profileEvent = new ProfileEvent(this, params()->profile);
231    }
232    tracer = params()->tracer;
233}
234
235void
236BaseCPU::enableFunctionTrace()
237{
238    functionTracingEnabled = true;
239}
240
241BaseCPU::~BaseCPU()
242{
243}
244
245void
246BaseCPU::init()
247{
248    if (!params()->defer_registration)
249        registerThreadContexts();
250}
251
252void
253BaseCPU::startup()
254{
255    if (FullSystem) {
256        if (!params()->defer_registration && profileEvent)
257            schedule(profileEvent, curTick());
258    }
259
260    if (params()->progress_interval) {
261        Tick num_ticks = ticks(params()->progress_interval);
262
263        new CPUProgressEvent(this, num_ticks);
264    }
265}
266
267
268void
269BaseCPU::regStats()
270{
271    using namespace Stats;
272
273    numCycles
274        .name(name() + ".numCycles")
275        .desc("number of cpu cycles simulated")
276        ;
277
278    numWorkItemsStarted
279        .name(name() + ".numWorkItemsStarted")
280        .desc("number of work items this cpu started")
281        ;
282
283    numWorkItemsCompleted
284        .name(name() + ".numWorkItemsCompleted")
285        .desc("number of work items this cpu completed")
286        ;
287
288    int size = threadContexts.size();
289    if (size > 1) {
290        for (int i = 0; i < size; ++i) {
291            stringstream namestr;
292            ccprintf(namestr, "%s.ctx%d", name(), i);
293            threadContexts[i]->regStats(namestr.str());
294        }
295    } else if (size == 1)
296        threadContexts[0]->regStats(name());
297}
298
299Port *
300BaseCPU::getPort(const string &if_name, int idx)
301{
302    // Get the right port based on name. This applies to all the
303    // subclasses of the base CPU and relies on their implementation
304    // of getDataPort and getInstPort. In all cases there methods
305    // return a CpuPort pointer.
306    if (if_name == "dcache_port")
307        return &getDataPort();
308    else if (if_name == "icache_port")
309        return &getInstPort();
310    else
311        panic("CPU %s has no port named %s\n", name(), if_name);
312}
313
314Tick
315BaseCPU::nextCycle()
316{
317    Tick next_tick = curTick() - phase + clock - 1;
318    next_tick -= (next_tick % clock);
319    next_tick += phase;
320    return next_tick;
321}
322
323Tick
324BaseCPU::nextCycle(Tick begin_tick)
325{
326    Tick next_tick = begin_tick;
327    if (next_tick % clock != 0)
328        next_tick = next_tick - (next_tick % clock) + clock;
329    next_tick += phase;
330
331    assert(next_tick >= curTick());
332    return next_tick;
333}
334
335void
336BaseCPU::registerThreadContexts()
337{
338    ThreadID size = threadContexts.size();
339    for (ThreadID tid = 0; tid < size; ++tid) {
340        ThreadContext *tc = threadContexts[tid];
341
342        /** This is so that contextId and cpuId match where there is a
343         * 1cpu:1context relationship.  Otherwise, the order of registration
344         * could affect the assignment and cpu 1 could have context id 3, for
345         * example.  We may even want to do something like this for SMT so that
346         * cpu 0 has the lowest thread contexts and cpu N has the highest, but
347         * I'll just do this for now
348         */
349        if (numThreads == 1)
350            tc->setContextId(system->registerThreadContext(tc, _cpuId));
351        else
352            tc->setContextId(system->registerThreadContext(tc));
353
354        if (!FullSystem)
355            tc->getProcessPtr()->assignThreadContext(tc->contextId());
356    }
357}
358
359
360int
361BaseCPU::findContext(ThreadContext *tc)
362{
363    ThreadID size = threadContexts.size();
364    for (ThreadID tid = 0; tid < size; ++tid) {
365        if (tc == threadContexts[tid])
366            return tid;
367    }
368    return 0;
369}
370
371void
372BaseCPU::switchOut()
373{
374    if (profileEvent && profileEvent->scheduled())
375        deschedule(profileEvent);
376}
377
378void
379BaseCPU::takeOverFrom(BaseCPU *oldCPU)
380{
381    CpuPort &ic = getInstPort();
382    CpuPort &dc = getDataPort();
383    assert(threadContexts.size() == oldCPU->threadContexts.size());
384
385    _cpuId = oldCPU->cpuId();
386
387    ThreadID size = threadContexts.size();
388    for (ThreadID i = 0; i < size; ++i) {
389        ThreadContext *newTC = threadContexts[i];
390        ThreadContext *oldTC = oldCPU->threadContexts[i];
391
392        newTC->takeOverFrom(oldTC);
393
394        CpuEvent::replaceThreadContext(oldTC, newTC);
395
396        assert(newTC->contextId() == oldTC->contextId());
397        assert(newTC->threadId() == oldTC->threadId());
398        system->replaceThreadContext(newTC, newTC->contextId());
399
400        /* This code no longer works since the zero register (e.g.,
401         * r31 on Alpha) doesn't necessarily contain zero at this
402         * point.
403           if (DTRACE(Context))
404            ThreadContext::compare(oldTC, newTC);
405        */
406
407        Port  *old_itb_port, *old_dtb_port, *new_itb_port, *new_dtb_port;
408        old_itb_port = oldTC->getITBPtr()->getPort();
409        old_dtb_port = oldTC->getDTBPtr()->getPort();
410        new_itb_port = newTC->getITBPtr()->getPort();
411        new_dtb_port = newTC->getDTBPtr()->getPort();
412
413        // Move over any table walker ports if they exist
414        if (new_itb_port && !new_itb_port->isConnected()) {
415            assert(old_itb_port);
416            Port *peer = old_itb_port->getPeer();;
417            new_itb_port->setPeer(peer);
418            peer->setPeer(new_itb_port);
419        }
420        if (new_dtb_port && !new_dtb_port->isConnected()) {
421            assert(old_dtb_port);
422            Port *peer = old_dtb_port->getPeer();;
423            new_dtb_port->setPeer(peer);
424            peer->setPeer(new_dtb_port);
425        }
426
427#if USE_CHECKER
428        Port *old_checker_itb_port, *old_checker_dtb_port;
429        Port *new_checker_itb_port, *new_checker_dtb_port;
430
431        CheckerCPU *oldChecker =
432            dynamic_cast<CheckerCPU*>(oldTC->getCheckerCpuPtr());
433        CheckerCPU *newChecker =
434            dynamic_cast<CheckerCPU*>(newTC->getCheckerCpuPtr());
435        old_checker_itb_port = oldChecker->getITBPtr()->getPort();
436        old_checker_dtb_port = oldChecker->getDTBPtr()->getPort();
437        new_checker_itb_port = newChecker->getITBPtr()->getPort();
438        new_checker_dtb_port = newChecker->getDTBPtr()->getPort();
439
440        // Move over any table walker ports if they exist for checker
441        if (new_checker_itb_port && !new_checker_itb_port->isConnected()) {
442            assert(old_checker_itb_port);
443            Port *peer = old_checker_itb_port->getPeer();;
444            new_checker_itb_port->setPeer(peer);
445            peer->setPeer(new_checker_itb_port);
446        }
447        if (new_checker_dtb_port && !new_checker_dtb_port->isConnected()) {
448            assert(old_checker_dtb_port);
449            Port *peer = old_checker_dtb_port->getPeer();;
450            new_checker_dtb_port->setPeer(peer);
451            peer->setPeer(new_checker_dtb_port);
452        }
453#endif
454
455    }
456
457    interrupts = oldCPU->interrupts;
458    interrupts->setCPU(this);
459
460    if (FullSystem) {
461        for (ThreadID i = 0; i < size; ++i)
462            threadContexts[i]->profileClear();
463
464        if (profileEvent)
465            schedule(profileEvent, curTick());
466    }
467
468    // Connect new CPU to old CPU's memory only if new CPU isn't
469    // connected to anything.  Also connect old CPU's memory to new
470    // CPU.
471    if (!ic.isConnected()) {
472        Port *peer = oldCPU->getInstPort().getPeer();
473        ic.setPeer(peer);
474        peer->setPeer(&ic);
475    }
476
477    if (!dc.isConnected()) {
478        Port *peer = oldCPU->getDataPort().getPeer();
479        dc.setPeer(peer);
480        peer->setPeer(&dc);
481    }
482}
483
484
485BaseCPU::ProfileEvent::ProfileEvent(BaseCPU *_cpu, Tick _interval)
486    : cpu(_cpu), interval(_interval)
487{ }
488
489void
490BaseCPU::ProfileEvent::process()
491{
492    ThreadID size = cpu->threadContexts.size();
493    for (ThreadID i = 0; i < size; ++i) {
494        ThreadContext *tc = cpu->threadContexts[i];
495        tc->profileSample();
496    }
497
498    cpu->schedule(this, curTick() + interval);
499}
500
501void
502BaseCPU::serialize(std::ostream &os)
503{
504    SERIALIZE_SCALAR(instCnt);
505    interrupts->serialize(os);
506}
507
508void
509BaseCPU::unserialize(Checkpoint *cp, const std::string &section)
510{
511    UNSERIALIZE_SCALAR(instCnt);
512    interrupts->unserialize(cp, section);
513}
514
515void
516BaseCPU::traceFunctionsInternal(Addr pc)
517{
518    if (!debugSymbolTable)
519        return;
520
521    // if pc enters different function, print new function symbol and
522    // update saved range.  Otherwise do nothing.
523    if (pc < currentFunctionStart || pc >= currentFunctionEnd) {
524        string sym_str;
525        bool found = debugSymbolTable->findNearestSymbol(pc, sym_str,
526                                                         currentFunctionStart,
527                                                         currentFunctionEnd);
528
529        if (!found) {
530            // no symbol found: use addr as label
531            sym_str = csprintf("0x%x", pc);
532            currentFunctionStart = pc;
533            currentFunctionEnd = pc + 1;
534        }
535
536        ccprintf(*functionTraceStream, " (%d)\n%d: %s",
537                 curTick() - functionEntryTick, curTick(), sym_str);
538        functionEntryTick = curTick();
539    }
540}
541
542bool
543BaseCPU::CpuPort::recvTiming(PacketPtr pkt)
544{
545    panic("BaseCPU doesn't expect recvTiming callback!");
546    return true;
547}
548
549void
550BaseCPU::CpuPort::recvRetry()
551{
552    panic("BaseCPU doesn't expect recvRetry callback!");
553}
554
555Tick
556BaseCPU::CpuPort::recvAtomic(PacketPtr pkt)
557{
558    panic("BaseCPU doesn't expect recvAtomic callback!");
559    return curTick();
560}
561
562void
563BaseCPU::CpuPort::recvFunctional(PacketPtr pkt)
564{
565    // No internal storage to update (in the general case). In the
566    // long term this should never be called, but that assumed a split
567    // into master/slave and request/response.
568}
569
570void
571BaseCPU::CpuPort::recvRangeChange()
572{
573}
574