Skip to content

Internals

Repositories and packages

A campaign repository pins the versions it needs in hfim.yaml.

flowchart LR
  tpl["hfim-template-#lt;board#gt;"]
  repo["campaign repository<br/>hfim.yaml, board.yaml,<br/>benchmarks/, campaigns/"]
  core["hfim<br/>command"]
  sdk["hfim-sdk<br/>build.sh, hfim.h"]
  qemu["hfim-sim-qemu<br/>QEMU, icount plugin"]
  gem5["hfim-sim-gem5<br/>gem5.opt, FIM controller"]
  srv["hfim-server<br/>Gateway, workers"]

  tpl -- "hfim init copies the files" --> repo
  repo -- "campaign YAML, benchmark sources" --> core
  core -- "benchmark C, build target" --> sdk
  sdk -- "ELF" --> core
  core -- "manifest.yaml: binary, GDB, plugin paths" --> qemu
  core -- "manifest.yaml: gem5.opt, config scripts" --> gem5
  core -- "hfim run --on: files over Server API v1" --> srv
  srv -- "results/#lt;campaign_id#gt;/ fetched back" --> repo
Package Version Role Depends on
hfim 1.17.0 CLI, campaign engine, fault models, classifier, Server provisioning nothing in this list
hfim-sim-qemu 9.2.4 QEMU binaries per architecture, gdb-multiarch, libicount_breakpoint.so hfim >=1.1,<2
hfim-sim-qemu-xuantie 9.0.2 the XuanTie fork of QEMU, its plugin and XuanTie's compiler, in a linux/amd64 image hfim >=1.1,<2
hfim-sim-gem5 23.2.0 gem5.opt (classic and Ruby), DRAMsim3, config scripts hfim >=1.1,<2
hfim-sdk 1.5.0 build script and the fim_init/fim_exit contract hfim >=1.1,<2
hfim-server 1.7.4 Gateway, workers, Redis ACL, systemd units hfim >=1.17.0,<1.18
hfim-template-nezha-c906-qemu 1.1.2 board, startup code, benchmarks, campaigns simulator: hfim-sim-qemu-xuantie@9.0.2, sdk: "hfim-sdk>=1.3,<2"
hfim-template-nezha-c906-gem5 1.2.0 board, benchmarks, campaigns simulator: hfim-sim-gem5@23.2.0, sdk: "hfim-sdk>=1.5,<2"

hfim init nezha-c906 selects hfim-template-nezha-c906-qemu. To use your own template, pass its Git URL or local checkout to hfim init.

Simulator manifests

A campaign names its simulator as simulator: <name>@<version>, for example hfim-sim-gem5@23.2.0. HFIM resolves the reference to the package's manifest.yaml and checks the manifest's core: range against its own version.

Lookup order:

  1. simulator_manifest: <path> in the campaign file.
  2. $HFIM_SIM_<NAME>, a native install root that contains manifest.yaml (for example HFIM_SIM_QEMU).
  3. $HFIM_HOME/simulators/<name>/<version>/manifest.yaml, the registry hfim sim install writes. HFIM_HOME defaults to ~/.hfim.
Manifest key Meaning
name, version the reference a campaign uses
core HFIM versions the package works with
backends qemu, or gem5 and gem5-ruby
sdk.build_target what the SDK must produce: qemu-bare or gem5-se
runtime.docker image name and paths inside the image
runtime.docker.prebuilt the registry image an install downloads instead of building, pinned by digest (Prebuilt images)
runtime.native install.sh and paths under ${HFIM_SIM_QEMU} or ${HFIM_SIM_GEM5}
plugin_features (QEMU) arguments the bundled icount plugin understands
qemu_patches (QEMU) fixes the build carries; a board that needs one lists it under emulation.requires_qemu_patches
configs (gem5) fim_golden.py, fim_inject.py, fim_inject_ruby.py
env variables set for the simulator process, for example LD_LIBRARY_PATH for DRAMsim3

