base.cc revision 2356
1/*
2 * Copyright (c) 2002-2005 The Regents of The University of Michigan
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met: redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer;
9 * redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution;
12 * neither the name of the copyright holders nor the names of its
13 * contributors may be used to endorse or promote products derived from
14 * this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29#include <iostream>
30#include <string>
31#include <sstream>
32
33#include "base/cprintf.hh"
34#include "base/loader/symtab.hh"
35#include "base/misc.hh"
36#include "base/output.hh"
37#include "cpu/base.hh"
38#include "cpu/exec_context.hh"
39#include "cpu/profile.hh"
40#include "cpu/sampler/sampler.hh"
41#include "sim/param.hh"
42#include "sim/process.hh"
43#include "sim/sim_events.hh"
44#include "sim/system.hh"
45
46#include "base/trace.hh"
47
48using namespace std;
49
50vector<BaseCPU *> BaseCPU::cpuList;
51
52// This variable reflects the max number of threads in any CPU.  Be
53// careful to only use it once all the CPUs that you care about have
54// been initialized
55int maxThreadsPerCPU = 1;
56
57void
58CPUProgressEvent::process()
59{
60#ifndef NDEBUG
61    Counter temp = cpu->totalInstructions();
62    double ipc = double(temp - lastNumInst) / (interval / cpu->cycles(1));
63    DPRINTFN("%s progress event, instructions committed: %lli, IPC: %0.8d\n",
64             cpu->name(), temp - lastNumInst, ipc);
65    ipc = 0.0;
66    lastNumInst = temp;
67    schedule(curTick + interval);
68#endif
69}
70
71const char *
72CPUProgressEvent::description()
73{
74    return "CPU Progress event";
75}
76
77#if FULL_SYSTEM
78BaseCPU::BaseCPU(Params *p)
79    : SimObject(p->name), clock(p->clock), checkInterrupts(true),
80      params(p), number_of_threads(p->numberOfThreads), system(p->system)
81#else
82BaseCPU::BaseCPU(Params *p)
83    : SimObject(p->name), clock(p->clock), params(p),
84      number_of_threads(p->numberOfThreads)
85#endif
86{
87    DPRINTF(FullCPU, "BaseCPU: Creating object, mem address %#x.\n", this);
88
89    // add self to global list of CPUs
90    cpuList.push_back(this);
91
92    DPRINTF(FullCPU, "BaseCPU: CPU added to cpuList, mem address %#x.\n",
93            this);
94
95    if (number_of_threads > maxThreadsPerCPU)
96        maxThreadsPerCPU = number_of_threads;
97
98    // allocate per-thread instruction-based event queues
99    comInstEventQueue = new EventQueue *[number_of_threads];
100    for (int i = 0; i < number_of_threads; ++i)
101        comInstEventQueue[i] = new EventQueue("instruction-based event queue");
102
103    //
104    // set up instruction-count-based termination events, if any
105    //
106    if (p->max_insts_any_thread != 0)
107        for (int i = 0; i < number_of_threads; ++i)
108            new SimExitEvent(comInstEventQueue[i], p->max_insts_any_thread,
109                "a thread reached the max instruction count");
110
111    if (p->max_insts_all_threads != 0) {
112        // allocate & initialize shared downcounter: each event will
113        // decrement this when triggered; simulation will terminate
114        // when counter reaches 0
115        int *counter = new int;
116        *counter = number_of_threads;
117        for (int i = 0; i < number_of_threads; ++i)
118            new CountedExitEvent(comInstEventQueue[i],
119                "all threads reached the max instruction count",
120                p->max_insts_all_threads, *counter);
121    }
122
123    // allocate per-thread load-based event queues
124    comLoadEventQueue = new EventQueue *[number_of_threads];
125    for (int i = 0; i < number_of_threads; ++i)
126        comLoadEventQueue[i] = new EventQueue("load-based event queue");
127
128    //
129    // set up instruction-count-based termination events, if any
130    //
131    if (p->max_loads_any_thread != 0)
132        for (int i = 0; i < number_of_threads; ++i)
133            new SimExitEvent(comLoadEventQueue[i], p->max_loads_any_thread,
134                "a thread reached the max load count");
135
136    if (p->max_loads_all_threads != 0) {
137        // allocate & initialize shared downcounter: each event will
138        // decrement this when triggered; simulation will terminate
139        // when counter reaches 0
140        int *counter = new int;
141        *counter = number_of_threads;
142        for (int i = 0; i < number_of_threads; ++i)
143            new CountedExitEvent(comLoadEventQueue[i],
144                "all threads reached the max load count",
145                p->max_loads_all_threads, *counter);
146    }
147
148#if FULL_SYSTEM
149    memset(interrupts, 0, sizeof(interrupts));
150    intstatus = 0;
151#endif
152
153    functionTracingEnabled = false;
154    if (p->functionTrace) {
155        functionTraceStream = simout.find(csprintf("ftrace.%s", name()));
156        currentFunctionStart = currentFunctionEnd = 0;
157        functionEntryTick = p->functionTraceStart;
158
159        if (p->functionTraceStart == 0) {
160            functionTracingEnabled = true;
161        } else {
162            Event *e =
163                new EventWrapper<BaseCPU, &BaseCPU::enableFunctionTrace>(this,
164                                                                         true);
165            e->schedule(p->functionTraceStart);
166        }
167    }
168#if FULL_SYSTEM
169    profileEvent = NULL;
170    if (params->profile)
171        profileEvent = new ProfileEvent(this, params->profile);
172#endif
173}
174
175BaseCPU::Params::Params()
176{
177#if FULL_SYSTEM
178    profile = false;
179#endif
180    checker = NULL;
181}
182
183void
184BaseCPU::enableFunctionTrace()
185{
186    functionTracingEnabled = true;
187}
188
189BaseCPU::~BaseCPU()
190{
191}
192
193void
194BaseCPU::init()
195{
196    if (!params->deferRegistration)
197        registerExecContexts();
198}
199
200void
201BaseCPU::startup()
202{
203#if FULL_SYSTEM
204    if (!params->deferRegistration && profileEvent)
205        profileEvent->schedule(curTick);
206#endif
207
208    if (params->progress_interval) {
209        new CPUProgressEvent(&mainEventQueue, params->progress_interval,
210                             this);
211    }
212}
213
214
215void
216BaseCPU::regStats()
217{
218    using namespace Stats;
219
220    numCycles
221        .name(name() + ".numCycles")
222        .desc("number of cpu cycles simulated")
223        ;
224
225    int size = execContexts.size();
226    if (size > 1) {
227        for (int i = 0; i < size; ++i) {
228            stringstream namestr;
229            ccprintf(namestr, "%s.ctx%d", name(), i);
230            execContexts[i]->regStats(namestr.str());
231        }
232    } else if (size == 1)
233        execContexts[0]->regStats(name());
234
235#if FULL_SYSTEM
236#endif
237}
238
239
240void
241BaseCPU::registerExecContexts()
242{
243    for (int i = 0; i < execContexts.size(); ++i) {
244        ExecContext *xc = execContexts[i];
245
246        if (xc->status() == ExecContext::Suspended) {
247#if FULL_SYSTEM
248            int id = params->cpu_id;
249            if (id != -1)
250                id += i;
251
252        xc->setCpuId(system->registerExecContext(xc, id));
253#else
254        xc->setCpuId(xc->getProcessPtr()->registerExecContext(xc));
255#endif
256        }
257    }
258}
259
260
261void
262BaseCPU::switchOut(Sampler *sampler)
263{
264    panic("This CPU doesn't support sampling!");
265}
266
267void
268BaseCPU::takeOverFrom(BaseCPU *oldCPU)
269{
270    assert(execContexts.size() == oldCPU->execContexts.size());
271
272    for (int i = 0; i < execContexts.size(); ++i) {
273        ExecContext *newXC = execContexts[i];
274        ExecContext *oldXC = oldCPU->execContexts[i];
275
276        newXC->takeOverFrom(oldXC);
277        assert(newXC->readCpuId() == oldXC->readCpuId());
278#if FULL_SYSTEM
279        system->replaceExecContext(newXC, newXC->readCpuId());
280#else
281        assert(newXC->getProcessPtr() == oldXC->getProcessPtr());
282        newXC->getProcessPtr()->replaceExecContext(newXC, newXC->readCpuId());
283#endif
284    }
285
286#if FULL_SYSTEM
287    for (int i = 0; i < TheISA::NumInterruptLevels; ++i)
288        interrupts[i] = oldCPU->interrupts[i];
289    intstatus = oldCPU->intstatus;
290
291    for (int i = 0; i < execContexts.size(); ++i)
292        execContexts[i]->profileClear();
293
294    if (profileEvent)
295        profileEvent->schedule(curTick);
296#endif
297}
298
299
300#if FULL_SYSTEM
301BaseCPU::ProfileEvent::ProfileEvent(BaseCPU *_cpu, int _interval)
302    : Event(&mainEventQueue), cpu(_cpu), interval(_interval)
303{ }
304
305void
306BaseCPU::ProfileEvent::process()
307{
308    for (int i = 0, size = cpu->execContexts.size(); i < size; ++i) {
309        ExecContext *xc = cpu->execContexts[i];
310        xc->profileSample();
311    }
312
313    schedule(curTick + interval);
314}
315
316void
317BaseCPU::post_interrupt(int int_num, int index)
318{
319    DPRINTF(Interrupt, "Interrupt %d:%d posted\n", int_num, index);
320
321    if (int_num < 0 || int_num >= TheISA::NumInterruptLevels)
322        panic("int_num out of bounds\n");
323
324    if (index < 0 || index >= sizeof(uint64_t) * 8)
325        panic("int_num out of bounds\n");
326
327    checkInterrupts = true;
328    interrupts[int_num] |= 1 << index;
329    intstatus |= (ULL(1) << int_num);
330}
331
332void
333BaseCPU::clear_interrupt(int int_num, int index)
334{
335    DPRINTF(Interrupt, "Interrupt %d:%d cleared\n", int_num, index);
336
337    if (int_num < 0 || int_num >= TheISA::NumInterruptLevels)
338        panic("int_num out of bounds\n");
339
340    if (index < 0 || index >= sizeof(uint64_t) * 8)
341        panic("int_num out of bounds\n");
342
343    interrupts[int_num] &= ~(1 << index);
344    if (interrupts[int_num] == 0)
345        intstatus &= ~(ULL(1) << int_num);
346}
347
348void
349BaseCPU::clear_interrupts()
350{
351    DPRINTF(Interrupt, "Interrupts all cleared\n");
352
353    memset(interrupts, 0, sizeof(interrupts));
354    intstatus = 0;
355}
356
357
358void
359BaseCPU::serialize(std::ostream &os)
360{
361    SERIALIZE_ARRAY(interrupts, TheISA::NumInterruptLevels);
362    SERIALIZE_SCALAR(intstatus);
363}
364
365void
366BaseCPU::unserialize(Checkpoint *cp, const std::string &section)
367{
368    UNSERIALIZE_ARRAY(interrupts, TheISA::NumInterruptLevels);
369    UNSERIALIZE_SCALAR(intstatus);
370}
371
372#endif // FULL_SYSTEM
373
374void
375BaseCPU::traceFunctionsInternal(Addr pc)
376{
377    if (!debugSymbolTable)
378        return;
379
380    // if pc enters different function, print new function symbol and
381    // update saved range.  Otherwise do nothing.
382    if (pc < currentFunctionStart || pc >= currentFunctionEnd) {
383        string sym_str;
384        bool found = debugSymbolTable->findNearestSymbol(pc, sym_str,
385                                                         currentFunctionStart,
386                                                         currentFunctionEnd);
387
388        if (!found) {
389            // no symbol found: use addr as label
390            sym_str = csprintf("0x%x", pc);
391            currentFunctionStart = pc;
392            currentFunctionEnd = pc + 1;
393        }
394
395        ccprintf(*functionTraceStream, " (%d)\n%d: %s",
396                 curTick - functionEntryTick, curTick, sym_str);
397        functionEntryTick = curTick;
398    }
399}
400
401
402DEFINE_SIM_OBJECT_CLASS_NAME("BaseCPU", BaseCPU)
403