base.cc (9608:e2b6b86fda03) base.cc (9647:5b6b315472e7)
1/*
2 * Copyright (c) 2011-2012 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 "cpu/base.hh"
57#include "cpu/checker/cpu.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// Hack
70#include "sim/stat_control.hh"
71
72using namespace std;
73
74vector<BaseCPU *> BaseCPU::cpuList;
75
76// This variable reflects the max number of threads in any CPU. Be
77// careful to only use it once all the CPUs that you care about have
78// been initialized
79int maxThreadsPerCPU = 1;
80
81CPUProgressEvent::CPUProgressEvent(BaseCPU *_cpu, Tick ival)
82 : Event(Event::Progress_Event_Pri), _interval(ival), lastNumInst(0),
83 cpu(_cpu), _repeatEvent(true)
84{
85 if (_interval)
86 cpu->schedule(this, curTick() + _interval);
87}
88
89void
90CPUProgressEvent::process()
91{
92 Counter temp = cpu->totalOps();
93#ifndef NDEBUG
94 double ipc = double(temp - lastNumInst) / (_interval / cpu->clockPeriod());
95
96 DPRINTFN("%s progress event, total committed:%i, progress insts committed: "
97 "%lli, IPC: %0.8d\n", cpu->name(), temp, temp - lastNumInst,
98 ipc);
99 ipc = 0.0;
100#else
101 cprintf("%lli: %s progress event, total committed:%i, progress insts "
102 "committed: %lli\n", curTick(), cpu->name(), temp,
103 temp - lastNumInst);
104#endif
105 lastNumInst = temp;
106
107 if (_repeatEvent)
108 cpu->schedule(this, curTick() + _interval);
109}
110
111const char *
112CPUProgressEvent::description() const
113{
114 return "CPU Progress";
115}
116
117BaseCPU::BaseCPU(Params *p, bool is_checker)
118 : MemObject(p), instCnt(0), _cpuId(p->cpu_id),
119 _instMasterId(p->system->getMasterId(name() + ".inst")),
120 _dataMasterId(p->system->getMasterId(name() + ".data")),
121 _taskId(ContextSwitchTaskId::Unknown), _pid(Request::invldPid),
122 _switchedOut(p->switched_out),
123 interrupts(p->interrupts), profileEvent(NULL),
124 numThreads(p->numThreads), system(p->system)
125{
126 // if Python did not provide a valid ID, do it here
127 if (_cpuId == -1 ) {
128 _cpuId = cpuList.size();
129 }
130
131 // add self to global list of CPUs
132 cpuList.push_back(this);
133
134 DPRINTF(SyscallVerbose, "Constructing CPU with id %d\n", _cpuId);
135
136 if (numThreads > maxThreadsPerCPU)
137 maxThreadsPerCPU = numThreads;
138
139 // allocate per-thread instruction-based event queues
140 comInstEventQueue = new EventQueue *[numThreads];
141 for (ThreadID tid = 0; tid < numThreads; ++tid)
142 comInstEventQueue[tid] =
143 new EventQueue("instruction-based event queue");
144
145 //
146 // set up instruction-count-based termination events, if any
147 //
148 if (p->max_insts_any_thread != 0) {
149 const char *cause = "a thread reached the max instruction count";
150 for (ThreadID tid = 0; tid < numThreads; ++tid) {
151 Event *event = new SimLoopExitEvent(cause, 0);
152 comInstEventQueue[tid]->schedule(event, p->max_insts_any_thread);
153 }
154 }
155
1/*
2 * Copyright (c) 2011-2012 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 "cpu/base.hh"
57#include "cpu/checker/cpu.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// Hack
70#include "sim/stat_control.hh"
71
72using namespace std;
73
74vector<BaseCPU *> BaseCPU::cpuList;
75
76// This variable reflects the max number of threads in any CPU. Be
77// careful to only use it once all the CPUs that you care about have
78// been initialized
79int maxThreadsPerCPU = 1;
80
81CPUProgressEvent::CPUProgressEvent(BaseCPU *_cpu, Tick ival)
82 : Event(Event::Progress_Event_Pri), _interval(ival), lastNumInst(0),
83 cpu(_cpu), _repeatEvent(true)
84{
85 if (_interval)
86 cpu->schedule(this, curTick() + _interval);
87}
88
89void
90CPUProgressEvent::process()
91{
92 Counter temp = cpu->totalOps();
93#ifndef NDEBUG
94 double ipc = double(temp - lastNumInst) / (_interval / cpu->clockPeriod());
95
96 DPRINTFN("%s progress event, total committed:%i, progress insts committed: "
97 "%lli, IPC: %0.8d\n", cpu->name(), temp, temp - lastNumInst,
98 ipc);
99 ipc = 0.0;
100#else
101 cprintf("%lli: %s progress event, total committed:%i, progress insts "
102 "committed: %lli\n", curTick(), cpu->name(), temp,
103 temp - lastNumInst);
104#endif
105 lastNumInst = temp;
106
107 if (_repeatEvent)
108 cpu->schedule(this, curTick() + _interval);
109}
110
111const char *
112CPUProgressEvent::description() const
113{
114 return "CPU Progress";
115}
116
117BaseCPU::BaseCPU(Params *p, bool is_checker)
118 : MemObject(p), instCnt(0), _cpuId(p->cpu_id),
119 _instMasterId(p->system->getMasterId(name() + ".inst")),
120 _dataMasterId(p->system->getMasterId(name() + ".data")),
121 _taskId(ContextSwitchTaskId::Unknown), _pid(Request::invldPid),
122 _switchedOut(p->switched_out),
123 interrupts(p->interrupts), profileEvent(NULL),
124 numThreads(p->numThreads), system(p->system)
125{
126 // if Python did not provide a valid ID, do it here
127 if (_cpuId == -1 ) {
128 _cpuId = cpuList.size();
129 }
130
131 // add self to global list of CPUs
132 cpuList.push_back(this);
133
134 DPRINTF(SyscallVerbose, "Constructing CPU with id %d\n", _cpuId);
135
136 if (numThreads > maxThreadsPerCPU)
137 maxThreadsPerCPU = numThreads;
138
139 // allocate per-thread instruction-based event queues
140 comInstEventQueue = new EventQueue *[numThreads];
141 for (ThreadID tid = 0; tid < numThreads; ++tid)
142 comInstEventQueue[tid] =
143 new EventQueue("instruction-based event queue");
144
145 //
146 // set up instruction-count-based termination events, if any
147 //
148 if (p->max_insts_any_thread != 0) {
149 const char *cause = "a thread reached the max instruction count";
150 for (ThreadID tid = 0; tid < numThreads; ++tid) {
151 Event *event = new SimLoopExitEvent(cause, 0);
152 comInstEventQueue[tid]->schedule(event, p->max_insts_any_thread);
153 }
154 }
155
156 // Set up instruction-count-based termination events for SimPoints
157 // Typically, there are more than one action points.
158 // Simulation.py is responsible to take the necessary actions upon
159 // exitting the simulation loop.
160 if (!p->simpoint_start_insts.empty()) {
161 const char *cause = "simpoint starting point found";
162 for (size_t i = 0; i < p->simpoint_start_insts.size(); ++i) {
163 Event *event = new SimLoopExitEvent(cause, 0);
164 comInstEventQueue[0]->schedule(event, p->simpoint_start_insts[i]);
165 }
166 }
167
156 if (p->max_insts_all_threads != 0) {
157 const char *cause = "all threads reached the max instruction count";
158
159 // allocate & initialize shared downcounter: each event will
160 // decrement this when triggered; simulation will terminate
161 // when counter reaches 0
162 int *counter = new int;
163 *counter = numThreads;
164 for (ThreadID tid = 0; tid < numThreads; ++tid) {
165 Event *event = new CountedExitEvent(cause, *counter);
166 comInstEventQueue[tid]->schedule(event, p->max_insts_all_threads);
167 }
168 }
169
170 // allocate per-thread load-based event queues
171 comLoadEventQueue = new EventQueue *[numThreads];
172 for (ThreadID tid = 0; tid < numThreads; ++tid)
173 comLoadEventQueue[tid] = new EventQueue("load-based event queue");
174
175 //
176 // set up instruction-count-based termination events, if any
177 //
178 if (p->max_loads_any_thread != 0) {
179 const char *cause = "a thread reached the max load count";
180 for (ThreadID tid = 0; tid < numThreads; ++tid) {
181 Event *event = new SimLoopExitEvent(cause, 0);
182 comLoadEventQueue[tid]->schedule(event, p->max_loads_any_thread);
183 }
184 }
185
186 if (p->max_loads_all_threads != 0) {
187 const char *cause = "all threads reached the max load count";
188 // allocate & initialize shared downcounter: each event will
189 // decrement this when triggered; simulation will terminate
190 // when counter reaches 0
191 int *counter = new int;
192 *counter = numThreads;
193 for (ThreadID tid = 0; tid < numThreads; ++tid) {
194 Event *event = new CountedExitEvent(cause, *counter);
195 comLoadEventQueue[tid]->schedule(event, p->max_loads_all_threads);
196 }
197 }
198
199 functionTracingEnabled = false;
200 if (p->function_trace) {
201 const string fname = csprintf("ftrace.%s", name());
202 functionTraceStream = simout.find(fname);
203 if (!functionTraceStream)
204 functionTraceStream = simout.create(fname);
205
206 currentFunctionStart = currentFunctionEnd = 0;
207 functionEntryTick = p->function_trace_start;
208
209 if (p->function_trace_start == 0) {
210 functionTracingEnabled = true;
211 } else {
212 typedef EventWrapper<BaseCPU, &BaseCPU::enableFunctionTrace> wrap;
213 Event *event = new wrap(this, true);
214 schedule(event, p->function_trace_start);
215 }
216 }
217
218 // The interrupts should always be present unless this CPU is
219 // switched in later or in case it is a checker CPU
220 if (!params()->switched_out && !is_checker) {
221 if (interrupts) {
222 interrupts->setCPU(this);
223 } else {
224 fatal("CPU %s has no interrupt controller.\n"
225 "Ensure createInterruptController() is called.\n", name());
226 }
227 }
228
229 if (FullSystem) {
230 if (params()->profile)
231 profileEvent = new ProfileEvent(this, params()->profile);
232 }
233 tracer = params()->tracer;
234
235 if (params()->isa.size() != numThreads) {
236 fatal("Number of ISAs (%i) assigned to the CPU does not equal number "
237 "of threads (%i).\n", params()->isa.size(), numThreads);
238 }
239}
240
241void
242BaseCPU::enableFunctionTrace()
243{
244 functionTracingEnabled = true;
245}
246
247BaseCPU::~BaseCPU()
248{
249 delete profileEvent;
250 delete[] comLoadEventQueue;
251 delete[] comInstEventQueue;
252}
253
254void
255BaseCPU::init()
256{
257 if (!params()->switched_out) {
258 registerThreadContexts();
259
260 verifyMemoryMode();
261 }
262}
263
264void
265BaseCPU::startup()
266{
267 if (FullSystem) {
268 if (!params()->switched_out && profileEvent)
269 schedule(profileEvent, curTick());
270 }
271
272 if (params()->progress_interval) {
273 new CPUProgressEvent(this, params()->progress_interval);
274 }
275}
276
277
278void
279BaseCPU::regStats()
280{
281 using namespace Stats;
282
283 numCycles
284 .name(name() + ".numCycles")
285 .desc("number of cpu cycles simulated")
286 ;
287
288 numWorkItemsStarted
289 .name(name() + ".numWorkItemsStarted")
290 .desc("number of work items this cpu started")
291 ;
292
293 numWorkItemsCompleted
294 .name(name() + ".numWorkItemsCompleted")
295 .desc("number of work items this cpu completed")
296 ;
297
298 int size = threadContexts.size();
299 if (size > 1) {
300 for (int i = 0; i < size; ++i) {
301 stringstream namestr;
302 ccprintf(namestr, "%s.ctx%d", name(), i);
303 threadContexts[i]->regStats(namestr.str());
304 }
305 } else if (size == 1)
306 threadContexts[0]->regStats(name());
307}
308
309BaseMasterPort &
310BaseCPU::getMasterPort(const string &if_name, PortID idx)
311{
312 // Get the right port based on name. This applies to all the
313 // subclasses of the base CPU and relies on their implementation
314 // of getDataPort and getInstPort. In all cases there methods
315 // return a MasterPort pointer.
316 if (if_name == "dcache_port")
317 return getDataPort();
318 else if (if_name == "icache_port")
319 return getInstPort();
320 else
321 return MemObject::getMasterPort(if_name, idx);
322}
323
324void
325BaseCPU::registerThreadContexts()
326{
327 ThreadID size = threadContexts.size();
328 for (ThreadID tid = 0; tid < size; ++tid) {
329 ThreadContext *tc = threadContexts[tid];
330
331 /** This is so that contextId and cpuId match where there is a
332 * 1cpu:1context relationship. Otherwise, the order of registration
333 * could affect the assignment and cpu 1 could have context id 3, for
334 * example. We may even want to do something like this for SMT so that
335 * cpu 0 has the lowest thread contexts and cpu N has the highest, but
336 * I'll just do this for now
337 */
338 if (numThreads == 1)
339 tc->setContextId(system->registerThreadContext(tc, _cpuId));
340 else
341 tc->setContextId(system->registerThreadContext(tc));
342
343 if (!FullSystem)
344 tc->getProcessPtr()->assignThreadContext(tc->contextId());
345 }
346}
347
348
349int
350BaseCPU::findContext(ThreadContext *tc)
351{
352 ThreadID size = threadContexts.size();
353 for (ThreadID tid = 0; tid < size; ++tid) {
354 if (tc == threadContexts[tid])
355 return tid;
356 }
357 return 0;
358}
359
360void
361BaseCPU::switchOut()
362{
363 assert(!_switchedOut);
364 _switchedOut = true;
365 if (profileEvent && profileEvent->scheduled())
366 deschedule(profileEvent);
367
368 // Flush all TLBs in the CPU to avoid having stale translations if
369 // it gets switched in later.
370 flushTLBs();
371}
372
373void
374BaseCPU::takeOverFrom(BaseCPU *oldCPU)
375{
376 assert(threadContexts.size() == oldCPU->threadContexts.size());
377 assert(_cpuId == oldCPU->cpuId());
378 assert(_switchedOut);
379 assert(oldCPU != this);
380 _pid = oldCPU->getPid();
381 _taskId = oldCPU->taskId();
382 _switchedOut = false;
383
384 ThreadID size = threadContexts.size();
385 for (ThreadID i = 0; i < size; ++i) {
386 ThreadContext *newTC = threadContexts[i];
387 ThreadContext *oldTC = oldCPU->threadContexts[i];
388
389 newTC->takeOverFrom(oldTC);
390
391 CpuEvent::replaceThreadContext(oldTC, newTC);
392
393 assert(newTC->contextId() == oldTC->contextId());
394 assert(newTC->threadId() == oldTC->threadId());
395 system->replaceThreadContext(newTC, newTC->contextId());
396
397 /* This code no longer works since the zero register (e.g.,
398 * r31 on Alpha) doesn't necessarily contain zero at this
399 * point.
400 if (DTRACE(Context))
401 ThreadContext::compare(oldTC, newTC);
402 */
403
404 BaseMasterPort *old_itb_port = oldTC->getITBPtr()->getMasterPort();
405 BaseMasterPort *old_dtb_port = oldTC->getDTBPtr()->getMasterPort();
406 BaseMasterPort *new_itb_port = newTC->getITBPtr()->getMasterPort();
407 BaseMasterPort *new_dtb_port = newTC->getDTBPtr()->getMasterPort();
408
409 // Move over any table walker ports if they exist
410 if (new_itb_port) {
411 assert(!new_itb_port->isConnected());
412 assert(old_itb_port);
413 assert(old_itb_port->isConnected());
414 BaseSlavePort &slavePort = old_itb_port->getSlavePort();
415 old_itb_port->unbind();
416 new_itb_port->bind(slavePort);
417 }
418 if (new_dtb_port) {
419 assert(!new_dtb_port->isConnected());
420 assert(old_dtb_port);
421 assert(old_dtb_port->isConnected());
422 BaseSlavePort &slavePort = old_dtb_port->getSlavePort();
423 old_dtb_port->unbind();
424 new_dtb_port->bind(slavePort);
425 }
426
427 // Checker whether or not we have to transfer CheckerCPU
428 // objects over in the switch
429 CheckerCPU *oldChecker = oldTC->getCheckerCpuPtr();
430 CheckerCPU *newChecker = newTC->getCheckerCpuPtr();
431 if (oldChecker && newChecker) {
432 BaseMasterPort *old_checker_itb_port =
433 oldChecker->getITBPtr()->getMasterPort();
434 BaseMasterPort *old_checker_dtb_port =
435 oldChecker->getDTBPtr()->getMasterPort();
436 BaseMasterPort *new_checker_itb_port =
437 newChecker->getITBPtr()->getMasterPort();
438 BaseMasterPort *new_checker_dtb_port =
439 newChecker->getDTBPtr()->getMasterPort();
440
441 // Move over any table walker ports if they exist for checker
442 if (new_checker_itb_port) {
443 assert(!new_checker_itb_port->isConnected());
444 assert(old_checker_itb_port);
445 assert(old_checker_itb_port->isConnected());
446 BaseSlavePort &slavePort =
447 old_checker_itb_port->getSlavePort();
448 old_checker_itb_port->unbind();
449 new_checker_itb_port->bind(slavePort);
450 }
451 if (new_checker_dtb_port) {
452 assert(!new_checker_dtb_port->isConnected());
453 assert(old_checker_dtb_port);
454 assert(old_checker_dtb_port->isConnected());
455 BaseSlavePort &slavePort =
456 old_checker_dtb_port->getSlavePort();
457 old_checker_dtb_port->unbind();
458 new_checker_dtb_port->bind(slavePort);
459 }
460 }
461 }
462
463 interrupts = oldCPU->interrupts;
464 interrupts->setCPU(this);
465 oldCPU->interrupts = NULL;
466
467 if (FullSystem) {
468 for (ThreadID i = 0; i < size; ++i)
469 threadContexts[i]->profileClear();
470
471 if (profileEvent)
472 schedule(profileEvent, curTick());
473 }
474
475 // All CPUs have an instruction and a data port, and the new CPU's
476 // ports are dangling while the old CPU has its ports connected
477 // already. Unbind the old CPU and then bind the ports of the one
478 // we are switching to.
479 assert(!getInstPort().isConnected());
480 assert(oldCPU->getInstPort().isConnected());
481 BaseSlavePort &inst_peer_port = oldCPU->getInstPort().getSlavePort();
482 oldCPU->getInstPort().unbind();
483 getInstPort().bind(inst_peer_port);
484
485 assert(!getDataPort().isConnected());
486 assert(oldCPU->getDataPort().isConnected());
487 BaseSlavePort &data_peer_port = oldCPU->getDataPort().getSlavePort();
488 oldCPU->getDataPort().unbind();
489 getDataPort().bind(data_peer_port);
490}
491
492void
493BaseCPU::flushTLBs()
494{
495 for (ThreadID i = 0; i < threadContexts.size(); ++i) {
496 ThreadContext &tc(*threadContexts[i]);
497 CheckerCPU *checker(tc.getCheckerCpuPtr());
498
499 tc.getITBPtr()->flushAll();
500 tc.getDTBPtr()->flushAll();
501 if (checker) {
502 checker->getITBPtr()->flushAll();
503 checker->getDTBPtr()->flushAll();
504 }
505 }
506}
507
508
509BaseCPU::ProfileEvent::ProfileEvent(BaseCPU *_cpu, Tick _interval)
510 : cpu(_cpu), interval(_interval)
511{ }
512
513void
514BaseCPU::ProfileEvent::process()
515{
516 ThreadID size = cpu->threadContexts.size();
517 for (ThreadID i = 0; i < size; ++i) {
518 ThreadContext *tc = cpu->threadContexts[i];
519 tc->profileSample();
520 }
521
522 cpu->schedule(this, curTick() + interval);
523}
524
525void
526BaseCPU::serialize(std::ostream &os)
527{
528 SERIALIZE_SCALAR(instCnt);
529
530 if (!_switchedOut) {
531 /* Unlike _pid, _taskId is not serialized, as they are dynamically
532 * assigned unique ids that are only meaningful for the duration of
533 * a specific run. We will need to serialize the entire taskMap in
534 * system. */
535 SERIALIZE_SCALAR(_pid);
536
537 interrupts->serialize(os);
538
539 // Serialize the threads, this is done by the CPU implementation.
540 for (ThreadID i = 0; i < numThreads; ++i) {
541 nameOut(os, csprintf("%s.xc.%i", name(), i));
542 serializeThread(os, i);
543 }
544 }
545}
546
547void
548BaseCPU::unserialize(Checkpoint *cp, const std::string &section)
549{
550 UNSERIALIZE_SCALAR(instCnt);
551
552 if (!_switchedOut) {
553 UNSERIALIZE_SCALAR(_pid);
554 interrupts->unserialize(cp, section);
555
556 // Unserialize the threads, this is done by the CPU implementation.
557 for (ThreadID i = 0; i < numThreads; ++i)
558 unserializeThread(cp, csprintf("%s.xc.%i", section, i), i);
559 }
560}
561
562void
563BaseCPU::traceFunctionsInternal(Addr pc)
564{
565 if (!debugSymbolTable)
566 return;
567
568 // if pc enters different function, print new function symbol and
569 // update saved range. Otherwise do nothing.
570 if (pc < currentFunctionStart || pc >= currentFunctionEnd) {
571 string sym_str;
572 bool found = debugSymbolTable->findNearestSymbol(pc, sym_str,
573 currentFunctionStart,
574 currentFunctionEnd);
575
576 if (!found) {
577 // no symbol found: use addr as label
578 sym_str = csprintf("0x%x", pc);
579 currentFunctionStart = pc;
580 currentFunctionEnd = pc + 1;
581 }
582
583 ccprintf(*functionTraceStream, " (%d)\n%d: %s",
584 curTick() - functionEntryTick, curTick(), sym_str);
585 functionEntryTick = curTick();
586 }
587}
168 if (p->max_insts_all_threads != 0) {
169 const char *cause = "all threads reached the max instruction count";
170
171 // allocate & initialize shared downcounter: each event will
172 // decrement this when triggered; simulation will terminate
173 // when counter reaches 0
174 int *counter = new int;
175 *counter = numThreads;
176 for (ThreadID tid = 0; tid < numThreads; ++tid) {
177 Event *event = new CountedExitEvent(cause, *counter);
178 comInstEventQueue[tid]->schedule(event, p->max_insts_all_threads);
179 }
180 }
181
182 // allocate per-thread load-based event queues
183 comLoadEventQueue = new EventQueue *[numThreads];
184 for (ThreadID tid = 0; tid < numThreads; ++tid)
185 comLoadEventQueue[tid] = new EventQueue("load-based event queue");
186
187 //
188 // set up instruction-count-based termination events, if any
189 //
190 if (p->max_loads_any_thread != 0) {
191 const char *cause = "a thread reached the max load count";
192 for (ThreadID tid = 0; tid < numThreads; ++tid) {
193 Event *event = new SimLoopExitEvent(cause, 0);
194 comLoadEventQueue[tid]->schedule(event, p->max_loads_any_thread);
195 }
196 }
197
198 if (p->max_loads_all_threads != 0) {
199 const char *cause = "all threads reached the max load count";
200 // allocate & initialize shared downcounter: each event will
201 // decrement this when triggered; simulation will terminate
202 // when counter reaches 0
203 int *counter = new int;
204 *counter = numThreads;
205 for (ThreadID tid = 0; tid < numThreads; ++tid) {
206 Event *event = new CountedExitEvent(cause, *counter);
207 comLoadEventQueue[tid]->schedule(event, p->max_loads_all_threads);
208 }
209 }
210
211 functionTracingEnabled = false;
212 if (p->function_trace) {
213 const string fname = csprintf("ftrace.%s", name());
214 functionTraceStream = simout.find(fname);
215 if (!functionTraceStream)
216 functionTraceStream = simout.create(fname);
217
218 currentFunctionStart = currentFunctionEnd = 0;
219 functionEntryTick = p->function_trace_start;
220
221 if (p->function_trace_start == 0) {
222 functionTracingEnabled = true;
223 } else {
224 typedef EventWrapper<BaseCPU, &BaseCPU::enableFunctionTrace> wrap;
225 Event *event = new wrap(this, true);
226 schedule(event, p->function_trace_start);
227 }
228 }
229
230 // The interrupts should always be present unless this CPU is
231 // switched in later or in case it is a checker CPU
232 if (!params()->switched_out && !is_checker) {
233 if (interrupts) {
234 interrupts->setCPU(this);
235 } else {
236 fatal("CPU %s has no interrupt controller.\n"
237 "Ensure createInterruptController() is called.\n", name());
238 }
239 }
240
241 if (FullSystem) {
242 if (params()->profile)
243 profileEvent = new ProfileEvent(this, params()->profile);
244 }
245 tracer = params()->tracer;
246
247 if (params()->isa.size() != numThreads) {
248 fatal("Number of ISAs (%i) assigned to the CPU does not equal number "
249 "of threads (%i).\n", params()->isa.size(), numThreads);
250 }
251}
252
253void
254BaseCPU::enableFunctionTrace()
255{
256 functionTracingEnabled = true;
257}
258
259BaseCPU::~BaseCPU()
260{
261 delete profileEvent;
262 delete[] comLoadEventQueue;
263 delete[] comInstEventQueue;
264}
265
266void
267BaseCPU::init()
268{
269 if (!params()->switched_out) {
270 registerThreadContexts();
271
272 verifyMemoryMode();
273 }
274}
275
276void
277BaseCPU::startup()
278{
279 if (FullSystem) {
280 if (!params()->switched_out && profileEvent)
281 schedule(profileEvent, curTick());
282 }
283
284 if (params()->progress_interval) {
285 new CPUProgressEvent(this, params()->progress_interval);
286 }
287}
288
289
290void
291BaseCPU::regStats()
292{
293 using namespace Stats;
294
295 numCycles
296 .name(name() + ".numCycles")
297 .desc("number of cpu cycles simulated")
298 ;
299
300 numWorkItemsStarted
301 .name(name() + ".numWorkItemsStarted")
302 .desc("number of work items this cpu started")
303 ;
304
305 numWorkItemsCompleted
306 .name(name() + ".numWorkItemsCompleted")
307 .desc("number of work items this cpu completed")
308 ;
309
310 int size = threadContexts.size();
311 if (size > 1) {
312 for (int i = 0; i < size; ++i) {
313 stringstream namestr;
314 ccprintf(namestr, "%s.ctx%d", name(), i);
315 threadContexts[i]->regStats(namestr.str());
316 }
317 } else if (size == 1)
318 threadContexts[0]->regStats(name());
319}
320
321BaseMasterPort &
322BaseCPU::getMasterPort(const string &if_name, PortID idx)
323{
324 // Get the right port based on name. This applies to all the
325 // subclasses of the base CPU and relies on their implementation
326 // of getDataPort and getInstPort. In all cases there methods
327 // return a MasterPort pointer.
328 if (if_name == "dcache_port")
329 return getDataPort();
330 else if (if_name == "icache_port")
331 return getInstPort();
332 else
333 return MemObject::getMasterPort(if_name, idx);
334}
335
336void
337BaseCPU::registerThreadContexts()
338{
339 ThreadID size = threadContexts.size();
340 for (ThreadID tid = 0; tid < size; ++tid) {
341 ThreadContext *tc = threadContexts[tid];
342
343 /** This is so that contextId and cpuId match where there is a
344 * 1cpu:1context relationship. Otherwise, the order of registration
345 * could affect the assignment and cpu 1 could have context id 3, for
346 * example. We may even want to do something like this for SMT so that
347 * cpu 0 has the lowest thread contexts and cpu N has the highest, but
348 * I'll just do this for now
349 */
350 if (numThreads == 1)
351 tc->setContextId(system->registerThreadContext(tc, _cpuId));
352 else
353 tc->setContextId(system->registerThreadContext(tc));
354
355 if (!FullSystem)
356 tc->getProcessPtr()->assignThreadContext(tc->contextId());
357 }
358}
359
360
361int
362BaseCPU::findContext(ThreadContext *tc)
363{
364 ThreadID size = threadContexts.size();
365 for (ThreadID tid = 0; tid < size; ++tid) {
366 if (tc == threadContexts[tid])
367 return tid;
368 }
369 return 0;
370}
371
372void
373BaseCPU::switchOut()
374{
375 assert(!_switchedOut);
376 _switchedOut = true;
377 if (profileEvent && profileEvent->scheduled())
378 deschedule(profileEvent);
379
380 // Flush all TLBs in the CPU to avoid having stale translations if
381 // it gets switched in later.
382 flushTLBs();
383}
384
385void
386BaseCPU::takeOverFrom(BaseCPU *oldCPU)
387{
388 assert(threadContexts.size() == oldCPU->threadContexts.size());
389 assert(_cpuId == oldCPU->cpuId());
390 assert(_switchedOut);
391 assert(oldCPU != this);
392 _pid = oldCPU->getPid();
393 _taskId = oldCPU->taskId();
394 _switchedOut = false;
395
396 ThreadID size = threadContexts.size();
397 for (ThreadID i = 0; i < size; ++i) {
398 ThreadContext *newTC = threadContexts[i];
399 ThreadContext *oldTC = oldCPU->threadContexts[i];
400
401 newTC->takeOverFrom(oldTC);
402
403 CpuEvent::replaceThreadContext(oldTC, newTC);
404
405 assert(newTC->contextId() == oldTC->contextId());
406 assert(newTC->threadId() == oldTC->threadId());
407 system->replaceThreadContext(newTC, newTC->contextId());
408
409 /* This code no longer works since the zero register (e.g.,
410 * r31 on Alpha) doesn't necessarily contain zero at this
411 * point.
412 if (DTRACE(Context))
413 ThreadContext::compare(oldTC, newTC);
414 */
415
416 BaseMasterPort *old_itb_port = oldTC->getITBPtr()->getMasterPort();
417 BaseMasterPort *old_dtb_port = oldTC->getDTBPtr()->getMasterPort();
418 BaseMasterPort *new_itb_port = newTC->getITBPtr()->getMasterPort();
419 BaseMasterPort *new_dtb_port = newTC->getDTBPtr()->getMasterPort();
420
421 // Move over any table walker ports if they exist
422 if (new_itb_port) {
423 assert(!new_itb_port->isConnected());
424 assert(old_itb_port);
425 assert(old_itb_port->isConnected());
426 BaseSlavePort &slavePort = old_itb_port->getSlavePort();
427 old_itb_port->unbind();
428 new_itb_port->bind(slavePort);
429 }
430 if (new_dtb_port) {
431 assert(!new_dtb_port->isConnected());
432 assert(old_dtb_port);
433 assert(old_dtb_port->isConnected());
434 BaseSlavePort &slavePort = old_dtb_port->getSlavePort();
435 old_dtb_port->unbind();
436 new_dtb_port->bind(slavePort);
437 }
438
439 // Checker whether or not we have to transfer CheckerCPU
440 // objects over in the switch
441 CheckerCPU *oldChecker = oldTC->getCheckerCpuPtr();
442 CheckerCPU *newChecker = newTC->getCheckerCpuPtr();
443 if (oldChecker && newChecker) {
444 BaseMasterPort *old_checker_itb_port =
445 oldChecker->getITBPtr()->getMasterPort();
446 BaseMasterPort *old_checker_dtb_port =
447 oldChecker->getDTBPtr()->getMasterPort();
448 BaseMasterPort *new_checker_itb_port =
449 newChecker->getITBPtr()->getMasterPort();
450 BaseMasterPort *new_checker_dtb_port =
451 newChecker->getDTBPtr()->getMasterPort();
452
453 // Move over any table walker ports if they exist for checker
454 if (new_checker_itb_port) {
455 assert(!new_checker_itb_port->isConnected());
456 assert(old_checker_itb_port);
457 assert(old_checker_itb_port->isConnected());
458 BaseSlavePort &slavePort =
459 old_checker_itb_port->getSlavePort();
460 old_checker_itb_port->unbind();
461 new_checker_itb_port->bind(slavePort);
462 }
463 if (new_checker_dtb_port) {
464 assert(!new_checker_dtb_port->isConnected());
465 assert(old_checker_dtb_port);
466 assert(old_checker_dtb_port->isConnected());
467 BaseSlavePort &slavePort =
468 old_checker_dtb_port->getSlavePort();
469 old_checker_dtb_port->unbind();
470 new_checker_dtb_port->bind(slavePort);
471 }
472 }
473 }
474
475 interrupts = oldCPU->interrupts;
476 interrupts->setCPU(this);
477 oldCPU->interrupts = NULL;
478
479 if (FullSystem) {
480 for (ThreadID i = 0; i < size; ++i)
481 threadContexts[i]->profileClear();
482
483 if (profileEvent)
484 schedule(profileEvent, curTick());
485 }
486
487 // All CPUs have an instruction and a data port, and the new CPU's
488 // ports are dangling while the old CPU has its ports connected
489 // already. Unbind the old CPU and then bind the ports of the one
490 // we are switching to.
491 assert(!getInstPort().isConnected());
492 assert(oldCPU->getInstPort().isConnected());
493 BaseSlavePort &inst_peer_port = oldCPU->getInstPort().getSlavePort();
494 oldCPU->getInstPort().unbind();
495 getInstPort().bind(inst_peer_port);
496
497 assert(!getDataPort().isConnected());
498 assert(oldCPU->getDataPort().isConnected());
499 BaseSlavePort &data_peer_port = oldCPU->getDataPort().getSlavePort();
500 oldCPU->getDataPort().unbind();
501 getDataPort().bind(data_peer_port);
502}
503
504void
505BaseCPU::flushTLBs()
506{
507 for (ThreadID i = 0; i < threadContexts.size(); ++i) {
508 ThreadContext &tc(*threadContexts[i]);
509 CheckerCPU *checker(tc.getCheckerCpuPtr());
510
511 tc.getITBPtr()->flushAll();
512 tc.getDTBPtr()->flushAll();
513 if (checker) {
514 checker->getITBPtr()->flushAll();
515 checker->getDTBPtr()->flushAll();
516 }
517 }
518}
519
520
521BaseCPU::ProfileEvent::ProfileEvent(BaseCPU *_cpu, Tick _interval)
522 : cpu(_cpu), interval(_interval)
523{ }
524
525void
526BaseCPU::ProfileEvent::process()
527{
528 ThreadID size = cpu->threadContexts.size();
529 for (ThreadID i = 0; i < size; ++i) {
530 ThreadContext *tc = cpu->threadContexts[i];
531 tc->profileSample();
532 }
533
534 cpu->schedule(this, curTick() + interval);
535}
536
537void
538BaseCPU::serialize(std::ostream &os)
539{
540 SERIALIZE_SCALAR(instCnt);
541
542 if (!_switchedOut) {
543 /* Unlike _pid, _taskId is not serialized, as they are dynamically
544 * assigned unique ids that are only meaningful for the duration of
545 * a specific run. We will need to serialize the entire taskMap in
546 * system. */
547 SERIALIZE_SCALAR(_pid);
548
549 interrupts->serialize(os);
550
551 // Serialize the threads, this is done by the CPU implementation.
552 for (ThreadID i = 0; i < numThreads; ++i) {
553 nameOut(os, csprintf("%s.xc.%i", name(), i));
554 serializeThread(os, i);
555 }
556 }
557}
558
559void
560BaseCPU::unserialize(Checkpoint *cp, const std::string &section)
561{
562 UNSERIALIZE_SCALAR(instCnt);
563
564 if (!_switchedOut) {
565 UNSERIALIZE_SCALAR(_pid);
566 interrupts->unserialize(cp, section);
567
568 // Unserialize the threads, this is done by the CPU implementation.
569 for (ThreadID i = 0; i < numThreads; ++i)
570 unserializeThread(cp, csprintf("%s.xc.%i", section, i), i);
571 }
572}
573
574void
575BaseCPU::traceFunctionsInternal(Addr pc)
576{
577 if (!debugSymbolTable)
578 return;
579
580 // if pc enters different function, print new function symbol and
581 // update saved range. Otherwise do nothing.
582 if (pc < currentFunctionStart || pc >= currentFunctionEnd) {
583 string sym_str;
584 bool found = debugSymbolTable->findNearestSymbol(pc, sym_str,
585 currentFunctionStart,
586 currentFunctionEnd);
587
588 if (!found) {
589 // no symbol found: use addr as label
590 sym_str = csprintf("0x%x", pc);
591 currentFunctionStart = pc;
592 currentFunctionEnd = pc + 1;
593 }
594
595 ccprintf(*functionTraceStream, " (%d)\n%d: %s",
596 curTick() - functionEntryTick, curTick(), sym_str);
597 functionEntryTick = curTick();
598 }
599}