HFIM_RUNTIME selects the form: docker on a laptop, native on a Server.

SDK build targets

Target Output Startup code Toolchain (riscv64)
qemu-bare freestanding ELF from the template (startup/<arch>/start.S, link.ld) riscv64-unknown-elf-gcc
gem5-se static Linux user-space ELF none; gem5 emulates syscalls riscv64-linux-gnu-gcc

The contract a benchmark compiles against is include/hfim.h with the symbols fim_init and fim_exit.

Campaign pipeline

flowchart TB
  cfg["campaigns/#lt;c#gt;.yaml<br/>+ benchmark ELF"]
  gold["golden run<br/>no fault"]
  gdir["golden/#lt;benchmark#gt;/#lt;record key#gt;/<br/>trace.json, observable_state.json"]
  fl["faultlist.json"]
  inj["injection runs 1..N<br/>one simulator process each"]
  st["per-run state<br/>exit code, console, observed values"]
  cls["classifier"]
  out["injections.csv<br/>results.txt"]

  cfg -- "ELF, execution setup" --> gold
  gold -- "window icounts, per-PC hits, observables" --> gdir
  cfg -- "seed, targets, num_injections" --> fl
  gdir -- "injection window" --> fl
  fl -- "one fault spec per run" --> inj
  inj -- "captured at fim_exit or limit" --> st
  st -- "observed state" --> cls
  gdir -- "golden state" --> cls
  cls -- "one outcome per row" --> out
  1. hfim run resolves the campaign file once: it fills what the file leaves unset from the files it includes (fim/core/configuration/includes.py), then validates every key (fim/core/configuration/resolver.py).
  2. hfim prepare asks the staleness service which artifacts are missing or stale, then builds the ELF, measures the golden run and takes the checkpoint as needed. See Golden staleness.
  3. The golden run records fim_init_icount, fim_exit_icount, the total instruction count, the per-PC hit histogram inside the window, the console output and the observable variables.
  4. SeededPRNG(seed) draws one fault spec per injection: target, bit or mask, and the injection point inside the golden window (fim/campaigns/faultlist_builder.py). The list is written to faultlist.json.
  5. Each injection starts a fresh simulator process, stops it at the injection point, writes the fault and resumes to fim_exit, a crash or a limit.
  6. The classifier compares each run with the golden run and assigns one outcome (fim/analysis/classifier.py).
  7. The campaign writes injections.csv, results.txt, metadata.json and provenance.json under results/<campaign_id>/.

On a Server the same steps run as Jobs: one Preparation Job runs hfim prepare, then one Injection Job per index runs run_campaign --inject-index I. A gem5 campaign runs as one Campaign Job. See Server administration.

Golden directory

File Content
input-record.json the Input Record; written last, so a directory without it is incomplete
trace.json instruction counts and the window
expected_output.txt console output of the golden run
observable_state.json values of the observable variables at fim_exit
initial_registers.json, final_registers.json register dumps
checkpoints/<key>/ checkpoints taken from this golden run

QEMU injection

Each injection is a fresh QEMU process. QEMU starts stopped (-S) with a GDB stub (-gdb tcp:<addr>:<port>) and a QMP socket (-qmp tcp:<addr>:<port>,server,wait=off). HFIM drives GDB over GDB/MI and QEMU over QMP. When a checkpoint is configured the run restores it with loadvm, then reconnects GDB so its register cache is refreshed.

The icount_breakpoint TCG plugin (plugins/icount_breakpoint.c in hfim-sim-qemu) counts retired instructions deterministically under -icount shift=0,align=off.

Plugin role Arguments What it does
count (golden run) output, fim_init_addr, fim_exit_addr writes total_instructions, fim_init_icount, fim_exit_icount and window_hits (per-PC histogram) as JSON
restrict counting instrument_lo, instrument_hi attaches the per-PC callback only to the program's code
icount trigger target_icount, trigger writes the trigger file at that instruction count and holds the vCPU
PC-hit trigger target_pc, target_pc_hits, trigger fires on the n-th execution of one PC, counted over every vCPU
early signal prearm_icount, prearm_file signals ahead of the target without stopping
hang cutoff hang_icount, hang_trigger past that count, writes the file and ends QEMU

