m5 package provides the raw wiring, while the gem5 standard library gives you pre-assembled modules you can snap together.
Table of Contents
Architecture Overview
The Python module is divided into two major packages: the low-level m5 infrastructure that provides PyBind11 bindings to C++ simulator objects, and the high-level gem5 standard library that offers composable board/processor/memory abstractions. Together they enable full system configuration from Python scripts.
flowchart TD
User["User Config Script"]
Sim["gem5.simulate.Simulator"]
Board["gem5.components.boards"]
Proc["gem5.components.processors"]
Mem["gem5.components.memory"]
Cache["gem5.components.cachehierarchies"]
Res["gem5.resources"]
M5["m5.SimObject"]
Params["m5.params"]
Simulate["m5.simulate"]
Bind["_m5 (PyBind11 C++)"]
CPP["C++ Simulator Core"]
User --> Sim
Sim --> Board
Board --> Proc
Board --> Mem
Board --> Cache
Sim --> Res
Board --> M5
M5 --> Params
M5 --> Simulate
Simulate --> Bind
Bind --> CPP
The architecture follows a layered design: user scripts interact with Simulator, which orchestrates AbstractBoard subclasses. Boards compose processors, caches, and memory modules. At the bottom, m5.SimObject and its metaclass system create C++ objects via the _m5 PyBind11 bridge.
m5 Package โ Core Bindings
The m5 package provides the foundational infrastructure that bridges Python configuration to C++ simulation objects. Key submodules:
| Module | Purpose |
|---|---|
m5.SimObject | Base class for all configurable objects; metaclass-driven parameter system |
m5.simulate | Simulation execution: instantiate(), simulate(), drain(), checkpoint() |
m5.params | Parameter descriptors: ParamDesc, VectorParamDesc, Port |
m5.proxy | Dynamic parameter resolution: Self, Parent proxies |
m5.event | Event scheduling interface to C++ EventQueue |
m5.stats | Pipeline โ gem5 Wiki" class="xref">Statistics collection and output formatting |
m5.core | Tick management, debugging, build info |
m5.ticks | Time-to-tick conversion utilities |
m5.trace | Debug trace flag management |
m5.objects | Auto-generated SimObject subclass registry |
MetaSimObject Metaclass
The MetaSimObject metaclass intercepts class creation for every SimObject subclass. It collects parameter declarations, builds parameter descriptors, resolves inheritance, and registers the class in the global SimObject type registry. This allows the declarative Python style to automatically generate C++ parameter structs.
gem5 Standard Library
The modern gem5 standard library provides a component-based API for building simulation systems without deep knowledge of m5 internals.
๐ boards
AbstractBoard connects processor, Cache Hierarchy | gem5 Wiki" href="../mem_doc/cache/index.html">cache hierarchy, and memory into a complete system. Implementations: SimpleBoard, X86Board, ArmBoard, RiscvBoard.
โ๏ธ processors
AbstractProcessor wraps CPU cores. Implementations: SimpleProcessor (timing/atomic/O3), SwitchableProcessor for CPU switching.
๐พ memory
AbstractMemorySystem for DRAM configuration. SingleChannelDDR4, DualChannelDDR4, HBM2Stack.
๐ cachehierarchies
Cache system abstraction. Classic (PrivateL1/SharedL2), Ruby (MESI, MOESI, CHI protocols).
๐ฆ resources
WorkloadResource, BinaryResource, DiskImageResource โ automatic download and caching from gem5-resources repository.
๐๏ธ prebuilt
Ready-to-use configurations: demo boards (X86/ARM/RISC-V), Viper GPU board, RiscvMatched SiFive board.
Key Classes
| Class | Package | Parent | Description |
|---|---|---|---|
MetaSimObject | m5 | type | Metaclass that intercepts SimObject class creation; collects params |
SimObject | m5 | โ | Base for all configurable objects; parameter declaration and C++ binding |
SimObjectCliWrapper | m5 | โ | CLI parameter override interface for SimObjects |
Simulator | gem5.simulate | โ | Top-level simulation runner; manages board, exit events, run loop |
AbstractBoard | gem5.components | SubSystem | Connects processor + cache + memory; handles clocking and ranges |
AbstractProcessor | gem5.components | SubSystem | CPU abstraction; exposes cores, ISA, switching interface |
AbstractMemorySystem | gem5.components | SubSystem | Memory controller configuration and range management |
AbstractCacheHierarchy | gem5.components | SubSystem | Cache topology abstraction; classic and Ruby implementations |
WorkloadResource | gem5.resources | โ | Downloadable workload binaries with metadata |
obtain_resource | gem5.resources | function | Fetches and caches resources from gem5-resources repository |
SimPoint | gem5.utils | โ | SimPoint analysis utility for sampling-based simulation |
requires | gem5.utils | function | Runtime ISA/protocol compatibility checks |
Deep Dive: SimObject System
Parameter Lifecycle
sequenceDiagram
participant U as User Script
participant Meta as MetaSimObject
participant SO as SimObject
participant Inst as m5.simulate
participant CPP as C++ Object
U->>Meta: class MyObj(SimObject): type='MyObj' ...
Meta->>Meta: Collect params, build descriptors
U->>SO: obj = MyObj(param1=val)
SO->>SO: Store params in _values dict
U->>Inst: instantiate(root)
Inst->>SO: adoptOrphanParams()
Inst->>SO: unproxyParams() (resolve Self/Parent)
Inst->>CPP: _create_cpp_objects()
Inst->>CPP: connectPorts()
Inst->>CPP: init() / startup()
The instantiation sequence resolves all proxy parameters (Self.attr, Parent.attr), creates the C++ objects in dependency order, connects ports, and calls init() and startup() on each object. The configuration can be dumped in INI, JSON, or DOT format for debugging.
Parameter Types
| Descriptor | Usage | Example |
|---|---|---|
Param.Int | Single integer | cache_size = Param.MemorySize('64kB') |
VectorParam | List of values | port = VectorRequestPort('mem ports') |
DictParamDesc | Key-value mapping | Dictionary-style parameters |
Proxy.Self | Late binding | clk_domain = Self.clk_domain |
Port | Connection point | mem_side = RequestPort('to memory') |
Deep Dive: Component Model
flowchart TD
AB["AbstractBoard"]
AP["AbstractProcessor"]
AM["AbstractMemorySystem"]
AC["AbstractCacheHierarchy"]
AB -->|"has-a"| AP
AB -->|"has-a"| AM
AB -->|"has-a"| AC
AP --> SP["SimpleProcessor"]
AP --> SWP["SwitchableProcessor"]
AM --> SC["SingleChannelDDR4"]
AM --> DC["DualChannelDDR4"]
AC --> CL["ClassicCacheHierarchy"]
AC --> RB["RubyCacheHierarchy"]
AB --> SB["SimpleBoard"]
AB --> X86["X86Board"]
AB --> ARM["ArmBoard"]
The component model follows an abstract factory pattern. Each board implements _pre_instantiate() to wire components and get_memory_ranges() to define the address map. The connect_things() method links processor ports to cache hierarchy ports and cache to memory controller ports.
Simulation Flow
flowchart LR
A["Create Board"] --> B["Set Workload"]
B --> C["Create Simulator"]
C --> D["simulator.run()"]
D --> E["instantiate()"]
E --> F["simulate()"]
F --> G{Exit Event?}
G -->|"handler"| H["On-exit handler"]
H --> F
G -->|"done"| I["Stats dump & cleanup"]
Runtime Operations
The simulation engine supports runtime control operations through the m5.simulate module:
switchCpus()โ hot-swap CPU models (e.g., atomic โ O3) during simulationdrain()โ drain all SimObjects for safe state transitionsmemWriteback()โ flush dirty cache lines to memorycheckpoint()โ write simulation state for later restorationscheduleTickExitFromCurrent()โ schedule simulation exit at specific tick
Cross-Module Interactions
| Dependency | Module | Purpose |
|---|---|---|
| C++ bindings | _m5 (PyBind11) | Core simulation engine, object creation, event scheduling |
| Parameter structs | all src/ modules | Every C++ SimObject has auto-generated Python params |
| gem5-resources | external | Workload binaries, disk images, checkpoints |
| ISA definitions | arch/* | ISA-specific board and processor configurations |
| Memory system | mem | System | gem5 Wiki" class="xref">MemCtrl, DRAM interface parameter wrappers |
Directory Map
Configuration Patterns
| Pattern | API | Use Case |
|---|---|---|
| Atomic and Timing Simple CPUs โ gem5 Wiki" href="../cpu_doc/simple/index.html">Simple SE mode | SimpleBoard + SimpleProcessor + SingleChannelDDR4 | Quick syscall emulation experiments |
| Full System | X86Board + SwitchableProcessor + DualChannelDDR4 | Full OS boot with CPU switching |
| GPU compute | prebuilt.viper.Board | AMD GPU + CPU heterogeneous system |
| Custom | Subclass AbstractBoard + override connect_things() | Bespoke system topologies |
Code Examples
Simple SE-mode Simulation
from gem5.components.boards.simple_board import SimpleBoard
from gem5.components.processors.simple_processor import SimpleProcessor
from gem5.components.memory.single_channel import SingleChannelDDR4_2400
from gem5.components.cachehierarchies.classic.private_l1_shared_l2 import (
PrivateL1SharedL2CacheHierarchy,
)
from gem5.isas import ISA
from gem5.resources.resource import obtain_resource
from gem5.simulate.simulator import Simulator
# Build system components
processor = SimpleProcessor(cpu_type="timing", isa=ISA.X86, num_cores=1)
cache = PrivateL1SharedL2CacheHierarchy(l1d_size="32kB", l1i_size="32kB",
l2_size="256kB")
memory = SingleChannelDDR4_2400(size="2GiB")
# Assemble board
board = SimpleBoard(processor=processor, cache_hierarchy=cache,
memory=memory, clk_freq="3GHz")
board.set_se_binary_workload(obtain_resource("x86-hello64-static"))
# Run simulation
sim = Simulator(board=board)
sim.run()
Custom SimObject Declaration
from m5.SimObject import SimObject
from m5.params import Param, VectorParam
class MyAccelerator(SimObject):
"""Custom accelerator SimObject with configurable parameters."""
type = 'MyAccelerator'
cxx_header = 'my_module/accelerator.hh'
cxx_class = 'gem5::MyAccelerator'
num_engines = Param.Int(4, "Number of compute engines")
queue_depth = Param.Int(16, "Command queue depth")
clock_freq = Param.Clock('1GHz', "Operating frequency")
mem_ports = VectorRequestPort("Memory-side ports")
CPU Switching at Runtime
from gem5.components.processors.switchable_processor import SwitchableProcessor
processor = SwitchableProcessor(
starting_core_type="atomic",
switch_core_type="o3",
isa=ISA.ARM,
num_cores=4,
)
# In exit event handler:
def switch_handler():
processor.switch() # Drains and swaps CPU models
yield False # Continue simulation