Clock: Move the clock and related functions to ClockedObject
[gem5.git] / src / cpu / base.cc
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
72 using namespace std;
73
74 vector<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
79 int maxThreadsPerCPU = 1;
80
81 CPUProgressEvent::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
89 void
90 CPUProgressEvent::process()
91 {
92 Counter temp = cpu->totalOps();
93 #ifndef NDEBUG
94 double ipc = double(temp - lastNumInst) / (_interval / cpu->ticks(1));
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
111 const char *
112 CPUProgressEvent::description() const
113 {
114 return "CPU Progress";
115 }
116
117 BaseCPU::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 interrupts(p->interrupts),
122 numThreads(p->numThreads), system(p->system)
123 {
124 // if Python did not provide a valid ID, do it here
125 if (_cpuId == -1 ) {
126 _cpuId = cpuList.size();
127 }
128
129 // add self to global list of CPUs
130 cpuList.push_back(this);
131
132 DPRINTF(SyscallVerbose, "Constructing CPU with id %d\n", _cpuId);
133
134 if (numThreads > maxThreadsPerCPU)
135 maxThreadsPerCPU = numThreads;
136
137 // allocate per-thread instruction-based event queues
138 comInstEventQueue = new EventQueue *[numThreads];
139 for (ThreadID tid = 0; tid < numThreads; ++tid)
140 comInstEventQueue[tid] =
141 new EventQueue("instruction-based event queue");
142
143 //
144 // set up instruction-count-based termination events, if any
145 //
146 if (p->max_insts_any_thread != 0) {
147 const char *cause = "a thread reached the max instruction count";
148 for (ThreadID tid = 0; tid < numThreads; ++tid) {
149 Event *event = new SimLoopExitEvent(cause, 0);
150 comInstEventQueue[tid]->schedule(event, p->max_insts_any_thread);
151 }
152 }
153
154 if (p->max_insts_all_threads != 0) {
155 const char *cause = "all threads reached the max instruction count";
156
157 // allocate & initialize shared downcounter: each event will
158 // decrement this when triggered; simulation will terminate
159 // when counter reaches 0
160 int *counter = new int;
161 *counter = numThreads;
162 for (ThreadID tid = 0; tid < numThreads; ++tid) {
163 Event *event = new CountedExitEvent(cause, *counter);
164 comInstEventQueue[tid]->schedule(event, p->max_insts_all_threads);
165 }
166 }
167
168 // allocate per-thread load-based event queues
169 comLoadEventQueue = new EventQueue *[numThreads];
170 for (ThreadID tid = 0; tid < numThreads; ++tid)
171 comLoadEventQueue[tid] = new EventQueue("load-based event queue");
172
173 //
174 // set up instruction-count-based termination events, if any
175 //
176 if (p->max_loads_any_thread != 0) {
177 const char *cause = "a thread reached the max load count";
178 for (ThreadID tid = 0; tid < numThreads; ++tid) {
179 Event *event = new SimLoopExitEvent(cause, 0);
180 comLoadEventQueue[tid]->schedule(event, p->max_loads_any_thread);
181 }
182 }
183
184 if (p->max_loads_all_threads != 0) {
185 const char *cause = "all threads reached the max load count";
186 // allocate & initialize shared downcounter: each event will
187 // decrement this when triggered; simulation will terminate
188 // when counter reaches 0
189 int *counter = new int;
190 *counter = numThreads;
191 for (ThreadID tid = 0; tid < numThreads; ++tid) {
192 Event *event = new CountedExitEvent(cause, *counter);
193 comLoadEventQueue[tid]->schedule(event, p->max_loads_all_threads);
194 }
195 }
196
197 functionTracingEnabled = false;
198 if (p->function_trace) {
199 const string fname = csprintf("ftrace.%s", name());
200 functionTraceStream = simout.find(fname);
201 if (!functionTraceStream)
202 functionTraceStream = simout.create(fname);
203
204 currentFunctionStart = currentFunctionEnd = 0;
205 functionEntryTick = p->function_trace_start;
206
207 if (p->function_trace_start == 0) {
208 functionTracingEnabled = true;
209 } else {
210 typedef EventWrapper<BaseCPU, &BaseCPU::enableFunctionTrace> wrap;
211 Event *event = new wrap(this, true);
212 schedule(event, p->function_trace_start);
213 }
214 }
215
216 // The interrupts should always be present unless this CPU is
217 // switched in later or in case it is a checker CPU
218 if (!params()->defer_registration && !is_checker) {
219 if (interrupts) {
220 interrupts->setCPU(this);
221 } else {
222 fatal("CPU %s has no interrupt controller.\n"
223 "Ensure createInterruptController() is called.\n", name());
224 }
225 }
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
235 void
236 BaseCPU::enableFunctionTrace()
237 {
238 functionTracingEnabled = true;
239 }
240
241 BaseCPU::~BaseCPU()
242 {
243 delete profileEvent;
244 delete[] comLoadEventQueue;
245 delete[] comInstEventQueue;
246 }
247
248 void
249 BaseCPU::init()
250 {
251 if (!params()->defer_registration)
252 registerThreadContexts();
253 }
254
255 void
256 BaseCPU::startup()
257 {
258 if (FullSystem) {
259 if (!params()->defer_registration && profileEvent)
260 schedule(profileEvent, curTick());
261 }
262
263 if (params()->progress_interval) {
264 Tick num_ticks = ticks(params()->progress_interval);
265
266 new CPUProgressEvent(this, num_ticks);
267 }
268 }
269
270
271 void
272 BaseCPU::regStats()
273 {
274 using namespace Stats;
275
276 numCycles
277 .name(name() + ".numCycles")
278 .desc("number of cpu cycles simulated")
279 ;
280
281 numWorkItemsStarted
282 .name(name() + ".numWorkItemsStarted")
283 .desc("number of work items this cpu started")
284 ;
285
286 numWorkItemsCompleted
287 .name(name() + ".numWorkItemsCompleted")
288 .desc("number of work items this cpu completed")
289 ;
290
291 int size = threadContexts.size();
292 if (size > 1) {
293 for (int i = 0; i < size; ++i) {
294 stringstream namestr;
295 ccprintf(namestr, "%s.ctx%d", name(), i);
296 threadContexts[i]->regStats(namestr.str());
297 }
298 } else if (size == 1)
299 threadContexts[0]->regStats(name());
300 }
301
302 MasterPort &
303 BaseCPU::getMasterPort(const string &if_name, int idx)
304 {
305 // Get the right port based on name. This applies to all the
306 // subclasses of the base CPU and relies on their implementation
307 // of getDataPort and getInstPort. In all cases there methods
308 // return a CpuPort pointer.
309 if (if_name == "dcache_port")
310 return getDataPort();
311 else if (if_name == "icache_port")
312 return getInstPort();
313 else
314 return MemObject::getMasterPort(if_name, idx);
315 }
316
317 void
318 BaseCPU::registerThreadContexts()
319 {
320 ThreadID size = threadContexts.size();
321 for (ThreadID tid = 0; tid < size; ++tid) {
322 ThreadContext *tc = threadContexts[tid];
323
324 /** This is so that contextId and cpuId match where there is a
325 * 1cpu:1context relationship. Otherwise, the order of registration
326 * could affect the assignment and cpu 1 could have context id 3, for
327 * example. We may even want to do something like this for SMT so that
328 * cpu 0 has the lowest thread contexts and cpu N has the highest, but
329 * I'll just do this for now
330 */
331 if (numThreads == 1)
332 tc->setContextId(system->registerThreadContext(tc, _cpuId));
333 else
334 tc->setContextId(system->registerThreadContext(tc));
335
336 if (!FullSystem)
337 tc->getProcessPtr()->assignThreadContext(tc->contextId());
338 }
339 }
340
341
342 int
343 BaseCPU::findContext(ThreadContext *tc)
344 {
345 ThreadID size = threadContexts.size();
346 for (ThreadID tid = 0; tid < size; ++tid) {
347 if (tc == threadContexts[tid])
348 return tid;
349 }
350 return 0;
351 }
352
353 void
354 BaseCPU::switchOut()
355 {
356 if (profileEvent && profileEvent->scheduled())
357 deschedule(profileEvent);
358 }
359
360 void
361 BaseCPU::takeOverFrom(BaseCPU *oldCPU)
362 {
363 assert(threadContexts.size() == oldCPU->threadContexts.size());
364 assert(_cpuId == oldCPU->cpuId());
365
366 ThreadID size = threadContexts.size();
367 for (ThreadID i = 0; i < size; ++i) {
368 ThreadContext *newTC = threadContexts[i];
369 ThreadContext *oldTC = oldCPU->threadContexts[i];
370
371 newTC->takeOverFrom(oldTC);
372
373 CpuEvent::replaceThreadContext(oldTC, newTC);
374
375 assert(newTC->contextId() == oldTC->contextId());
376 assert(newTC->threadId() == oldTC->threadId());
377 system->replaceThreadContext(newTC, newTC->contextId());
378
379 /* This code no longer works since the zero register (e.g.,
380 * r31 on Alpha) doesn't necessarily contain zero at this
381 * point.
382 if (DTRACE(Context))
383 ThreadContext::compare(oldTC, newTC);
384 */
385
386 MasterPort *old_itb_port = oldTC->getITBPtr()->getMasterPort();
387 MasterPort *old_dtb_port = oldTC->getDTBPtr()->getMasterPort();
388 MasterPort *new_itb_port = newTC->getITBPtr()->getMasterPort();
389 MasterPort *new_dtb_port = newTC->getDTBPtr()->getMasterPort();
390
391 // Move over any table walker ports if they exist
392 if (new_itb_port && !new_itb_port->isConnected()) {
393 assert(old_itb_port);
394 SlavePort &slavePort = old_itb_port->getSlavePort();
395 new_itb_port->bind(slavePort);
396 old_itb_port->unBind();
397 }
398 if (new_dtb_port && !new_dtb_port->isConnected()) {
399 assert(old_dtb_port);
400 SlavePort &slavePort = old_dtb_port->getSlavePort();
401 new_dtb_port->bind(slavePort);
402 old_dtb_port->unBind();
403 }
404
405 // Checker whether or not we have to transfer CheckerCPU
406 // objects over in the switch
407 CheckerCPU *oldChecker = oldTC->getCheckerCpuPtr();
408 CheckerCPU *newChecker = newTC->getCheckerCpuPtr();
409 if (oldChecker && newChecker) {
410 MasterPort *old_checker_itb_port =
411 oldChecker->getITBPtr()->getMasterPort();
412 MasterPort *old_checker_dtb_port =
413 oldChecker->getDTBPtr()->getMasterPort();
414 MasterPort *new_checker_itb_port =
415 newChecker->getITBPtr()->getMasterPort();
416 MasterPort *new_checker_dtb_port =
417 newChecker->getDTBPtr()->getMasterPort();
418
419 // Move over any table walker ports if they exist for checker
420 if (new_checker_itb_port && !new_checker_itb_port->isConnected()) {
421 assert(old_checker_itb_port);
422 SlavePort &slavePort = old_checker_itb_port->getSlavePort();;
423 new_checker_itb_port->bind(slavePort);
424 old_checker_itb_port->unBind();
425 }
426 if (new_checker_dtb_port && !new_checker_dtb_port->isConnected()) {
427 assert(old_checker_dtb_port);
428 SlavePort &slavePort = old_checker_dtb_port->getSlavePort();;
429 new_checker_dtb_port->bind(slavePort);
430 old_checker_dtb_port->unBind();
431 }
432 }
433 }
434
435 interrupts = oldCPU->interrupts;
436 interrupts->setCPU(this);
437 oldCPU->interrupts = NULL;
438
439 if (FullSystem) {
440 for (ThreadID i = 0; i < size; ++i)
441 threadContexts[i]->profileClear();
442
443 if (profileEvent)
444 schedule(profileEvent, curTick());
445 }
446
447 // Connect new CPU to old CPU's memory only if new CPU isn't
448 // connected to anything. Also connect old CPU's memory to new
449 // CPU.
450 if (!getInstPort().isConnected()) {
451 getInstPort().bind(oldCPU->getInstPort().getSlavePort());
452 oldCPU->getInstPort().unBind();
453 }
454
455 if (!getDataPort().isConnected()) {
456 getDataPort().bind(oldCPU->getDataPort().getSlavePort());
457 oldCPU->getDataPort().unBind();
458 }
459 }
460
461
462 BaseCPU::ProfileEvent::ProfileEvent(BaseCPU *_cpu, Tick _interval)
463 : cpu(_cpu), interval(_interval)
464 { }
465
466 void
467 BaseCPU::ProfileEvent::process()
468 {
469 ThreadID size = cpu->threadContexts.size();
470 for (ThreadID i = 0; i < size; ++i) {
471 ThreadContext *tc = cpu->threadContexts[i];
472 tc->profileSample();
473 }
474
475 cpu->schedule(this, curTick() + interval);
476 }
477
478 void
479 BaseCPU::serialize(std::ostream &os)
480 {
481 SERIALIZE_SCALAR(instCnt);
482 interrupts->serialize(os);
483 }
484
485 void
486 BaseCPU::unserialize(Checkpoint *cp, const std::string &section)
487 {
488 UNSERIALIZE_SCALAR(instCnt);
489 interrupts->unserialize(cp, section);
490 }
491
492 void
493 BaseCPU::traceFunctionsInternal(Addr pc)
494 {
495 if (!debugSymbolTable)
496 return;
497
498 // if pc enters different function, print new function symbol and
499 // update saved range. Otherwise do nothing.
500 if (pc < currentFunctionStart || pc >= currentFunctionEnd) {
501 string sym_str;
502 bool found = debugSymbolTable->findNearestSymbol(pc, sym_str,
503 currentFunctionStart,
504 currentFunctionEnd);
505
506 if (!found) {
507 // no symbol found: use addr as label
508 sym_str = csprintf("0x%x", pc);
509 currentFunctionStart = pc;
510 currentFunctionEnd = pc + 1;
511 }
512
513 ccprintf(*functionTraceStream, " (%d)\n%d: %s",
514 curTick() - functionEntryTick, curTick(), sym_str);
515 functionEntryTick = curTick();
516 }
517 }
518
519 bool
520 BaseCPU::CpuPort::recvTimingResp(PacketPtr pkt)
521 {
522 panic("BaseCPU doesn't expect recvTiming!\n");
523 return true;
524 }
525
526 void
527 BaseCPU::CpuPort::recvRetry()
528 {
529 panic("BaseCPU doesn't expect recvRetry!\n");
530 }
531
532 void
533 BaseCPU::CpuPort::recvFunctionalSnoop(PacketPtr pkt)
534 {
535 // No internal storage to update (in the general case). A CPU with
536 // internal storage, e.g. an LSQ that should be part of the
537 // coherent memory has to check against stored data.
538 }