The trigger file says what fired: instruction <n>, pc_hit <n> or fim_exit <n>. The campaign polls it, pauses the VM over QMP, removes the file and writes the fault through GDB. Unknown plugin arguments are ignored.

injection_mode Stop mechanism
icount (default) plugin target_icount
breakpoint GDB breakpoint on a PC drawn from window_hits, stopping on hit K; large K uses the plugin target_pc_hits
timer wall-clock delay of instruction count x timer_scale_factor (default 0.00001 s)
stepi GDB single-step up to max_instructions

Register writes go through GDB/MI. RISC-V float registers are read and written as raw 64-bit patterns with -data-write-register-values x <regnum> "0x<hex>"; register numbers come from -data-list-register-names. The bit arithmetic for every fault model lives in fim/core/fault_models.py, shared by all backends.

On a multicore board QEMU runs with -smp N. The fault goes to one hart, selected through the GDB thread of that hart.

QEMU and GDB constants

Constant Value Source
QMP_CONNECT_TIMEOUT 5.0 s fim/core/qemu_controller.py
QMP_COMMAND_TIMEOUT 10.0 s fim/core/qemu_controller.py
QEMU_START_TIMEOUT 5.0 s fim/core/qemu_controller.py
default GDB port, QMP port 1234, 4444 fim/core/qemu_controller.py
CONNECT_TIMEOUT (GDB) 10.0 s fim/core/gdb_controller.py
COMMAND_TIMEOUT (GDB) 5.0 s fim/core/gdb_controller.py
MAX_RETRIES (GDB) 3 fim/core/gdb_controller.py

Exit device

On the QEMU virt machine a 32-bit write to 0x100000 (sifive_test) ends QEMU.

Written QEMU exit code Written by
0x5555 0 fim_exit(0)
0x3333 1 fim_exit(1)
n (n >> 1) & 0x7f other values

A board whose board.yaml declares emulation.exit_device: none has no such device. There fim_exit loops, the run ends at a breakpoint on it and the exit code is read from a0.

gem5 injection

gem5 has no external debugger path. The injector is a SimObject, FIMController, compiled into gem5.opt from hfim-sim-gem5/integration/simobjects-fim/fim/. Each injection is a new gem5 process started with fim_inject.py (or fim_inject_ruby.py), which receives the fault as arguments (--fault-type, --fault-target, --fault-mask, --inject-at-instr, --fault-model, --fault-persistence).

FIMController is a sibling of system.cpu, not a child. It reaches its targets through the cpu, target_cache, memory and ruby_system parameters, and listens on two CPU probe points.

Probe Fires FIMController action
RetiredInsts every committed instruction counts; at inject_at_instruction calls injectFault(). Installed only when enabled=true
RetiredInstsPC every committed instruction, with its PC records the instruction count at fim_init_addr and fim_exit_addr. Installed in golden runs too

Sequence of one injection:

  1. gem5 restores the golden checkpoint when one exists.
  2. onInstCommit() counts committed instructions.
  3. At the target count injectFault() dispatches on fault_type to injectRegisterFault, injectMemoryFault, injectCacheFault, injectDramFault, injectUltraFault, injectNvmTags or injectRubyControllerFault.
  4. The method reads the original value, applies the mask through applyFaultModel() and writes it back. A permanent fault is reapplied by reapplyPermanentFault().
  5. writeReport() writes injection_report.json. No later trigger fires.
  6. At the exit callback dumpState() writes state_dump.json with the observable variables and registers.

Memory faults are one-byte read-modify-write. The faultlist caps bit_width at 8 for gem5 memory targets.

Two binaries

