2 * Copyright (c) 2011-2013, 2017, 2020 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.
42 #ifndef __CPU_BASE_HH__
43 #define __CPU_BASE_HH__
47 // Before we do anything else, check if this build is the NULL ISA,
48 // and if so stop here
49 #include "config/the_isa.hh"
50 #if THE_ISA == NULL_ISA
51 #error Including BaseCPU in a system without CPU support
53 #include "arch/generic/interrupts.hh"
54 #include "base/statistics.hh"
55 #include "mem/port_proxy.hh"
56 #include "sim/clocked_object.hh"
57 #include "sim/eventq.hh"
58 #include "sim/full_system.hh"
59 #include "sim/insttracer.hh"
60 #include "sim/probe/pmu.hh"
61 #include "sim/probe/probe.hh"
62 #include "sim/system.hh"
63 #include "debug/Mwait.hh"
73 bool doMonitor(PacketPtr pkt);
79 bool waiting; // 0=normal, 1=mwaiting
83 class CPUProgressEvent : public Event
92 CPUProgressEvent(BaseCPU *_cpu, Tick ival = 0);
96 void interval(Tick ival) { _interval = ival; }
97 Tick interval() { return _interval; }
99 void repeatEvent(bool repeat) { _repeatEvent = repeat; }
101 virtual const char *description() const;
104 class BaseCPU : public ClockedObject
108 /// Instruction count used for SPARC misc register
109 /// @todo unify this with the counters that cpus individually keep
112 // every cpu has an id, put it in the base cpu
113 // Set at initialization, only time a cpuId might change is during a
114 // takeover (which should be done from within the BaseCPU anyway,
115 // therefore no setCpuId() method is provided
118 /** Each cpu will have a socket ID that corresponds to its physical location
119 * in the system. This is usually used to bucket cpu cores under single DVFS
120 * domain. This information may also be required by the OS to identify the
121 * cpu core grouping (as in the case of ARM via MPIDR register)
123 const uint32_t _socketId;
125 /** instruction side request id that must be placed in all requests */
126 RequestorID _instRequestorId;
128 /** data side request id that must be placed in all requests */
129 RequestorID _dataRequestorId;
131 /** An intrenal representation of a task identifier within gem5. This is
132 * used so the CPU can add which taskId (which is an internal representation
133 * of the OS process ID) to each request so components in the memory system
134 * can track which process IDs are ultimately interacting with them
138 /** The current OS process ID that is executing on this processor. This is
139 * used to generate a taskId */
142 /** Is the CPU switched out or active? */
145 /** Cache the cache line size that we get from the system */
146 const unsigned int _cacheLineSize;
148 /** Global CPU statistics that are merged into the Root object. */
149 struct GlobalStats : public Stats::Group {
150 GlobalStats(::Stats::Group *parent);
152 ::Stats::Value simInsts;
153 ::Stats::Value simOps;
155 ::Stats::Formula hostInstRate;
156 ::Stats::Formula hostOpRate;
160 * Pointer to the global stat structure. This needs to be
161 * constructed from regStats since we merge it into the root
163 static std::unique_ptr<GlobalStats> globalStats;
168 * Purely virtual method that returns a reference to the data
169 * port. All subclasses must implement this method.
171 * @return a reference to the data port
173 virtual Port &getDataPort() = 0;
176 * Returns a sendFunctional delegate for use with port proxies.
178 virtual PortProxy::SendFunctionalFunc
181 auto port = dynamic_cast<RequestPort *>(&getDataPort());
183 return [port](PacketPtr pkt)->void { port->sendFunctional(pkt); };
187 * Purely virtual method that returns a reference to the instruction
188 * port. All subclasses must implement this method.
190 * @return a reference to the instruction port
192 virtual Port &getInstPort() = 0;
194 /** Reads this CPU's ID. */
195 int cpuId() const { return _cpuId; }
197 /** Reads this CPU's Socket ID. */
198 uint32_t socketId() const { return _socketId; }
200 /** Reads this CPU's unique data requestor ID */
201 RequestorID dataRequestorId() const { return _dataRequestorId; }
202 /** Reads this CPU's unique instruction requestor ID */
203 RequestorID instRequestorId() const { return _instRequestorId; }
206 * Get a port on this CPU. All CPUs have a data and
207 * instruction port, and this method uses getDataPort and
208 * getInstPort of the subclasses to resolve the two ports.
210 * @param if_name the port name
211 * @param idx ignored index
213 * @return a reference to the port with the given name
215 Port &getPort(const std::string &if_name,
216 PortID idx=InvalidPortID) override;
218 /** Get cpu task id */
219 uint32_t taskId() const { return _taskId; }
220 /** Set cpu task id */
221 void taskId(uint32_t id) { _taskId = id; }
223 uint32_t getPid() const { return _pid; }
224 void setPid(uint32_t pid) { _pid = pid; }
226 inline void workItemBegin() { numWorkItemsStarted++; }
227 inline void workItemEnd() { numWorkItemsCompleted++; }
228 // @todo remove me after debugging with legion done
229 Tick instCount() { return instCnt; }
232 std::vector<BaseInterrupts*> interrupts;
236 getInterruptController(ThreadID tid)
238 if (interrupts.empty())
241 assert(interrupts.size() > tid);
242 return interrupts[tid];
245 virtual void wakeup(ThreadID tid) = 0;
248 postInterrupt(ThreadID tid, int int_num, int index);
251 clearInterrupt(ThreadID tid, int int_num, int index)
253 interrupts[tid]->clear(int_num, index);
257 clearInterrupts(ThreadID tid)
259 interrupts[tid]->clearAll();
263 checkInterrupts(ThreadID tid) const
265 return FullSystem && interrupts[tid]->checkInterrupts();
269 std::vector<ThreadContext *> threadContexts;
271 Trace::InstTracer * tracer;
276 /** Invalid or unknown Pid. Possible when operating system is not present
277 * or has not assigned a pid yet */
278 static const uint32_t invldPid = std::numeric_limits<uint32_t>::max();
280 // Mask to align PCs to MachInst sized boundaries
281 static const Addr PCMask = ~((Addr)sizeof(TheISA::MachInst) - 1);
283 /// Provide access to the tracer pointer
284 Trace::InstTracer * getTracer() { return tracer; }
286 /// Notify the CPU that the indicated context is now active.
287 virtual void activateContext(ThreadID thread_num);
289 /// Notify the CPU that the indicated context is now suspended.
290 /// Check if possible to enter a lower power state
291 virtual void suspendContext(ThreadID thread_num);
293 /// Notify the CPU that the indicated context is now halted.
294 virtual void haltContext(ThreadID thread_num);
296 /// Given a Thread Context pointer return the thread num
297 int findContext(ThreadContext *tc);
299 /// Given a thread num get tho thread context for it
300 virtual ThreadContext *getContext(int tn) { return threadContexts[tn]; }
302 /// Get the number of thread contexts available
303 unsigned numContexts() {
304 return static_cast<unsigned>(threadContexts.size());
307 /// Convert ContextID to threadID
308 ThreadID contextToThread(ContextID cid)
309 { return static_cast<ThreadID>(cid - threadContexts[0]->contextId()); }
312 typedef BaseCPUParams Params;
316 return reinterpret_cast<const Params &>(_params);
318 BaseCPU(const Params ¶ms, bool is_checker = false);
321 void init() override;
322 void startup() override;
323 void regStats() override;
325 void regProbePoints() override;
327 void registerThreadContexts();
329 // Functions to deschedule and reschedule the events to enter the
330 // power gating sleep before and after checkpoiting respectively.
331 void deschedulePowerGatingEvent();
332 void schedulePowerGatingEvent();
335 * Prepare for another CPU to take over execution.
337 * When this method exits, all internal state should have been
338 * flushed. After the method returns, the simulator calls
339 * takeOverFrom() on the new CPU with this CPU as its parameter.
341 virtual void switchOut();
344 * Load the state of a CPU from the previous CPU object, invoked
345 * on all new CPUs that are about to be switched in.
347 * A CPU model implementing this method is expected to initialize
348 * its state from the old CPU and connect its memory (unless they
349 * are already connected) to the memories connected to the old
352 * @param cpu CPU to initialize read state from.
354 virtual void takeOverFrom(BaseCPU *cpu);
357 * Flush all TLBs in the CPU.
359 * This method is mainly used to flush stale translations when
360 * switching CPUs. It is also exported to the Python world to
361 * allow it to request a TLB flush after draining the CPU to make
362 * it easier to compare traces when debugging
363 * handover/checkpointing.
368 * Determine if the CPU is switched out.
370 * @return True if the CPU is switched out, false otherwise.
372 bool switchedOut() const { return _switchedOut; }
375 * Verify that the system is in a memory mode supported by the
378 * Implementations are expected to query the system for the
379 * current memory mode and ensure that it is what the CPU model
380 * expects. If the check fails, the implementation should
381 * terminate the simulation using fatal().
383 virtual void verifyMemoryMode() const { };
386 * Number of threads we're actually simulating (<= SMT_MAX_THREADS).
387 * This is a constant for the duration of the simulation.
394 * Get the cache line size of the system.
396 inline unsigned int cacheLineSize() const { return _cacheLineSize; }
399 * Serialize this object to the given output stream.
401 * @note CPU models should normally overload the serializeThread()
402 * method instead of the serialize() method as this provides a
403 * uniform data format for all CPU models and promotes better code
406 * @param cp The stream to serialize to.
408 void serialize(CheckpointOut &cp) const override;
411 * Reconstruct the state of this object from a checkpoint.
413 * @note CPU models should normally overload the
414 * unserializeThread() method instead of the unserialize() method
415 * as this provides a uniform data format for all CPU models and
416 * promotes better code reuse.
418 * @param cp The checkpoint use.
420 void unserialize(CheckpointIn &cp) override;
423 * Serialize a single thread.
425 * @param cp The stream to serialize to.
426 * @param tid ID of the current thread.
428 virtual void serializeThread(CheckpointOut &cp, ThreadID tid) const {};
431 * Unserialize one thread.
433 * @param cp The checkpoint use.
434 * @param tid ID of the current thread.
436 virtual void unserializeThread(CheckpointIn &cp, ThreadID tid) {};
438 virtual Counter totalInsts() const = 0;
440 virtual Counter totalOps() const = 0;
443 * Schedule an event that exits the simulation loops after a
444 * predefined number of instructions.
446 * This method is usually called from the configuration script to
447 * get an exit event some time in the future. It is typically used
448 * when the script wants to simulate for a specific number of
449 * instructions rather than ticks.
451 * @param tid Thread monitor.
452 * @param insts Number of instructions into the future.
453 * @param cause Cause to signal in the exit event.
455 void scheduleInstStop(ThreadID tid, Counter insts, const char *cause);
458 * Get the number of instructions executed by the specified thread
459 * on this CPU. Used by Python to control simulation.
461 * @param tid Thread monitor
462 * @return Number of instructions executed
464 uint64_t getCurrentInstCount(ThreadID tid);
469 * @name PMU Probe points.
473 * Helper method to trigger PMU probes for a committed
476 * @param inst Instruction that just committed
477 * @param pc PC of the instruction that just committed
479 virtual void probeInstCommit(const StaticInstPtr &inst, Addr pc);
483 * Helper method to instantiate probe points belonging to this
486 * @param name Name of the probe point.
487 * @return A unique_ptr to the new probe point.
489 ProbePoints::PMUUPtr pmuProbePoint(const char *name);
492 * Instruction commit probe point.
494 * This probe point is triggered whenever one or more instructions
495 * are committed. It is normally triggered once for every
496 * instruction. However, CPU models committing bundles of
497 * instructions may call notify once for the entire bundle.
499 ProbePoints::PMUUPtr ppRetiredInsts;
500 ProbePoints::PMUUPtr ppRetiredInstsPC;
502 /** Retired load instructions */
503 ProbePoints::PMUUPtr ppRetiredLoads;
504 /** Retired store instructions */
505 ProbePoints::PMUUPtr ppRetiredStores;
507 /** Retired branches (any type) */
508 ProbePoints::PMUUPtr ppRetiredBranches;
510 /** CPU cycle counter even if any thread Context is suspended*/
511 ProbePoints::PMUUPtr ppAllCycles;
513 /** CPU cycle counter, only counts if any thread contexts is active **/
514 ProbePoints::PMUUPtr ppActiveCycles;
517 * ProbePoint that signals transitions of threadContexts sets.
518 * The ProbePoint reports information through it bool parameter.
519 * - If the parameter is true then the last enabled threadContext of the
520 * CPU object was disabled.
521 * - If the parameter is false then a threadContext was enabled, all the
522 * remaining threadContexts are disabled.
524 ProbePointArg<bool> *ppSleeping;
533 Cycles previousCycle;
534 CPUState previousState;
536 /** base method keeping track of cycle progression **/
537 inline void updateCycleCounters(CPUState state)
539 uint32_t delta = curCycle() - previousCycle;
541 if (previousState == CPU_STATE_ON) {
542 ppActiveCycles->notify(delta);
547 case CPU_STATE_WAKEUP:
548 ppSleeping->notify(false);
550 case CPU_STATE_SLEEP:
551 ppSleeping->notify(true);
557 ppAllCycles->notify(delta);
559 previousCycle = curCycle();
560 previousState = state;
565 bool functionTracingEnabled;
566 std::ostream *functionTraceStream;
567 Addr currentFunctionStart;
568 Addr currentFunctionEnd;
569 Tick functionEntryTick;
570 void enableFunctionTrace();
571 void traceFunctionsInternal(Addr pc);
574 static std::vector<BaseCPU *> cpuList; //!< Static global cpu list
577 void traceFunctions(Addr pc)
579 if (functionTracingEnabled)
580 traceFunctionsInternal(pc);
583 static int numSimulatedCPUs() { return cpuList.size(); }
584 static Counter numSimulatedInsts()
588 int size = cpuList.size();
589 for (int i = 0; i < size; ++i)
590 total += cpuList[i]->totalInsts();
595 static Counter numSimulatedOps()
599 int size = cpuList.size();
600 for (int i = 0; i < size; ++i)
601 total += cpuList[i]->totalOps();
607 // Number of CPU cycles simulated
608 Stats::Scalar numCycles;
609 Stats::Scalar numWorkItemsStarted;
610 Stats::Scalar numWorkItemsCompleted;
613 std::vector<AddressMonitor> addressMonitor;
616 void armMonitor(ThreadID tid, Addr address);
617 bool mwait(ThreadID tid, PacketPtr pkt);
618 void mwaitAtomic(ThreadID tid, ThreadContext *tc, BaseMMU *mmu);
619 AddressMonitor *getCpuAddrMonitor(ThreadID tid)
621 assert(tid < numThreads);
622 return &addressMonitor[tid];
625 bool waitForRemoteGDB() const;
627 Cycles syscallRetryLatency;
629 // Enables CPU to enter power gating on a configurable cycle count
631 void enterPwrGating();
633 const Cycles pwrGatingLatency;
634 const bool powerGatingOnIdle;
635 EventFunctionWrapper enterPwrGatingEvent;
638 #endif // THE_ISA == NULL_ISA
640 #endif // __CPU_BASE_HH__