2 * Copyright (c) 2011-2013 ARM Limited
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.
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.
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.
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.
41 * Authors: Steve Reinhardt
46 #ifndef __CPU_BASE_HH__
47 #define __CPU_BASE_HH__
51 // Before we do anything else, check if this build is the NULL ISA,
52 // and if so stop here
53 #include "config/the_isa.hh"
54 #if THE_ISA == NULL_ISA
55 #include "arch/null/cpu_dummy.hh"
57 #include "arch/interrupts.hh"
58 #include "arch/isa_traits.hh"
59 #include "arch/microcode_rom.hh"
60 #include "base/statistics.hh"
61 #include "mem/mem_object.hh"
62 #include "sim/eventq.hh"
63 #include "sim/full_system.hh"
64 #include "sim/insttracer.hh"
65 #include "sim/system.hh"
71 class CPUProgressEvent : public Event
80 CPUProgressEvent(BaseCPU *_cpu, Tick ival = 0);
84 void interval(Tick ival) { _interval = ival; }
85 Tick interval() { return _interval; }
87 void repeatEvent(bool repeat) { _repeatEvent = repeat; }
89 virtual const char *description() const;
92 class BaseCPU : public MemObject
96 // @todo remove me after debugging with legion done
98 // every cpu has an id, put it in the base cpu
99 // Set at initialization, only time a cpuId might change is during a
100 // takeover (which should be done from within the BaseCPU anyway,
101 // therefore no setCpuId() method is provided
104 /** Each cpu will have a socket ID that corresponds to its physical location
105 * in the system. This is usually used to bucket cpu cores under single DVFS
106 * domain. This information may also be required by the OS to identify the
107 * cpu core grouping (as in the case of ARM via MPIDR register)
109 const uint32_t _socketId;
111 /** instruction side request id that must be placed in all requests */
112 MasterID _instMasterId;
114 /** data side request id that must be placed in all requests */
115 MasterID _dataMasterId;
117 /** An intrenal representation of a task identifier within gem5. This is
118 * used so the CPU can add which taskId (which is an internal representation
119 * of the OS process ID) to each request so components in the memory system
120 * can track which process IDs are ultimately interacting with them
124 /** The current OS process ID that is executing on this processor. This is
125 * used to generate a taskId */
128 /** Is the CPU switched out or active? */
131 /** Cache the cache line size that we get from the system */
132 const unsigned int _cacheLineSize;
137 * Purely virtual method that returns a reference to the data
138 * port. All subclasses must implement this method.
140 * @return a reference to the data port
142 virtual MasterPort &getDataPort() = 0;
145 * Purely virtual method that returns a reference to the instruction
146 * port. All subclasses must implement this method.
148 * @return a reference to the instruction port
150 virtual MasterPort &getInstPort() = 0;
152 /** Reads this CPU's ID. */
153 int cpuId() const { return _cpuId; }
155 /** Reads this CPU's Socket ID. */
156 uint32_t socketId() const { return _socketId; }
158 /** Reads this CPU's unique data requestor ID */
159 MasterID dataMasterId() { return _dataMasterId; }
160 /** Reads this CPU's unique instruction requestor ID */
161 MasterID instMasterId() { return _instMasterId; }
164 * Get a master port on this CPU. All CPUs have a data and
165 * instruction port, and this method uses getDataPort and
166 * getInstPort of the subclasses to resolve the two ports.
168 * @param if_name the port name
169 * @param idx ignored index
171 * @return a reference to the port with the given name
173 BaseMasterPort &getMasterPort(const std::string &if_name,
174 PortID idx = InvalidPortID);
176 /** Get cpu task id */
177 uint32_t taskId() const { return _taskId; }
178 /** Set cpu task id */
179 void taskId(uint32_t id) { _taskId = id; }
181 uint32_t getPid() const { return _pid; }
182 void setPid(uint32_t pid) { _pid = pid; }
184 inline void workItemBegin() { numWorkItemsStarted++; }
185 inline void workItemEnd() { numWorkItemsCompleted++; }
186 // @todo remove me after debugging with legion done
187 Tick instCount() { return instCnt; }
189 TheISA::MicrocodeRom microcodeRom;
192 TheISA::Interrupts *interrupts;
196 getInterruptController()
201 virtual void wakeup() = 0;
204 postInterrupt(int int_num, int index)
206 interrupts->post(int_num, index);
212 clearInterrupt(int int_num, int index)
214 interrupts->clear(int_num, index);
220 interrupts->clearAll();
224 checkInterrupts(ThreadContext *tc) const
226 return FullSystem && interrupts->checkInterrupts(tc);
229 class ProfileEvent : public Event
236 ProfileEvent(BaseCPU *cpu, Tick interval);
239 ProfileEvent *profileEvent;
242 std::vector<ThreadContext *> threadContexts;
244 Trace::InstTracer * tracer;
248 // Mask to align PCs to MachInst sized boundaries
249 static const Addr PCMask = ~((Addr)sizeof(TheISA::MachInst) - 1);
251 /// Provide access to the tracer pointer
252 Trace::InstTracer * getTracer() { return tracer; }
254 /// Notify the CPU that the indicated context is now active. The
255 /// delay parameter indicates the number of ticks to wait before
256 /// executing (typically 0 or 1).
257 virtual void activateContext(ThreadID thread_num, Cycles delay) {}
259 /// Notify the CPU that the indicated context is now suspended.
260 virtual void suspendContext(ThreadID thread_num) {}
262 /// Notify the CPU that the indicated context is now deallocated.
263 virtual void deallocateContext(ThreadID thread_num) {}
265 /// Notify the CPU that the indicated context is now halted.
266 virtual void haltContext(ThreadID thread_num) {}
268 /// Given a Thread Context pointer return the thread num
269 int findContext(ThreadContext *tc);
271 /// Given a thread num get tho thread context for it
272 virtual ThreadContext *getContext(int tn) { return threadContexts[tn]; }
274 /// Get the number of thread contexts available
275 unsigned numContexts() { return threadContexts.size(); }
278 typedef BaseCPUParams Params;
279 const Params *params() const
280 { return reinterpret_cast<const Params *>(_params); }
281 BaseCPU(Params *params, bool is_checker = false);
285 virtual void startup();
286 virtual void regStats();
288 virtual void activateWhenReady(ThreadID tid) {};
290 void registerThreadContexts();
293 * Prepare for another CPU to take over execution.
295 * When this method exits, all internal state should have been
296 * flushed. After the method returns, the simulator calls
297 * takeOverFrom() on the new CPU with this CPU as its parameter.
299 virtual void switchOut();
302 * Load the state of a CPU from the previous CPU object, invoked
303 * on all new CPUs that are about to be switched in.
305 * A CPU model implementing this method is expected to initialize
306 * its state from the old CPU and connect its memory (unless they
307 * are already connected) to the memories connected to the old
310 * @param cpu CPU to initialize read state from.
312 virtual void takeOverFrom(BaseCPU *cpu);
315 * Flush all TLBs in the CPU.
317 * This method is mainly used to flush stale translations when
318 * switching CPUs. It is also exported to the Python world to
319 * allow it to request a TLB flush after draining the CPU to make
320 * it easier to compare traces when debugging
321 * handover/checkpointing.
326 * Determine if the CPU is switched out.
328 * @return True if the CPU is switched out, false otherwise.
330 bool switchedOut() const { return _switchedOut; }
333 * Verify that the system is in a memory mode supported by the
336 * Implementations are expected to query the system for the
337 * current memory mode and ensure that it is what the CPU model
338 * expects. If the check fails, the implementation should
339 * terminate the simulation using fatal().
341 virtual void verifyMemoryMode() const { };
344 * Number of threads we're actually simulating (<= SMT_MAX_THREADS).
345 * This is a constant for the duration of the simulation.
350 * Vector of per-thread instruction-based event queues. Used for
351 * scheduling events based on number of instructions committed by
352 * a particular thread.
354 EventQueue **comInstEventQueue;
357 * Vector of per-thread load-based event queues. Used for
358 * scheduling events based on number of loads committed by
359 *a particular thread.
361 EventQueue **comLoadEventQueue;
366 * Get the cache line size of the system.
368 inline unsigned int cacheLineSize() const { return _cacheLineSize; }
371 * Serialize this object to the given output stream.
373 * @note CPU models should normally overload the serializeThread()
374 * method instead of the serialize() method as this provides a
375 * uniform data format for all CPU models and promotes better code
378 * @param os The stream to serialize to.
380 virtual void serialize(std::ostream &os);
383 * Reconstruct the state of this object from a checkpoint.
385 * @note CPU models should normally overload the
386 * unserializeThread() method instead of the unserialize() method
387 * as this provides a uniform data format for all CPU models and
388 * promotes better code reuse.
390 * @param cp The checkpoint use.
391 * @param section The section name of this object.
393 virtual void unserialize(Checkpoint *cp, const std::string §ion);
396 * Serialize a single thread.
398 * @param os The stream to serialize to.
399 * @param tid ID of the current thread.
401 virtual void serializeThread(std::ostream &os, ThreadID tid) {};
404 * Unserialize one thread.
406 * @param cp The checkpoint use.
407 * @param section The section name of this thread.
408 * @param tid ID of the current thread.
410 virtual void unserializeThread(Checkpoint *cp, const std::string §ion,
413 virtual Counter totalInsts() const = 0;
415 virtual Counter totalOps() const = 0;
418 * Schedule an event that exits the simulation loops after a
419 * predefined number of instructions.
421 * This method is usually called from the configuration script to
422 * get an exit event some time in the future. It is typically used
423 * when the script wants to simulate for a specific number of
424 * instructions rather than ticks.
426 * @param tid Thread monitor.
427 * @param insts Number of instructions into the future.
428 * @param cause Cause to signal in the exit event.
430 void scheduleInstStop(ThreadID tid, Counter insts, const char *cause);
433 * Schedule an event that exits the simulation loops after a
434 * predefined number of load operations.
436 * This method is usually called from the configuration script to
437 * get an exit event some time in the future. It is typically used
438 * when the script wants to simulate for a specific number of
439 * loads rather than ticks.
441 * @param tid Thread monitor.
442 * @param loads Number of load instructions into the future.
443 * @param cause Cause to signal in the exit event.
445 void scheduleLoadStop(ThreadID tid, Counter loads, const char *cause);
449 bool functionTracingEnabled;
450 std::ostream *functionTraceStream;
451 Addr currentFunctionStart;
452 Addr currentFunctionEnd;
453 Tick functionEntryTick;
454 void enableFunctionTrace();
455 void traceFunctionsInternal(Addr pc);
458 static std::vector<BaseCPU *> cpuList; //!< Static global cpu list
461 void traceFunctions(Addr pc)
463 if (functionTracingEnabled)
464 traceFunctionsInternal(pc);
467 static int numSimulatedCPUs() { return cpuList.size(); }
468 static Counter numSimulatedInsts()
472 int size = cpuList.size();
473 for (int i = 0; i < size; ++i)
474 total += cpuList[i]->totalInsts();
479 static Counter numSimulatedOps()
483 int size = cpuList.size();
484 for (int i = 0; i < size; ++i)
485 total += cpuList[i]->totalOps();
491 // Number of CPU cycles simulated
492 Stats::Scalar numCycles;
493 Stats::Scalar numWorkItemsStarted;
494 Stats::Scalar numWorkItemsCompleted;
497 #endif // THE_ISA == NULL_ISA
499 #endif // __CPU_BASE_HH__