A Ruby coherence protocol is generated C++ fixed at build time, so the package builds two binaries.

Binary Manifest backend Protocol Used for
gem5/build/RISCV/gem5.opt gem5 classic caches registers, memory, caches, ECC, DRAM, NVMain, pipeline structures
gem5/build/RISCV_MESI_Two_Level/gem5.opt gem5-ruby MESI_Two_Level ruby_mshr, ruby_tbe, ruby_directory, ruby_message_buffer

HFIM selects the Ruby binary and fim_inject_ruby.py when simulator_backend: gem5-ruby is set or the fault target starts with ruby_. Otherwise it uses the classic binary.

CPU model Caches Notes
AtomicSimpleCPU none register and memory campaigns
TimingSimpleCPU L1I, L1D, L2 cache, tag and ECC targets
DerivO3CPU L1I, L1D, L2 adds phys_reg, rename_map, rob, lsq

On DerivO3CPU a register fault writes the thread context out of band and gem5 aborts in Commit::commitInsts() (assertion on noSquashFromTC and trapPending). Use phys_reg on O3: it writes the physical register file that the architectural register maps to.

Building gem5

cd hfim-sim-gem5
./build.sh                  # Docker image hfim-sim-gem5:<version>, both binaries
./install.sh -j8 all        # native build in place, needs gem5's build dependencies
export HFIM_SIM_GEM5=$PWD
Fact Reason
bitflip=1 is mandatory it defines TU_DORTMUND=1; src/mem/mem_ctrl.hh guards the tracer member behind it and mem_ctrl.cc does not compile without it
EXTRAS=<repo>/integration/simobjects-fim/fim:<repo>/nvmain gem5's mechanism for external SimObjects; scons compiles the SConscript of each path into the binary
build and run in ghcr.io/gem5/ubuntu-22.04_all-dependencies:v23-0 the binary links libpython3.10; a different runtime libpython segfaults at teardown and loses state_dump.json
DRAMsim3 is cloned into gem5/ext/dramsim3/DRAMsim3 at commit 2981759 install.sh builds libdramsim3.so; the manifest puts it on LD_LIBRARY_PATH

On Apple Silicon the amd64 image runs under emulation.

Vendored sources

hfim-sim-gem5/gem5/ and hfim-sim-gem5/nvmain/ are flattened snapshots of unmaintained upstream forks. VENDOR_README.md in the package holds the refresh procedure.

Directory Upstream Pinned commit
gem5/ OMA-NVM/nv-gem5 (gem5 v23.0) af00e94a
nvmain/ OMA-NVM/nv-NVmain (NVMain 2.0) 05b0e36

Edits on top of upstream, made directly in the vendored source:

File Edit Needed by
gem5/src/mem/mem_ctrl.cc null guards on the tracer path, and parseConfigFile only with a config path every campaign that does not configure NVMain; without them gem5 segfaults at tick 0
gem5/src/mem/cache/base.hh public BaseTags* getTags() injectCacheFault iterates valid cache blocks
gem5/src/cpu/o3/cpu.hh forward declaration class UltraInjector; pipeline targets reach private O3 state
gem5/src/mem/ruby/system/RubySystem.hh public getControllers() injectRubyControllerFault walks the Ruby controllers and calls their functionalRead/functionalWrite

Hardware injection

The hardware backend (fim/core/hardware_simulator.py) drives a physical board behind a GDB server. One run:

  1. Reset the board, load the ELF, place every hart of the cluster at the entry point.
  2. Run to fim_init, then wait a time drawn from the golden window.
  3. Halt, check that every hart is stopped, write the fault on the target hart.
  4. Resume to fim_exit or the timeout, then read the exit code, the observables and the console.

Board specifics live in the hardware: section of board.yaml (fim/core/hardware_spec.py) and in the probe package manifest. The backend names no board or probe. See Hardware backend.

Golden staleness

