base.cc revision 4918:3214e3694fb2
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 * Authors: Steve Reinhardt
29 *          Nathan Binkert
30 */
31
32#include <iostream>
33#include <string>
34#include <sstream>
35
36#include "base/cprintf.hh"
37#include "base/loader/symtab.hh"
38#include "base/misc.hh"
39#include "base/output.hh"
40#include "cpu/base.hh"
41#include "cpu/cpuevent.hh"
42#include "cpu/thread_context.hh"
43#include "cpu/profile.hh"
44#include "sim/sim_exit.hh"
45#include "sim/process.hh"
46#include "sim/sim_events.hh"
47#include "sim/system.hh"
48
49#include "base/trace.hh"
50
51// Hack
52#include "sim/stat_control.hh"
53
54using namespace std;
55
56vector<BaseCPU *> BaseCPU::cpuList;
57
58// This variable reflects the max number of threads in any CPU.  Be
59// careful to only use it once all the CPUs that you care about have
60// been initialized
61int maxThreadsPerCPU = 1;
62
63CPUProgressEvent::CPUProgressEvent(EventQueue *q, Tick ival,
64                                   BaseCPU *_cpu)
65    : Event(q, Event::Progress_Event_Pri), interval(ival),
66      lastNumInst(0), cpu(_cpu)
67{
68    if (interval)
69        schedule(curTick + interval);
70}
71
72void
73CPUProgressEvent::process()
74{
75    Counter temp = cpu->totalInstructions();
76#ifndef NDEBUG
77    double ipc = double(temp - lastNumInst) / (interval / cpu->cycles(1));
78
79    DPRINTFN("%s progress event, instructions committed: %lli, IPC: %0.8d\n",
80             cpu->name(), temp - lastNumInst, ipc);
81    ipc = 0.0;
82#else
83    cprintf("%lli: %s progress event, instructions committed: %lli\n",
84            curTick, cpu->name(), temp - lastNumInst);
85#endif
86    lastNumInst = temp;
87    schedule(curTick + interval);
88}
89
90const char *
91CPUProgressEvent::description()
92{
93    return "CPU Progress";
94}
95
96#if FULL_SYSTEM
97BaseCPU::BaseCPU(Params *p)
98    : MemObject(p->name), clock(p->clock), instCnt(0),
99      params(p), number_of_threads(p->numberOfThreads), system(p->system),
100      phase(p->phase)
101#else
102BaseCPU::BaseCPU(Params *p)
103    : MemObject(p->name), clock(p->clock), params(p),
104      number_of_threads(p->numberOfThreads), system(p->system),
105      phase(p->phase)
106#endif
107{
108//    currentTick = curTick;
109    DPRINTF(FullCPU, "BaseCPU: Creating object, mem address %#x.\n", this);
110
111    // add self to global list of CPUs
112    cpuList.push_back(this);
113
114    DPRINTF(FullCPU, "BaseCPU: CPU added to cpuList, mem address %#x.\n",
115            this);
116
117    if (number_of_threads > maxThreadsPerCPU)
118        maxThreadsPerCPU = number_of_threads;
119
120    // allocate per-thread instruction-based event queues
121    comInstEventQueue = new EventQueue *[number_of_threads];
122    for (int i = 0; i < number_of_threads; ++i)
123        comInstEventQueue[i] = new EventQueue("instruction-based event queue");
124
125    //
126    // set up instruction-count-based termination events, if any
127    //
128    if (p->max_insts_any_thread != 0)
129        for (int i = 0; i < number_of_threads; ++i)
130            schedExitSimLoop("a thread reached the max instruction count",
131                             p->max_insts_any_thread, 0,
132                             comInstEventQueue[i]);
133
134    if (p->max_insts_all_threads != 0) {
135        // allocate & initialize shared downcounter: each event will
136        // decrement this when triggered; simulation will terminate
137        // when counter reaches 0
138        int *counter = new int;
139        *counter = number_of_threads;
140        for (int i = 0; i < number_of_threads; ++i)
141            new CountedExitEvent(comInstEventQueue[i],
142                "all threads reached the max instruction count",
143                p->max_insts_all_threads, *counter);
144    }
145
146    // allocate per-thread load-based event queues
147    comLoadEventQueue = new EventQueue *[number_of_threads];
148    for (int i = 0; i < number_of_threads; ++i)
149        comLoadEventQueue[i] = new EventQueue("load-based event queue");
150
151    //
152    // set up instruction-count-based termination events, if any
153    //
154    if (p->max_loads_any_thread != 0)
155        for (int i = 0; i < number_of_threads; ++i)
156            schedExitSimLoop("a thread reached the max load count",
157                             p->max_loads_any_thread, 0,
158                             comLoadEventQueue[i]);
159
160    if (p->max_loads_all_threads != 0) {
161        // allocate & initialize shared downcounter: each event will
162        // decrement this when triggered; simulation will terminate
163        // when counter reaches 0
164        int *counter = new int;
165        *counter = number_of_threads;
166        for (int i = 0; i < number_of_threads; ++i)
167            new CountedExitEvent(comLoadEventQueue[i],
168                "all threads reached the max load count",
169                p->max_loads_all_threads, *counter);
170    }
171
172    functionTracingEnabled = false;
173    if (p->functionTrace) {
174        functionTraceStream = simout.find(csprintf("ftrace.%s", name()));
175        currentFunctionStart = currentFunctionEnd = 0;
176        functionEntryTick = p->functionTraceStart;
177
178        if (p->functionTraceStart == 0) {
179            functionTracingEnabled = true;
180        } else {
181            new EventWrapper<BaseCPU, &BaseCPU::enableFunctionTrace>(this,
182                                                                     p->functionTraceStart,
183                                                                     true);
184        }
185    }
186#if FULL_SYSTEM
187    profileEvent = NULL;
188    if (params->profile)
189        profileEvent = new ProfileEvent(this, params->profile);
190#endif
191}
192
193BaseCPU::Params::Params()
194{
195#if FULL_SYSTEM
196    profile = false;
197#endif
198    checker = NULL;
199}
200
201void
202BaseCPU::enableFunctionTrace()
203{
204    functionTracingEnabled = true;
205}
206
207BaseCPU::~BaseCPU()
208{
209}
210
211void
212BaseCPU::init()
213{
214    if (!params->deferRegistration)
215        registerThreadContexts();
216}
217
218void
219BaseCPU::startup()
220{
221#if FULL_SYSTEM
222    if (!params->deferRegistration && profileEvent)
223        profileEvent->schedule(curTick);
224#endif
225
226    if (params->progress_interval) {
227        new CPUProgressEvent(&mainEventQueue,
228                             cycles(params->progress_interval),
229                             this);
230    }
231}
232
233
234void
235BaseCPU::regStats()
236{
237    using namespace Stats;
238
239    numCycles
240        .name(name() + ".numCycles")
241        .desc("number of cpu cycles simulated")
242        ;
243
244    int size = threadContexts.size();
245    if (size > 1) {
246        for (int i = 0; i < size; ++i) {
247            stringstream namestr;
248            ccprintf(namestr, "%s.ctx%d", name(), i);
249            threadContexts[i]->regStats(namestr.str());
250        }
251    } else if (size == 1)
252        threadContexts[0]->regStats(name());
253
254#if FULL_SYSTEM
255#endif
256}
257
258Tick
259BaseCPU::nextCycle()
260{
261    Tick next_tick = curTick - phase + clock - 1;
262    next_tick -= (next_tick % clock);
263    next_tick += phase;
264    return next_tick;
265}
266
267Tick
268BaseCPU::nextCycle(Tick begin_tick)
269{
270    Tick next_tick = begin_tick;
271    if (next_tick % clock != 0)
272        next_tick = next_tick - (next_tick % clock) + clock;
273    next_tick += phase;
274
275    assert(next_tick >= curTick);
276    return next_tick;
277}
278
279void
280BaseCPU::registerThreadContexts()
281{
282    for (int i = 0; i < threadContexts.size(); ++i) {
283        ThreadContext *tc = threadContexts[i];
284
285#if FULL_SYSTEM
286        int id = params->cpu_id;
287        if (id != -1)
288            id += i;
289
290        tc->setCpuId(system->registerThreadContext(tc, id));
291#else
292        tc->setCpuId(tc->getProcessPtr()->registerThreadContext(tc));
293#endif
294    }
295}
296
297
298int
299BaseCPU::findContext(ThreadContext *tc)
300{
301    for (int i = 0; i < threadContexts.size(); ++i) {
302        if (tc == threadContexts[i])
303            return i;
304    }
305    return 0;
306}
307
308void
309BaseCPU::switchOut()
310{
311//    panic("This CPU doesn't support sampling!");
312#if FULL_SYSTEM
313    if (profileEvent && profileEvent->scheduled())
314        profileEvent->deschedule();
315#endif
316}
317
318void
319BaseCPU::takeOverFrom(BaseCPU *oldCPU, Port *ic, Port *dc)
320{
321    assert(threadContexts.size() == oldCPU->threadContexts.size());
322
323    for (int i = 0; i < threadContexts.size(); ++i) {
324        ThreadContext *newTC = threadContexts[i];
325        ThreadContext *oldTC = oldCPU->threadContexts[i];
326
327        newTC->takeOverFrom(oldTC);
328
329        CpuEvent::replaceThreadContext(oldTC, newTC);
330
331        assert(newTC->readCpuId() == oldTC->readCpuId());
332#if FULL_SYSTEM
333        system->replaceThreadContext(newTC, newTC->readCpuId());
334#else
335        assert(newTC->getProcessPtr() == oldTC->getProcessPtr());
336        newTC->getProcessPtr()->replaceThreadContext(newTC, newTC->readCpuId());
337#endif
338
339//    TheISA::compareXCs(oldXC, newXC);
340    }
341
342#if FULL_SYSTEM
343    interrupts = oldCPU->interrupts;
344
345    for (int i = 0; i < threadContexts.size(); ++i)
346        threadContexts[i]->profileClear();
347
348    // The Sampler must take care of this!
349//    if (profileEvent)
350//        profileEvent->schedule(curTick);
351#endif
352
353    // Connect new CPU to old CPU's memory only if new CPU isn't
354    // connected to anything.  Also connect old CPU's memory to new
355    // CPU.
356    Port *peer;
357    if (ic->getPeer() == NULL) {
358        peer = oldCPU->getPort("icache_port")->getPeer();
359        ic->setPeer(peer);
360    } else {
361        peer = ic->getPeer();
362    }
363    peer->setPeer(ic);
364
365    if (dc->getPeer() == NULL) {
366        peer = oldCPU->getPort("dcache_port")->getPeer();
367        dc->setPeer(peer);
368    } else {
369        peer = dc->getPeer();
370    }
371    peer->setPeer(dc);
372}
373
374
375#if FULL_SYSTEM
376BaseCPU::ProfileEvent::ProfileEvent(BaseCPU *_cpu, int _interval)
377    : Event(&mainEventQueue), cpu(_cpu), interval(_interval)
378{ }
379
380void
381BaseCPU::ProfileEvent::process()
382{
383    for (int i = 0, size = cpu->threadContexts.size(); i < size; ++i) {
384        ThreadContext *tc = cpu->threadContexts[i];
385        tc->profileSample();
386    }
387
388    schedule(curTick + interval);
389}
390
391void
392BaseCPU::post_interrupt(int int_num, int index)
393{
394    interrupts.post(int_num, index);
395}
396
397void
398BaseCPU::clear_interrupt(int int_num, int index)
399{
400    interrupts.clear(int_num, index);
401}
402
403void
404BaseCPU::clear_interrupts()
405{
406    interrupts.clear_all();
407}
408
409uint64_t
410BaseCPU::get_interrupts(int int_num)
411{
412    return interrupts.get_vec(int_num);
413}
414
415void
416BaseCPU::serialize(std::ostream &os)
417{
418    SERIALIZE_SCALAR(instCnt);
419    interrupts.serialize(os);
420}
421
422void
423BaseCPU::unserialize(Checkpoint *cp, const std::string &section)
424{
425    UNSERIALIZE_SCALAR(instCnt);
426    interrupts.unserialize(cp, section);
427}
428
429#endif // FULL_SYSTEM
430
431void
432BaseCPU::traceFunctionsInternal(Addr pc)
433{
434    if (!debugSymbolTable)
435        return;
436
437    // if pc enters different function, print new function symbol and
438    // update saved range.  Otherwise do nothing.
439    if (pc < currentFunctionStart || pc >= currentFunctionEnd) {
440        string sym_str;
441        bool found = debugSymbolTable->findNearestSymbol(pc, sym_str,
442                                                         currentFunctionStart,
443                                                         currentFunctionEnd);
444
445        if (!found) {
446            // no symbol found: use addr as label
447            sym_str = csprintf("0x%x", pc);
448            currentFunctionStart = pc;
449            currentFunctionEnd = pc + 1;
450        }
451
452        ccprintf(*functionTraceStream, " (%d)\n%d: %s",
453                 curTick - functionEntryTick, curTick, sym_str);
454        functionEntryTick = curTick;
455    }
456}
457