diff --git a/build.zig b/build.zig index 808c2745..641e93d1 100644 --- a/build.zig +++ b/build.zig @@ -1,5 +1,17 @@ const std = @import("std"); +/// The mask sources and data that cpumask.zig embeds, as imports of `mod`. +fn addMaskFiles(b: *std.Build, mod: *std.Build.Module) void { + const files = [_][2][]const u8{ + .{ "mask_profiles", "share/eb-local/mask/profiles.conf" }, + .{ "mask_cpuidmask_c", "share/eb-local/mask/cpuidmask.c" }, + .{ "mask_armmask_c", "share/eb-local/mask/armmask.c" }, + .{ "mask_probe_c", "share/eb-local/mask/cpuid-probe.c" }, + .{ "mask_hooks_py", "share/eb-local/mask/eb_local_hooks.py" }, + }; + for (files) |f| mod.addAnonymousImport(f[0], .{ .root_source_file = b.path(f[1]) }); +} + pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{ .default_target = .{ .abi = .musl, .cpu_model = .baseline } }); const optimize = b.standardOptimizeOption(.{ .preferred_optimize_mode = .ReleaseSafe }); @@ -28,8 +40,12 @@ pub fn build(b: *std.Build) void { .{ .name = "build_options", .module = options.createModule() }, }, }); + addMaskFiles(b, mod); const exe = b.addExecutable(.{ .name = "eb-local", .root_module = mod, .linkage = .static }); b.installArtifact(exe); + // The sources and profiles the binary embeds, for reading and for builds + // that compile the preload library by hand. + b.installDirectory(.{ .source_dir = b.path("share/eb-local/mask"), .install_dir = .prefix, .install_subdir = "share/eb-local/mask" }); // The Zig autodoc site, into /docs, which the documentation // serves at api/. A compile of its own: asking the installed binary for @@ -58,19 +74,17 @@ pub fn build(b: *std.Build) void { suite_options.addOption([]const u8, "commit", commit); suite_options.addOption(bool, "test_ops", true); const suite_common = b.dependency("zig_common", .{ .target = target, .optimize = .Debug }); - break :blk b.addExecutable(.{ - .name = "eb-local", - .root_module = b.createModule(.{ - .root_source_file = b.path("src/main.zig"), - .target = target, - .optimize = .Debug, - .imports = &.{ - .{ .name = "zig_common", .module = suite_common.module("zig_common") }, - .{ .name = "build_options", .module = suite_options.createModule() }, - }, - }), - .linkage = .static, + const suite_mod = b.createModule(.{ + .root_source_file = b.path("src/main.zig"), + .target = target, + .optimize = .Debug, + .imports = &.{ + .{ .name = "zig_common", .module = suite_common.module("zig_common") }, + .{ .name = "build_options", .module = suite_options.createModule() }, + }, }); + addMaskFiles(b, suite_mod); + break :blk b.addExecutable(.{ .name = "eb-local", .root_module = suite_mod, .linkage = .static }); }; const suite = b.addSystemCommand(&.{ "bash", "-c", "EB_LOCAL_BIN=\"$(realpath \"$0\")\" exec python3 -m unittest discover -s tests" }); suite.addArtifactArg(suite_exe); diff --git a/changelog.d/+cpu-target.feature.md b/changelog.d/+cpu-target.feature.md new file mode 100644 index 00000000..b46f77da --- /dev/null +++ b/changelog.d/+cpu-target.feature.md @@ -0,0 +1 @@ +`--cpu-target TARGET` builds an easyconfig for another CPU target than the build host's, with `--mask auto|cpuid|kvm|tcg` choosing the route. The `cpuid` route runs the build with CPUID faulting and a target `/proc/cpuinfo` in an unprivileged namespace, refuses to build unless EESSI archdetect, archspec, gcc and the CPUID vendor name the target, pins the GROMACS SIMD level to the target, audits the installed tree and records the route in `easybuild/eb-local-build-mode.json`; `doctor --cpu-target` reports what the host can present. diff --git a/docs/howto/build-for-another-cpu.md b/docs/howto/build-for-another-cpu.md new file mode 100644 index 00000000..6bd71922 --- /dev/null +++ b/docs/howto/build-for-another-cpu.md @@ -0,0 +1,89 @@ + + +# Build for another CPU target + +A build on a Zen 5 machine installs for `x86_64/amd/zen5`. +These steps build the same recipe for `x86_64/amd/zen4`, `x86_64/amd/zen3`, or an Intel target such as `x86_64/intel/icelake`, on that machine, so the tree is installed in the subdirectory the nodes of that target read. + +## Before you start + +- eb-local that builds on this machine, as [Install software on top of EESSI with EasyBuild](install-software.md) describes; on a workstation without Slurm, add `--workstation`. +- A C compiler (`cc`), `unshare` and `mount` on `PATH`, for the `cpuid` route. +- The easyconfig of the package. Here it is `zlib-2.3.2-GCCcore-15.2.0.eb`. + +## Check what this machine can present + +```bash +eb-local doctor --cpu-target zen4 +``` + +The lines under `host:` say whether CPUID faulting works (AMD CPUs need Linux 6.17 or later), whether `/dev/kvm` and the QEMU binaries exist, and the last line says which route `--mask auto` takes for the target. +A target with no mask profile, or a host that cannot present it, shows as a `warn` line with the reason. + +## Build + +```bash +eb-local --workstation --cpu-target zen4 zlib-2.3.2-GCCcore-15.2.0.eb --robot +``` + +`zen4` means `x86_64/amd/zen4`; the full subdirectory works too, and a short name that two architectures share, such as `generic`, needs the architecture. +Before `eb` starts, the build prints one line per check, all inside the mask: + +```text +eb-local: --cpu-target x86_64/amd/zen4, cpuid route (CPUID faulting, namespaced /proc/cpuinfo) +eb-local: preflight ok: /dev/fd exists +eb-local: preflight ok: EESSI archdetect names x86_64/amd/zen4 +eb-local: preflight ok: archspec names zen4 +eb-local: preflight ok: gcc -march=native is znver4 +eb-local: preflight ok: CPUID vendor is AuthenticAMD +eb-local: preflight ok: CPUID faulting is active +``` + +A line that says `FAILED` stops the build before any compile. +The package installs below `/versions/2026.06/software/linux/x86_64/amd/zen4/`. + +`eb-local --explain --cpu-target zen4 ...` prints the route and the variables it sets, and runs nothing. + +## Read the record of how it was built + +Each directory the build installed has `easybuild/eb-local-build-mode.json`: + +```json +{ + "cpu_target": "x86_64/amd/zen4", + "route": "cpuid", + "profile": "x86_64/amd/zen4", + "host_cpu": "AMD Ryzen 9 9950X 16-Core Processor", + "kernel": "7.0.13-arch1-1-rg", + "eb_local_version": "3.5.0", + "isa_audit": "pass" +} +``` + +`isa_audit` is `skipped` with `--no-audit`. +The audit, `eb-local audit-isa DIR --target TARGET`, looks for instructions the target does not have; a failure fails the run and the installed tree stays for inspection. + +## When a build refuses + +| Message | Meaning | +|---|---| +| `CPUID faulting is not available` | The kernel cannot make `CPUID` fault. Use `--mask kvm` on the same architecture, or run on a newer kernel. | +| `the zen4 profile cannot be shown on a GenuineIntel CPU` | The profile for an AMD target keeps the host's vendor string; an Intel host cannot present it. | +| `this CPU lacks avx512_fp16` | A mask removes features and cannot add them. `sapphirerapids` needs a host that has AVX512-FP16 and AMX. | +| `no mask profile exists for ...` | Only the virtual machine routes can present that target. | +| `preflight FAILED: archspec names ...` | An easyblock that asks archspec would build for another CPU than the tree is labelled for. | +| `/dev/fd is missing` | EESSI's `eessi_archdetect.sh` fails without it and EESSI falls back to the generic target. | +| `__vm-run` | This eb-local has no virtual machine helper; the `kvm` and `tcg` routes refuse. | + +## GROMACS and Intel targets + +GROMACS chooses the SIMD level of a CPU whose brand string says Intel by timing AVX-512 FMA loops. +A Zen 5 core measures one unit and GROMACS picks `AVX2_256`, so an Ice Lake tree built there would be an AVX2 build, unlike the tree EESSI ships. +A `--cpu-target` build adds `-DGMX_SIMD` from the target to every GROMACS configure line (`AVX_512` for `skylake_avx512`, `cascadelake`, `icelake`, `sapphirerapids`, `zen4` and `zen5`; `AVX2_256` for `haswell`, `zen2` and `zen3`), unless the easyconfig sets it. +The EasyBuild log of the build says `eb-local: setting GMX_SIMD=LEVEL for CPU target TARGET`. + +## What the mask does not reach + +- Statically linked programs, and code that runs before the dynamic loader's constructors, see the real CPU. +- On x86\_64, the `cpuid` route masks the CPUID instruction only. `XGETBV` is not trapped, so a feature that GCC reads from the extended control registers, such as AMX, stays as the host has it. +- On aarch64 the kernel's emulated reads of ID registers cannot be masked; `getauxval` and `/proc/cpuinfo` are. diff --git a/docs/howto/index.md b/docs/howto/index.md index 70787ce8..dd1a384f 100644 --- a/docs/howto/index.md +++ b/docs/howto/index.md @@ -20,6 +20,7 @@ eb-without-a-site-file build-for-every-node-type build-against-a-site-gpu-module build-for-profiling +build-for-another-cpu install-what-eessi-lacks find-what-is-wrong refresh-the-module-cache diff --git a/docs/orgmode/howto/build-for-another-cpu.org b/docs/orgmode/howto/build-for-another-cpu.org new file mode 100644 index 00000000..244c4aec --- /dev/null +++ b/docs/orgmode/howto/build-for-another-cpu.org @@ -0,0 +1,87 @@ +#+title: Build for another CPU target + +A build on a Zen 5 machine installs for =x86_64/amd/zen5=. +These steps build the same recipe for =x86_64/amd/zen4=, =x86_64/amd/zen3=, or an Intel target such as =x86_64/intel/icelake=, on that machine, so the tree is installed in the subdirectory the nodes of that target read. + +* Before you start + +- eb-local that builds on this machine, as [[file:install-software.org][Install software on top of EESSI with EasyBuild]] describes; on a workstation without Slurm, add =--workstation=. +- A C compiler (=cc=), =unshare= and =mount= on =PATH=, for the =cpuid= route. +- The easyconfig of the package. Here it is =zlib-2.3.2-GCCcore-15.2.0.eb=. + +* Check what this machine can present + +#+begin_src bash +eb-local doctor --cpu-target zen4 +#+end_src + +The lines under =host:= say whether CPUID faulting works (AMD CPUs need Linux 6.17 or later), whether =/dev/kvm= and the QEMU binaries exist, and the last line says which route =--mask auto= takes for the target. +A target with no mask profile, or a host that cannot present it, shows as a =warn= line with the reason. + +* Build + +#+begin_src bash +eb-local --workstation --cpu-target zen4 zlib-2.3.2-GCCcore-15.2.0.eb --robot +#+end_src + +=zen4= means =x86_64/amd/zen4=; the full subdirectory works too, and a short name that two architectures share, such as =generic=, needs the architecture. +Before =eb= starts, the build prints one line per check, all inside the mask: + +#+begin_example +eb-local: --cpu-target x86_64/amd/zen4, cpuid route (CPUID faulting, namespaced /proc/cpuinfo) +eb-local: preflight ok: /dev/fd exists +eb-local: preflight ok: EESSI archdetect names x86_64/amd/zen4 +eb-local: preflight ok: archspec names zen4 +eb-local: preflight ok: gcc -march=native is znver4 +eb-local: preflight ok: CPUID vendor is AuthenticAMD +eb-local: preflight ok: CPUID faulting is active +#+end_example + +A line that says =FAILED= stops the build before any compile. +The package installs below =/versions/2026.06/software/linux/x86_64/amd/zen4/=. + +=eb-local --explain --cpu-target zen4 ...= prints the route and the variables it sets, and runs nothing. + +* Read the record of how it was built + +Each directory the build installed has =easybuild/eb-local-build-mode.json=: + +#+begin_src json +{ + "cpu_target": "x86_64/amd/zen4", + "route": "cpuid", + "profile": "x86_64/amd/zen4", + "host_cpu": "AMD Ryzen 9 9950X 16-Core Processor", + "kernel": "7.0.13-arch1-1-rg", + "eb_local_version": "3.5.0", + "isa_audit": "pass" +} +#+end_src + +=isa_audit= is =skipped= with =--no-audit=. +The audit, =eb-local audit-isa DIR --target TARGET=, looks for instructions the target does not have; a failure fails the run and the installed tree stays for inspection. + +* When a build refuses + +| Message | Meaning | +|---------+---------| +| =CPUID faulting is not available= | The kernel cannot make =CPUID= fault. Use =--mask kvm= on the same architecture, or run on a newer kernel. | +| =the zen4 profile cannot be shown on a GenuineIntel CPU= | The profile for an AMD target keeps the host's vendor string; an Intel host cannot present it. | +| =this CPU lacks avx512_fp16= | A mask removes features and cannot add them. =sapphirerapids= needs a host that has AVX512-FP16 and AMX. | +| =no mask profile exists for ...= | Only the virtual machine routes can present that target. | +| =preflight FAILED: archspec names ...= | An easyblock that asks archspec would build for another CPU than the tree is labelled for. | +| =/dev/fd is missing= | EESSI's =eessi_archdetect.sh= fails without it and EESSI falls back to the generic target. | +| =__vm-run= | This eb-local has no virtual machine helper; the =kvm= and =tcg= routes refuse. | + +* GROMACS and Intel targets + +GROMACS chooses the SIMD level of a CPU whose brand string says Intel by timing AVX-512 FMA loops. +A Zen 5 core measures one unit and GROMACS picks =AVX2_256=, so an Ice Lake tree built there would be an AVX2 build, unlike the tree EESSI ships. +A =--cpu-target= build adds =-DGMX_SIMD= from the target to every GROMACS configure line (=AVX_512= for =skylake_avx512=, =cascadelake=, =icelake=, =sapphirerapids=, =zen4= and =zen5=; =AVX2_256= for =haswell=, =zen2= and =zen3=), unless the easyconfig sets it. +The EasyBuild log of the build says =eb-local: setting GMX_SIMD=LEVEL for CPU target TARGET=. + +* What the mask does not reach + +- Statically linked programs, and code that runs before the dynamic loader's constructors, see the real CPU. +- On x86_64, the =cpuid= route masks the CPUID instruction only. =XGETBV= is not trapped, so a feature that GCC reads from the extended control registers, such as AMX, stays as the host has it. +- On aarch64 the kernel's emulated reads of ID registers cannot be masked; =getauxval= and =/proc/cpuinfo= are. diff --git a/docs/orgmode/howto/index.org b/docs/orgmode/howto/index.org index 757a9ff0..0503e8dd 100644 --- a/docs/orgmode/howto/index.org +++ b/docs/orgmode/howto/index.org @@ -19,6 +19,7 @@ eb-without-a-site-file build-for-every-node-type build-against-a-site-gpu-module build-for-profiling +build-for-another-cpu install-what-eessi-lacks find-what-is-wrong refresh-the-module-cache diff --git a/docs/orgmode/reference/cli.org b/docs/orgmode/reference/cli.org index 0ef5fa52..be9d1e4b 100644 --- a/docs/orgmode/reference/cli.org +++ b/docs/orgmode/reference/cli.org @@ -10,6 +10,7 @@ The repository's shell shim delegates every command to this Zig program. eb-local [OPTION]... [eb options] eb-local [OPTION]... --explain [eb options] eb-local [OPTION]... --variant perf|debug [eb options] +eb-local [OPTION]... --cpu-target TARGET [--mask auto|cpuid|kvm|tcg] [--no-audit] [eb options] eb-local eb [--] [eb options] eb-local --explain eb [--] [eb options] eb-local [OPTION]... env [--strict] [--json] @@ -21,7 +22,7 @@ eb-local check (--module NAME/VERSION... | --dev | --prefix DIR) [--recursive] [ eb-local audit-isa PATH --target TARGET [--json] [--allow FILE] [--objdump PATH] eb-local [OPTION]... submit [--on NAME,...] [--print] [eb options] eb-local [OPTION]... list [--json | --missing] [NAME[/VERSION]...] -eb-local [OPTION]... doctor [--json] [--strict] [--workspace PATH] [--cvmfs] [--cvmfs-parallel N] [--mpi] [--profiling] +eb-local [OPTION]... doctor [--json] [--strict] [--workspace PATH] [--cvmfs] [--cvmfs-parallel N] [--mpi] [--profiling] [--cpu-target TARGET] eb-local lmod-cache --modulepath DIR[:DIR] --cache-dir DIR --timestamp FILE [--spider CMD] [--verify] eb-local lmod-cache --prefix DIR [--eessi-version VER] [--update-cmd CMD] [--dry-run] eb-local modulerc --module-tree DIR [--default MODULE]... @@ -57,6 +58,14 @@ directory you own. build that easyconfig with debug symbols and frame pointers (perf) or unoptimised (debug), as a module whose version ends in -perf or -debug + eb-local --cpu-target TARGET [--mask auto|cpuid|kvm|tcg] [--no-audit] [eb options] + build for another CPU target on this machine: TARGET is + an EESSI subdirectory (x86_64/amd/zen4) or its last + component (zen4). The build sees that CPU through the + route --mask picks, refuses to go on when the EESSI + detection, archspec, gcc and CPUID do not all name the + target, and audits the installed binaries for + instructions the target lacks eb-local eb [--] [eb options] load EESSI-extend and run eb; configured prefix, no Slurm job. At most one of EESSI_USER_INSTALL, EESSI_PROJECT_INSTALL, EESSI_SITE_INSTALL, EESSI_CVMFS_INSTALL may be set, and a @@ -116,7 +125,7 @@ directory you own. what this node's target lacks; --json prints one line of JSON with schema_version 1; --missing lists only modules missing on this node's target - eb-local doctor [--json] [--strict] [--workspace PATH] [--cvmfs] [--cvmfs-parallel N] [--mpi] [--profiling] + eb-local doctor [--json] [--strict] [--workspace PATH] [--cvmfs] [--cvmfs-parallel N] [--mpi] [--profiling] [--cpu-target TARGET] what in this shell, node or configuration would stop a build or a module load; changes nothing; --json prints one line of JSON with schema_version 1. @@ -129,6 +138,8 @@ directory you own. allocation runs a two-rank hello per approved transport --profiling reports whether perf may sample and debuggers attach, and finds perf, valgrind and gdb + --cpu-target TARGET reports whether this machine can + present TARGET, and by which route eb-local lmod-cache --modulepath DIR[:DIR] --cache-dir DIR --timestamp FILE [--spider CMD] [--verify] write Lmod's spiderT.lua for those module @@ -237,6 +248,9 @@ After =eb=, every word goes to =eb= except =-h= and =--help=; after =eb --=, eve | =--config FILE= | Read FILE in place of the site file when root or the owner of this program owns it; otherwise in place of =~/.config/eb-local/config.toml=, when you own it. The other file is still read. | | =--explain= | Before an easyconfig, or before =eb=: print what would run, and create and run nothing. | | =--variant NAME= | Before an easyconfig: build it as the =perf= or =debug= variant, described in the =--variant= section below. | +| =--cpu-target TARGET= | Before an easyconfig: build for the CPU target TARGET on this machine, described in the =--cpu-target= section below. | +| =--mask ROUTE= | With =--cpu-target=: =auto=, =cpuid=, =kvm= or =tcg=. | +| =--no-audit= | With =--cpu-target=: skip the instruction audit after the build. | | =-h=, =--help=, =help= | Print the usage on stdout and exit 0. | | =--version= | Print the version line on stdout and exit 0. | | =--json= | On =list=, =check=, =doctor=, =modulerc=, =clean=, =config=, =profiles=, and =site list=: print one line of JSON with =schema_version= 1 on stdout instead of the text report. Not with =config --env= or =config --get=. | @@ -305,6 +319,52 @@ Dependencies build as usual. =--explain= shows the variant as =EB_LOCAL_VARIANT= and =EB_LOCAL_VARIANT_BLOCK=, the lines appended. [[file:../howto/build-for-profiling.org][Build software to profile or debug]] uses both. +** =--cpu-target= + +=--cpu-target TARGET= builds the easyconfig for another CPU target than this machine's, and installs it where EESSI-extend puts software for that target. +TARGET is an EESSI software subdirectory such as =x86_64/amd/zen4=, =x86_64/intel/icelake= or =aarch64/neoverse_n1=, or its last component when only one subdirectory ends in it (=zen4=; =generic= needs the architecture too). +[[file:../howto/build-for-another-cpu.org][Build for another CPU target]] walks through a build. + +=--mask= picks how the build sees the target CPU. + +| =--mask= | Route | Reaches | +|----------+-------+---------| +| =auto= | =cpuid= when this host can present TARGET that way, else =kvm= for the same architecture, else =tcg=; the host's own target needs no mask | | +| =cpuid= | CPUID faulting (x86_64) or a masked =getauxval= (aarch64), and a =/proc/cpuinfo= of the target bound in a user and mount namespace | x86_64 targets with a profile, on a host that traps CPUID (Intel since Linux 4.12, AMD since 6.17); aarch64 targets with a profile on an aarch64 host | +| =kvm= | =eb-local __vm-run --mode kvm=, a virtual machine with the target's CPU model | the host's architecture | +| =tcg= | =eb-local __vm-run --mode tcg=, an emulated CPU | any architecture, slowly | + +The =kvm= and =tcg= routes refuse, naming =__vm-run=, in an eb-local that does not have the helper. + +The profiles for the =cpuid= route are in =share/eb-local/mask/profiles.conf=, which =tools/mask/gen_profiles.py= writes from =tools/mask/targets.toml= and the CPUID rule files in =tools/mask/rules=. +They cover =x86_64/amd/zen2=, =zen3=, =zen4=, =x86_64/intel/skylake_avx512=, =cascadelake=, =icelake=, =sapphirerapids=, =aarch64/neoverse_n1= and =aarch64/generic=. +A mask only removes what the host has: =sapphirerapids= needs a host with AVX512-FP16 and AMX, so an AMD host refuses it. + +The =cpuid= route runs the whole build in an unprivileged user and mount namespace that keeps your user id, with the target's =/proc/cpuinfo= bound over the real one, and a library in =LD_PRELOAD= that answers every CPUID as the target. +The library is compiled with the host's =cc= on first use into =$XDG_CACHE_HOME/eb-local/mask-KEY= (=~/.cache/eb-local/mask-KEY=), where KEY is a hash of its source, the compiler's target triple and the C library's version. +A host without CPUID faulting is refused; the build never falls back to a native one. +=--cpu-target= with the target this host already is needs no mask. + +All routes set =EESSI_SOFTWARE_SUBDIR_OVERRIDE= to TARGET for the build, and run EasyBuild with the hooks of the EESSI stack plus one rule: GROMACS gets =-DGMX_SIMD= from TARGET (=AVX_512= for the AVX-512 targets, =AVX2_256= for zen2 and zen3), unless its configure options set it. +GROMACS chooses the SIMD level of a CPU with an Intel brand string by timing AVX-512 FMA loops, and a Zen 5 host measures one unit and picks =AVX2_256=, so without the rule the Ice Lake tree on such a host holds an AVX2 build. + +Before =eb= starts, in the mask, the build checks and refuses to go on unless each of these names TARGET: + +| Check | Source | +|-------+--------| +| =/dev/fd= exists | without it EESSI's =eessi_archdetect.sh= fails and EESSI picks the generic target | +| EESSI archdetect | =eessi_archdetect.sh cpupath=, first entry | +| archspec | =archspec.cpu.host()=, when the EESSI Python imports it | +| gcc | the =-march= (x86_64) or =-mcpu= (aarch64) of =gcc -march=native= | +| CPUID vendor, faulting | a probe run in the mask | + +After a successful build, =eb-local audit-isa DIR --target TARGET= runs on each directory the build installed, and a non-zero result fails the run; =--no-audit= skips it, and is required in an eb-local that has no =audit-isa=. +Each installed directory gets =easybuild/eb-local-build-mode.json=, with =cpu_target=, =route=, =profile=, =host_cpu=, =kernel=, =eb_local_version= and =isa_audit= (=pass=, =fail= or =skipped=). + +=--explain= shows the route and the variables it sets, =EB_LOCAL_CPU_TARGET= and =EESSI_SOFTWARE_SUBDIR_OVERRIDE=. +The =sbatch= lines of =submit=, and the replay hints, carry =--cpu-target=, =--mask= and =--no-audit=. +=eb-local doctor --cpu-target TARGET= reports whether CPUID faulting works here, whether =/dev/kvm= and the QEMU binaries exist, and which route =auto= would take. + ** eb Load EESSI and EESSI-extend in a bash with no profile and no rc file, and run =eb= with the arguments, with no Slurm job. @@ -534,6 +594,7 @@ The shape is in [[file:json/list.schema.json][list.schema.json]]. Print one line for each check of what would stop a build, =eb-local eb= or a module load, each starting =ok=, =info=, =warn= or =FAIL=, then a line that says whether anything stops a build. It checks the site file, the secrets a build reads (never their values), the prefix and its permissions, install variables and =LD_LIBRARY_PATH= left in the shell, the EESSI init =eb-local eb= sources, whether an explicitly exported install variable disagrees with the configured destination, the allocation's node-local mount, whether EESSI is loaded and your modules are on =MODULEPATH=, the Lmod init a build sources where the shell has no module command, eessi-arch-guard, and rtrash. With =--workspace PATH=, it also creates, writes, renames, executes and removes a small probe in that existing directory. +With =--cpu-target TARGET=, it also reports whether this machine can present that CPU target: whether CPUID faulting works, whether =/dev/kvm= and the QEMU binaries exist, whether a mask profile exists for TARGET, and which route =--mask auto= takes. It reports the file-system type, whether the storage is node-local or shared, free bytes and inodes, a =noexec= mount, and whether the effective =XDG_CACHE_HOME= (or =$HOME/.cache= when unset) is inside the workspace. The check does not create a build workspace and never starts a build. It names an entry of =PERL5LIB=, =PYTHONPATH=, =R_LIBS*=, =JULIA_LOAD_PATH=, =JULIA_DEPOT_PATH=, =NODE_PATH=, =CMAKE_PREFIX_PATH= or =PKG_CONFIG_PATH=, and a compiler-wrapper variable (=CC=, =CXX=, =FC=, =F77=, =F90=, =F95=, =CPP=, the =OMPI_=, =MPICH_= and =I_MPI_= forms, =RUSTC_WRAPPER=, =CARGO_BUILD_RUSTC_WRAPPER=, =RUSTC_WORKSPACE_WRAPPER=, =CARGO_TARGET_*_LINKER=, =R_MAKEVARS_USER=, =R_MAKEVARS_SITE=, =CCACHE_*=, =SCCACHE_*= and =CMAKE_*_COMPILER_LAUNCHER=), that resolves outside the approved prefixes. =RUSTFLAGS= and =CARGO_TARGET_*_RUSTFLAGS= are flag strings, not paths, so they are not named. diff --git a/docs/orgmode/reference/environment.org b/docs/orgmode/reference/environment.org index f9288a5e..0c6df860 100644 --- a/docs/orgmode/reference/environment.org +++ b/docs/orgmode/reference/environment.org @@ -43,6 +43,7 @@ The site settings, =storage.*=, =build.site_toolchains= and =build.node_types=, | =EB_LOCAL_CONFIG= | Names a configuration file to read when =--config= does not. | | =EB_LOCAL_PIN_BUILDENV_PYTHON= | =1= prepends the stable private compatibility-layer =python3= directory after =dev= loads a build environment. | | =EB_LOCAL_KEEP_WORK= | =1= keeps the workspace of a build that succeeds. | +| =EB_LOCAL_CPU_TARGET=, =EB_LOCAL_MASK_ROUTE=, =EB_LOCAL_PROBE=, =EB_LOCAL_SELF=, =EB_LOCAL_HOOKS_FILE=, =EB_LOCAL_BASE_HOOKS= | Set by a build with =--cpu-target= for its script, as the target, the route, the CPUID probe, this program, the EasyBuild hooks file and the hooks the stack set; a value in your shell is dropped. | | =EB_LOCAL_VARIANT=, =EB_LOCAL_VARIANT_BLOCK= | Set by a build with =--variant= for its script, which unsets them; a value in your shell is dropped. | | =EB_LOCAL_LOCK_TIMEOUT_MS= | Positive integer milliseconds to wait for a busy =flock= lock before exiting non-zero; default =300000=. | | =EB_LOCAL_EESSI_EXTEND= | Set, not empty and not =0=, it sends every argument to =eb=, as after =eb-local eb --=. An eb-stack EESSI target runs eb-local this way. | diff --git a/docs/reference/cli.md b/docs/reference/cli.md index fe1b039a..65bb7fe2 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -12,6 +12,7 @@ The repository's shell shim delegates every command to this Zig program. eb-local [OPTION]... [eb options] eb-local [OPTION]... --explain [eb options] eb-local [OPTION]... --variant perf|debug [eb options] +eb-local [OPTION]... --cpu-target TARGET [--mask auto|cpuid|kvm|tcg] [--no-audit] [eb options] eb-local eb [--] [eb options] eb-local --explain eb [--] [eb options] eb-local [OPTION]... env [--strict] [--json] @@ -23,7 +24,7 @@ eb-local check (--module NAME/VERSION... | --dev | --prefix DIR) [--recursive] [ eb-local audit-isa PATH --target TARGET [--json] [--allow FILE] [--objdump PATH] eb-local [OPTION]... submit [--on NAME,...] [--print] [eb options] eb-local [OPTION]... list [--json | --missing] [NAME[/VERSION]...] -eb-local [OPTION]... doctor [--json] [--strict] [--workspace PATH] [--cvmfs] [--cvmfs-parallel N] [--mpi] [--profiling] +eb-local [OPTION]... doctor [--json] [--strict] [--workspace PATH] [--cvmfs] [--cvmfs-parallel N] [--mpi] [--profiling] [--cpu-target TARGET] eb-local lmod-cache --modulepath DIR[:DIR] --cache-dir DIR --timestamp FILE [--spider CMD] [--verify] eb-local lmod-cache --prefix DIR [--eessi-version VER] [--update-cmd CMD] [--dry-run] eb-local modulerc --module-tree DIR [--default MODULE]... @@ -59,6 +60,14 @@ directory you own. build that easyconfig with debug symbols and frame pointers (perf) or unoptimised (debug), as a module whose version ends in -perf or -debug + eb-local --cpu-target TARGET [--mask auto|cpuid|kvm|tcg] [--no-audit] [eb options] + build for another CPU target on this machine: TARGET is + an EESSI subdirectory (x86_64/amd/zen4) or its last + component (zen4). The build sees that CPU through the + route --mask picks, refuses to go on when the EESSI + detection, archspec, gcc and CPUID do not all name the + target, and audits the installed binaries for + instructions the target lacks eb-local eb [--] [eb options] load EESSI-extend and run eb; configured prefix, no Slurm job. At most one of EESSI_USER_INSTALL, EESSI_PROJECT_INSTALL, EESSI_SITE_INSTALL, EESSI_CVMFS_INSTALL may be set, and a @@ -118,7 +127,7 @@ directory you own. what this node's target lacks; --json prints one line of JSON with schema_version 1; --missing lists only modules missing on this node's target - eb-local doctor [--json] [--strict] [--workspace PATH] [--cvmfs] [--cvmfs-parallel N] [--mpi] [--profiling] + eb-local doctor [--json] [--strict] [--workspace PATH] [--cvmfs] [--cvmfs-parallel N] [--mpi] [--profiling] [--cpu-target TARGET] what in this shell, node or configuration would stop a build or a module load; changes nothing; --json prints one line of JSON with schema_version 1. @@ -131,6 +140,8 @@ directory you own. allocation runs a two-rank hello per approved transport --profiling reports whether perf may sample and debuggers attach, and finds perf, valgrind and gdb + --cpu-target TARGET reports whether this machine can + present TARGET, and by which route eb-local lmod-cache --modulepath DIR[:DIR] --cache-dir DIR --timestamp FILE [--spider CMD] [--verify] write Lmod's spiderT.lua for those module @@ -239,6 +250,9 @@ After `eb`, every word goes to `eb` except `-h` and `--help`; after `eb --`, eve | `--config FILE` | Read FILE in place of the site file when root or the owner of this program owns it; otherwise in place of `~/.config/eb-local/config.toml`, when you own it. The other file is still read. | | `--explain` | Before an easyconfig, or before `eb`: print what would run, and create and run nothing. | | `--variant NAME` | Before an easyconfig: build it as the `perf` or `debug` variant, described in the `--variant` section below. | +| `--cpu-target TARGET` | Before an easyconfig: build for the CPU target TARGET on this machine, described in the `--cpu-target` section below. | +| `--mask ROUTE` | With `--cpu-target`: `auto`, `cpuid`, `kvm` or `tcg`. | +| `--no-audit` | With `--cpu-target`: skip the instruction audit after the build. | | `-h`, `--help`, `help` | Print the usage on stdout and exit 0. | | `--version` | Print the version line on stdout and exit 0. | | `--json` | On `list`, `check`, `doctor`, `modulerc`, `clean`, `config`, `profiles`, and `site list`: print one line of JSON with `schema_version` 1 on stdout instead of the text report. Not with `config --env` or `config --get`. | @@ -307,6 +321,52 @@ Dependencies build as usual. `--explain` shows the variant as `EB_LOCAL_VARIANT` and `EB_LOCAL_VARIANT_BLOCK`, the lines appended. [Build software to profile or debug](../howto/build-for-profiling.md) uses both. +### `--cpu-target` + +`--cpu-target TARGET` builds the easyconfig for another CPU target than this machine's, and installs it where EESSI-extend puts software for that target. +TARGET is an EESSI software subdirectory such as `x86_64/amd/zen4`, `x86_64/intel/icelake` or `aarch64/neoverse_n1`, or its last component when only one subdirectory ends in it (`zen4`; `generic` needs the architecture too). +[Build for another CPU target](../howto/build-for-another-cpu.md) walks through a build. + +`--mask` picks how the build sees the target CPU. + +| `--mask` | Route | Reaches | +|---|---|---| +| `auto` | `cpuid` when this host can present TARGET that way, else `kvm` for the same architecture, else `tcg`; the host's own target needs no mask | | +| `cpuid` | CPUID faulting (x86\_64) or a masked `getauxval` (aarch64), and a `/proc/cpuinfo` of the target bound in a user and mount namespace | x86\_64 targets with a profile, on a host that traps CPUID (Intel since Linux 4.12, AMD since 6.17); aarch64 targets with a profile on an aarch64 host | +| `kvm` | `eb-local __vm-run --mode kvm`, a virtual machine with the target's CPU model | the host's architecture | +| `tcg` | `eb-local __vm-run --mode tcg`, an emulated CPU | any architecture, slowly | + +The `kvm` and `tcg` routes refuse, naming `__vm-run`, in an eb-local that does not have the helper. + +The profiles for the `cpuid` route are in `share/eb-local/mask/profiles.conf`, which `tools/mask/gen_profiles.py` writes from `tools/mask/targets.toml` and the CPUID rule files in `tools/mask/rules`. +They cover `x86_64/amd/zen2`, `zen3`, `zen4`, `x86_64/intel/skylake_avx512`, `cascadelake`, `icelake`, `sapphirerapids`, `aarch64/neoverse_n1` and `aarch64/generic`. +A mask only removes what the host has: `sapphirerapids` needs a host with AVX512-FP16 and AMX, so an AMD host refuses it. + +The `cpuid` route runs the whole build in an unprivileged user and mount namespace that keeps your user id, with the target's `/proc/cpuinfo` bound over the real one, and a library in `LD_PRELOAD` that answers every CPUID as the target. +The library is compiled with the host's `cc` on first use into `$XDG_CACHE_HOME/eb-local/mask-KEY` (`~/.cache/eb-local/mask-KEY`), where KEY is a hash of its source, the compiler's target triple and the C library's version. +A host without CPUID faulting is refused; the build never falls back to a native one. +`--cpu-target` with the target this host already is needs no mask. + +All routes set `EESSI_SOFTWARE_SUBDIR_OVERRIDE` to TARGET for the build, and run EasyBuild with the hooks of the EESSI stack plus one rule: GROMACS gets `-DGMX_SIMD` from TARGET (`AVX_512` for the AVX-512 targets, `AVX2_256` for zen2 and zen3), unless its configure options set it. +GROMACS chooses the SIMD level of a CPU with an Intel brand string by timing AVX-512 FMA loops, and a Zen 5 host measures one unit and picks `AVX2_256`, so without the rule the Ice Lake tree on such a host holds an AVX2 build. + +Before `eb` starts, in the mask, the build checks and refuses to go on unless each of these names TARGET: + +| Check | Source | +|---|---| +| `/dev/fd` exists | without it EESSI's `eessi_archdetect.sh` fails and EESSI picks the generic target | +| EESSI archdetect | `eessi_archdetect.sh cpupath`, first entry | +| archspec | `archspec.cpu.host()`, when the EESSI Python imports it | +| gcc | the `-march` (x86\_64) or `-mcpu` (aarch64) of `gcc -march=native` | +| CPUID vendor, faulting | a probe run in the mask | + +After a successful build, `eb-local audit-isa DIR --target TARGET` runs on each directory the build installed, and a non-zero result fails the run; `--no-audit` skips it, and is required in an eb-local that has no `audit-isa`. +Each installed directory gets `easybuild/eb-local-build-mode.json`, with `cpu_target`, `route`, `profile`, `host_cpu`, `kernel`, `eb_local_version` and `isa_audit` (`pass`, `fail` or `skipped`). + +`--explain` shows the route and the variables it sets, `EB_LOCAL_CPU_TARGET` and `EESSI_SOFTWARE_SUBDIR_OVERRIDE`. +The `sbatch` lines of `submit`, and the replay hints, carry `--cpu-target`, `--mask` and `--no-audit`. +`eb-local doctor --cpu-target TARGET` reports whether CPUID faulting works here, whether `/dev/kvm` and the QEMU binaries exist, and which route `auto` would take. + ### eb Load EESSI and EESSI-extend in a bash with no profile and no rc file, and run `eb` with the arguments, with no Slurm job. @@ -538,6 +598,7 @@ The shape is in [list.schema.json](json/list.schema.json). Print one line for each check of what would stop a build, `eb-local eb` or a module load, each starting `ok`, `info`, `warn` or `FAIL`, then a line that says whether anything stops a build. It checks the site file, the secrets a build reads (never their values), the prefix and its permissions, install variables and `LD_LIBRARY_PATH` left in the shell, the EESSI init `eb-local eb` sources, whether an explicitly exported install variable disagrees with the configured destination, the allocation's node-local mount, whether EESSI is loaded and your modules are on `MODULEPATH`, the Lmod init a build sources where the shell has no module command, eessi-arch-guard, and rtrash. With `--workspace PATH`, it also creates, writes, renames, executes and removes a small probe in that existing directory. +With `--cpu-target TARGET`, it also reports whether this machine can present that CPU target: whether CPUID faulting works, whether `/dev/kvm` and the QEMU binaries exist, whether a mask profile exists for TARGET, and which route `--mask auto` takes. It reports the file-system type, whether the storage is node-local or shared, free bytes and inodes, a `noexec` mount, and whether the effective `XDG_CACHE_HOME` (or `$HOME/.cache` when unset) is inside the workspace. The check does not create a build workspace and never starts a build. It names an entry of `PERL5LIB`, `PYTHONPATH`, `R_LIBS*`, `JULIA_LOAD_PATH`, `JULIA_DEPOT_PATH`, `NODE_PATH`, `CMAKE_PREFIX_PATH` or `PKG_CONFIG_PATH`, and a compiler-wrapper variable (`CC`, `CXX`, `FC`, `F77`, `F90`, `F95`, `CPP`, the `OMPI_`, `MPICH_` and `I_MPI_` forms, `RUSTC_WRAPPER`, `CARGO_BUILD_RUSTC_WRAPPER`, `RUSTC_WORKSPACE_WRAPPER`, `CARGO_TARGET_*_LINKER`, `R_MAKEVARS_USER`, `R_MAKEVARS_SITE`, `CCACHE_*`, `SCCACHE_*` and `CMAKE_*_COMPILER_LAUNCHER`), that resolves outside the approved prefixes. `RUSTFLAGS` and `CARGO_TARGET_*_RUSTFLAGS` are flag strings, not paths, so they are not named. diff --git a/docs/reference/environment.md b/docs/reference/environment.md index 7aed079e..fd239e24 100644 --- a/docs/reference/environment.md +++ b/docs/reference/environment.md @@ -45,6 +45,7 @@ The site settings, `storage.*`, `build.site_toolchains` and `build.node_types`, | `EB_LOCAL_CONFIG` | Names a configuration file to read when `--config` does not. | | `EB_LOCAL_PIN_BUILDENV_PYTHON` | `1` prepends the stable private compatibility-layer `python3` directory after `dev` loads a build environment. | | `EB_LOCAL_KEEP_WORK` | `1` keeps the workspace of a build that succeeds. | +| `EB_LOCAL_CPU_TARGET`, `EB_LOCAL_MASK_ROUTE`, `EB_LOCAL_PROBE`, `EB_LOCAL_SELF`, `EB_LOCAL_HOOKS_FILE`, `EB_LOCAL_BASE_HOOKS` | Set by a build with `--cpu-target` for its script, as the target, the route, the CPUID probe, this program, the EasyBuild hooks file and the hooks the stack set; a value in your shell is dropped. | | `EB_LOCAL_VARIANT`, `EB_LOCAL_VARIANT_BLOCK` | Set by a build with `--variant` for its script, which unsets them; a value in your shell is dropped. | | `EB_LOCAL_LOCK_TIMEOUT_MS` | Positive integer milliseconds to wait for a busy `flock` lock before exiting non-zero; default `300000`. | | `EB_LOCAL_EESSI_EXTEND` | Set, not empty and not `0`, it sends every argument to `eb`, as after `eb-local eb --`. An eb-stack EESSI target runs eb-local this way. | diff --git a/share/eb-local/mask/armmask.c b/share/eb-local/mask/armmask.c new file mode 100644 index 00000000..5b00b9f4 --- /dev/null +++ b/share/eb-local/mask/armmask.c @@ -0,0 +1,36 @@ +/* + * armmask: present another aarch64 CPU's capabilities to the dynamically + * linked processes of a tree, without a VM. + * + * aarch64 software learns the CPU three ways: getauxval(AT_HWCAP/AT_HWCAP2) + * (Highway, most runtime dispatchers), /proc/cpuinfo (GCC -mcpu=native, + * archspec, EESSI archdetect, OpenBLAS getarch), and MRS reads of ID + * registers, which the kernel emulates without a signal. This library covers + * the first by interposing getauxval; eb-local covers the second with a + * bind-mounted cpuinfo. The third cannot be reached from userspace. + * + * ARMMASK_HWCAP and ARMMASK_HWCAP2 hold the words to keep, in hexadecimal; + * the result is the real word AND the kept one. Without ARMMASK_HWCAP the + * library does nothing. + */ +#define _GNU_SOURCE +#include +#include +#include + +typedef unsigned long (*getauxval_fn)(unsigned long); + +unsigned long getauxval(unsigned long type) +{ + static getauxval_fn real; + if (!real) + real = (getauxval_fn)dlsym(RTLD_NEXT, "getauxval"); + unsigned long v = real(type); + if (type != AT_HWCAP && type != AT_HWCAP2) + return v; + const char *on = getenv("ARMMASK_HWCAP"); + const char *keep = getenv(type == AT_HWCAP ? "ARMMASK_HWCAP" : "ARMMASK_HWCAP2"); + if (!on || !*on || !keep) + return v; + return v & strtoul(keep, NULL, 16); +} diff --git a/share/eb-local/mask/cpuid-probe.c b/share/eb-local/mask/cpuid-probe.c new file mode 100644 index 00000000..3f44bdc3 --- /dev/null +++ b/share/eb-local/mask/cpuid-probe.c @@ -0,0 +1,45 @@ +/* + * cpuid-probe: print what this process sees of the CPU, for the preflight of + * a masked build. Run under the preload library it prints the masked view. + * + * x86_64: `vendor=NAME family=N model=N faulting=on|off`, from CPUID leaves 0 + * and 1 (family and model as the kernel computes them) and from + * arch_prctl(ARCH_GET_CPUID). aarch64: `hwcap=0xH hwcap2=0xH`. + */ +#define _GNU_SOURCE +#include + +#if defined(__x86_64__) +#include +#include +#include +#include +#include + +int main(void) +{ + unsigned a, b, c, d; + char vendor[13]; + __cpuid(0, a, b, c, d); + memcpy(vendor, &b, 4); + memcpy(vendor + 4, &d, 4); + memcpy(vendor + 8, &c, 4); + vendor[12] = 0; + __cpuid(1, a, b, c, d); + unsigned base = (a >> 8) & 0xf, family = base, model = (a >> 4) & 0xf; + if (base == 0xf) family += (a >> 20) & 0xff; + if (base == 0xf || base == 0x6) model += ((a >> 16) & 0xf) << 4; + /* ARCH_GET_CPUID gives 0 while CPUID faults. */ + long mode = syscall(SYS_arch_prctl, ARCH_GET_CPUID, 0); + printf("vendor=%s family=%u model=%u faulting=%s\n", vendor, family, model, mode == 0 ? "on" : "off"); + return 0; +} +#else +#include + +int main(void) +{ + printf("hwcap=%#lx hwcap2=%#lx\n", getauxval(AT_HWCAP), getauxval(AT_HWCAP2)); + return 0; +} +#endif diff --git a/share/eb-local/mask/cpuidmask.c b/share/eb-local/mask/cpuidmask.c new file mode 100644 index 00000000..74892a3d --- /dev/null +++ b/share/eb-local/mask/cpuidmask.c @@ -0,0 +1,201 @@ +/* + * cpuidmask: present another x86 CPU to every dynamically linked process in a + * tree, without a VM. + * + * The constructor turns on CPUID faulting for the process (arch_prctl + * ARCH_SET_CPUID 0), so each CPUID instruction raises SIGSEGV. The handler + * runs the real CPUID with faulting briefly off, applies the rules, writes the + * result into the trapped context and steps past the two-byte instruction. + * Faulting resets on execve, so the library has to stay in LD_PRELOAD for + * children to inherit the view. + * + * Programs that install their own SIGSEGV handler (GCC's cc1, GNU grep's + * stack-overflow guard) would otherwise take the trap themselves, so sigaction + * and signal are interposed: the program's SIGSEGV handler is recorded, ours + * stays installed, and every fault that is not a CPUID is passed to theirs. + * + * CPUIDMASK_RULES=FILE names the rules, one per line, + * clear LEAF SUB REG MASK replace LEAF SUB REG VALUE + * with REG 0 to 3 for EAX to EDX; '#' starts a comment. Without it the + * library does nothing. + * CPUIDMASK_STRICT=1 exits with status 97 when the kernel has no CPUID + * faulting, instead of running with the real CPU visible. + * CPUIDMASK_STATS=1 reports at exit how many CPUIDs the process had answered. + * Limits: statically linked binaries and code that runs before constructors + * (the dynamic loader's own CPU probe) see the real CPU. + */ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* Leaves whose output depends on the subleaf in ECX. For the others ECX is + * ignored by the CPU and may hold anything, so rules match subleaf 0. */ +static int has_subleaves(uint32_t leaf) +{ + switch (leaf) { + case 0x4: case 0x7: case 0xb: case 0xd: case 0xf: case 0x10: case 0x12: + case 0x14: case 0x17: case 0x18: case 0x19: case 0x1d: case 0x1e: case 0x1f: + case 0x20: case 0x23: case 0x24: case 0x8000001d: case 0x80000020: case 0x80000026: + return 1; + } + return 0; +} + +struct rule { uint32_t leaf, sub; int reg; uint32_t clear, set; int replace; uint32_t value; }; +enum { EAX, EBX, ECX, EDX }; + +static unsigned long ntrapped; +static const struct rule *rules; +static size_t nrules; +static struct rule file_rules[128]; + +/* Read CPUIDMASK_RULES; returns the number of rules, or -1 on any bad line. */ +static long load_rules(const char *path) +{ + FILE *f = fopen(path, "r"); + if (!f) return -1; + char line[256], kind[16]; + unsigned long leaf, sub, reg, val; + size_t n = 0; + long rc = 0; + while (fgets(line, sizeof line, f)) { + char *hash = strchr(line, '#'); + if (hash) *hash = 0; + if (sscanf(line, "%15s", kind) != 1) continue; + if (n == sizeof file_rules / sizeof *file_rules + || sscanf(line, "%15s %li %li %li %li", kind, (long *)&leaf, (long *)&sub, (long *)®, (long *)&val) != 5 + || reg > EDX) { rc = -1; break; } + struct rule r = { (uint32_t)leaf, (uint32_t)sub, (int)reg, 0, 0, 0, 0 }; + if (strcmp(kind, "clear") == 0) r.clear = (uint32_t)val; + else if (strcmp(kind, "replace") == 0) { r.replace = 1; r.value = (uint32_t)val; } + else { rc = -1; break; } + file_rules[n++] = r; + } + fclose(f); + return rc < 0 ? -1 : (long)n; +} + +static long set_cpuid(int on) { return syscall(SYS_arch_prctl, ARCH_SET_CPUID, on); } + +typedef int (*sigaction_fn)(int, const struct sigaction *, struct sigaction *); +static sigaction_fn real_sigaction; +static int armed; +/* The program's own SIGSEGV disposition, which ours forwards to. */ +static struct sigaction user_segv = { .sa_handler = SIG_DFL }; + +static void forward(int sig, siginfo_t *si, void *ctx) +{ + if (user_segv.sa_flags & SA_SIGINFO) { + user_segv.sa_sigaction(sig, si, ctx); + } else if (user_segv.sa_handler == SIG_IGN) { + return; + } else if (user_segv.sa_handler != SIG_DFL) { + user_segv.sa_handler(sig); + } else { + /* Default action: restore it and return, so the fault repeats and kills. */ + struct sigaction dfl = { .sa_handler = SIG_DFL }; + sigemptyset(&dfl.sa_mask); + real_sigaction(SIGSEGV, &dfl, NULL); + } +} + +static void on_segv(int sig, siginfo_t *si, void *ctx) +{ + ucontext_t *uc = ctx; + greg_t *g = uc->uc_mcontext.gregs; + const unsigned char *ip = (const unsigned char *)g[REG_RIP]; + if (!(ip[0] == 0x0f && ip[1] == 0xa2)) { + forward(sig, si, ctx); + return; + } + ntrapped++; + uint32_t leaf = (uint32_t)g[REG_RAX], sub = (uint32_t)g[REG_RCX]; + uint32_t r[4]; + set_cpuid(1); + __cpuid_count(leaf, sub, r[EAX], r[EBX], r[ECX], r[EDX]); + set_cpuid(0); + for (size_t i = 0; i < nrules; i++) { + const struct rule *ru = &rules[i]; + if (ru->leaf != leaf || ru->sub != (has_subleaves(leaf) ? sub : 0)) continue; + if (ru->replace) r[ru->reg] = ru->value; + else r[ru->reg] = (r[ru->reg] & ~ru->clear) | ru->set; + } + g[REG_RAX] = r[EAX]; g[REG_RBX] = r[EBX]; g[REG_RCX] = r[ECX]; g[REG_RDX] = r[EDX]; + g[REG_RIP] += 2; +} + +int sigaction(int sig, const struct sigaction *act, struct sigaction *old) +{ + if (!real_sigaction) + real_sigaction = (sigaction_fn)dlsym(RTLD_NEXT, "sigaction"); + if (sig != SIGSEGV || !armed) + return real_sigaction(sig, act, old); + if (old) + *old = user_segv; + if (act) + user_segv = *act; + return 0; +} + +sighandler_t signal(int sig, sighandler_t handler) +{ + struct sigaction act, old; + memset(&act, 0, sizeof act); + act.sa_handler = handler; + act.sa_flags = SA_RESTART; + sigemptyset(&act.sa_mask); + if (sigaction(sig, &act, &old) < 0) + return SIG_ERR; + return old.sa_handler; +} + +/* CPUIDMASK_STATS=1: report how many CPUIDs this process had answered. */ +__attribute__((destructor)) static void cpuidmask_fini(void) +{ + if (armed && getenv("CPUIDMASK_STATS")) { + char buf[96]; + int n = snprintf(buf, sizeof buf, "cpuidmask: pid %d answered %lu cpuid\n", (int)getpid(), ntrapped); + if (n > 0) (void)!write(2, buf, (size_t)n); + } +} + +__attribute__((constructor)) static void cpuidmask_init(void) +{ + const char *rf = getenv("CPUIDMASK_RULES"); + if (!real_sigaction) + real_sigaction = (sigaction_fn)dlsym(RTLD_NEXT, "sigaction"); + if (!rf || !*rf) + return; + long n = load_rules(rf); + if (n < 0) { + static const char msg[] = "cpuidmask: cannot read CPUIDMASK_RULES; CPUID not masked\n"; + (void)!write(2, msg, sizeof msg - 1); + if (getenv("CPUIDMASK_STRICT")) _exit(97); + return; + } + rules = file_rules; nrules = (size_t)n; + struct sigaction sa; + memset(&sa, 0, sizeof sa); + sa.sa_sigaction = on_segv; + sa.sa_flags = SA_SIGINFO | SA_NODEFER; + sigemptyset(&sa.sa_mask); + real_sigaction(SIGSEGV, &sa, NULL); + armed = 1; + if (set_cpuid(0) != 0) { + /* No CPUID faulting (AMD: Linux 6.17, or a kernel with the backport): + * every CPUID would see the real CPU. CPUIDMASK_STRICT=1 stops the + * process so a build cannot go on unmasked. */ + static const char msg[] = "cpuidmask: CPUID faulting unavailable; CPUID is not masked\n"; + (void)!write(2, msg, sizeof msg - 1); + if (getenv("CPUIDMASK_STRICT")) _exit(97); + } +} diff --git a/share/eb-local/mask/eb_local_hooks.py b/share/eb-local/mask/eb_local_hooks.py new file mode 100644 index 00000000..4a12b4ce --- /dev/null +++ b/share/eb-local/mask/eb_local_hooks.py @@ -0,0 +1,49 @@ +"""EasyBuild hooks for `eb-local --cpu-target`. + +The site's own hooks (EASYBUILD_HOOKS as EESSI-extend sets it, passed in +EB_LOCAL_BASE_HOOKS) are loaded and re-exported unchanged, and one rule is +added on top: GROMACS gets -DGMX_SIMD from the CPU target. + +GROMACS picks the SIMD level of an x86_64 CPU whose brand string says Intel by +timing AVX-512 FMA loops, and a host with one 512-bit FMA unit (Zen 5) measures +AVX2. A tree built there for an Intel AVX-512 target would hold an AVX2 build. +The level follows the target instead, as it does in EESSI's own trees. +""" +import importlib.util +import os + +from easybuild.tools.build_log import print_msg + +GROMACS_SIMD_BY_CPU_TARGET = { + 'x86_64/amd/zen2': 'AVX2_256', + 'x86_64/amd/zen3': 'AVX2_256', + 'x86_64/amd/zen4': 'AVX_512', + 'x86_64/amd/zen5': 'AVX_512', + 'x86_64/intel/haswell': 'AVX2_256', + 'x86_64/intel/skylake_avx512': 'AVX_512', + 'x86_64/intel/cascadelake': 'AVX_512', + 'x86_64/intel/icelake': 'AVX_512', + 'x86_64/intel/sapphirerapids': 'AVX_512', +} + +_base = None +_base_path = os.environ.get('EB_LOCAL_BASE_HOOKS', '') +if _base_path: + _spec = importlib.util.spec_from_file_location('eb_local_base_hooks', _base_path) + _base = importlib.util.module_from_spec(_spec) + _spec.loader.exec_module(_base) + for _name in dir(_base): + if _name.endswith('_hook') and callable(getattr(_base, _name)): + globals()[_name] = getattr(_base, _name) + + +def pre_configure_hook(self, *args, **kwargs): + """The site's pre-configure hook, then the GROMACS SIMD rule.""" + if _base is not None and hasattr(_base, 'pre_configure_hook'): + _base.pre_configure_hook(self, *args, **kwargs) + if self.name == 'GROMACS': + cpu_target = os.environ.get('EB_LOCAL_CPU_TARGET', '') + simd = GROMACS_SIMD_BY_CPU_TARGET.get(cpu_target) + if simd and '-DGMX_SIMD=' not in self.cfg['configopts']: + print_msg("eb-local: setting GMX_SIMD=%s for CPU target %s", simd, cpu_target, log=self.log) + self.cfg.update('configopts', '-DGMX_SIMD=%s' % simd) diff --git a/share/eb-local/mask/profiles.conf b/share/eb-local/mask/profiles.conf new file mode 100644 index 00000000..b9683444 --- /dev/null +++ b/share/eb-local/mask/profiles.conf @@ -0,0 +1,199 @@ +# generated by tools/mask/gen_profiles.py from tools/mask/targets.toml and tools/mask/rules; do not edit + +[x86_64/amd/zen2] +arch = x86_64 +vendor = AuthenticAMD +family = 23 +model = 49 +model_name = AMD EPYC-Rome (eb-local mask) +gcc_march = znver2 +host_vendors = AuthenticAMD +needs = +drop_flags = avx512_vp2intersect avx_vnni movdiri movdir64b avx512f avx512dq avx512ifma avx512cd avx512bw avx512vl avx512_bf16 avx512vbmi avx512_vbmi2 gfni avx512_vnni avx512_bitalg avx512_vpopcntdq pku ospke vaes vpclmulqdq +rule = replace 0x1 0 0 0x00830F10 +rule = replace 0x80000001 0 0 0x00830F10 +rule = clear 0x7 0 1 0xd0230814 +rule = clear 0x7 0 2 0x3a005ff2 +rule = clear 0x7 0 3 0x03c54120 +rule = clear 0x7 1 0 0x00e000bf +rule = clear 0x7 1 3 0x0020c530 +rule = clear 0x14 0 1 0x00000010 +rule = clear 0x19 0 1 0x00000004 +rule = clear 0x80000001 0 2 0x00218800 +rule = clear 0x80000001 0 3 0x80000000 + +[x86_64/amd/zen3] +arch = x86_64 +vendor = AuthenticAMD +family = 25 +model = 1 +model_name = AMD EPYC-Milan (eb-local mask) +gcc_march = znver3 +host_vendors = AuthenticAMD +needs = +drop_flags = avx512_vp2intersect avx_vnni movdiri movdir64b avx512f avx512dq avx512ifma avx512cd avx512bw avx512vl avx512_bf16 avx512vbmi avx512_vbmi2 gfni avx512_vnni avx512_bitalg avx512_vpopcntdq +rule = replace 0x1 0 0 0x00A00F11 +rule = replace 0x80000001 0 0 0x00A00F11 +rule = clear 0x7 0 1 0xd0230814 +rule = clear 0x7 0 2 0x3a0059e2 +rule = clear 0x7 0 3 0x03c54120 +rule = clear 0x7 1 0 0x00e000bf +rule = clear 0x7 1 3 0x0020c530 +rule = clear 0x14 0 1 0x00000010 +rule = clear 0x19 0 1 0x00000004 +rule = clear 0x80000001 0 2 0x00218800 +rule = clear 0x80000001 0 3 0x80000000 + +[x86_64/amd/zen4] +arch = x86_64 +vendor = AuthenticAMD +family = 25 +model = 17 +model_name = AMD EPYC-Genoa (eb-local mask) +gcc_march = znver4 +host_vendors = AuthenticAMD +needs = avx512f avx512_bf16 +drop_flags = avx512_vp2intersect avx_vnni movdiri movdir64b +rule = replace 0x1 0 0 0x00A10F11 +rule = replace 0x80000001 0 0 0x00A10F11 +rule = clear 0x7 0 1 0x00000814 +rule = clear 0x7 0 2 0x3a0000a0 +rule = clear 0x7 0 3 0x03c54120 +rule = clear 0x7 1 0 0x00e0009f +rule = clear 0x7 1 3 0x0020c530 +rule = clear 0x14 0 1 0x00000010 +rule = clear 0x19 0 1 0x00000004 +rule = clear 0x80000001 0 2 0x20218800 +rule = clear 0x80000001 0 3 0x80000000 + +[x86_64/intel/skylake_avx512] +arch = x86_64 +vendor = GenuineIntel +family = 6 +model = 85 +model_name = Intel Xeon Skylake-SP (eb-local mask) +gcc_march = skylake-avx512 +host_vendors = AuthenticAMD GenuineIntel +needs = avx512f +drop_flags = avx512_vp2intersect avx_vnni movdiri movdir64b avx512_bf16 sse4a misalignsse clzero mwaitx rdpru avx512ifma avx512vbmi avx512_vbmi2 avx512_vnni avx512_bitalg avx512_vpopcntdq gfni vaes vpclmulqdq sha_ni wbnoinvd rdpid +rule = replace 0x0 0 1 0x756e6547 +rule = replace 0x0 0 3 0x49656e69 +rule = replace 0x0 0 2 0x6c65746e +rule = replace 0x80000000 0 1 0x00000000 +rule = replace 0x80000000 0 2 0x00000000 +rule = replace 0x80000000 0 3 0x00000000 +rule = replace 0x80000001 0 0 0x00000000 +rule = replace 0x1 0 0 0x00050654 +rule = clear 0x7 0 1 0x20200800 +rule = clear 0x7 0 2 0x3a405fe2 +rule = clear 0x7 0 3 0x03c54120 +rule = clear 0x7 1 0 0x00e000bf +rule = clear 0x7 1 3 0x0020c530 +rule = clear 0x14 0 1 0x00000010 +rule = clear 0x19 0 1 0x00000004 +rule = clear 0x80000001 0 2 0x20218840 +rule = clear 0x80000001 0 3 0x80000000 +rule = clear 0x80000008 0 1 0x00000201 + +[x86_64/intel/cascadelake] +arch = x86_64 +vendor = GenuineIntel +family = 6 +model = 85 +model_name = Intel Xeon Cascade Lake-SP (eb-local mask) +gcc_march = cascadelake +host_vendors = AuthenticAMD GenuineIntel +needs = avx512_vnni +drop_flags = avx512_vp2intersect avx_vnni movdiri movdir64b avx512_bf16 sse4a misalignsse clzero mwaitx rdpru avx512ifma avx512vbmi avx512_vbmi2 avx512_bitalg avx512_vpopcntdq gfni vaes vpclmulqdq sha_ni wbnoinvd rdpid +rule = replace 0x0 0 1 0x756e6547 +rule = replace 0x0 0 3 0x49656e69 +rule = replace 0x0 0 2 0x6c65746e +rule = replace 0x80000000 0 1 0x00000000 +rule = replace 0x80000000 0 2 0x00000000 +rule = replace 0x80000000 0 3 0x00000000 +rule = replace 0x80000001 0 0 0x00000000 +rule = replace 0x1 0 0 0x00050657 +rule = clear 0x7 0 1 0x20200800 +rule = clear 0x7 0 2 0x3a4057e2 +rule = clear 0x7 0 3 0x03c54120 +rule = clear 0x7 1 0 0x00e000bf +rule = clear 0x7 1 3 0x0020c530 +rule = clear 0x14 0 1 0x00000010 +rule = clear 0x19 0 1 0x00000004 +rule = clear 0x80000001 0 2 0x20218840 +rule = clear 0x80000001 0 3 0x80000000 +rule = clear 0x80000008 0 1 0x00000201 + +[x86_64/intel/icelake] +arch = x86_64 +vendor = GenuineIntel +family = 6 +model = 106 +model_name = Intel Xeon Ice Lake-SP (eb-local mask) +gcc_march = icelake-server +host_vendors = AuthenticAMD GenuineIntel +needs = avx512_vbmi2 +drop_flags = avx512_vp2intersect avx_vnni movdiri movdir64b avx512_bf16 sse4a misalignsse clzero mwaitx rdpru +rule = replace 0x0 0 1 0x756e6547 +rule = replace 0x0 0 3 0x49656e69 +rule = replace 0x0 0 2 0x6c65746e +rule = replace 0x80000000 0 1 0x00000000 +rule = replace 0x80000000 0 2 0x00000000 +rule = replace 0x80000000 0 3 0x00000000 +rule = replace 0x80000001 0 0 0x00000000 +rule = replace 0x1 0 0 0x000606A6 +rule = clear 0x7 0 1 0x00000814 +rule = clear 0x7 0 2 0x3a0000a0 +rule = clear 0x7 0 3 0x03c54120 +rule = clear 0x7 1 0 0x00e000bf +rule = clear 0x7 1 3 0x0020c530 +rule = clear 0x14 0 1 0x00000010 +rule = clear 0x19 0 1 0x00000004 +rule = clear 0x80000001 0 2 0x20218840 +rule = clear 0x80000001 0 3 0x80000000 +rule = clear 0x80000008 0 1 0x00000001 + +[x86_64/intel/sapphirerapids] +arch = x86_64 +vendor = GenuineIntel +family = 6 +model = 143 +model_name = Intel Xeon Sapphire Rapids (eb-local mask) +gcc_march = sapphirerapids +host_vendors = AuthenticAMD GenuineIntel +needs = avx512_fp16 amx_tile amx_int8 amx_bf16 +drop_flags = avx512_vp2intersect sse4a misalignsse clzero mwaitx rdpru +rule = replace 0x0 0 1 0x756e6547 +rule = replace 0x0 0 3 0x49656e69 +rule = replace 0x0 0 2 0x6c65746e +rule = replace 0x80000000 0 1 0x00000000 +rule = replace 0x80000000 0 2 0x00000000 +rule = replace 0x80000000 0 3 0x00000000 +rule = replace 0x80000001 0 0 0x00000000 +rule = replace 0x1 0 0 0x000806F8 +rule = clear 0x7 0 1 0x00000814 +rule = clear 0x7 0 2 0x20000080 +rule = clear 0x7 0 3 0x00050120 +rule = clear 0x7 1 0 0x00e0008f +rule = clear 0x7 1 3 0x0020c530 +rule = clear 0x14 0 1 0x00000010 +rule = clear 0x19 0 1 0x00000004 +rule = clear 0x80000001 0 2 0x20218840 +rule = clear 0x80000001 0 3 0x80000000 +rule = clear 0x80000008 0 1 0x00000001 + +[aarch64/neoverse_n1] +arch = aarch64 +cpu_part = 0xd0c +gcc_cpu = neoverse-n1 +features = fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm lrcpc dcpop asimddp ssbs +hwcap = 0x10119fff +hwcap2 = 0x0 + +[aarch64/generic] +arch = aarch64 +cpu_part = 0xd07 +gcc_cpu = cortex-a57 +features = fp asimd evtstrm cpuid +hwcap = 0x807 +hwcap2 = 0x0 diff --git a/src/cpumask.zig b/src/cpumask.zig new file mode 100644 index 00000000..e8096722 --- /dev/null +++ b/src/cpumask.zig @@ -0,0 +1,1066 @@ +//! `eb-local --cpu-target`: build for another CPU target on this machine. +//! +//! The target is an EESSI software subdirectory. A build for it runs in one of +//! four routes: `native` (the host already is the target), `cpuid` (the host +//! CPU shows the target's identity to every child process: CPUID faulting on +//! x86_64, a masked `getauxval` and `/proc/cpuinfo` on aarch64), `kvm` and +//! `tcg` (a virtual machine, run by `eb-local __vm-run`). This file holds the +//! target and profile data, the route choice, the preflight decision, the +//! files of the cpuid route and the provenance record. The process handling +//! stays in main.zig. +const std = @import("std"); +const builtin = @import("builtin"); +const linux = std.os.linux; +const common = @import("zig_common"); +const sys = common.sys; +const fsx = common.fsx; +const proc = common.proc; +const Allocator = std.mem.Allocator; + +/// Profile data, generated by tools/mask/gen_profiles.py. +const profiles_text = @embedFile("mask_profiles"); +/// The preloaded libraries and the probe, compiled with the host's cc. +const cpuidmask_c = @embedFile("mask_cpuidmask_c"); +const armmask_c = @embedFile("mask_armmask_c"); +const probe_c = @embedFile("mask_probe_c"); +/// EasyBuild hooks that chain the site's and pin the GROMACS SIMD level. +pub const hooks_py = @embedFile("mask_hooks_py"); + +/// The exit status of a process that cpuidmask stopped because the kernel has +/// no CPUID faulting and CPUIDMASK_STRICT is set. +pub const strict_exit: u8 = 97; + +/// The architectures a CPU target can have. +pub const Arch = enum { + x86_64, + aarch64, + + /// The architecture this program runs on, null when it has no profile. + pub fn host() ?Arch { + return switch (builtin.cpu.arch) { + .x86_64 => .x86_64, + .aarch64 => .aarch64, + else => null, + }; + } +}; + +// ---- targets -------------------------------------------------------------- + +/// The EESSI subdirectories eb-local knows by name. A short name resolves +/// when it is the last component of exactly one of them. +pub const known_subdirs = [_][]const u8{ + "x86_64/generic", + "x86_64/amd/zen2", + "x86_64/amd/zen3", + "x86_64/amd/zen4", + "x86_64/amd/zen5", + "x86_64/intel/haswell", + "x86_64/intel/skylake_avx512", + "x86_64/intel/cascadelake", + "x86_64/intel/icelake", + "x86_64/intel/sapphirerapids", + "aarch64/generic", + "aarch64/neoverse_n1", + "aarch64/neoverse_n2", + "aarch64/neoverse_v1", + "aarch64/google/axion", + "aarch64/nvidia/grace", + "aarch64/a64fx", +}; + +/// What a `--cpu-target` word names. +pub const Resolved = union(enum) { + subdir: []const u8, + /// A message for the user. + refused: []const u8, +}; + +/// The subdirectory `text` names: a full subdirectory, or a short name that +/// one known subdirectory ends in. +pub fn resolveTarget(a: Allocator, text: []const u8) Resolved { + const t = std.mem.trimEnd(u8, text, "/"); + if (t.len == 0) return .{ .refused = "--cpu-target needs a CPU target such as x86_64/amd/zen4 or zen4" }; + for (t) |ch| if (!(std.ascii.isAlphanumeric(ch) or ch == '/' or ch == '_' or ch == '-' or ch == '.')) + return .{ .refused = "a CPU target holds letters, digits, '/', '_', '-' and '.' only" }; + for (known_subdirs) |k| if (std.mem.eql(u8, k, t)) return .{ .subdir = k }; + if (std.mem.indexOfScalar(u8, t, '/') != null) { + if (std.mem.startsWith(u8, t, "x86_64/") or std.mem.startsWith(u8, t, "aarch64/")) + return .{ .subdir = t }; + return .{ .refused = std.fmt.allocPrint(a, "'{s}' is not an EESSI CPU target; it starts with x86_64/ or aarch64/", .{t}) catch "unknown CPU target" }; + } + var found: ?[]const u8 = null; + var count: usize = 0; + for (known_subdirs) |k| if (std.mem.eql(u8, std.fs.path.basename(k), t)) { + found = k; + count += 1; + }; + if (count == 1) return .{ .subdir = found.? }; + if (count > 1) return .{ .refused = std.fmt.allocPrint(a, "'{s}' names more than one CPU target; give the architecture too, as x86_64/{s} or aarch64/{s}", .{ t, t, t }) catch "ambiguous CPU target" }; + return .{ .refused = std.fmt.allocPrint(a, "'{s}' is not a CPU target eb-local knows; give the EESSI subdirectory, for example x86_64/amd/zen4", .{t}) catch "unknown CPU target" }; +} + +/// The architecture a subdirectory is for. +pub fn archOf(subdir: []const u8) ?Arch { + const slash = std.mem.indexOfScalar(u8, subdir, '/') orelse return null; + return std.meta.stringToEnum(Arch, subdir[0..slash]); +} + +// ---- profiles ------------------------------------------------------------- + +/// One target's identity, as `profiles.conf` records it. +pub const Profile = struct { + subdir: []const u8, + arch: Arch, + vendor: []const u8 = "", + family: u32 = 0, + model: u32 = 0, + model_name: []const u8 = "", + gcc_march: []const u8 = "", + host_vendors: []const []const u8 = &.{}, + needs: []const []const u8 = &.{}, + drop_flags: []const []const u8 = &.{}, + rules: []const []const u8 = &.{}, + cpu_part: []const u8 = "", + gcc_cpu: []const u8 = "", + features: []const []const u8 = &.{}, + hwcap: []const u8 = "0x0", + hwcap2: []const u8 = "0x0", +}; + +fn words(a: Allocator, text: []const u8) []const []const u8 { + var out: std.ArrayList([]const u8) = .empty; + var it = std.mem.tokenizeAny(u8, text, " \t"); + while (it.next()) |w| out.append(a, w) catch @panic("out of memory"); + return out.items; +} + +/// The profiles in `text`, in file order. +pub fn parseProfiles(a: Allocator, text: []const u8) []Profile { + var out: std.ArrayList(Profile) = .empty; + var rules: std.ArrayList([]const u8) = .empty; + var cur: ?Profile = null; + var lines = std.mem.splitScalar(u8, text, '\n'); + while (lines.next()) |raw| { + const line = std.mem.trim(u8, raw, " \t\r"); + if (line.len == 0 or line[0] == '#') continue; + if (line[0] == '[' and line[line.len - 1] == ']') { + if (cur) |*p| { + p.rules = rules.toOwnedSlice(a) catch @panic("out of memory"); + out.append(a, p.*) catch @panic("out of memory"); + } + cur = .{ .subdir = line[1 .. line.len - 1], .arch = .x86_64 }; + continue; + } + const p = &(cur orelse continue); + const eq = std.mem.indexOfScalar(u8, line, '=') orelse continue; + const key = std.mem.trim(u8, line[0..eq], " \t"); + const val = std.mem.trim(u8, line[eq + 1 ..], " \t"); + if (std.mem.eql(u8, key, "arch")) { + p.arch = std.meta.stringToEnum(Arch, val) orelse .x86_64; + } else if (std.mem.eql(u8, key, "vendor")) { + p.vendor = val; + } else if (std.mem.eql(u8, key, "family")) { + p.family = std.fmt.parseInt(u32, val, 10) catch 0; + } else if (std.mem.eql(u8, key, "model")) { + p.model = std.fmt.parseInt(u32, val, 10) catch 0; + } else if (std.mem.eql(u8, key, "model_name")) { + p.model_name = val; + } else if (std.mem.eql(u8, key, "gcc_march")) { + p.gcc_march = val; + } else if (std.mem.eql(u8, key, "host_vendors")) { + p.host_vendors = words(a, val); + } else if (std.mem.eql(u8, key, "needs")) { + p.needs = words(a, val); + } else if (std.mem.eql(u8, key, "drop_flags")) { + p.drop_flags = words(a, val); + } else if (std.mem.eql(u8, key, "rule")) { + rules.append(a, val) catch @panic("out of memory"); + } else if (std.mem.eql(u8, key, "cpu_part")) { + p.cpu_part = val; + } else if (std.mem.eql(u8, key, "gcc_cpu")) { + p.gcc_cpu = val; + } else if (std.mem.eql(u8, key, "features")) { + p.features = words(a, val); + } else if (std.mem.eql(u8, key, "hwcap")) { + p.hwcap = val; + } else if (std.mem.eql(u8, key, "hwcap2")) { + p.hwcap2 = val; + } + } + if (cur) |*p| { + p.rules = rules.toOwnedSlice(a) catch @panic("out of memory"); + out.append(a, p.*) catch @panic("out of memory"); + } + return out.items; +} + +/// The profiles that ship with eb-local. +pub fn builtinProfiles(a: Allocator) []Profile { + return parseProfiles(a, profiles_text); +} + +/// The profile for `subdir`, or null. +pub fn findProfile(profiles: []const Profile, subdir: []const u8) ?Profile { + for (profiles) |p| if (std.mem.eql(u8, p.subdir, subdir)) return p; + return null; +} + +/// The rule lines of `p` as cpuidmask reads them from CPUIDMASK_RULES. +pub fn rulesFile(a: Allocator, p: Profile) []const u8 { + var out: std.ArrayList(u8) = .empty; + for (p.rules) |r| { + out.appendSlice(a, r) catch @panic("out of memory"); + out.append(a, '\n') catch @panic("out of memory"); + } + return out.items; +} + +// ---- the masked /proc/cpuinfo -------------------------------------------- + +fn hasWord(list: []const []const u8, w: []const u8) bool { + for (list) |x| if (std.mem.eql(u8, x, w)) return true; + return false; +} + +/// `host`, the text of /proc/cpuinfo, as it reads on the target: the +/// identity fields of `p`, and without the flags `p` drops. Lines that name +/// nothing the profile changes stay as they are. +pub fn maskedCpuinfo(a: Allocator, p: Profile, host: []const u8) []const u8 { + var out: std.ArrayList(u8) = .empty; + var lines = std.mem.splitScalar(u8, host, '\n'); + var first = true; + while (lines.next()) |line| { + if (!first) out.append(a, '\n') catch @panic("out of memory"); + first = false; + const colon = std.mem.indexOfScalar(u8, line, ':') orelse { + out.appendSlice(a, line) catch @panic("out of memory"); + continue; + }; + const key = std.mem.trim(u8, line[0..colon], " \t"); + const head = line[0 .. colon + 1]; + const value = std.mem.trim(u8, line[colon + 1 ..], " \t"); + var replaced: ?[]const u8 = null; + switch (p.arch) { + .x86_64 => { + if (std.mem.eql(u8, key, "vendor_id")) { + replaced = p.vendor; + } else if (std.mem.eql(u8, key, "cpu family")) { + replaced = std.fmt.allocPrint(a, "{d}", .{p.family}) catch @panic("out of memory"); + } else if (std.mem.eql(u8, key, "model")) { + replaced = std.fmt.allocPrint(a, "{d}", .{p.model}) catch @panic("out of memory"); + } else if (std.mem.eql(u8, key, "model name")) { + replaced = p.model_name; + } else if (std.mem.eql(u8, key, "flags")) { + var kept: std.ArrayList(u8) = .empty; + var it = std.mem.tokenizeScalar(u8, value, ' '); + while (it.next()) |f| { + if (hasWord(p.drop_flags, f)) continue; + if (kept.items.len > 0) kept.append(a, ' ') catch @panic("out of memory"); + kept.appendSlice(a, f) catch @panic("out of memory"); + } + replaced = kept.items; + } + }, + .aarch64 => { + if (std.mem.eql(u8, key, "Features")) { + replaced = std.mem.join(a, " ", p.features) catch @panic("out of memory"); + } else if (std.mem.eql(u8, key, "CPU part")) { + replaced = p.cpu_part; + } + }, + } + out.appendSlice(a, head) catch @panic("out of memory"); + if (replaced) |r| { + out.append(a, ' ') catch @panic("out of memory"); + out.appendSlice(a, r) catch @panic("out of memory"); + } else out.appendSlice(a, line[colon + 1 ..]) catch @panic("out of memory"); + } + return out.items; +} + +// ---- routes --------------------------------------------------------------- + +/// What `--mask` asks for. +pub const Mode = enum { auto, cpuid, kvm, tcg }; + +/// How the build runs. +pub const Route = enum { native, cpuid, kvm, tcg }; + +/// What the choice of a route needs to know about this machine. +pub const Host = struct { + arch: Arch, + /// vendor_id of an x86_64 CPU, empty on aarch64. + vendor: []const u8 = "", + /// The `flags` (x86_64) or `Features` (aarch64) line of /proc/cpuinfo. + flags: []const u8 = "", + /// The EESSI subdirectory of this host, when it could be detected. + subdir: ?[]const u8 = null, + /// CPUID faulting works (x86_64). + faulting: bool = false, + /// /dev/kvm is usable. + kvm: bool = false, + /// `eb-local __vm-run` exists in this binary. + vm_helper: bool = false, +}; + +/// The outcome of the route choice. +pub const Choice = union(enum) { + route: Route, + /// The message for the user. + refuse: []const u8, +}; + +fn fmt(a: Allocator, comptime f: []const u8, args: anytype) []const u8 { + return std.fmt.allocPrint(a, f, args) catch @panic("out of memory"); +} + +fn hostHasFlag(flags: []const u8, flag: []const u8) bool { + var it = std.mem.tokenizeScalar(u8, flags, ' '); + while (it.next()) |f| if (std.mem.eql(u8, f, flag)) return true; + return false; +} + +/// Why the cpuid route cannot present `target` on `host`, or null when it can. +pub fn cpuidProblem(a: Allocator, target: []const u8, profile: ?Profile, host: Host) ?[]const u8 { + const p = profile orelse return fmt(a, "no mask profile exists for {s}", .{target}); + if (p.arch != host.arch) + return fmt(a, "the cpuid route presents a CPU of this machine's architecture ({s}), not {s}", .{ @tagName(host.arch), @tagName(p.arch) }); + if (p.arch == .x86_64) { + if (!host.faulting) + return "CPUID faulting is not available here (Intel CPUs have it with Linux 4.12 and later, AMD CPUs with Linux 6.17 and later)"; + var allowed = false; + for (p.host_vendors) |v| if (std.mem.eql(u8, v, host.vendor)) { + allowed = true; + }; + if (!allowed) return fmt(a, "the {s} profile cannot be shown on a {s} CPU", .{ target, host.vendor }); + } + for (p.needs) |flag| if (!hostHasFlag(host.flags, flag)) + return fmt(a, "this CPU lacks {s}, which {s} has and a mask cannot add", .{ flag, target }); + return null; +} + +/// The route for `target`. The target the host already is needs no mask. +pub fn choose(a: Allocator, mode: Mode, target: []const u8, profile: ?Profile, host: Host) Choice { + if (host.subdir) |h| if (std.mem.eql(u8, h, target)) return .{ .route = .native }; + const arch = archOf(target) orelse return .{ .refuse = "the CPU target names no architecture" }; + const helper_missing = "this build of eb-local has no `__vm-run` helper, which the kvm and tcg routes call"; + switch (mode) { + .cpuid => { + if (cpuidProblem(a, target, profile, host)) |why| return .{ .refuse = why }; + return .{ .route = .cpuid }; + }, + .kvm => { + if (arch != host.arch) return .{ .refuse = fmt(a, "kvm runs a CPU of this machine's architecture ({s}); {s} is {s}; use --mask tcg", .{ @tagName(host.arch), target, @tagName(arch) }) }; + if (!host.vm_helper) return .{ .refuse = helper_missing }; + if (!host.kvm) return .{ .refuse = "/dev/kvm is not usable by this user" }; + return .{ .route = .kvm }; + }, + .tcg => { + if (!host.vm_helper) return .{ .refuse = helper_missing }; + return .{ .route = .tcg }; + }, + .auto => { + if (arch != host.arch) { + if (!host.vm_helper) return .{ .refuse = fmt(a, "{s} is another architecture than this machine ({s}), which only the tcg route reaches, and {s}", .{ target, @tagName(host.arch), helper_missing }) }; + return .{ .route = .tcg }; + } + const why = cpuidProblem(a, target, profile, host) orelse return .{ .route = .cpuid }; + if (host.kvm and host.vm_helper) return .{ .route = .kvm }; + return .{ .refuse = fmt(a, "cannot present {s} here: {s}; kvm is {s}. --mask tcg emulates it, slowly", .{ + target, + why, + if (!host.vm_helper) "not built into this eb-local" else "not usable (/dev/kvm)", + }) }; + }, + } +} + +// ---- preflight ------------------------------------------------------------ + +/// What the build script saw inside the mask. A null field was not +/// observable: the tool is missing. +pub const Observed = struct { + devfd: bool, + /// The output of `eessi_archdetect.sh cpupath`: subdirectories separated by ':'. + archdetect: ?[]const u8 = null, + /// What archspec names the host, null when it cannot be imported. + archspec: ?[]const u8 = null, + /// The -march (x86_64) or -mcpu (aarch64) value of `gcc -march=native`. + gcc: ?[]const u8 = null, + /// The CPUID vendor string of a probe run in the mask. + vendor: ?[]const u8 = null, + /// Whether CPUID faulting is active in the probe. + faulting: ?bool = null, +}; + +/// One preflight check and what it found. +pub const Finding = struct { ok: bool, text: []const u8 }; + +/// The names archspec gives the targets whose archspec name differs from the +/// last component of the subdirectory. +fn archspecName(subdir: []const u8) []const u8 { + if (std.mem.eql(u8, subdir, "aarch64/generic")) return "aarch64"; + if (std.mem.eql(u8, subdir, "x86_64/generic")) return "x86_64"; + return std.fs.path.basename(subdir); +} + +/// Compare what the detectors report with `p`. Every detector must name the +/// target; a build that goes on with one that does not would install a tree +/// labelled for one CPU and compiled for another. +pub fn preflight(a: Allocator, p: Profile, route: Route, obs: Observed) []const Finding { + var out: std.ArrayList(Finding) = .empty; + const add = struct { + fn f(list: *std.ArrayList(Finding), al: Allocator, ok: bool, comptime tmpl: []const u8, args: anytype) void { + list.append(al, .{ .ok = ok, .text = fmt(al, tmpl, args) }) catch @panic("out of memory"); + } + }.f; + if (obs.devfd) { + add(&out, a, true, "/dev/fd exists", .{}); + } else add(&out, a, false, "/dev/fd is missing, so EESSI archdetect fails on its process substitution and EESSI falls back to the generic target", .{}); + if (obs.archdetect) |ad| { + const first = ad[0 .. std.mem.indexOfScalar(u8, ad, ':') orelse ad.len]; + const trimmed = std.mem.trim(u8, first, " \t\r\n"); + if (std.mem.eql(u8, trimmed, p.subdir)) { + add(&out, a, true, "EESSI archdetect names {s}", .{p.subdir}); + } else add(&out, a, false, "EESSI archdetect names '{s}', not {s}", .{ trimmed, p.subdir }); + } else add(&out, a, false, "EESSI archdetect gave no answer", .{}); + if (obs.archspec) |sp| { + const want = archspecName(p.subdir); + if (std.mem.eql(u8, sp, want)) { + add(&out, a, true, "archspec names {s}", .{want}); + } else add(&out, a, false, "archspec names '{s}', not {s}; an easyblock that asks archspec would build for another CPU than the tree is labelled for", .{ sp, want }); + } else add(&out, a, true, "archspec is not importable here; not checked", .{}); + const want_gcc = if (p.arch == .x86_64) p.gcc_march else p.gcc_cpu; + const gcc_what = if (p.arch == .x86_64) "-march" else "-mcpu"; + if (obs.gcc) |g| { + if (std.mem.eql(u8, g, want_gcc)) { + add(&out, a, true, "gcc {s}=native is {s}", .{ gcc_what, want_gcc }); + } else add(&out, a, false, "gcc {s}=native is '{s}', not {s}", .{ gcc_what, g, want_gcc }); + } else add(&out, a, false, "gcc gave no {s}=native value", .{gcc_what}); + if (p.arch == .x86_64) { + if (obs.vendor) |v| { + if (std.mem.eql(u8, v, p.vendor)) { + add(&out, a, true, "CPUID vendor is {s}", .{p.vendor}); + } else add(&out, a, false, "CPUID vendor is '{s}', not {s}", .{ v, p.vendor }); + } else add(&out, a, false, "the CPUID probe gave no answer", .{}); + if (route == .cpuid) { + if (obs.faulting) |f| { + if (f) { + add(&out, a, true, "CPUID faulting is active", .{}); + } else add(&out, a, false, "CPUID faulting is not active in the build; every CPUID would see the real CPU", .{}); + } else add(&out, a, false, "the probe did not say whether CPUID faulting is active", .{}); + } + } + return out.items; +} + +/// Whether any finding refuses the build. +pub fn refused(findings: []const Finding) bool { + for (findings) |f| if (!f.ok) return true; + return false; +} + +// ---- host facts ----------------------------------------------------------- + +/// The first value of `key` in /proc/cpuinfo text. +pub fn cpuinfoField(text: []const u8, key: []const u8) ?[]const u8 { + var lines = std.mem.splitScalar(u8, text, '\n'); + while (lines.next()) |line| { + const colon = std.mem.indexOfScalar(u8, line, ':') orelse continue; + if (!std.mem.eql(u8, std.mem.trim(u8, line[0..colon], " \t"), key)) continue; + return std.mem.trim(u8, line[colon + 1 ..], " \t"); + } + return null; +} + +/// Whether the kernel lets this process turn on CPUID faulting. +pub fn faultingAvailable() bool { + if (builtin.cpu.arch != .x86_64) return false; + const set_cpuid = 0x1012; + if (linux.errno(linux.syscall2(.arch_prctl, set_cpuid, 0)) != .SUCCESS) return false; + _ = linux.syscall2(.arch_prctl, set_cpuid, 1); + return true; +} + +/// Whether /dev/kvm can be opened for reading and writing. +pub fn kvmUsable() bool { + return linux.errno(linux.faccessat(linux.AT.FDCWD, "/dev/kvm", linux.R_OK | linux.W_OK, 0)) == .SUCCESS; +} + +/// The first `limit` bytes of the regular file `path`, or null. +pub fn readFile(a: Allocator, path: []const u8, limit: usize) ?[]const u8 { + const f = fsx.openRegular(fsx.cwd, path, true) catch return null; + defer sys.close(f.fd); + return fsx.readAll(a, f.fd, limit) catch null; +} + +/// This machine as the route choice sees it. `subdir` is the detected EESSI +/// subdirectory of the host, `vm_helper` whether `__vm-run` exists. +pub fn readHost(a: Allocator, subdir: ?[]const u8, vm_helper: bool) ?Host { + const arch = Arch.host() orelse return null; + const text = readFile(a, "/proc/cpuinfo", 4 << 20) orelse ""; + return .{ + .arch = arch, + .vendor = cpuinfoField(text, "vendor_id") orelse "", + .flags = cpuinfoField(text, if (arch == .x86_64) "flags" else "Features") orelse "", + .subdir = subdir, + .faulting = faultingAvailable(), + .kvm = kvmUsable(), + .vm_helper = vm_helper, + }; +} + +/// A one-line name of the host CPU, for the provenance record. +pub fn hostModel(a: Allocator) []const u8 { + const text = readFile(a, "/proc/cpuinfo", 4 << 20) orelse return "unknown"; + if (cpuinfoField(text, "model name")) |m| return m; + if (cpuinfoField(text, "Model")) |m| return m; + if (cpuinfoField(text, "CPU part")) |m| return fmt(a, "aarch64 CPU part {s}", .{m}); + return "unknown"; +} + +/// The running kernel's release, from /proc/sys/kernel/osrelease. +pub fn kernelRelease(a: Allocator) []const u8 { + const text = readFile(a, "/proc/sys/kernel/osrelease", 256) orelse return "unknown"; + return std.mem.trim(u8, text, " \t\r\n"); +} + +// ---- the compiled preload libraries -------------------------------------- + +/// The compiled preload library and probe. +pub const Libs = struct { + /// The preload library for the host architecture. + preload: []const u8, + probe: []const u8, + dir: []const u8, +}; + +fn runText(a: Allocator, envp: proc.Envp, argv: []const []const u8, path_env: []const u8) ?[]const u8 { + const exe = (proc.which(a, argv[0], path_env) catch null) orelse return null; + const r = proc.run(a, exe, argv, envp, .{ .stdout_limit = 4096, .timeout_ms = 20_000 }) catch return null; + if (r.term.code() != 0) return null; + return std.mem.trim(u8, r.stdout, " \t\r\n"); +} + +fn writeNew(a: Allocator, path: []const u8, bytes: []const u8, mode: linux.mode_t) !void { + const tmp = try std.fmt.allocPrint(a, "{s}.tmp.{d}", .{ path, linux.getpid() }); + const fd = try sys.openat(fsx.cwd, tmp, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true, .NOFOLLOW = true }, mode); + var done = false; + defer { + sys.close(fd); + if (!done) sys.unlinkat(fsx.cwd, tmp, 0) catch {}; + } + try sys.writeAll(fd, bytes); + try sys.renameat(fsx.cwd, tmp, fsx.cwd, path); + done = true; +} + +/// The cache key of the compiled libraries: the sources, the compiler's target +/// triple and the C library's version. A library built against one glibc does +/// not load into every other. +pub fn cacheKey(a: Allocator, triple: []const u8, libc: []const u8) []const u8 { + var h = std.crypto.hash.sha2.Sha256.init(.{}); + for ([_][]const u8{ cpuidmask_c, armmask_c, probe_c, triple, libc }) |part| { + h.update(part); + h.update("\x00"); + } + var digest: [32]u8 = undefined; + h.final(&digest); + return fmt(a, "{x}", .{digest[0..8]}); +} + +/// The preload library and probe for this host, compiled with the host's cc +/// into `cache_home/eb-local/mask-KEY` on first use. A static binary cannot be +/// preloaded into the dynamically linked programs of a build, so the library +/// is built from the C source embedded here. +pub fn ensureLibs(a: Allocator, envp: proc.Envp, path_env: []const u8, cache_home: []const u8, failure: *[]const u8) ?Libs { + const arch = Arch.host() orelse { + failure.* = "this machine's architecture has no mask library"; + return null; + }; + const triple = runText(a, envp, &.{ "cc", "-dumpmachine" }, path_env) orelse { + failure.* = "no C compiler (cc) on PATH; the cpuid route compiles its preload library with it"; + return null; + }; + const libc = runText(a, envp, &.{ "getconf", "GNU_LIBC_VERSION" }, path_env) orelse "unknown"; + const key = cacheKey(a, triple, libc); + const dir = std.fmt.allocPrint(a, "{s}/eb-local/mask-{s}", .{ cache_home, key }) catch @panic("out of memory"); + const lib_name = if (arch == .x86_64) "libcpuidmask.so" else "libarmmask.so"; + const preload = std.fmt.allocPrint(a, "{s}/{s}", .{ dir, lib_name }) catch @panic("out of memory"); + const probe = std.fmt.allocPrint(a, "{s}/cpuid-probe", .{dir}) catch @panic("out of memory"); + const libs: Libs = .{ .preload = preload, .probe = probe, .dir = dir }; + if (isFile(preload) and isFile(probe)) return libs; + + common.atomic.makedirs(dir) catch |e| { + failure.* = fmt(a, "cannot create {s} ({s})", .{ dir, sys.describe(e) }); + return null; + }; + const cc = (proc.which(a, "cc", path_env) catch null) orelse { + failure.* = "no C compiler (cc) on PATH"; + return null; + }; + const lib_src_name = if (arch == .x86_64) "cpuidmask.c" else "armmask.c"; + const lib_src = if (arch == .x86_64) cpuidmask_c else armmask_c; + const lib_src_path = fmt(a, "{s}/{s}", .{ dir, lib_src_name }); + const probe_src_path = fmt(a, "{s}/cpuid-probe.c", .{dir}); + writeNew(a, lib_src_path, lib_src, 0o600) catch |e| { + failure.* = fmt(a, "cannot write {s} ({s})", .{ lib_src_path, @errorName(e) }); + return null; + }; + writeNew(a, probe_src_path, probe_c, 0o600) catch |e| { + failure.* = fmt(a, "cannot write {s} ({s})", .{ probe_src_path, @errorName(e) }); + return null; + }; + const tmp_lib = fmt(a, "{s}.tmp.{d}", .{ preload, linux.getpid() }); + const tmp_probe = fmt(a, "{s}.tmp.{d}", .{ probe, linux.getpid() }); + const builds = [_][]const []const u8{ + &.{ cc, "-O2", "-shared", "-fPIC", "-o", tmp_lib, lib_src_path, "-ldl" }, + &.{ cc, "-O2", "-o", tmp_probe, probe_src_path }, + }; + for (builds) |argv| { + const r = proc.run(a, cc, argv, envp, .{ .stdout_limit = 4096, .stderr_limit = 8192, .timeout_ms = 120_000 }) catch |e| { + failure.* = fmt(a, "cannot run {s} ({s})", .{ cc, @errorName(e) }); + return null; + }; + if (r.term.code() != 0) { + failure.* = fmt(a, "{s} failed building the mask library:\n{s}", .{ cc, r.stderr }); + return null; + } + } + sys.renameat(fsx.cwd, tmp_lib, fsx.cwd, preload) catch |e| { + failure.* = fmt(a, "cannot install {s} ({s})", .{ preload, sys.describe(e) }); + return null; + }; + sys.renameat(fsx.cwd, tmp_probe, fsx.cwd, probe) catch |e| { + failure.* = fmt(a, "cannot install {s} ({s})", .{ probe, sys.describe(e) }); + return null; + }; + return libs; +} + +fn isFile(path: []const u8) bool { + const st = fsx.statAt(fsx.cwd, path, true) catch return false; + return st.isReg(); +} + +// ---- the command the build runs ------------------------------------------ + +/// The words in front of the build command for the cpuid route: an +/// unprivileged user and mount namespace that keeps the caller's uid (a +/// mapped root makes OpenMPI's prterun refuse to start), with `fake` bound +/// over /proc/cpuinfo. The ambient capabilities the namespace gives are +/// dropped before the command runs when `setpriv` exists. +pub fn namespaceWords(a: Allocator, unshare: []const u8, setpriv: ?[]const u8, fake: []const u8) []const []const u8 { + const script = if (setpriv != null) + "mount --bind \"$0\" /proc/cpuinfo || exit 98; exec \"$1\" --ambient-caps=-all --inh-caps=-all \"${@:2}\"" + else + "mount --bind \"$0\" /proc/cpuinfo || exit 98; exec \"$@\""; + var out: std.ArrayList([]const u8) = .empty; + out.appendSlice(a, &.{ unshare, "--user", "--map-current-user", "--keep-caps", "--mount", "--propagation", "slave", "bash", "-c", script, fake }) catch @panic("out of memory"); + if (setpriv) |s| out.append(a, s) catch @panic("out of memory"); + return out.items; +} + +/// The variables the masked command gets. +pub fn maskVariables(a: Allocator, p: Profile, libs: Libs, rules_path: []const u8, hooks_path: []const u8, self_exe: []const u8, route: Route) []const [2][]const u8 { + var out: std.ArrayList([2][]const u8) = .empty; + const add = struct { + fn f(list: *std.ArrayList([2][]const u8), al: Allocator, k: []const u8, v: []const u8) void { + list.append(al, .{ k, v }) catch @panic("out of memory"); + } + }.f; + add(&out, a, "EB_LOCAL_CPU_TARGET", p.subdir); + add(&out, a, "EB_LOCAL_MASK_ROUTE", @tagName(route)); + add(&out, a, "EB_LOCAL_PROBE", libs.probe); + add(&out, a, "EB_LOCAL_SELF", self_exe); + add(&out, a, "EB_LOCAL_HOOKS_FILE", hooks_path); + add(&out, a, "EESSI_SOFTWARE_SUBDIR_OVERRIDE", p.subdir); + if (route == .cpuid) { + add(&out, a, "LD_PRELOAD", libs.preload); + if (p.arch == .x86_64) { + add(&out, a, "CPUIDMASK_RULES", rules_path); + add(&out, a, "CPUIDMASK_STRICT", "1"); + } else { + add(&out, a, "ARMMASK_HWCAP", p.hwcap); + add(&out, a, "ARMMASK_HWCAP2", p.hwcap2); + } + } + return out.items; +} + +// ---- provenance ----------------------------------------------------------- + +fn jsonString(a: Allocator, out: *std.ArrayList(u8), s: []const u8) void { + out.append(a, '"') catch @panic("out of memory"); + for (s) |ch| switch (ch) { + '"' => out.appendSlice(a, "\\\"") catch @panic("out of memory"), + '\\' => out.appendSlice(a, "\\\\") catch @panic("out of memory"), + '\n' => out.appendSlice(a, "\\n") catch @panic("out of memory"), + 0...9, 11...31 => out.print(a, "\\u{x:0>4}", .{ch}) catch @panic("out of memory"), + else => out.append(a, ch) catch @panic("out of memory"), + }; + out.append(a, '"') catch @panic("out of memory"); +} + +/// What `easybuild/eb-local-build-mode.json` records. +pub const Provenance = struct { + target: []const u8, + route: Route, + /// The profile's subdirectory, empty for a route without one. + profile: []const u8, + host_cpu: []const u8, + kernel: []const u8, + version: []const u8, + /// "pass", "fail" or "skipped". + audit: []const u8, +}; + +/// The text of easybuild/eb-local-build-mode.json. +pub fn provenanceJson(a: Allocator, p: Provenance) []const u8 { + var out: std.ArrayList(u8) = .empty; + out.appendSlice(a, "{\n") catch @panic("out of memory"); + const fields = [_][2][]const u8{ + .{ "cpu_target", p.target }, + .{ "route", @tagName(p.route) }, + .{ "profile", p.profile }, + .{ "host_cpu", p.host_cpu }, + .{ "kernel", p.kernel }, + .{ "eb_local_version", p.version }, + .{ "isa_audit", p.audit }, + }; + for (fields, 0..) |f, i| { + out.appendSlice(a, " ") catch @panic("out of memory"); + jsonString(a, &out, f[0]); + out.appendSlice(a, ": ") catch @panic("out of memory"); + jsonString(a, &out, f[1]); + out.appendSlice(a, if (i + 1 < fields.len) ",\n" else "\n") catch @panic("out of memory"); + } + out.appendSlice(a, "}\n") catch @panic("out of memory"); + return out.items; +} + +/// Write `text` as `dir/name`, replacing what is there. +pub fn writeProvenance(a: Allocator, dir: []const u8, text: []const u8) bool { + const path = fmt(a, "{s}/eb-local-build-mode.json", .{dir}); + writeNew(a, path, text, 0o644) catch return false; + return true; +} + +/// Write `bytes` to `path` with `mode`, replacing what is there. +pub fn writeFile(a: Allocator, path: []const u8, bytes: []const u8, mode: linux.mode_t) bool { + writeNew(a, path, bytes, mode) catch return false; + return true; +} + +// ---- tests ---------------------------------------------------------------- + +const testing = std.testing; + +fn testProfiles(a: Allocator) []Profile { + return builtinProfiles(a); +} + +test "a full subdirectory and a unique short name resolve" { + var arena = std.heap.ArenaAllocator.init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + try testing.expectEqualStrings("x86_64/amd/zen4", resolveTarget(a, "x86_64/amd/zen4").subdir); + try testing.expectEqualStrings("x86_64/amd/zen4", resolveTarget(a, "x86_64/amd/zen4/").subdir); + try testing.expectEqualStrings("x86_64/amd/zen4", resolveTarget(a, "zen4").subdir); + try testing.expectEqualStrings("x86_64/intel/icelake", resolveTarget(a, "icelake").subdir); + try testing.expectEqualStrings("aarch64/neoverse_n1", resolveTarget(a, "neoverse_n1").subdir); + try testing.expectEqualStrings("x86_64/generic", resolveTarget(a, "x86_64/generic").subdir); +} + +test "a short name that two targets share, and unknown names, are refused" { + var arena = std.heap.ArenaAllocator.init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + try testing.expect(std.mem.indexOf(u8, resolveTarget(a, "generic").refused, "more than one") != null); + try testing.expect(resolveTarget(a, "zen9").refused.len > 0); + try testing.expect(resolveTarget(a, "").refused.len > 0); + try testing.expect(resolveTarget(a, "x86_64/amd/zen4; rm").refused.len > 0); + try testing.expect(resolveTarget(a, "riscv64/generic").refused.len > 0); + try testing.expectEqualStrings("x86_64/amd/zen9", resolveTarget(a, "x86_64/amd/zen9").subdir); +} + +test "the shipped profiles parse and cover the supported targets" { + var arena = std.heap.ArenaAllocator.init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const ps = testProfiles(a); + for ([_][]const u8{ "x86_64/amd/zen2", "x86_64/amd/zen3", "x86_64/amd/zen4", "x86_64/intel/skylake_avx512", "x86_64/intel/cascadelake", "x86_64/intel/icelake", "x86_64/intel/sapphirerapids", "aarch64/neoverse_n1", "aarch64/generic" }) |t| + try testing.expect(findProfile(ps, t) != null); + try testing.expect(findProfile(ps, "x86_64/amd/zen5") == null); + const z4 = findProfile(ps, "x86_64/amd/zen4").?; + try testing.expectEqual(Arch.x86_64, z4.arch); + try testing.expectEqual(@as(u32, 25), z4.family); + try testing.expectEqual(@as(u32, 17), z4.model); + try testing.expectEqualStrings("znver4", z4.gcc_march); + try testing.expect(z4.rules.len > 0); + try testing.expect(std.mem.startsWith(u8, z4.rules[0], "replace 0x1 0 0 0x00A10F11")); + const n1 = findProfile(ps, "aarch64/neoverse_n1").?; + try testing.expectEqualStrings("0x10119fff", n1.hwcap); + try testing.expectEqualStrings("neoverse-n1", n1.gcc_cpu); + for (ps) |p| if (p.arch == .x86_64) { + try testing.expect(p.host_vendors.len > 0); + try testing.expect(p.rules.len > 0); + }; +} + +test "the profile rules are the lines cpuidmask reads" { + var arena = std.heap.ArenaAllocator.init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const ice = findProfile(testProfiles(a), "x86_64/intel/icelake").?; + const text = rulesFile(a, ice); + var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, text, "\n"), '\n'); + while (lines.next()) |l| try testing.expect(std.mem.startsWith(u8, l, "clear ") or std.mem.startsWith(u8, l, "replace ")); + try testing.expect(std.mem.indexOf(u8, text, "replace 0x0 0 1 0x756e6547") != null); +} + +fn testHost(h: Host) Host { + return h; +} + +test "the host's own target needs no mask" { + var arena = std.heap.ArenaAllocator.init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const ps = testProfiles(a); + const h = testHost(.{ .arch = .x86_64, .vendor = "AuthenticAMD", .subdir = "x86_64/amd/zen4" }); + const c = choose(a, .auto, "x86_64/amd/zen4", findProfile(ps, "x86_64/amd/zen4"), h); + try testing.expectEqual(Route.native, c.route); + const k = choose(a, .kvm, "x86_64/amd/zen4", findProfile(ps, "x86_64/amd/zen4"), h); + try testing.expectEqual(Route.native, k.route); +} + +test "auto picks cpuid where faulting works" { + var arena = std.heap.ArenaAllocator.init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const ps = testProfiles(a); + const h = testHost(.{ .arch = .x86_64, .vendor = "AuthenticAMD", .flags = "avx512f avx512_bf16 avx512_vbmi2", .subdir = "x86_64/amd/zen5", .faulting = true, .kvm = true, .vm_helper = true }); + try testing.expectEqual(Route.cpuid, choose(a, .auto, "x86_64/amd/zen4", findProfile(ps, "x86_64/amd/zen4"), h).route); + try testing.expectEqual(Route.cpuid, choose(a, .auto, "x86_64/intel/icelake", findProfile(ps, "x86_64/intel/icelake"), h).route); +} + +test "auto falls back to kvm without faulting, and refuses without kvm" { + var arena = std.heap.ArenaAllocator.init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const ps = testProfiles(a); + const p = findProfile(ps, "x86_64/amd/zen4"); + var h = testHost(.{ .arch = .x86_64, .vendor = "AuthenticAMD", .flags = "avx512f avx512_bf16", .subdir = "x86_64/amd/zen5", .faulting = false, .kvm = true, .vm_helper = true }); + try testing.expectEqual(Route.kvm, choose(a, .auto, "x86_64/amd/zen4", p, h).route); + h.kvm = false; + const c = choose(a, .auto, "x86_64/amd/zen4", p, h); + try testing.expect(std.mem.indexOf(u8, c.refuse, "CPUID faulting") != null); + try testing.expect(std.mem.indexOf(u8, c.refuse, "--mask tcg") != null); +} + +test "another architecture is the tcg route" { + var arena = std.heap.ArenaAllocator.init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const ps = testProfiles(a); + var h = testHost(.{ .arch = .x86_64, .vendor = "AuthenticAMD", .subdir = "x86_64/amd/zen5", .faulting = true, .kvm = true, .vm_helper = true }); + try testing.expectEqual(Route.tcg, choose(a, .auto, "aarch64/neoverse_n1", findProfile(ps, "aarch64/neoverse_n1"), h).route); + try testing.expect(choose(a, .kvm, "aarch64/neoverse_n1", null, h).refuse.len > 0); + try testing.expect(choose(a, .cpuid, "aarch64/neoverse_n1", findProfile(ps, "aarch64/neoverse_n1"), h).refuse.len > 0); + h.vm_helper = false; + try testing.expect(std.mem.indexOf(u8, choose(a, .auto, "aarch64/neoverse_n1", null, h).refuse, "__vm-run") != null); + try testing.expect(std.mem.indexOf(u8, choose(a, .tcg, "x86_64/amd/zen4", null, h).refuse, "__vm-run") != null); + try testing.expect(std.mem.indexOf(u8, choose(a, .kvm, "x86_64/amd/zen4", null, h).refuse, "__vm-run") != null); +} + +test "the cpuid route refuses what a mask cannot reach" { + var arena = std.heap.ArenaAllocator.init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const ps = testProfiles(a); + const base: Host = .{ .arch = .x86_64, .vendor = "AuthenticAMD", .flags = "avx512f avx512_bf16", .subdir = "x86_64/amd/zen5", .faulting = true }; + // An AMD profile does not run on an Intel host: the rules keep the vendor string. + var intel = base; + intel.vendor = "GenuineIntel"; + try testing.expect(std.mem.indexOf(u8, choose(a, .cpuid, "x86_64/amd/zen4", findProfile(ps, "x86_64/amd/zen4"), intel).refuse, "GenuineIntel") != null); + // Sapphire Rapids needs flags the host must have. + try testing.expect(std.mem.indexOf(u8, choose(a, .cpuid, "x86_64/intel/sapphirerapids", findProfile(ps, "x86_64/intel/sapphirerapids"), base).refuse, "avx512_fp16") != null); + // A target without a profile. + try testing.expect(std.mem.indexOf(u8, choose(a, .cpuid, "x86_64/generic", null, base).refuse, "no mask profile") != null); + // No faulting. + var nofault = base; + nofault.faulting = false; + try testing.expect(std.mem.indexOf(u8, choose(a, .cpuid, "x86_64/amd/zen4", findProfile(ps, "x86_64/amd/zen4"), nofault).refuse, "faulting") != null); +} + +test "aarch64 needs no faulting" { + var arena = std.heap.ArenaAllocator.init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const ps = testProfiles(a); + const h: Host = .{ .arch = .aarch64, .subdir = "aarch64/neoverse_v2", .faulting = false }; + try testing.expectEqual(Route.cpuid, choose(a, .auto, "aarch64/neoverse_n1", findProfile(ps, "aarch64/neoverse_n1"), h).route); +} + +test "preflight passes when every detector names the target" { + var arena = std.heap.ArenaAllocator.init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const z4 = findProfile(testProfiles(a), "x86_64/amd/zen4").?; + const fs = preflight(a, z4, .cpuid, .{ + .devfd = true, + .archdetect = "x86_64/amd/zen4:x86_64/amd/zen3:x86_64/amd/zen2:x86_64/generic\n", + .archspec = "zen4", + .gcc = "znver4", + .vendor = "AuthenticAMD", + .faulting = true, + }); + try testing.expect(!refused(fs)); +} + +test "preflight refuses on each mismatch" { + var arena = std.heap.ArenaAllocator.init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const z4 = findProfile(testProfiles(a), "x86_64/amd/zen4").?; + const good: Observed = .{ .devfd = true, .archdetect = "x86_64/amd/zen4:x86_64/generic", .archspec = "zen4", .gcc = "znver4", .vendor = "AuthenticAMD", .faulting = true }; + try testing.expect(!refused(preflight(a, z4, .cpuid, good))); + var o = good; + o.devfd = false; + try testing.expect(refused(preflight(a, z4, .cpuid, o))); + o = good; + o.archdetect = "x86_64/amd/zen5:x86_64/amd/zen4"; + try testing.expect(refused(preflight(a, z4, .cpuid, o))); + o = good; + o.archdetect = null; + try testing.expect(refused(preflight(a, z4, .cpuid, o))); + o = good; + o.archspec = "x86_64_v4"; + try testing.expect(refused(preflight(a, z4, .cpuid, o))); + o = good; + o.gcc = "znver5"; + try testing.expect(refused(preflight(a, z4, .cpuid, o))); + o = good; + o.gcc = null; + try testing.expect(refused(preflight(a, z4, .cpuid, o))); + o = good; + o.vendor = "GenuineIntel"; + try testing.expect(refused(preflight(a, z4, .cpuid, o))); + o = good; + o.faulting = false; + try testing.expect(refused(preflight(a, z4, .cpuid, o))); + // An archspec that cannot be imported is noted, not refused. + o = good; + o.archspec = null; + try testing.expect(!refused(preflight(a, z4, .cpuid, o))); + // A virtual machine route does not need faulting. + o = good; + o.faulting = null; + try testing.expect(!refused(preflight(a, z4, .kvm, o))); +} + +test "preflight reads the aarch64 target from -mcpu and archspec" { + var arena = std.heap.ArenaAllocator.init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const ps = testProfiles(a); + const n1 = findProfile(ps, "aarch64/neoverse_n1").?; + try testing.expect(!refused(preflight(a, n1, .cpuid, .{ .devfd = true, .archdetect = "aarch64/neoverse_n1:aarch64/generic", .archspec = "neoverse_n1", .gcc = "neoverse-n1" }))); + try testing.expect(refused(preflight(a, n1, .cpuid, .{ .devfd = true, .archdetect = "aarch64/neoverse_n1", .archspec = "neoverse_n1", .gcc = "neoverse-v2" }))); + const gen = findProfile(ps, "aarch64/generic").?; + try testing.expect(!refused(preflight(a, gen, .cpuid, .{ .devfd = true, .archdetect = "aarch64/generic", .archspec = "aarch64", .gcc = "cortex-a57" }))); +} + +test "the masked cpuinfo carries the target's identity and drops its flags" { + var arena = std.heap.ArenaAllocator.init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const ps = testProfiles(a); + const host = + "processor\t: 0\nvendor_id\t: AuthenticAMD\ncpu family\t: 26\nmodel\t\t: 68\nmodel name\t: AMD Ryzen 9 9950X\n" ++ + "flags\t\t: fpu avx2 avx512f avx512_vp2intersect avx_vnni sse4a movdiri\n\n"; + const ice = maskedCpuinfo(a, findProfile(ps, "x86_64/intel/icelake").?, host); + try testing.expectEqualStrings("GenuineIntel", cpuinfoField(ice, "vendor_id").?); + try testing.expectEqualStrings("6", cpuinfoField(ice, "cpu family").?); + try testing.expectEqualStrings("106", cpuinfoField(ice, "model").?); + try testing.expectEqualStrings("Intel Xeon Ice Lake-SP (eb-local mask)", cpuinfoField(ice, "model name").?); + try testing.expectEqualStrings("fpu avx2 avx512f", cpuinfoField(ice, "flags").?); + try testing.expectEqualStrings("0", cpuinfoField(ice, "processor").?); + const z4 = maskedCpuinfo(a, findProfile(ps, "x86_64/amd/zen4").?, host); + try testing.expectEqualStrings("AuthenticAMD", cpuinfoField(z4, "vendor_id").?); + try testing.expectEqualStrings("25", cpuinfoField(z4, "cpu family").?); + try testing.expectEqualStrings("fpu avx2 avx512f sse4a", cpuinfoField(z4, "flags").?); + try testing.expect(std.mem.endsWith(u8, z4, "\n\n")); +} + +test "the masked aarch64 cpuinfo carries the part and the features" { + var arena = std.heap.ArenaAllocator.init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const host = "processor\t: 0\nBogoMIPS\t: 2000.00\nFeatures\t: fp asimd sve sve2\nCPU implementer\t: 0x41\nCPU part\t: 0xd4f\n"; + const n1 = maskedCpuinfo(a, findProfile(testProfiles(a), "aarch64/neoverse_n1").?, host); + try testing.expectEqualStrings("0xd0c", cpuinfoField(n1, "CPU part").?); + try testing.expect(std.mem.indexOf(u8, cpuinfoField(n1, "Features").?, "sve") == null); + try testing.expectEqualStrings("0x41", cpuinfoField(n1, "CPU implementer").?); +} + +test "the namespace keeps the caller's uid and binds the cpuinfo" { + var arena = std.heap.ArenaAllocator.init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const w = namespaceWords(a, "/usr/bin/unshare", null, "/w/cpuinfo"); + try testing.expectEqualStrings("--map-current-user", w[2]); + for (w) |x| try testing.expect(!std.mem.eql(u8, x, "--map-root-user")); + try testing.expect(std.mem.indexOf(u8, w[9], "mount --bind \"$0\" /proc/cpuinfo") != null); + try testing.expectEqualStrings("/w/cpuinfo", w[10]); + const sp = namespaceWords(a, "/usr/bin/unshare", "/usr/bin/setpriv", "/w/cpuinfo"); + try testing.expectEqualStrings("/usr/bin/setpriv", sp[sp.len - 1]); + try testing.expect(std.mem.indexOf(u8, sp[9], "--ambient-caps=-all") != null); +} + +test "the cache key follows the libc and the compiler" { + var arena = std.heap.ArenaAllocator.init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const k1 = cacheKey(a, "x86_64-pc-linux-gnu", "glibc 2.44"); + try testing.expectEqualStrings(k1, cacheKey(a, "x86_64-pc-linux-gnu", "glibc 2.44")); + try testing.expect(!std.mem.eql(u8, k1, cacheKey(a, "x86_64-pc-linux-gnu", "glibc 2.39"))); + try testing.expect(!std.mem.eql(u8, k1, cacheKey(a, "aarch64-linux-gnu", "glibc 2.44"))); + try testing.expectEqual(@as(usize, 16), k1.len); +} + +test "the provenance record is valid JSON with the route and the audit result" { + var arena = std.heap.ArenaAllocator.init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const text = provenanceJson(a, .{ .target = "x86_64/amd/zen4", .route = .cpuid, .profile = "x86_64/amd/zen4", .host_cpu = "AMD \"Ryzen\"", .kernel = "7.0.13", .version = "3.6.0", .audit = "pass" }); + const parsed = try std.json.parseFromSlice(std.json.Value, a, text, .{}); + const o = parsed.value.object; + try testing.expectEqualStrings("cpuid", o.get("route").?.string); + try testing.expectEqualStrings("pass", o.get("isa_audit").?.string); + try testing.expectEqualStrings("AMD \"Ryzen\"", o.get("host_cpu").?.string); +} + +test "mask variables set the preload only for the cpuid route" { + var arena = std.heap.ArenaAllocator.init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const z4 = findProfile(testProfiles(a), "x86_64/amd/zen4").?; + const libs: Libs = .{ .preload = "/c/libcpuidmask.so", .probe = "/c/cpuid-probe", .dir = "/c" }; + const has = struct { + fn f(vars: []const [2][]const u8, k: []const u8) bool { + for (vars) |v| if (std.mem.eql(u8, v[0], k)) return true; + return false; + } + }.f; + const cp = maskVariables(a, z4, libs, "/w/rules", "/w/hooks.py", "/bin/eb-local", .cpuid); + try testing.expect(has(cp, "LD_PRELOAD")); + try testing.expect(has(cp, "CPUIDMASK_RULES")); + try testing.expect(has(cp, "CPUIDMASK_STRICT")); + try testing.expect(has(cp, "EESSI_SOFTWARE_SUBDIR_OVERRIDE")); + const kv = maskVariables(a, z4, libs, "/w/rules", "/w/hooks.py", "/bin/eb-local", .kvm); + try testing.expect(!has(kv, "LD_PRELOAD")); + try testing.expect(has(kv, "EB_LOCAL_CPU_TARGET")); +} diff --git a/src/main.zig b/src/main.zig index a4fe1b08..e7b57cce 100644 --- a/src/main.zig +++ b/src/main.zig @@ -37,6 +37,8 @@ pub const foreign = @import("foreign.zig"); pub const cvmfs = @import("cvmfs.zig"); /// MPI transport checks for `doctor --mpi`. A build does not call them. pub const mpi = @import("mpi.zig"); +/// `--cpu-target`: targets, profiles, routes and the preflight decision. +pub const cpumask = @import("cpumask.zig"); /// `eb-local overlay`: declarative site overlays for upstream easyconfigs. pub const recipe_overlay = @import("recipe_overlay.zig"); /// `--json` for scriptable commands. @@ -61,6 +63,14 @@ const usage_text = \\ build that easyconfig with debug symbols and frame \\ pointers (perf) or unoptimised (debug), as a module \\ whose version ends in -perf or -debug + \\ eb-local --cpu-target TARGET [--mask auto|cpuid|kvm|tcg] [--no-audit] [eb options] + \\ build for another CPU target on this machine: TARGET is + \\ an EESSI subdirectory (x86_64/amd/zen4) or its last + \\ component (zen4). The build sees that CPU through the + \\ route --mask picks, refuses to go on when the EESSI + \\ detection, archspec, gcc and CPUID do not all name the + \\ target, and audits the installed binaries for + \\ instructions the target lacks \\ eb-local eb [--] [eb options] load EESSI-extend and run eb; configured prefix, no Slurm job. \\ At most one of EESSI_USER_INSTALL, EESSI_PROJECT_INSTALL, \\ EESSI_SITE_INSTALL, EESSI_CVMFS_INSTALL may be set, and a @@ -120,7 +130,7 @@ const usage_text = \\ what this node's target lacks; --json prints one \\ line of JSON with schema_version 1; --missing \\ lists only modules missing on this node's target - \\ eb-local doctor [--json] [--strict] [--workspace PATH] [--cvmfs] [--cvmfs-parallel N] [--mpi] [--profiling] + \\ eb-local doctor [--json] [--strict] [--workspace PATH] [--cvmfs] [--cvmfs-parallel N] [--mpi] [--profiling] [--cpu-target TARGET] \\ what in this shell, node or configuration would \\ stop a build or a module load; changes nothing; \\ --json prints one line of JSON with schema_version 1. @@ -133,6 +143,8 @@ const usage_text = \\ allocation runs a two-rank hello per approved transport \\ --profiling reports whether perf may sample and \\ debuggers attach, and finds perf, valgrind and gdb + \\ --cpu-target TARGET reports whether this machine can + \\ present TARGET, and by which route \\ eb-local lmod-cache --modulepath DIR[:DIR] --cache-dir DIR \\ --timestamp FILE [--spider CMD] [--verify] \\ write Lmod's spiderT.lua for those module @@ -597,7 +609,10 @@ fn replay(a: Allocator, command: []const u8, s: config.Settings, g: Global, cano if (s.profile) |p| parts.appendSlice(a, &.{ "--profile", q(a, p) }) catch oom(); if (s.project.value != null) parts.appendSlice(a, &.{ "--project", q(a, canonical_prefix) }) catch oom(); parts.append(a, command) catch oom(); - if (std.mem.eql(u8, command, "--explain")) if (g.variant) |v| parts.appendSlice(a, &.{ "--variant", v }) catch oom(); + if (std.mem.eql(u8, command, "--explain")) { + if (g.variant) |v| parts.appendSlice(a, &.{ "--variant", v }) catch oom(); + parts.appendSlice(a, maskOptionWords(a, g)) catch oom(); + } if (std.mem.eql(u8, command, "dev")) { if (g.pure) parts.append(a, "--pure") catch oom(); if (g.replace) parts.append(a, "--replace") catch oom(); @@ -713,6 +728,12 @@ const Global = struct { workstation: bool = false, /// `--variant NAME`: build the named easyconfig as that variant. variant: ?[]const u8 = null, + /// `--cpu-target TARGET`: build for this CPU target. + cpu_target: ?[]const u8 = null, + /// `--mask`: how `--cpu-target` presents the target. + mask: cpumask.Mode = .auto, + /// `--no-audit`: skip the instruction audit after a `--cpu-target` build. + no_audit: bool = false, /// `env --strict`: refuse to print load lines when the EESSI init path is absent. env_strict: bool = false, /// One line of JSON on stdout instead of the human report. @@ -4604,6 +4625,28 @@ const build_script_tail = \\ set -- "$out" "$@" \\fi \\unset EB_LOCAL_VARIANT EB_LOCAL_VARIANT_BLOCK + \\# --cpu-target: EasyBuild runs the site's hooks and one more rule (the + \\# GROMACS SIMD level follows the target). When the build presents another + \\# CPU, every detector the build uses must name the target before eb starts. + \\if [ -n "${EB_LOCAL_CPU_TARGET:-}" ]; then + \\ export EB_LOCAL_BASE_HOOKS=${EASYBUILD_HOOKS-} + \\ export EASYBUILD_HOOKS=$EB_LOCAL_HOOKS_FILE + \\ case ${EB_LOCAL_MASK_ROUTE:-} in + \\ cpuid | kvm | tcg) + \\ pf_fd=no + \\ [ -d /dev/fd ] && pf_fd=yes + \\ pf_ad=$(env -u EESSI_SOFTWARE_SUBDIR_OVERRIDE bash "${EESSI_INIT_DIR_PATH:-${EESSI_PREFIX:-/nonexistent}/init}/eessi_archdetect.sh" cpupath 2>/dev/null) || pf_ad= + \\ pf_sp=$(python3 -c 'import archspec.cpu as c; print(c.host())' 2>/dev/null) || pf_sp= + \\ case $EB_LOCAL_CPU_TARGET in + \\ aarch64/*) pf_flag=-mcpu pf_key=-mcpu= ;; + \\ *) pf_flag=-march pf_key=-march= ;; + \\ esac + \\ pf_gcc=$(gcc "$pf_flag=native" -Q --help=target 2>/dev/null | awk -v k="$pf_key" '$1 == k { v = $2 } END { print v }') || pf_gcc= + \\ pf_probe=$("${EB_LOCAL_PROBE:-/nonexistent}" 2>/dev/null) || pf_probe= + \\ "$EB_LOCAL_SELF" __mask-preflight "$EB_LOCAL_CPU_TARGET" "$EB_LOCAL_MASK_ROUTE" "$pf_fd" "$pf_ad" "$pf_sp" "$pf_gcc" "$pf_probe" || exit 1 + \\ ;; + \\ esac + \\fi \\trap - INT \\exec eb "$@" ; @@ -4703,12 +4746,291 @@ fn buildCommand(a: Allocator, c: Ctx, s: config.Settings, p: Place, args: []cons return argv.items; } +// ---- --cpu-target --------------------------------------------------------- + +/// The route chosen for a `--cpu-target` build. +const MaskPlan = struct { + subdir: []const u8, + route: cpumask.Route, + profile: ?cpumask.Profile, +}; + +/// Whether this binary has the `__vm-run` helper the kvm and tcg routes call. +fn vmHelperKnown() bool { + return subcommand("__vm-run") != null; +} + +/// Whether this binary has the `audit-isa` command the audit step calls. +fn auditKnown() bool { + return subcommand("audit-isa") != null; +} + +/// The EESSI subdirectory this host detects, from the archdetect script of +/// the EESSI version the build uses, or null when it cannot run. +fn hostSubdir(c: Ctx) ?[]const u8 { + const repo = nonEmpty(c.env.get("EESSI_CVMFS_REPO")) orelse "/cvmfs/software.eessi.io"; + const ver = nonEmpty(c.env.get("EESSI_VERSION")) orelse "2026.06"; + const script = str(c.a, "{s}/versions/{s}/init/eessi_archdetect.sh", .{ repo, ver }); + if (!exists(script)) return null; + const bash = (proc.which(c.a, "bash", c.env.get("PATH") orelse "/usr/bin:/bin") catch null) orelse return null; + const r = proc.run(c.a, bash, &.{ bash, "--noprofile", "--norc", script, "cpupath" }, c.envp, .{ .stdout_limit = 4096, .timeout_ms = 60_000 }) catch return null; + if (r.term.code() != 0) return null; + const out = std.mem.trim(u8, r.stdout, " \t\r\n"); + return c.a.dupe(u8, out[0 .. std.mem.indexOfScalar(u8, out, ':') orelse out.len]) catch oom(); +} + +/// The route for `--cpu-target`, or the reason there is none. +fn maskDecide(c: Ctx, g: Global, want_audit: bool) MaskPlan { + const text = g.cpu_target.?; + const subdir = switch (cpumask.resolveTarget(c.a, text)) { + .subdir => |sd| sd, + .refused => |m| die("--cpu-target {s}: {s}", .{ text, m }), + }; + if (want_audit and !g.no_audit and !auditKnown()) + die("--cpu-target audits the installed tree with `eb-local audit-isa`, which this build of eb-local does not have; nothing was built. Give --no-audit to build without the audit.", .{}); + const profile = cpumask.findProfile(cpumask.builtinProfiles(c.a), subdir); + const host = cpumask.readHost(c.a, hostSubdir(c), vmHelperKnown()) orelse die("--cpu-target works on x86_64 and aarch64 machines only", .{}); + return switch (cpumask.choose(c.a, g.mask, subdir, profile, host)) { + .route => |r| .{ .subdir = subdir, .route = r, .profile = profile }, + .refuse => |m| die("--cpu-target {s}: {s}; nothing was built.", .{ subdir, m }), + }; +} + +/// What a masked build adds to its command and environment. +const Masked = struct { + vars: []const [2][]const u8, + /// The words in front of the build command. + prefix: []const []const u8, +}; + +/// Make the files `plan` needs in `dir` and the command words and variables +/// that apply them, or the reason they cannot be made. +fn maskMaterialize(c: Ctx, plan: MaskPlan, dir: []const u8) union(enum) { ok: Masked, failed: []const u8 } { + const a = c.a; + common.atomic.makedirs(dir) catch |e| return .{ .failed = str(a, "cannot create {s} ({s})", .{ dir, sys.describe(e) }) }; + var exe_buf: [sys.path_max]u8 = undefined; + const self_exe = a.dupe(u8, selfExe(&exe_buf) orelse return .{ .failed = "cannot find this program's own path" }) catch oom(); + const hooks = str(a, "{s}/eb_local_hooks.py", .{dir}); + if (!cpumask.writeFile(a, hooks, cpumask.hooks_py, 0o644)) return .{ .failed = str(a, "cannot write {s}", .{hooks}) }; + var libs: cpumask.Libs = .{ .preload = "", .probe = "", .dir = "" }; + var rules_path: []const u8 = ""; + var prefix: []const []const u8 = &.{}; + if (plan.route == .kvm or plan.route == .tcg) { + prefix = &.{ self_exe, "__vm-run", "--mode", @tagName(plan.route), "--cpu-target", plan.subdir, "--" }; + } + if (plan.route == .cpuid) { + const profile = plan.profile.?; + const cache = rpath.cacheHome(a, c.env) catch return .{ .failed = "the cpuid route keeps its compiled library under $XDG_CACHE_HOME or $HOME/.cache, and neither is set" }; + var why: []const u8 = ""; + libs = cpumask.ensureLibs(a, c.envp, c.env.get("PATH") orelse "/usr/bin:/bin", cache, &why) orelse return .{ .failed = why }; + const host_text = cpumask.readFile(a, "/proc/cpuinfo", 4 << 20) orelse return .{ .failed = "cannot read /proc/cpuinfo" }; + const fake = str(a, "{s}/cpuinfo", .{dir}); + if (!cpumask.writeFile(a, fake, cpumask.maskedCpuinfo(a, profile, host_text), 0o644)) return .{ .failed = str(a, "cannot write {s}", .{fake}) }; + if (profile.arch == .x86_64) { + rules_path = str(a, "{s}/rules", .{dir}); + if (!cpumask.writeFile(a, rules_path, cpumask.rulesFile(a, profile), 0o644)) return .{ .failed = str(a, "cannot write {s}", .{rules_path}) }; + } + const path_env = c.env.get("PATH") orelse "/usr/bin:/bin"; + const unshare = (proc.which(a, "unshare", path_env) catch null) orelse return .{ .failed = "unshare is not on PATH; the cpuid route needs it for a user and mount namespace" }; + const setpriv = proc.which(a, "setpriv", path_env) catch null; + prefix = cpumask.namespaceWords(a, unshare, setpriv, fake); + } + const vars = cpumask.maskVariables(a, plan.profile orelse .{ .subdir = plan.subdir, .arch = cpumask.archOf(plan.subdir) orelse .x86_64 }, libs, rules_path, hooks, self_exe, plan.route); + return .{ .ok = .{ .vars = vars, .prefix = prefix } }; +} + +/// `__mask-preflight TARGET ROUTE DEVFD ARCHDETECT ARCHSPEC GCC PROBE`: what the +/// build script saw inside the mask, checked against the target. Prints one +/// line per check and exits 1 when any fails. +fn cmdMaskPreflight(c: Ctx, args: []const []const u8) u8 { + if (args.len != 7) die("__mask-preflight takes TARGET ROUTE DEVFD ARCHDETECT ARCHSPEC GCC PROBE", .{}); + const a = c.a; + const target = args[0]; + const route = std.meta.stringToEnum(cpumask.Route, args[1]) orelse die("__mask-preflight: unknown route {s}", .{args[1]}); + const profile = cpumask.findProfile(cpumask.builtinProfiles(a), target) orelse die("no mask profile for {s}", .{target}); + var obs: cpumask.Observed = .{ .devfd = std.mem.eql(u8, args[2], "yes") }; + if (args[3].len > 0) obs.archdetect = args[3]; + if (args[4].len > 0) obs.archspec = std.mem.trim(u8, args[4], " \t\r\n"); + if (args[5].len > 0) obs.gcc = std.mem.trim(u8, args[5], " \t\r\n"); + var it = std.mem.tokenizeAny(u8, args[6], " \t\r\n"); + while (it.next()) |tok| { + const eq = std.mem.indexOfScalar(u8, tok, '=') orelse continue; + if (std.mem.eql(u8, tok[0..eq], "vendor")) obs.vendor = tok[eq + 1 ..]; + if (std.mem.eql(u8, tok[0..eq], "faulting")) obs.faulting = std.mem.eql(u8, tok[eq + 1 ..], "on"); + } + const findings = cpumask.preflight(a, profile, route, obs); + for (findings) |f| { + if (f.ok) say("eb-local: preflight ok: {s}", .{f.text}) else say("eb-local: preflight FAILED: {s}", .{f.text}); + } + if (cpumask.refused(findings)) { + cli.err("eb-local: the build does not see {s}; nothing was built.\n", .{target}); + return 1; + } + return 0; +} + +/// `__mask-run [--cpu-target T] [--mask M] -- COMMAND...`: run COMMAND the way +/// a `--cpu-target` build runs eb, with the same view of the CPU and no build. +fn cmdMaskRun(c: Ctx, g: Global, args: []const []const u8) u8 { + if (g.cpu_target == null) die("__mask-run needs --cpu-target", .{}); + if (args.len == 0) die("__mask-run needs a command after --", .{}); + const a = c.a; + const plan = maskDecide(c, g, false); + const tmp = nonEmpty(c.env.get("TMPDIR")) orelse "/tmp"; + const dir = fsx.mkdtemp(a, tmp, "eb-local-mask-") catch |e| die("cannot make a directory in {s} ({s})", .{ tmp, @errorName(e) }); + defer fsx.deleteTree(a, fsx.cwd, dir) catch {}; + const masked = switch (maskMaterialize(c, plan, dir)) { + .ok => |m| m, + .failed => |why| die("{s}", .{why}), + }; + var env = c.env.clone(a) catch oom(); + for (masked.vars) |kv| env.put(kv[0], kv[1]) catch oom(); + const argv = std.mem.concat(a, []const u8, &.{ masked.prefix, args }) catch oom(); + const exe = if (argv[0].len > 0 and argv[0][0] == '/') argv[0] else (proc.which(a, argv[0], c.env.get("PATH") orelse "/usr/bin:/bin") catch null) orelse die("{s}: not found", .{argv[0]}); + const full = a.dupe([]const u8, argv) catch oom(); + full[0] = exe; + return switch (runAttached(a, full, envpOf(a, &env))) { + .exit => |code| code, + .signal, .unreaped => 1, + }; +} + +/// `doctor --cpu-target TARGET`: whether this machine can present TARGET, and +/// by which route. +fn reportCpuTarget(c: Ctx, text: []const u8, out: *std.ArrayList(u8), json_lines: ?*std.ArrayList(DoctorLine)) void { + const a = c.a; + const path_env = c.env.get("PATH") orelse ""; + const host = cpumask.readHost(a, hostSubdir(c), vmHelperKnown()) orelse { + note(a, out, json_lines, "warn", "--cpu-target works on x86_64 and aarch64 machines only", .{}); + return; + }; + note(a, out, json_lines, "info", "host: {s}, {s}, kernel {s}", .{ @tagName(host.arch), cpumask.hostModel(a), cpumask.kernelRelease(a) }); + if (host.subdir) |h| note(a, out, json_lines, "info", "EESSI detects this host as {s}", .{h}) else note(a, out, json_lines, "info", "the EESSI archdetect script was not found; the host's own target is not known", .{}); + if (host.arch == .x86_64) { + if (host.faulting) { + note(a, out, json_lines, "ok ", "CPUID faulting is available: the cpuid route can present another x86_64 CPU", .{}); + } else note(a, out, json_lines, "info", "CPUID faulting is not available (AMD CPUs need Linux 6.17 or later); the cpuid route is out", .{}); + } else note(a, out, json_lines, "info", "aarch64 has no CPUID trap; the cpuid route masks getauxval and /proc/cpuinfo", .{}); + if (host.kvm) { + note(a, out, json_lines, "ok ", "/dev/kvm is usable: the kvm route can run a CPU model of this architecture", .{}); + } else note(a, out, json_lines, "info", "/dev/kvm is not usable by this user; the kvm route is out", .{}); + for ([_][]const u8{ "qemu-system-x86_64", "qemu-system-aarch64" }) |name| { + if (proc.which(a, name, path_env) catch null) |exe| { + note(a, out, json_lines, "ok ", "{s}: {s}", .{ name, exe }); + } else note(a, out, json_lines, "info", "{s} is not on PATH; the tcg route for that architecture is out", .{name}); + } + for ([_][]const u8{ "cc", "unshare", "mount" }) |name| { + if (proc.which(a, name, path_env) catch null) |exe| { + note(a, out, json_lines, "ok ", "{s}: {s}", .{ name, exe }); + } else note(a, out, json_lines, "warn", "{s} is not on PATH; the cpuid route needs it", .{name}); + } + if (vmHelperKnown()) note(a, out, json_lines, "ok ", "this eb-local has the virtual machine routes (__vm-run)", .{}) else note(a, out, json_lines, "info", "this eb-local has no __vm-run helper: the kvm and tcg routes refuse", .{}); + if (auditKnown()) note(a, out, json_lines, "ok ", "this eb-local has audit-isa", .{}) else note(a, out, json_lines, "info", "this eb-local has no audit-isa: a --cpu-target build needs --no-audit", .{}); + const subdir = switch (cpumask.resolveTarget(a, text)) { + .subdir => |sd| sd, + .refused => |m| { + note(a, out, json_lines, "warn", "{s}", .{m}); + return; + }, + }; + const profile = cpumask.findProfile(cpumask.builtinProfiles(a), subdir); + if (profile != null) { + note(a, out, json_lines, "ok ", "a mask profile exists for {s}", .{subdir}); + } else note(a, out, json_lines, "info", "no mask profile exists for {s}; only the virtual machine routes can present it", .{subdir}); + switch (cpumask.choose(a, .auto, subdir, profile, host)) { + .route => |r| note(a, out, json_lines, "ok ", "--mask auto builds {s} by the {s} route", .{ subdir, @tagName(r) }), + .refuse => |m| note(a, out, json_lines, "warn", "{s} cannot be built here: {s}", .{ subdir, m }), + } +} + +/// The software directories (NAME/VERSION) below the tree for `subdir` that +/// this build made, by the time their directories were created. +fn installedSince(c: Ctx, prefix: []const u8, subdir: []const u8, started: i64) []const []const u8 { + const a = c.a; + var trees: std.ArrayList([]const u8) = .empty; + findTrees(c, std.fs.path.join(a, &.{ prefix, "versions" }) catch oom(), &trees, 0); + var out: std.ArrayList([]const u8) = .empty; + for (trees.items) |tree| { + if (!std.mem.eql(u8, treeTarget(tree), subdir)) continue; + const software = std.fs.path.join(a, &.{ tree, "software" }) catch oom(); + const sfd = fsx.openDir(fsx.cwd, software, false) catch continue; + defer sys.close(sfd); + var names = fsx.DirIter.init(a, sfd) catch continue; + while (names.next() catch null) |n| { + if (n.name.len == 0 or n.name[0] == '.' or !isDirAt(sfd, n.name)) continue; + const name_path = std.fs.path.join(a, &.{ software, a.dupe(u8, n.name) catch oom() }) catch oom(); + const nfd = fsx.openDir(fsx.cwd, name_path, false) catch continue; + defer sys.close(nfd); + var vers = fsx.DirIter.init(a, nfd) catch continue; + while (vers.next() catch null) |v| { + if (v.name.len == 0 or v.name[0] == '.' or !isDirAt(nfd, v.name)) continue; + const vp = std.fs.path.join(a, &.{ name_path, a.dupe(u8, v.name) catch oom() }) catch oom(); + const st = fsx.statAt(fsx.cwd, vp, false) catch continue; + if (st.ctime.sec >= started - 1) out.append(a, vp) catch oom(); + } + } + } + return out.items; +} + +fn setMode(path: []const u8, mode: u32) void { + var zb: [sys.path_max:0]u8 = undefined; + const z = sys.z(&zb, path) catch return; + _ = linux.fchmodat(linux.AT.FDCWD, z.ptr, @as(linux.mode_t, @intCast(mode))); +} + +/// After a successful `--cpu-target` build: audit what it installed for +/// instructions the target lacks, and write the provenance record into each +/// installed directory. Returns false when the audit fails. +fn maskAfterBuild(c: Ctx, g: Global, plan: MaskPlan, prefix: []const u8, started: i64) bool { + const a = c.a; + const installed = installedSince(c, prefix, plan.subdir, started); + var exe_buf: [sys.path_max]u8 = undefined; + const self_exe = selfExe(&exe_buf) orelse ""; + var failed = false; + const model = cpumask.hostModel(a); + const kernel = cpumask.kernelRelease(a); + if (installed.len == 0) warn("--cpu-target {s}: the build installed nothing new below {s}, so there is nothing to audit or record", .{ plan.subdir, prefix }); + for (installed) |dir| { + var audit: []const u8 = "skipped"; + if (!g.no_audit) { + say("eb-local: auditing {s} for instructions {s} lacks", .{ dir, plan.subdir }); + const rc = switch (runAttached(a, &.{ self_exe, "audit-isa", dir, "--target", plan.subdir }, c.envp)) { + .exit => |code| code, + .signal, .unreaped => 1, + }; + audit = if (rc == 0) "pass" else "fail"; + if (rc != 0) { + failed = true; + cli.err("eb-local: the ISA audit of {s} for {s} failed\n", .{ dir, plan.subdir }); + } + } + const eb_dir = std.fs.path.join(a, &.{ dir, "easybuild" }) catch oom(); + if (!isDir(eb_dir)) continue; + const text = cpumask.provenanceJson(a, .{ + .target = plan.subdir, + .route = plan.route, + .profile = if (plan.profile) |pr| pr.subdir else "", + .host_cpu = model, + .kernel = kernel, + .version = version, + .audit = audit, + }); + // EasyBuild leaves an installation read-only; the record goes in and the mode goes back. + const old_mode: ?u32 = if (fsx.statAt(fsx.cwd, eb_dir, false)) |st| st.perm() else |_| null; + if (old_mode) |m| setMode(eb_dir, m | 0o200); + if (!cpumask.writeProvenance(a, eb_dir, text)) warn("cannot write the build-mode record in {s}", .{eb_dir}); + if (old_mode) |m| setMode(eb_dir, m); + } + return !failed; +} + /// What a build runs: its script, after the variables eb-local sets for it /// and a `set --` line with its arguments, and the checks eb-local makes /// first as comments. Nothing is created and nothing runs, so it also works /// outside an allocation. $W stands for the workspace a build makes in the /// selected local workspace root. -fn explainBuild(c: Ctx, s: config.Settings, g: Global, args: []const []const u8) u8 { +fn explainBuild(c: Ctx, s: config.Settings, g: Global, args: []const []const u8, mask_plan: ?MaskPlan) u8 { const a = c.a; const p = place(c, s); const install = configuredInstall(p); @@ -4764,6 +5086,18 @@ fn explainBuild(c: Ctx, s: config.Settings, g: Global, args: []const []const u8) out.print(a, "export EB_LOCAL_VARIANT={s}\n", .{q(a, v)}) catch oom(); out.print(a, "export EB_LOCAL_VARIANT_BLOCK={s}\n", .{q(a, variantBlock(v).?)}) catch oom(); } + if (mask_plan) |m| { + out.print(a, "# --cpu-target {s}: the {s} route", .{ m.subdir, @tagName(m.route) }) catch oom(); + switch (m.route) { + .native => out.appendSlice(a, "; this host already is the target, so nothing is masked.\n") catch oom(), + .cpuid => out.appendSlice(a, ".\n# The build runs in a user and mount namespace that keeps your uid, with a /proc/cpuinfo\n# of the target bound over the real one, and a preload library (compiled with this host's cc\n# on first use) that answers every CPUID as the target. Before eb starts, EESSI archdetect,\n# archspec, gcc -march=native and the CPUID vendor must all name the target.\n") catch oom(), + .kvm, .tcg => out.print(a, ".\n# The build runs in a virtual machine: eb-local __vm-run --mode {s} --cpu-target {s} -- COMMAND...\n", .{ @tagName(m.route), m.subdir }) catch oom(), + } + out.print(a, "export EESSI_SOFTWARE_SUBDIR_OVERRIDE={s}\n", .{q(a, m.subdir)}) catch oom(); + out.print(a, "export EB_LOCAL_CPU_TARGET={s}\n", .{q(a, m.subdir)}) catch oom(); + if (!g.no_audit) out.print(a, "# After a successful build: eb-local audit-isa DIR --target {s}, for each installed directory.\n", .{m.subdir}) catch oom(); + out.appendSlice(a, "# Each installed directory gets easybuild/eb-local-build-mode.json: route, profile, host CPU, kernel, eb-local version, audit result.\n") catch oom(); + } out.print(a, "umask {o:0>3}\n", .{buildUmask(p)}) catch oom(); const argv = buildCommand(a, c, s, p, args); out.appendSlice(a, "# It runs in a clean bash (no profile, no rc file):\n# ") catch oom(); @@ -4825,7 +5159,8 @@ fn cmdBuild(c: Ctx, s: config.Settings, g: Global, args: []const []const u8) u8 } if (g.variant != null and !std.mem.endsWith(u8, args[0], ".eb")) die("--variant needs the easyconfig as the first argument; got '{s}'", .{args[0]}); - if (g.explain) return explainBuild(c, s, g, args); + const mask_plan: ?MaskPlan = if (g.cpu_target != null) maskDecide(c, g, true) else null; + if (g.explain) return explainBuild(c, s, g, args, mask_plan); if (!localStorage(s, c, g) and nonEmpty(c.env.get("SLURM_JOB_ID")) == null) { warn("not inside a Slurm job: SLURM_JOB_ID is unset or empty; nothing was built.", .{}); if (s.node_local_root.value.len == 0) { @@ -5014,6 +5349,7 @@ fn cmdBuild(c: Ctx, s: config.Settings, g: Global, args: []const []const u8) u8 _ = env.swapRemove("EB_LOCAL_SITE_TOOLCHAINS"); _ = env.swapRemove("EB_LOCAL_VARIANT"); _ = env.swapRemove("EB_LOCAL_VARIANT_BLOCK"); + for ([_][]const u8{ "EB_LOCAL_CPU_TARGET", "EB_LOCAL_MASK_ROUTE", "EB_LOCAL_PROBE", "EB_LOCAL_SELF", "EB_LOCAL_HOOKS_FILE", "EB_LOCAL_BASE_HOOKS" }) |name| _ = env.swapRemove(name); for (shell_startup) |name| _ = env.swapRemove(name); for (s.secrets.items) |sec| if (config.withheldSource(s, sec)) |name| { _ = env.swapRemove(name); @@ -5040,6 +5376,20 @@ fn cmdBuild(c: Ctx, s: config.Settings, g: Global, args: []const []const u8) u8 for (buildVariables(a, work, d)) |kv| env.put(kv[0], kv[1]) catch oom(); for (s.eessi.items) |v| env.put(v.name, v.value) catch oom(); for (values) |v| env.put(v.name, v.value) catch oom(); + var wrap: []const []const u8 = &.{}; + if (mask_plan) |m| { + switch (maskMaterialize(c, m, std.fs.path.join(a, &.{ work, "mask" }) catch oom())) { + .ok => |masked| { + for (masked.vars) |kv| env.put(kv[0], kv[1]) catch oom(); + wrap = masked.prefix; + }, + .failed => |why| { + if (storage.ownWorkspace(job_root, work, callerUid(c))) storage.removeTree(a, work) catch {}; + die("--cpu-target {s}: {s}; nothing was built.", .{ m.subdir, why }); + }, + } + say("eb-local: --cpu-target {s}, {s} route{s}", .{ m.subdir, @tagName(m.route), if (m.route == .cpuid) " (CPUID faulting, namespaced /proc/cpuinfo)" else "" }); + } if (guard.received()) |sig| { if (storage.ownWorkspace(job_root, work, callerUid(c))) storage.removeTree(a, work) catch {}; @@ -5050,13 +5400,20 @@ fn cmdBuild(c: Ctx, s: config.Settings, g: Global, args: []const []const u8) u8 // eb-local first waits for EasyBuild, which writes them, to exit. Logs // are cleaned only after the process group is reaped. A SIGKILL timeout // leaves them in place. - const build_argv = buildCommand(a, c, s, p, args); + const build_argv = std.mem.concat(a, []const u8, &.{ wrap, buildCommand(a, c, s, p, args) }) catch oom(); const ran = guard.run(a, build_argv, envpOf(a, &env)) catch die("cannot start {s}", .{build_argv[0]}); - const rc: u8 = if (guard.received() != null) 1 else switch (ran) { + var rc: u8 = if (guard.received() != null) 1 else switch (ran) { .exit => |code| code, .signal => 1, .unreaped => 1, }; + var audit_failed = false; + if (mask_plan) |m| if (rc == 0) { + if (!maskAfterBuild(c, g, m, p.prefix, started)) { + audit_failed = true; + rc = 1; + } + }; // Redaction requires ECHILD. A descendant still alive after the SIGKILL // deadline can write a secret into a log that was just cleaned, so a @@ -5112,7 +5469,7 @@ fn cmdBuild(c: Ctx, s: config.Settings, g: Global, args: []const []const u8) u8 const mask = blockPassedOn(); const ended: Run = if (guard.received()) |sig| .{ .signal = sig } else ran; const code: u8 = switch (ended) { - .exit => |x| if (x != 0) x else released, + .exit => |x| if (x != 0) x else if (audit_failed) 1 else released, .signal => 1, .unreaped => 1, }; @@ -5455,6 +5812,8 @@ const DoctorOpts = struct { mpi: bool = false, /// `--profiling`: report what perf, valgrind and debuggers may do here. profiling: bool = false, + /// `--cpu-target TARGET`: report whether this machine can present TARGET. + cpu_target: ?[]const u8 = null, /// `--workspace`: exercise and describe this existing build workspace. workspace: ?[]const u8 = null, }; @@ -6126,6 +6485,7 @@ fn cmdDoctor(c: Ctx, s: config.Settings, g: Global, opts: DoctorOpts) u8 { } if (opts.mpi) reportMpi(c, s, &out, lines_ptr); if (opts.profiling) reportProfiling(c, &out, lines_ptr); + if (opts.cpu_target) |t| reportCpuTarget(c, t, &out, lines_ptr); if (opts.workspace) |workspace| { if (reportWorkspace(c, s, workspace, &out, lines_ptr)) failed = true; } @@ -6200,6 +6560,18 @@ fn appendConfigurationOptions(c: Ctx, s: config.Settings, g: Global, p: Place, l if (s.profile) |pr| line.appendSlice(a, &.{ "--profile", qSingleLine(a, pr) }) catch oom(); if (p.project) line.appendSlice(a, &.{ "--project", qSingleLine(a, p.prefix) }) catch oom(); if (g.variant) |v| line.appendSlice(a, &.{ "--variant", v }) catch oom(); + line.appendSlice(a, maskOptionWords(a, g)) catch oom(); +} + +/// `--cpu-target`, `--mask` and `--no-audit` as the command line that +/// reproduces them, empty without a target. +fn maskOptionWords(a: Allocator, g: Global) []const []const u8 { + const t = g.cpu_target orelse return &.{}; + var out: std.ArrayList([]const u8) = .empty; + out.appendSlice(a, &.{ "--cpu-target", qSingleLine(a, t) }) catch oom(); + if (g.mask != .auto) out.appendSlice(a, &.{ "--mask", @tagName(g.mask) }) catch oom(); + if (g.no_audit) out.append(a, "--no-audit") catch oom(); + return out.items; } /// The command a batch job runs to build: this program, the options that @@ -7428,7 +7800,16 @@ fn runMain(init: std.process.Init) u8 { var args: []const [:0]const u8 = argv_all[1..]; var command: Command = .build; + // The helpers a build calls on this program itself; they are not part of its interface. + var hidden: enum { none, mask_run, mask_preflight } = .none; if (args.len > 0) { + const first: []const u8 = args[0]; + if (std.mem.eql(u8, first, "__mask-run") or std.mem.eql(u8, first, "__mask-preflight")) { + hidden = if (first[7] == 'r') .mask_run else .mask_preflight; + args = args[1..]; + } + } + if (args.len > 0 and hidden == .none) { const first: []const u8 = args[0]; if (std.mem.eql(u8, first, "help") or std.mem.eql(u8, first, "-h") or std.mem.eql(u8, first, "--help")) { return if (emit(usage_text)) 0 else 1; @@ -7478,6 +7859,7 @@ fn runMain(init: std.process.Init) u8 { var doctor_parallel: ?u8 = null; var doctor_mpi = false; var doctor_profiling = false; + var doctor_cpu_target: ?[]const u8 = null; var doctor_workspace: ?[]const u8 = null; var list_missing = false; var overlay_action: []const u8 = ""; @@ -7503,6 +7885,10 @@ fn runMain(init: std.process.Init) u8 { }.get; while (i < args.len) : (i += 1) { const x: []const u8 = args[i]; + if (hidden == .mask_run and std.mem.eql(u8, x, "--")) { + for (args[i + 1 ..]) |arg| rest.append(a, arg) catch oom(); + break; + } if (command == .eb and std.mem.eql(u8, x, "--")) { // eb's own --help, and any option eb-local also knows, is eb's. for (args[i..]) |arg| rest.append(a, arg) catch oom(); @@ -7536,6 +7922,13 @@ fn runMain(init: std.process.Init) u8 { const v = if (joined(x, "--variant")) |j| j else value(args, &i, "--variant"); if (variantBlock(v) == null) die("--variant takes perf or debug", .{}); g.variant = v; + } else if ((std.mem.eql(u8, x, "--cpu-target") or joined(x, "--cpu-target") != null) and command == .build and rest.items.len == 0) { + g.cpu_target = if (joined(x, "--cpu-target")) |j| j else value(args, &i, "--cpu-target"); + } else if ((std.mem.eql(u8, x, "--mask") or joined(x, "--mask") != null) and command == .build and rest.items.len == 0) { + const v = if (joined(x, "--mask")) |j| j else value(args, &i, "--mask"); + g.mask = std.meta.stringToEnum(cpumask.Mode, v) orelse die("--mask takes auto, cpuid, kvm or tcg", .{}); + } else if (std.mem.eql(u8, x, "--no-audit") and command == .build and rest.items.len == 0) { + g.no_audit = true; } else if (command == .build and rest.items.len == 0 and subcommand(x) != null) { // Global options may come first: eb-local --profile gpu dev. command = subcommand(x).?; @@ -7629,13 +8022,17 @@ fn runMain(init: std.process.Init) u8 { doctor_mpi = true; } else if (std.mem.eql(u8, x, "--profiling")) { doctor_profiling = true; + } else if (std.mem.eql(u8, x, "--cpu-target")) { + doctor_cpu_target = value(args, &i, "--cpu-target"); + } else if (joined(x, "--cpu-target")) |v| { + doctor_cpu_target = v; } else if (std.mem.eql(u8, x, "--workspace")) { if (doctor_workspace != null) die("doctor takes one --workspace", .{}); doctor_workspace = value(args, &i, "--workspace"); } else if (joined(x, "--workspace")) |v| { if (doctor_workspace != null) die("doctor takes one --workspace", .{}); doctor_workspace = v; - } else die("doctor takes --json, --strict, --workspace, --cvmfs, --cvmfs-parallel, --mpi and --profiling; got '{s}'", .{x}); + } else die("doctor takes --json, --strict, --workspace, --cvmfs, --cvmfs-parallel, --mpi, --profiling and --cpu-target; got '{s}'", .{x}); }, .@"lmod-cache" => { if (std.mem.eql(u8, x, "--modulepath")) { @@ -7944,6 +8341,8 @@ fn runMain(init: std.process.Init) u8 { return if (g.explain) explainExtend(c, s, rest.items) else cmdExtend(c, s, rest.items); } if (command == .leave) return cmdLeave(c); + if (hidden == .mask_preflight) return cmdMaskPreflight(c, rest.items); + if (hidden == .mask_run) return cmdMaskRun(c, g, rest.items); const s = loadSettings(c, g); return switch (command) { .env => cmdEnv(c, s, g), @@ -7965,7 +8364,7 @@ fn runMain(init: std.process.Init) u8 { if (list_missing and g.json_out) die("list takes --missing or --json, not both", .{}); break :blk cmdList(c, s, rest.items, g.json_out, list_missing); }, - .doctor => cmdDoctor(c, s, g, .{ .strict = doctor_strict, .cvmfs = doctor_cvmfs, .parallel = doctor_parallel, .mpi = doctor_mpi, .profiling = doctor_profiling, .workspace = doctor_workspace }), + .doctor => cmdDoctor(c, s, g, .{ .strict = doctor_strict, .cvmfs = doctor_cvmfs, .parallel = doctor_parallel, .mpi = doctor_mpi, .profiling = doctor_profiling, .cpu_target = doctor_cpu_target, .workspace = doctor_workspace }), .submit => cmdSubmit(c, s, g, rest.items, submit), .eb, .leave, .profiles, .site, .@"rpath-wrappers", .check, .@"audit-isa", .@"lmod-cache", .modulerc, .overlay => unreachable, }; diff --git a/tests/test_cpu_target_cli.py b/tests/test_cpu_target_cli.py new file mode 100644 index 00000000..8fdf97de --- /dev/null +++ b/tests/test_cpu_target_cli.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python3 +"""Black-box CLI tests for `--cpu-target`: option parsing, refusals and the +preflight that decides whether a masked build may start. None of them needs +CPUID faulting, KVM or EESSI.""" +from pathlib import Path +import subprocess +import tempfile +import unittest + +import binary + +ZEN4_GOOD = ( + "x86_64/amd/zen4", + "cpuid", + "yes", + "x86_64/amd/zen4:x86_64/amd/zen3:x86_64/generic\n", + "zen4\n", + "znver4", + "vendor=AuthenticAMD family=25 model=17 faulting=on\n", +) + + +@unittest.skipUnless(binary.ZIG, "--cpu-target is a feature of the Zig build") +class CpuTargetCli(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory(prefix="eb-local-cpu-target-") + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name).resolve() + (self.root / "home").mkdir() + + def run_cli(self, *args): + env = {"PATH": "/usr/bin:/bin", "HOME": str(self.root / "home"), "EB_LOCAL_CONFIG": ""} + return subprocess.run([binary.ZIG, *args], env=env, cwd=self.root, capture_output=True, text=True) + + def preflight(self, **changes): + words = list(ZEN4_GOOD) + for key, value in changes.items(): + words[{"target": 0, "route": 1, "devfd": 2, "detect": 3, "spec": 4, "gcc": 5, "probe": 6}[key]] = value + return self.run_cli("__mask-preflight", *words) + + def test_preflight_passes_when_every_detector_names_the_target(self): + r = self.preflight() + self.assertEqual(r.returncode, 0, r.stderr) + self.assertIn("preflight ok: EESSI archdetect names x86_64/amd/zen4", r.stdout) + self.assertIn("preflight ok: gcc -march=native is znver4", r.stdout) + self.assertNotIn("FAILED", r.stdout) + + def test_preflight_refuses_each_mismatch(self): + cases = { + "devfd": ("no", "/dev/fd is missing"), + "detect": ("x86_64/generic", "archdetect names 'x86_64/generic'"), + "spec": ("x86_64_v4", "archspec names 'x86_64_v4'"), + "gcc": ("znver5", "gcc -march=native is 'znver5'"), + "probe": ("vendor=GenuineIntel family=6 model=106 faulting=on", "CPUID vendor is 'GenuineIntel'"), + } + for key, (value, text) in cases.items(): + with self.subTest(key=key): + r = self.preflight(**{key: value}) + self.assertEqual(r.returncode, 1) + self.assertIn("preflight FAILED", r.stdout) + self.assertIn(text, r.stdout) + self.assertIn("nothing was built", r.stderr) + + def test_preflight_refuses_a_cpuid_build_whose_faulting_is_off(self): + r = self.preflight(probe="vendor=AuthenticAMD family=25 model=17 faulting=off") + self.assertEqual(r.returncode, 1) + self.assertIn("CPUID faulting is not active", r.stdout) + + def test_preflight_refuses_missing_answers(self): + r = self.preflight(detect="", gcc="") + self.assertEqual(r.returncode, 1) + self.assertIn("archdetect gave no answer", r.stdout) + self.assertIn("gcc gave no -march=native value", r.stdout) + + def test_preflight_notes_an_archspec_that_cannot_be_imported(self): + r = self.preflight(spec="") + self.assertEqual(r.returncode, 0, r.stdout) + self.assertIn("archspec is not importable here", r.stdout) + + def test_a_short_name_two_architectures_share_is_refused(self): + r = self.run_cli("--cpu-target", "generic", "--explain", "x.eb") + self.assertEqual(r.returncode, 2) + self.assertIn("more than one CPU target", r.stderr) + + def test_an_unknown_target_is_refused(self): + r = self.run_cli("--cpu-target", "zen9", "--explain", "x.eb") + self.assertEqual(r.returncode, 2) + self.assertIn("not a CPU target eb-local knows", r.stderr) + + def test_mask_takes_four_routes(self): + r = self.run_cli("--cpu-target", "zen4", "--mask", "vm", "--explain", "x.eb") + self.assertEqual(r.returncode, 2) + self.assertIn("--mask takes auto, cpuid, kvm or tcg", r.stderr) + + def test_cpu_target_needs_a_value(self): + r = self.run_cli("--cpu-target") + self.assertEqual(r.returncode, 2) + self.assertIn("--cpu-target needs a value", r.stderr) + + def test_doctor_names_what_it_checks(self): + r = self.run_cli("doctor", "--cpu-target", "zen4") + self.assertIn("host: ", r.stdout) + self.assertIn("CPUID", r.stdout) + self.assertIn("/dev/kvm", r.stdout) + self.assertIn("a mask profile exists for x86_64/amd/zen4", r.stdout) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/mask/gen_cpuid_rules.py b/tools/mask/gen_cpuid_rules.py new file mode 100644 index 00000000..bbaa0059 --- /dev/null +++ b/tools/mask/gen_cpuid_rules.py @@ -0,0 +1,143 @@ +"""Generate a cpuidmask rules file for an x86 CPU target. + +The target is described by a reference, the -m options GCC resolved +-march=native into on that hardware (one per line or whitespace separated), or +by a GCC -march name, whose disabled -m options `gcc -march=NAME -Q +--help=target` lists. Every -mno-X becomes a CPUID bit to clear. The bit is +found through GCC's own tables, nothing written by hand: + + i386-isas.h option "-mX" -> FEATURE_X + cpuinfo.h FEATURE_X -> register and bit_ name, under the CPUID + leaf and subleaf last queried above it + cpuid.h bit_ name -> bit mask + + python gen_cpuid_rules.py GCC_SRC_DIR (REFERENCE | --march NAME) + [--signature LEAF1_EAX] + [--vendor GenuineIntel|AuthenticAMD] > rules + +GCC_SRC_DIR holds cpuid.h, i386-isas.h and cpuinfo.h of the GCC version the +reference was recorded with. Output lines: + clear LEAF SUB REG MASK # -mno-X + replace LEAF SUB REG VALUE # signature, vendor +and a trailer listing -mno- options with no CPUID bit (XCR0-gated, or not a +CPUID feature), which a mask cannot express. +""" +import argparse +import os +import re +import subprocess +import sys + +REGS = {"eax": 0, "ebx": 1, "ecx": 2, "edx": 3} + +# -mabm and -mlzcnt read one CPUID bit, and every target here has LZCNT, so a +# target whose -march leaves -mabm out must not lose the bit. +KEEP = {"-mno-abm"} + + +def bit_masks(cpuid_h): + masks = {} + for m in re.finditer(r"#define\s+(bit_\w+)\s+\(\s*(\d+)u?\s*<<\s*(\d+)\s*\)", open(cpuid_h).read()): + masks[m.group(1)] = int(m.group(2)) << int(m.group(3)) + return masks + + +def option_features(isas_h): + opts = {} + for m in re.finditer(r'ISA_NAMES_TABLE_ENTRY\s*\(\s*"[^"]*"\s*,\s*(FEATURE_\w+)\s*,\s*\w+\s*,\s*"(-m[\w.-]+)"', + open(isas_h).read()): + opts[m.group(2)] = m.group(1) + return opts + + +def feature_bits(cpuinfo_h): + """FEATURE_X -> list of (leaf, sub, reg, bit_name), from get_available_features.""" + text = open(cpuinfo_h).read() + # the definition starts at the beginning of a line (GNU style) + start = re.search(r"^get_available_features\b", text, re.M).start() + leaf, sub = 1, 0 + found, pending = {}, None + for line in text[start:].splitlines(): + call = re.search(r"__cpuid_count\s*\(\s*(0x[0-9a-fA-F]+|\d+)\s*,\s*(0x[0-9a-fA-F]+|\d+)", line) + call1 = re.search(r"__cpuid\s*\(\s*(0x[0-9a-fA-F]+|\d+)\s*,", line) + if call: + leaf, sub = int(call.group(1), 0), int(call.group(2), 0) + elif call1: + leaf, sub = int(call1.group(1), 0), 0 + test = re.search(r"\bif\s*\(\s*(eax|ebx|ecx|edx)\s*&\s*(bit_\w+)\s*\)", line) + if test: + pending = (leaf, sub, test.group(1), test.group(2)) + setf = re.search(r"set_feature\s*\(\s*(FEATURE_\w+)", line) + if setf and pending: + found.setdefault(setf.group(1), []).append(pending) + pending = None + elif not test and line.strip() and not setf: + pending = None + if line.startswith("}"): + break + return found + + +def reference_tokens(a): + """The -m options of the reference, as -mno-X for each feature it lacks.""" + if a.march: + out = subprocess.run(["gcc", "-march=" + a.march, "-Q", "--help=target"], check=True, + capture_output=True, text=True).stdout + for m in re.finditer(r"^\s+(-m[\w.-]+)\s+\[disabled\]", out, re.M): + yield "-mno-" + m.group(1)[2:] + return + if not a.reference: + sys.exit("give a REFERENCE file or --march NAME") + for line in open(a.reference): + yield from line.split() + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("gcc_src") + ap.add_argument("reference", nargs="?") + ap.add_argument("--march", help="a GCC -march name; its disabled -m options are the reference") + ap.add_argument("--signature", help="leaf 1 and 0x80000001 EAX, e.g. 0x00A10F11") + ap.add_argument("--vendor", choices=["GenuineIntel", "AuthenticAMD"]) + a = ap.parse_args() + masks = bit_masks(os.path.join(a.gcc_src, "cpuid.h")) + opts = option_features(os.path.join(a.gcc_src, "i386-isas.h")) + bits = feature_bits(os.path.join(a.gcc_src, "cpuinfo.h")) + clear, unmapped = {}, [] + for tok in reference_tokens(a): + if not tok.startswith("-mno-") or tok in KEEP: + continue + feat = opts.get("-m" + tok[5:]) + if not feat: + continue # not an ISA feature: a tuning or ABI option + where = bits.get(feat, []) + if not where: + unmapped.append(tok) + continue + for leaf, sub, reg, bname in where: + key = (leaf, sub, REGS[reg]) + clear.setdefault(key, [0, []]) + clear[key][0] |= masks[bname] + clear[key][1].append(tok[5:]) + print(f"# generated by gen_cpuid_rules.py from {a.march and 'gcc -march=' + a.march or os.path.basename(a.reference)}") + if a.vendor: + v = a.vendor.encode() + for reg, chunk in ((1, v[0:4]), (3, v[4:8]), (2, v[8:12])): + print(f"replace 0x0 0 {reg} {int.from_bytes(chunk, 'little'):#010x}") + intel = a.vendor == "GenuineIntel" + if intel: + # Intel leaves the extended vendor string and signature empty + for reg in (1, 2, 3): + print(f"replace 0x80000000 0 {reg} 0x00000000") + print("replace 0x80000001 0 0 0x00000000") + if a.signature: + print(f"replace 0x1 0 0 {a.signature}") + if not intel: + print(f"replace 0x80000001 0 0 {a.signature}") + for (leaf, sub, reg), (mask, names) in sorted(clear.items()): + print(f"clear {leaf:#x} {sub} {reg} {mask:#010x} # {' '.join(sorted(set(names)))}") + print(f"# no CPUID bit for: {' '.join(unmapped) if unmapped else '(none)'}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/mask/gen_profiles.py b/tools/mask/gen_profiles.py new file mode 100644 index 00000000..e3ac9a4a --- /dev/null +++ b/tools/mask/gen_profiles.py @@ -0,0 +1,59 @@ +"""Write share/eb-local/mask/profiles.conf from targets.toml and rules/*.rules. + + python tools/mask/gen_profiles.py > share/eb-local/mask/profiles.conf + +The output is the file eb-local embeds. One [SUBDIR] section per target, one +`key = value` per line; an x86_64 target's CPUID rules follow as repeated +`rule = clear|replace LEAF SUB REG VALUE` lines, and an aarch64 target's +hardware capability words are computed from its feature names (the order and +bit numbers of arch/arm64/include/uapi/asm/hwcap.h). +""" +import os +import sys +import tomllib + +HERE = os.path.dirname(os.path.abspath(__file__)) + +HWCAP = ["fp", "asimd", "evtstrm", "aes", "pmull", "sha1", "sha2", "crc32", "atomics", "fphp", "asimdhp", "cpuid", + "asimdrdm", "jscvt", "fcma", "lrcpc", "dcpop", "sha3", "sm3", "sm4", "asimddp", "sha512", "sve", "asimdfhm", + "dit", "uscat", "ilrcpc", "flagm", "ssbs", "sb", "paca", "pacg"] + + +def rules(name): + out = [] + with open(os.path.join(HERE, "rules", name + ".rules")) as f: + for line in f: + line = line.split("#", 1)[0].split() + if line: + out.append(" ".join(line)) + return out + + +def main(): + with open(os.path.join(HERE, "targets.toml"), "rb") as f: + targets = tomllib.load(f) + print("# generated by tools/mask/gen_profiles.py from tools/mask/targets.toml and tools/mask/rules; do not edit") + for name, t in targets.items(): + print(f"\n[{t['subdir']}]") + print(f"arch = {t['arch']}") + if t["arch"] == "x86_64": + for key in ("vendor", "family", "model", "model_name", "gcc_march"): + print(f"{key} = {t[key]}") + print("host_vendors = " + " ".join(t["host_vendors"])) + print("needs = " + " ".join(t.get("needs", []))) + print("drop_flags = " + " ".join(t["drop_flags"])) + for r in rules(name): + print("rule = " + r) + else: + hw = 0 + for feat in t["features"]: + hw |= 1 << HWCAP.index(feat) + for key in ("cpu_part", "gcc_cpu"): + print(f"{key} = {t[key]}") + print("features = " + " ".join(t["features"])) + print(f"hwcap = {hw:#x}") + print("hwcap2 = 0x0") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/mask/rules/cascadelake.rules b/tools/mask/rules/cascadelake.rules new file mode 100644 index 00000000..7207c7e3 --- /dev/null +++ b/tools/mask/rules/cascadelake.rules @@ -0,0 +1,20 @@ +# generated by gen_cpuid_rules.py from gcc -march=cascadelake +replace 0x0 0 1 0x756e6547 +replace 0x0 0 3 0x49656e69 +replace 0x0 0 2 0x6c65746e +replace 0x80000000 0 1 0x00000000 +replace 0x80000000 0 2 0x00000000 +replace 0x80000000 0 3 0x00000000 +replace 0x80000001 0 0 0x00000000 +replace 0x1 0 0 0x00050657 +clear 0x7 0 1 0x20200800 # avx512ifma rtm sha +clear 0x7 0 2 0x3a4057e2 # avx512bitalg avx512vbmi avx512vbmi2 avx512vpopcntdq cldemote enqcmd gfni movdir64b movdiri rdpid shstk vaes vpclmulqdq waitpkg +clear 0x7 0 3 0x03c54120 # amx-bf16 amx-int8 amx-tile avx512fp16 avx512vp2intersect pconfig serialize tsxldtrk uintr +clear 0x7 1 0 0x00e000bf # amx-fp16 avx512bf16 avxifma avxvnni cmpccxadd hreset raoint sha512 sm3 sm4 +clear 0x7 1 3 0x0020c530 # amx-complex apxf avxneconvert avxvnniint16 avxvnniint8 prefetchi usermsr +clear 0x14 0 1 0x00000010 # ptwrite +clear 0x19 0 1 0x00000004 # widekl +clear 0x80000001 0 2 0x20218840 # fma4 lwp mwaitx sse4a tbm xop +clear 0x80000001 0 3 0x80000000 # 3dnow +clear 0x80000008 0 1 0x00000201 # clzero wbnoinvd +# no CPUID bit for: -mno-avx10.1 -mno-kl diff --git a/tools/mask/rules/icelake.rules b/tools/mask/rules/icelake.rules new file mode 100644 index 00000000..47f8de18 --- /dev/null +++ b/tools/mask/rules/icelake.rules @@ -0,0 +1,20 @@ +# generated by gen_profile.py from icelake-gcc-14.3.0.txt +replace 0x0 0 1 0x756e6547 +replace 0x0 0 3 0x49656e69 +replace 0x0 0 2 0x6c65746e +replace 0x80000000 0 1 0x00000000 +replace 0x80000000 0 2 0x00000000 +replace 0x80000000 0 3 0x00000000 +replace 0x80000001 0 0 0x00000000 +replace 0x1 0 0 0x000606A6 +clear 0x7 0 1 0x00000814 # hle rtm sgx +clear 0x7 0 2 0x3a0000a0 # cldemote enqcmd movdir64b movdiri shstk waitpkg +clear 0x7 0 3 0x03c54120 # amx-bf16 amx-int8 amx-tile avx512fp16 avx512vp2intersect pconfig serialize tsxldtrk uintr +clear 0x7 1 0 0x00e000bf # amx-fp16 avx512bf16 avxifma avxvnni cmpccxadd hreset raoint sha512 sm3 sm4 +clear 0x7 1 3 0x0020c530 # amx-complex apxf avxneconvert avxvnniint16 avxvnniint8 prefetchi usermsr +clear 0x14 0 1 0x00000010 # ptwrite +clear 0x19 0 1 0x00000004 # widekl +clear 0x80000001 0 2 0x20218840 # fma4 lwp mwaitx sse4a tbm xop +clear 0x80000001 0 3 0x80000000 # 3dnow +clear 0x80000008 0 1 0x00000001 # clzero +# no CPUID bit for: -mno-kl diff --git a/tools/mask/rules/sapphirerapids.rules b/tools/mask/rules/sapphirerapids.rules new file mode 100644 index 00000000..746ad414 --- /dev/null +++ b/tools/mask/rules/sapphirerapids.rules @@ -0,0 +1,20 @@ +# generated by gen_profile.py from sapphirerapids-gcc-14.3.0.txt +replace 0x0 0 1 0x756e6547 +replace 0x0 0 3 0x49656e69 +replace 0x0 0 2 0x6c65746e +replace 0x80000000 0 1 0x00000000 +replace 0x80000000 0 2 0x00000000 +replace 0x80000000 0 3 0x00000000 +replace 0x80000001 0 0 0x00000000 +replace 0x1 0 0 0x000806F8 +clear 0x7 0 1 0x00000814 # hle rtm sgx +clear 0x7 0 2 0x20000080 # enqcmd shstk +clear 0x7 0 3 0x00050120 # avx512vp2intersect pconfig tsxldtrk uintr +clear 0x7 1 0 0x00e0008f # amx-fp16 avxifma cmpccxadd hreset raoint sha512 sm3 sm4 +clear 0x7 1 3 0x0020c530 # amx-complex apxf avxneconvert avxvnniint16 avxvnniint8 prefetchi usermsr +clear 0x14 0 1 0x00000010 # ptwrite +clear 0x19 0 1 0x00000004 # widekl +clear 0x80000001 0 2 0x20218840 # fma4 lwp mwaitx sse4a tbm xop +clear 0x80000001 0 3 0x80000000 # 3dnow +clear 0x80000008 0 1 0x00000001 # clzero +# no CPUID bit for: -mno-kl diff --git a/tools/mask/rules/skylake_avx512.rules b/tools/mask/rules/skylake_avx512.rules new file mode 100644 index 00000000..3f8170a4 --- /dev/null +++ b/tools/mask/rules/skylake_avx512.rules @@ -0,0 +1,20 @@ +# generated by gen_cpuid_rules.py from gcc -march=skylake-avx512 +replace 0x0 0 1 0x756e6547 +replace 0x0 0 3 0x49656e69 +replace 0x0 0 2 0x6c65746e +replace 0x80000000 0 1 0x00000000 +replace 0x80000000 0 2 0x00000000 +replace 0x80000000 0 3 0x00000000 +replace 0x80000001 0 0 0x00000000 +replace 0x1 0 0 0x00050654 +clear 0x7 0 1 0x20200800 # avx512ifma rtm sha +clear 0x7 0 2 0x3a405fe2 # avx512bitalg avx512vbmi avx512vbmi2 avx512vnni avx512vpopcntdq cldemote enqcmd gfni movdir64b movdiri rdpid shstk vaes vpclmulqdq waitpkg +clear 0x7 0 3 0x03c54120 # amx-bf16 amx-int8 amx-tile avx512fp16 avx512vp2intersect pconfig serialize tsxldtrk uintr +clear 0x7 1 0 0x00e000bf # amx-fp16 avx512bf16 avxifma avxvnni cmpccxadd hreset raoint sha512 sm3 sm4 +clear 0x7 1 3 0x0020c530 # amx-complex apxf avxneconvert avxvnniint16 avxvnniint8 prefetchi usermsr +clear 0x14 0 1 0x00000010 # ptwrite +clear 0x19 0 1 0x00000004 # widekl +clear 0x80000001 0 2 0x20218840 # fma4 lwp mwaitx sse4a tbm xop +clear 0x80000001 0 3 0x80000000 # 3dnow +clear 0x80000008 0 1 0x00000201 # clzero wbnoinvd +# no CPUID bit for: -mno-avx10.1 -mno-kl diff --git a/tools/mask/rules/zen2.rules b/tools/mask/rules/zen2.rules new file mode 100644 index 00000000..1711d10d --- /dev/null +++ b/tools/mask/rules/zen2.rules @@ -0,0 +1,13 @@ +# generated by gen_cpuid_rules.py from gcc -march=znver2 +replace 0x1 0 0 0x00830F10 +replace 0x80000001 0 0 0x00830F10 +clear 0x7 0 1 0xd0230814 # avx512bw avx512cd avx512dq avx512f avx512ifma avx512vl hle rtm sgx +clear 0x7 0 2 0x3a005ff2 # avx512bitalg avx512vbmi avx512vbmi2 avx512vnni avx512vpopcntdq cldemote enqcmd gfni movdir64b movdiri pku shstk vaes vpclmulqdq waitpkg +clear 0x7 0 3 0x03c54120 # amx-bf16 amx-int8 amx-tile avx512fp16 avx512vp2intersect pconfig serialize tsxldtrk uintr +clear 0x7 1 0 0x00e000bf # amx-fp16 avx512bf16 avxifma avxvnni cmpccxadd hreset raoint sha512 sm3 sm4 +clear 0x7 1 3 0x0020c530 # amx-complex apxf avxneconvert avxvnniint16 avxvnniint8 prefetchi usermsr +clear 0x14 0 1 0x00000010 # ptwrite +clear 0x19 0 1 0x00000004 # widekl +clear 0x80000001 0 2 0x00218800 # fma4 lwp tbm xop +clear 0x80000001 0 3 0x80000000 # 3dnow +# no CPUID bit for: -mno-avx10.1 -mno-kl diff --git a/tools/mask/rules/zen3.rules b/tools/mask/rules/zen3.rules new file mode 100644 index 00000000..2aa6ec72 --- /dev/null +++ b/tools/mask/rules/zen3.rules @@ -0,0 +1,13 @@ +# generated by gen_cpuid_rules.py from gcc -march=znver3 +replace 0x1 0 0 0x00A00F11 +replace 0x80000001 0 0 0x00A00F11 +clear 0x7 0 1 0xd0230814 # avx512bw avx512cd avx512dq avx512f avx512ifma avx512vl hle rtm sgx +clear 0x7 0 2 0x3a0059e2 # avx512bitalg avx512vbmi avx512vbmi2 avx512vnni avx512vpopcntdq cldemote enqcmd gfni movdir64b movdiri shstk waitpkg +clear 0x7 0 3 0x03c54120 # amx-bf16 amx-int8 amx-tile avx512fp16 avx512vp2intersect pconfig serialize tsxldtrk uintr +clear 0x7 1 0 0x00e000bf # amx-fp16 avx512bf16 avxifma avxvnni cmpccxadd hreset raoint sha512 sm3 sm4 +clear 0x7 1 3 0x0020c530 # amx-complex apxf avxneconvert avxvnniint16 avxvnniint8 prefetchi usermsr +clear 0x14 0 1 0x00000010 # ptwrite +clear 0x19 0 1 0x00000004 # widekl +clear 0x80000001 0 2 0x00218800 # fma4 lwp tbm xop +clear 0x80000001 0 3 0x80000000 # 3dnow +# no CPUID bit for: -mno-avx10.1 -mno-kl diff --git a/tools/mask/rules/zen4.rules b/tools/mask/rules/zen4.rules new file mode 100644 index 00000000..ab374778 --- /dev/null +++ b/tools/mask/rules/zen4.rules @@ -0,0 +1,13 @@ +# generated by gen_profile.py from zen4-gcc-14.3.0.txt +replace 0x1 0 0 0x00A10F11 +replace 0x80000001 0 0 0x00A10F11 +clear 0x7 0 1 0x00000814 # hle rtm sgx +clear 0x7 0 2 0x3a0000a0 # cldemote enqcmd movdir64b movdiri shstk waitpkg +clear 0x7 0 3 0x03c54120 # amx-bf16 amx-int8 amx-tile avx512fp16 avx512vp2intersect pconfig serialize tsxldtrk uintr +clear 0x7 1 0 0x00e0009f # amx-fp16 avxifma avxvnni cmpccxadd hreset raoint sha512 sm3 sm4 +clear 0x7 1 3 0x0020c530 # amx-complex apxf avxneconvert avxvnniint16 avxvnniint8 prefetchi usermsr +clear 0x14 0 1 0x00000010 # ptwrite +clear 0x19 0 1 0x00000004 # widekl +clear 0x80000001 0 2 0x20218800 # fma4 lwp mwaitx tbm xop +clear 0x80000001 0 3 0x80000000 # 3dnow +# no CPUID bit for: -mno-kl diff --git a/tools/mask/targets.toml b/tools/mask/targets.toml new file mode 100644 index 00000000..5fdb7436 --- /dev/null +++ b/tools/mask/targets.toml @@ -0,0 +1,111 @@ +# The CPU targets `eb-local --cpu-target` can present on a host that has +# another one, by the cpuid route. gen_profiles.py turns this file and +# rules/NAME.rules into share/eb-local/mask/profiles.conf. +# +# x86_64 targets: `family`, `model` and `model_name` are the /proc/cpuinfo +# fields; `rules` names the CPUID rule file (gen_cpuid_rules.py); `drop_flags` +# are the /proc/cpuinfo flags that go with the cleared CPUID bits; +# `host_vendors` are the CPU vendors whose hosts the rules can present the +# target on (a rule file that sets the vendor string reaches the other +# vendor); `needs` are flags the host must have and a mask cannot add. +# aarch64 targets: `cpu_part` and `features` are the /proc/cpuinfo fields, +# `gcc_cpu` is the -mcpu value GCC resolves from them, and the hardware +# capability words come from `features`. + +[zen2] +subdir = "x86_64/amd/zen2" +arch = "x86_64" +vendor = "AuthenticAMD" +family = 23 +model = 49 +model_name = "AMD EPYC-Rome (eb-local mask)" +gcc_march = "znver2" +host_vendors = ["AuthenticAMD"] +drop_flags = ["avx512_vp2intersect", "avx_vnni", "movdiri", "movdir64b", "avx512f", "avx512dq", "avx512ifma", "avx512cd", "avx512bw", "avx512vl", "avx512_bf16", "avx512vbmi", "avx512_vbmi2", "gfni", "avx512_vnni", "avx512_bitalg", "avx512_vpopcntdq", "pku", "ospke", "vaes", "vpclmulqdq"] + +[zen3] +subdir = "x86_64/amd/zen3" +arch = "x86_64" +vendor = "AuthenticAMD" +family = 25 +model = 1 +model_name = "AMD EPYC-Milan (eb-local mask)" +gcc_march = "znver3" +host_vendors = ["AuthenticAMD"] +drop_flags = ["avx512_vp2intersect", "avx_vnni", "movdiri", "movdir64b", "avx512f", "avx512dq", "avx512ifma", "avx512cd", "avx512bw", "avx512vl", "avx512_bf16", "avx512vbmi", "avx512_vbmi2", "gfni", "avx512_vnni", "avx512_bitalg", "avx512_vpopcntdq"] + +[zen4] +subdir = "x86_64/amd/zen4" +arch = "x86_64" +vendor = "AuthenticAMD" +family = 25 +model = 17 +model_name = "AMD EPYC-Genoa (eb-local mask)" +gcc_march = "znver4" +host_vendors = ["AuthenticAMD"] +needs = ["avx512f", "avx512_bf16"] +drop_flags = ["avx512_vp2intersect", "avx_vnni", "movdiri", "movdir64b"] + +[skylake_avx512] +subdir = "x86_64/intel/skylake_avx512" +arch = "x86_64" +vendor = "GenuineIntel" +family = 6 +model = 85 +model_name = "Intel Xeon Skylake-SP (eb-local mask)" +gcc_march = "skylake-avx512" +host_vendors = ["AuthenticAMD", "GenuineIntel"] +needs = ["avx512f"] +drop_flags = ["avx512_vp2intersect", "avx_vnni", "movdiri", "movdir64b", "avx512_bf16", "sse4a", "misalignsse", "clzero", "mwaitx", "rdpru", "avx512ifma", "avx512vbmi", "avx512_vbmi2", "avx512_vnni", "avx512_bitalg", "avx512_vpopcntdq", "gfni", "vaes", "vpclmulqdq", "sha_ni", "wbnoinvd", "rdpid"] + +[cascadelake] +subdir = "x86_64/intel/cascadelake" +arch = "x86_64" +vendor = "GenuineIntel" +family = 6 +model = 85 +model_name = "Intel Xeon Cascade Lake-SP (eb-local mask)" +gcc_march = "cascadelake" +host_vendors = ["AuthenticAMD", "GenuineIntel"] +needs = ["avx512_vnni"] +drop_flags = ["avx512_vp2intersect", "avx_vnni", "movdiri", "movdir64b", "avx512_bf16", "sse4a", "misalignsse", "clzero", "mwaitx", "rdpru", "avx512ifma", "avx512vbmi", "avx512_vbmi2", "avx512_bitalg", "avx512_vpopcntdq", "gfni", "vaes", "vpclmulqdq", "sha_ni", "wbnoinvd", "rdpid"] + +[icelake] +subdir = "x86_64/intel/icelake" +arch = "x86_64" +vendor = "GenuineIntel" +family = 6 +model = 106 +model_name = "Intel Xeon Ice Lake-SP (eb-local mask)" +gcc_march = "icelake-server" +host_vendors = ["AuthenticAMD", "GenuineIntel"] +needs = ["avx512_vbmi2"] +drop_flags = ["avx512_vp2intersect", "avx_vnni", "movdiri", "movdir64b", "avx512_bf16", "sse4a", "misalignsse", "clzero", "mwaitx", "rdpru"] + +[sapphirerapids] +subdir = "x86_64/intel/sapphirerapids" +arch = "x86_64" +vendor = "GenuineIntel" +family = 6 +model = 143 +model_name = "Intel Xeon Sapphire Rapids (eb-local mask)" +gcc_march = "sapphirerapids" +host_vendors = ["AuthenticAMD", "GenuineIntel"] +needs = ["avx512_fp16", "amx_tile", "amx_int8", "amx_bf16"] +drop_flags = ["avx512_vp2intersect", "sse4a", "misalignsse", "clzero", "mwaitx", "rdpru"] + +[neoverse_n1] +subdir = "aarch64/neoverse_n1" +arch = "aarch64" +cpu_part = "0xd0c" +gcc_cpu = "neoverse-n1" +features = ["fp", "asimd", "evtstrm", "aes", "pmull", "sha1", "sha2", "crc32", "atomics", "fphp", "asimdhp", "cpuid", "asimdrdm", "lrcpc", "dcpop", "asimddp", "ssbs"] + +[aarch64_generic] +subdir = "aarch64/generic" +arch = "aarch64" +# An Armv8.0 core (Cortex-A57): GCC builds -mcpu=native from the part and +# keeps every extension its cpuinfo strings name, so a newer part would keep SVE. +cpu_part = "0xd07" +gcc_cpu = "cortex-a57" +features = ["fp", "asimd", "evtstrm", "cpuid"]