The staleness service (fim/core/artifacts/staleness.py) decides whether a Build, a Golden or a Checkpoint still matches its inputs. Every entry point that injects calls it before the first injection (fim/campaigns/golden_gate.py).

Each artifact has an Input Record: a list of fingerprints (category, name, value). The Record Key is the hash of that list, and names the artifact directory.

Record Fingerprints Parent
Build benchmark sources, shared sources, toolchain identity, build command, build target, program settings, OPTFLAG none
Golden ELF and firmware content, execution_setup settings, board properties, simulator install, measurement version (MEASUREMENT_VERSION in fim/core/artifacts/records.py, 3 from HFIM 1.15) Build key
Checkpoint checkpoint settings Golden key

Every campaign key belongs to one group (fim/core/artifacts/classification.py):

Group A change reaches Example keys
program Build, and through it everything after arch, benchmark, build_optflag, build_runtime
build_output Golden, by file content, never by path elf_path, firmware_path
execution_setup Golden board, simulator, injection_mode, cpu_model, cache_config, observable_outputs
checkpoint Checkpoint only checkpoint, checkpoint_locations
injection_plan the campaign result only seed, num_injections, fault, target_registers, fault_model
neutral nothing; listed in provenance campaign_label, num_workers, gdb_port, log_level

A key outside the table counts as execution_setup, so an unclassified key measures the golden run again. tests/artifacts/test_classification.py fails on any accepted key without an entry.

A golden directory is golden/<benchmark>/<record key>/. It is written into a temporary directory, its input-record.json is written last, and the directory is renamed into place. A published golden is never rewritten. A checkpoint lives in golden/<benchmark>/<golden key>/checkpoints/<key>/.

Verdict Meaning Action
fresh a Record with the needed key exists reuse it
missing no artifact with that key hfim prepare makes it
stale an older artifact exists with other inputs the verdict names each differing input; the campaign refuses unless --allow-stale, which provenance records
legacy the directory has no Input Record measured again

Classification

OutcomeClassifier.classify() (fim/analysis/classifier.py) applies these rules in order and stops at the first match:

  1. A crash_patterns string in the console output: crash.
  2. The run timed out: timeout.
  3. An infrastructure marker in the error message (failed to start qemu, exited immediately, failed to connect gdb, infrastructure failure): infrastructure_failure.
  4. The controller's crash verdict, or, for a run that did not complete, an exit code above 1 or an error message: crash.
  5. Exit code 1, or detection_string in the output: detected.
  6. With observable_outputs configured: compare the observed state with observable_state.json. Equal is masked, different is sdc. No observed state is crash when the output carries a simulator abort signature, else infrastructure_failure. A comparison that raises is infrastructure_failure.
  7. Without observable state: compare the console output with expected_output.txt. Equal is masked, different is sdc. No golden output is unknown.

When observable state is configured it is authoritative; the console is not consulted.

The crash verdict is made once, by decide_crash(), for every backend:

Rule Result
timed out not a crash
panic, abort, fatal, segfault, segmentation fault, page table fault in the exit cause or error crash
infrastructure marker not a crash
run completed (stats and injection report present) not a crash, whatever the exit code
exit code above 1 crash
no exit code and an error message crash

A completed gem5 run exits non-zero from a teardown segfault in Py_FinalizeEx; rule 4 keeps that from counting as a crash.

