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/probe/pmu.hh"
66 #include "sim/system.hh"
72 class CPUProgressEvent : public Event
81 CPUProgressEvent(BaseCPU *_cpu, Tick ival = 0);
85 void interval(Tick ival) { _interval = ival; }
86 Tick interval() { return _interval; }
88 void repeatEvent(bool repeat) { _repeatEvent = repeat; }
90 virtual const char *description() const;
93 class BaseCPU : public MemObject
97 // @todo remove me after debugging with legion done
99 // every cpu has an id, put it in the base cpu
100 // Set at initialization, only time a cpuId might change is during a
101 // takeover (which should be done from within the BaseCPU anyway,
102 // therefore no setCpuId() method is provided
105 /** Each cpu will have a socket ID that corresponds to its physical location
106 * in the system. This is usually used to bucket cpu cores under single DVFS
107 * domain. This information may also be required by the OS to identify the
108 * cpu core grouping (as in the case of ARM via MPIDR register)
110 const uint32_t _socketId;
112 /** instruction side request id that must be placed in all requests */
113 MasterID _instMasterId;
115 /** data side request id that must be placed in all requests */
116 MasterID _dataMasterId;
118 /** An intrenal representation of a task identifier within gem5. This is
119 * used so the CPU can add which taskId (which is an internal representation
120 * of the OS process ID) to each request so components in the memory system
121 * can track which process IDs are ultimately interacting with them
125 /** The current OS process ID that is executing on this processor. This is
126 * used to generate a taskId */
129 /** Is the CPU switched out or active? */
132 /** Cache the cache line size that we get from the system */
133 const unsigned int _cacheLineSize;
138 * Purely virtual method that returns a reference to the data
139 * port. All subclasses must implement this method.
141 * @return a reference to the data port
143 virtual MasterPort &getDataPort() = 0;
146 * Purely virtual method that returns a reference to the instruction
147 * port. All subclasses must implement this method.
149 * @return a reference to the instruction port
151 virtual MasterPort &getInstPort() = 0;
153 /** Reads this CPU's ID. */
154 int cpuId() const { return _cpuId; }
156 /** Reads this CPU's Socket ID. */
157 uint32_t socketId() const { return _socketId; }
159 /** Reads this CPU's unique data requestor ID */
160 MasterID dataMasterId() { return _dataMasterId; }
161 /** Reads this CPU's unique instruction requestor ID */
162 MasterID instMasterId() { return _instMasterId; }
165 * Get a master port on this CPU. All CPUs have a data and
166 * instruction port, and this method uses getDataPort and
167 * getInstPort of the subclasses to resolve the two ports.
169 * @param if_name the port name
170 * @param idx ignored index
172 * @return a reference to the port with the given name
174 BaseMasterPort &getMasterPort(const std::string &if_name,
175 PortID idx = InvalidPortID);
177 /** Get cpu task id */
178 uint32_t taskId() const { return _taskId; }
179 /** Set cpu task id */
180 void taskId(uint32_t id) { _taskId = id; }
182 uint32_t getPid() const { return _pid; }
183 void setPid(uint32_t pid) { _pid = pid; }
185 inline void workItemBegin() { numWorkItemsStarted++; }
186 inline void workItemEnd() { numWorkItemsCompleted++; }
187 // @todo remove me after debugging with legion done
188 Tick instCount() { return instCnt; }
190 TheISA::MicrocodeRom microcodeRom;
193 TheISA::Interrupts *interrupts;
197 getInterruptController()
202 virtual void wakeup() = 0;
205 postInterrupt(int int_num, int index)
207 interrupts->post(int_num, index);
213 clearInterrupt(int int_num, int index)
215 interrupts->clear(int_num, index);
221 interrupts->clearAll();
225 checkInterrupts(ThreadContext *tc) const
227 return FullSystem && interrupts->checkInterrupts(tc);
230 class ProfileEvent : public Event
237 ProfileEvent(BaseCPU *cpu, Tick interval);
240 ProfileEvent *profileEvent;
243 std::vector<ThreadContext *> threadContexts;
245 Trace::InstTracer * tracer;
249 // Mask to align PCs to MachInst sized boundaries
250 static const Addr PCMask = ~((Addr)sizeof(TheISA::MachInst) - 1);
252 /// Provide access to the tracer pointer
253 Trace::InstTracer * getTracer() { return tracer; }
255 /// Notify the CPU that the indicated context is now active.
256 virtual void activateContext(ThreadID thread_num) {}
258 /// Notify the CPU that the indicated context is now suspended.
259 virtual void suspendContext(ThreadID thread_num) {}
261 /// Notify the CPU that the indicated context is now halted.
262 virtual void haltContext(ThreadID thread_num) {}
264 /// Given a Thread Context pointer return the thread num
265 int findContext(ThreadContext *tc);
267 /// Given a thread num get tho thread context for it
268 virtual ThreadContext *getContext(int tn) { return threadContexts[tn]; }
270 /// Get the number of thread contexts available
271 unsigned numContexts() { return threadContexts.size(); }
274 typedef BaseCPUParams Params;
275 const Params *params() const
276 { return reinterpret_cast<const Params *>(_params); }
277 BaseCPU(Params *params, bool is_checker = false);
281 virtual void startup();
282 virtual void regStats();
284 void regProbePoints() M5_ATTR_OVERRIDE;
286 void registerThreadContexts();
289 * Prepare for another CPU to take over execution.
291 * When this method exits, all internal state should have been
292 * flushed. After the method returns, the simulator calls
293 * takeOverFrom() on the new CPU with this CPU as its parameter.
295 virtual void switchOut();
298 * Load the state of a CPU from the previous CPU object, invoked
299 * on all new CPUs that are about to be switched in.
301 * A CPU model implementing this method is expected to initialize
302 * its state from the old CPU and connect its memory (unless they
303 * are already connected) to the memories connected to the old
306 * @param cpu CPU to initialize read state from.
308 virtual void takeOverFrom(BaseCPU *cpu);
311 * Flush all TLBs in the CPU.
313 * This method is mainly used to flush stale translations when
314 * switching CPUs. It is also exported to the Python world to
315 * allow it to request a TLB flush after draining the CPU to make
316 * it easier to compare traces when debugging
317 * handover/checkpointing.
322 * Determine if the CPU is switched out.
324 * @return True if the CPU is switched out, false otherwise.
326 bool switchedOut() const { return _switchedOut; }
329 * Verify that the system is in a memory mode supported by the
332 * Implementations are expected to query the system for the
333 * current memory mode and ensure that it is what the CPU model
334 * expects. If the check fails, the implementation should
335 * terminate the simulation using fatal().
337 virtual void verifyMemoryMode() const { };
340 * Number of threads we're actually simulating (<= SMT_MAX_THREADS).
341 * This is a constant for the duration of the simulation.
346 * Vector of per-thread instruction-based event queues. Used for
347 * scheduling events based on number of instructions committed by
348 * a particular thread.
350 EventQueue **comInstEventQueue;
353 * Vector of per-thread load-based event queues. Used for
354 * scheduling events based on number of loads committed by
355 *a particular thread.
357 EventQueue **comLoadEventQueue;
362 * Get the cache line size of the system.
364 inline unsigned int cacheLineSize() const { return _cacheLineSize; }
367 * Serialize this object to the given output stream.
369 * @note CPU models should normally overload the serializeThread()
370 * method instead of the serialize() method as this provides a
371 * uniform data format for all CPU models and promotes better code
374 * @param os The stream to serialize to.
376 virtual void serialize(std::ostream &os);
379 * Reconstruct the state of this object from a checkpoint.
381 * @note CPU models should normally overload the
382 * unserializeThread() method instead of the unserialize() method
383 * as this provides a uniform data format for all CPU models and
384 * promotes better code reuse.
386 * @param cp The checkpoint use.
387 * @param section The section name of this object.
389 virtual void unserialize(Checkpoint *cp, const std::string §ion);
392 * Serialize a single thread.
394 * @param os The stream to serialize to.
395 * @param tid ID of the current thread.
397 virtual void serializeThread(std::ostream &os, ThreadID tid) {};
400 * Unserialize one thread.
402 * @param cp The checkpoint use.
403 * @param section The section name of this thread.
404 * @param tid ID of the current thread.
406 virtual void unserializeThread(Checkpoint *cp, const std::string §ion,
409 virtual Counter totalInsts() const = 0;
411 virtual Counter totalOps() const = 0;
414 * Schedule an event that exits the simulation loops after a
415 * predefined number of instructions.
417 * This method is usually called from the configuration script to
418 * get an exit event some time in the future. It is typically used
419 * when the script wants to simulate for a specific number of
420 * instructions rather than ticks.
422 * @param tid Thread monitor.
423 * @param insts Number of instructions into the future.
424 * @param cause Cause to signal in the exit event.
426 void scheduleInstStop(ThreadID tid, Counter insts, const char *cause);
429 * Schedule an event that exits the simulation loops after a
430 * predefined number of load operations.
432 * This method is usually called from the configuration script to
433 * get an exit event some time in the future. It is typically used
434 * when the script wants to simulate for a specific number of
435 * loads rather than ticks.
437 * @param tid Thread monitor.
438 * @param loads Number of load instructions into the future.
439 * @param cause Cause to signal in the exit event.
441 void scheduleLoadStop(ThreadID tid, Counter loads, const char *cause);
446 * @name PMU Probe points.
450 * Helper method to trigger PMU probes for a committed
453 * @param inst Instruction that just committed
455 virtual void probeInstCommit(const StaticInstPtr &inst);
458 * Helper method to instantiate probe points belonging to this
461 * @param name Name of the probe point.
462 * @return A unique_ptr to the new probe point.
464 ProbePoints::PMUUPtr pmuProbePoint(const char *name);
466 /** CPU cycle counter */
467 ProbePoints::PMUUPtr ppCycles;
470 * Instruction commit probe point.
472 * This probe point is triggered whenever one or more instructions
473 * are committed. It is normally triggered once for every
474 * instruction. However, CPU models committing bundles of
475 * instructions may call notify once for the entire bundle.
477 ProbePoints::PMUUPtr ppRetiredInsts;
479 /** Retired load instructions */
480 ProbePoints::PMUUPtr ppRetiredLoads;
481 /** Retired store instructions */
482 ProbePoints::PMUUPtr ppRetiredStores;
484 /** Retired branches (any type) */
485 ProbePoints::PMUUPtr ppRetiredBranches;
493 bool functionTracingEnabled;
494 std::ostream *functionTraceStream;
495 Addr currentFunctionStart;
496 Addr currentFunctionEnd;
497 Tick functionEntryTick;
498 void enableFunctionTrace();
499 void traceFunctionsInternal(Addr pc);
502 static std::vector<BaseCPU *> cpuList; //!< Static global cpu list
505 void traceFunctions(Addr pc)
507 if (functionTracingEnabled)
508 traceFunctionsInternal(pc);
511 static int numSimulatedCPUs() { return cpuList.size(); }
512 static Counter numSimulatedInsts()
516 int size = cpuList.size();
517 for (int i = 0; i < size; ++i)
518 total += cpuList[i]->totalInsts();
523 static Counter numSimulatedOps()
527 int size = cpuList.size();
528 for (int i = 0; i < size; ++i)
529 total += cpuList[i]->totalOps();
535 // Number of CPU cycles simulated
536 Stats::Scalar numCycles;
537 Stats::Scalar numWorkItemsStarted;
538 Stats::Scalar numWorkItemsCompleted;
541 #endif // THE_ISA == NULL_ISA
543 #endif // __CPU_BASE_HH__