Simulator abort signatures (rule 6): program aborted at tick, panic:, fatal:, Assertion `, segmentation fault, --- BEGIN LIBC BACKTRACE ---, QEMU: Terminated.

Outcomes beyond the five in Fault classification, set by gem5 post-processing hooks:

Outcome Set by Meaning
infrastructure_failure classifier the fault was never written or the result cannot be read
unknown classifier no golden output and no observable state
stuck_after_wear override_outcome_for_endurance NVMain endurance limit turned a cell stuck
latent_clean, latent_dirty override_outcome_for_cache_ecc faulty cache line evicted before it was read, clean or written back
ecc_false_correct override_outcome_for_cache_ecc a check-bit fault made the decoder miscorrect a data bit
tag_false_miss, tag_false_hit, tag_latent override_outcome_for_tag_parity effect of a tag-array fault

infrastructure_failure and unknown describe the framework, not the chip. Summaries count them in the total so the denominator matches the runs made.

Reproducibility

Mechanism Where Guarantees
seed seed: in the campaign, SeededPRNG (fim/utils/prng.py) wrapping random.Random(seed) same seed, same golden and same keys give the same faultlist.json
faultlist replay faultlist_csv: naming a CSV in injections.csv format runs those faults instead of drawing; seed and num_injections become advisory
Input Records golden/<benchmark>/<key>/input-record.json the golden run was measured from these exact inputs
provenance results/<campaign_id>/provenance.json input hashes, toolchain, parameters, environment, outputs and the Records of every artifact used
manifest hash integrity.manifest_hash in provenance.json SHA-256 of the canonical JSON of the manifest; same hash means same inputs, toolchain and parameters

faultlist_csv reads the provenance.json beside the CSV to find the Build the faults were drawn from. A replay against a different Build refuses, because its PCs and hit counts may not exist in the running Build; --allow-stale replays it and provenance records the mismatch. A CSV with no provenance.json beside it is replayed unchecked, with a warning.

python3 -m fim.scripts.verify_provenance <campaign_id> [--results-dir results] checks the recorded inputs, toolchain binaries and output files of a campaign against their current state.

Two runs with the same manifest hash and different results indicate non-determinism in a simulator or in the framework. QEMU under -smp above 1 is such a case: see Known limitations.

Known limitations

Limitation Consequence Instead
No correlation with silicon simulator SDC rates are not calibrated against beam tests report results as "in a QEMU or gem5 simulation of the board"
McPAT power is a generic model total_power_W underestimates silicon power each row carries power_model_note; the value is not corrected
QEMU models no caches, pipeline or memory controller cache and microarchitectural targets are rejected on QEMU use gem5
QEMU multicore is not a bit-exact replay -icount is a global budget and record/replay is single-vCPU fault on one hart works; repeat runs can differ
serial-feeder benchmarks have an unstable instruction count icount points drift between runs injection_mode: breakpoint
one fault event per run two distinct events in one run are not modelled multi_bit_count for adjacent bits; fault_persistence: permanent for a stuck fault
gem5 syscall-emulation runs in user mode no CSRs, no mhartid, no wfi; secondary harts start only through clone() use QEMU for machine-mode code
register on DerivO3CPU aborts gem5 the run is classified crash phys_reg
gem5 Ruby needs a physical address ruby_target_addr is translated through the page table results of hfim-sim-gem5 23.0.1 Ruby campaigns are not comparable with 23.0.2
no interconnect (Garnet) faults router buffers, virtual channels and credits are unreachable none
NVMain ECP is not wired ECP.cpp in nv-NVmain has no caller none
gem5 is RISC-V only in this package other architectures need QEMU none
AArch64 exit through PSCI SYSTEM_OFF QEMU always exits 0; detected cannot be signalled by exit code detection_string
Server workers run gem5 as one Job per campaign gem5 injections of one campaign do not spread over the fleet locally, num_workers above 1 runs gem5 injections in a process pool

Raspberry Pi 5 McPAT profile

Use fim/configs/mcpat/raspberry_pi_5.xml with gem5 McPAT 0.8 and a four-core Arm O3 trace at 2.4 GHz. It models the CPU cluster, 64 KiB instruction and data caches per core, and four 512 KiB private L2 caches. The system result includes all four cores. The component CSV fields report the first core, data cache and L2.

McPAT 0.8 supports a minimum technology node of 22 nm. The output identifies the 22 nm proxy in power_model. Runtime dynamic power excludes leakage, the shared L3, DRAM, GPU and peripherals. Unavailable activity counters contribute zero. Use the result for model comparisons; physical BCM2712 power and area require calibration. BCM2712 specifications