From e42b31e0c79a574d51b6398416333369f7b22c2b Mon Sep 17 00:00:00 2001 From: Cong Wang Date: Sun, 29 Nov 2026 15:38:36 -0800 Subject: [PATCH 1/2] cpus: List the CPUs with their physical IDs --cpus takes physical CPU IDs, the one name of a CPU that every kernel on the machine agrees on. An APIC ID is at least in /proc/cpuinfo. An MPIDR is not: it has to be dug out of the reg of the CPU's device tree node, or out of the MADT on an ACPI host, and kerf itself only showed the IDs in the error for a wrong one. Add kerf cpus, which lists every CPU with the logical number the host gives it, its physical ID, its NUMA node, and who holds it: the host, the pool, or an instance. MPIDRs are written in hex, where each affinity level is a byte to read. A machine with more than one kind of CPU gets a KIND column. The host forgets a CPU it gave to the pool to a degree that depends on the architecture, so such a CPU may be listed without a logical number or a node. Signed-off-by: Cong Wang --- README.md | 6 ++ src/kerf/cli.py | 2 + src/kerf/cpus/__init__.py | 19 +++++ src/kerf/cpus/main.py | 157 ++++++++++++++++++++++++++++++++++++++ src/kerf/init/main.py | 3 +- src/kerf/topology.py | 8 ++ tests/test_cpus.py | 157 ++++++++++++++++++++++++++++++++++++++ 7 files changed, 351 insertions(+), 1 deletion(-) create mode 100644 src/kerf/cpus/__init__.py create mode 100644 src/kerf/cpus/main.py create mode 100644 tests/test_cpus.py diff --git a/README.md b/README.md index efb5d87..ae84f67 100644 --- a/README.md +++ b/README.md @@ -182,6 +182,9 @@ kerf exec -u nobody web-server id kerf show kerf show web-server +# List the CPUs with the physical IDs that --cpus takes, and who holds each +kerf cpus + # Dump the device tree the kernel holds: DTB to replay, --dts to read kerf dump -o host.dtb kerf dump web-server -o web.dtb @@ -368,6 +371,9 @@ pip install -e . kerf --help kerf init --help +# Find the physical IDs of the CPUs to hand over +kerf cpus + # Carve a pool out of the host: 7 CPUs (by APIC ID) and 1GB on their NUMA node sudo kerf init --cpus=128-134 --memory=1GB --report ``` diff --git a/src/kerf/cli.py b/src/kerf/cli.py index 4ba16cf..9814af5 100644 --- a/src/kerf/cli.py +++ b/src/kerf/cli.py @@ -27,6 +27,7 @@ from .unload.main import unload from .delete.main import delete from .show.main import show +from .cpus.main import cpus from .dump.main import dump from .console.main import console from .sign.main import sign @@ -53,6 +54,7 @@ def main(ctx, debug): main.add_command(unload) main.add_command(delete) main.add_command(show) +main.add_command(cpus) main.add_command(dump) main.add_command(console) main.add_command(sign) diff --git a/src/kerf/cpus/__init__.py b/src/kerf/cpus/__init__.py new file mode 100644 index 0000000..12ba2cc --- /dev/null +++ b/src/kerf/cpus/__init__.py @@ -0,0 +1,19 @@ +# Copyright 2026 Multikernel Technologies, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""List the CPUs of the machine by the physical IDs kerf names them by.""" + +from .main import cpus + +__all__ = ["cpus"] diff --git a/src/kerf/cpus/main.py b/src/kerf/cpus/main.py new file mode 100644 index 0000000..3cd2ce2 --- /dev/null +++ b/src/kerf/cpus/main.py @@ -0,0 +1,157 @@ +# Copyright 2026 Multikernel Technologies, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""List the CPUs of the machine by the physical IDs kerf names them by.""" + +from dataclasses import dataclass +from typing import Dict, List, Optional + +import click + +from ..baseline import BaselineManager +from ..exceptions import KernelInterfaceError, ParseError +from ..init.main import list_instance_names, pool_is_live, read_current_pool +from ..models import GlobalDeviceTree +from ..runtime import DeviceTreeManager +from ..topology import cpu_id_name, cpu_numa_nodes, format_cpu_id, logical_to_physical + +UNKNOWN = "-" + + +@dataclass(frozen=True) +class CpuRow: + """One CPU of the machine, as kerf cpus lists it.""" + + physical: int + logical: Optional[int] + node: Optional[int] + kind: Optional[int] + state: str + + +def instance_cpus() -> Dict[int, str]: + """Map each CPU an instance holds to the name of that instance.""" + manager = DeviceTreeManager() + owners: Dict[int, str] = {} + for name in list_instance_names(): + try: + instance = manager.read_instance(name) + except (KernelInterfaceError, ParseError): + continue + for cpu in instance.resources.cpus: + owners[cpu] = name + return owners + + +def cpu_rows( + physical_of: Dict[int, int], + nodes: Dict[int, int], + pool: Optional[GlobalDeviceTree], + owners: Dict[int, str], +) -> List[CpuRow]: + """ + Describe every CPU the host or the pool knows of. + + Args: + physical_of: Logical CPU number to physical ID, as the host reports it + nodes: Physical ID to NUMA node + pool: The live pool, or None if there is none + owners: Physical ID to the instance that holds the CPU + + Returns: + One row per CPU: the host's in logical order, then the pool CPUs + the host no longer reports + """ + logical_of = {physical: logical for logical, physical in physical_of.items()} + boot_cpu = physical_of.get(0) + pool_cpus = pool.hardware.cpus if pool else None + in_pool = set(pool_cpus.available) | set(pool_cpus.unclaimed) if pool_cpus else set() + unclaimed = set(pool_cpus.unclaimed) if pool_cpus else set() + kinds = pool_cpus.kinds if pool_cpus else {} + + def state(cpu: int) -> str: + if cpu in owners: + return owners[cpu] + if cpu in unclaimed: + return "pool (unclaimed)" + if cpu in in_pool: + return "pool" + return "host (boot)" if cpu == boot_cpu else "host" + + # A pool CPU without a logical number sorts behind the ones that have one. + def position(cpu: int): + return (cpu not in logical_of, logical_of.get(cpu, cpu)) + + return [ + CpuRow( + physical=cpu, + logical=logical_of.get(cpu), + node=nodes.get(cpu), + kind=kinds.get(cpu), + state=state(cpu), + ) + for cpu in sorted(set(logical_of) | in_pool, key=position) + ] + + +def render(rows: List[CpuRow]) -> str: + """Lay the rows out as a table, with a KIND column where CPUs differ.""" + def cell(value: Optional[int]) -> str: + return UNKNOWN if value is None else str(value) + + with_kinds = any(row.kind is not None for row in rows) + table = [["CPU", cpu_id_name().upper(), "NODE"] + (["KIND"] if with_kinds else []) + ["STATE"]] + for row in rows: + table.append( + [cell(row.logical), format_cpu_id(row.physical), cell(row.node)] + + ([cell(row.kind)] if with_kinds else []) + + [row.state] + ) + + widths = [max(len(line[column]) for line in table) for column in range(len(table[0]))] + return "\n".join( + " ".join(text.ljust(width) for text, width in zip(line, widths)).rstrip() + for line in table + ) + + +@click.command(name="cpus") +def cpus(): + """ + List the CPUs of this machine and the physical IDs that name them. + + --cpus takes physical CPU IDs, the APIC ID on x86 or the MPIDR on + arm64, which are the same in every kernel on the machine. This lists + them next to the logical CPU numbers of the host, with the NUMA node + of each CPU and who holds it: the host, the pool, or an instance. + + A CPU the host gave away may have no logical number or node left to + show, which reads as "-". + + Examples: + + \b + kerf cpus + """ + pool = read_current_pool(BaselineManager()) + if not pool_is_live(pool): + pool = None + + rows = cpu_rows(logical_to_physical(), cpu_numa_nodes(), pool, instance_cpus() if pool else {}) + if not rows: + raise click.ClickException( + "Could not read the physical CPU IDs (APIC ids from /proc/cpuinfo, " + "or MPIDRs from /sys/devices/system/cpu on arm64)." + ) + click.echo(render(rows)) diff --git a/src/kerf/init/main.py b/src/kerf/init/main.py index eb9d2d3..44250d7 100644 --- a/src/kerf/init/main.py +++ b/src/kerf/init/main.py @@ -629,7 +629,8 @@ def build_baseline_from_cmdline( if invalid_cpus: raise ValueError( f"Invalid {cpu_id_name()}(s) specified: {sorted(invalid_cpus)}. " - f"Valid {cpu_id_name()}s on this system: {sorted(valid_apic_ids)}" + f"Valid {cpu_id_name()}s on this system: {sorted(valid_apic_ids)}. " + "'kerf cpus' lists them." ) total_cpus = len(valid_apic_ids) diff --git a/src/kerf/topology.py b/src/kerf/topology.py index 17b4701..151498f 100644 --- a/src/kerf/topology.py +++ b/src/kerf/topology.py @@ -52,6 +52,14 @@ def cpu_id_name() -> str: return "APIC ID" +def format_cpu_id(cpu: int) -> str: + """Write a physical CPU ID the way its architecture does.""" + # An MPIDR packs one affinity level per byte, which only hex shows. + if cpu_id_name() == "MPIDR": + return hex(cpu) + return str(cpu) + + def _parse_cpulist(text: str) -> List[int]: """Expand a sysfs cpulist ("0-3,8") into logical CPU numbers.""" cpus: List[int] = [] diff --git a/tests/test_cpus.py b/tests/test_cpus.py new file mode 100644 index 0000000..44758fe --- /dev/null +++ b/tests/test_cpus.py @@ -0,0 +1,157 @@ +# Copyright 2026 Multikernel Technologies, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Tests for `kerf cpus`, the listing of physical CPU IDs. +""" + +import pytest +from click.testing import CliRunner + +from kerf.cpus import main +from kerf.cpus.main import CpuRow, cpu_rows, render +from kerf.models import ( + CPUAllocation, + GlobalDeviceTree, + HardwareInventory, + MemoryAllocation, +) +from kerf.topology import format_cpu_id + + +def _pool(available, available_free=None, unclaimed=(), kinds=None): + cpus = CPUAllocation( + total=0, + host_reserved=[], + available=list(available), + available_free=available_free, + unclaimed=list(unclaimed), + kinds=kinds or {}, + ) + memory = MemoryAllocation(total_bytes=0, host_reserved_bytes=0) + hardware = HardwareInventory(cpus=cpus, memory=memory, devices={}) + return GlobalDeviceTree(hardware=hardware, instances={}, device_references={}) + + +@pytest.fixture(name="arm64") +def _arm64(monkeypatch): + monkeypatch.setattr("platform.machine", lambda: "aarch64") + + +@pytest.fixture(name="x86") +def _x86(monkeypatch): + monkeypatch.setattr("platform.machine", lambda: "x86_64") + + +@pytest.mark.usefixtures("arm64") +def test_mpidrs_are_written_in_hex(): + assert format_cpu_id(0x10100) == "0x10100" + + +@pytest.mark.usefixtures("x86") +def test_apic_ids_are_written_in_decimal(): + assert format_cpu_id(128) == "128" + + +def test_without_a_pool_every_cpu_is_the_hosts(): + rows = cpu_rows({0: 0, 1: 0x100}, {0: 0, 0x100: 1}, None, {}) + + assert rows == [ + CpuRow(physical=0, logical=0, node=0, kind=None, state="host (boot)"), + CpuRow(physical=0x100, logical=1, node=1, kind=None, state="host"), + ] + + +def test_rows_follow_the_logical_order_of_the_host(): + rows = cpu_rows({0: 8, 1: 0, 2: 4}, {}, None, {}) + + assert [row.physical for row in rows] == [8, 0, 4] + assert rows[0].state == "host (boot)" + + +def test_pool_cpus_show_who_holds_them(): + pool = _pool(available=[2, 3, 4], available_free=[3], unclaimed=[4]) + + rows = cpu_rows({0: 0, 1: 1, 2: 2, 3: 3, 4: 4}, {}, pool, {2: "web"}) + + assert [row.state for row in rows] == ["host (boot)", "host", "web", "pool", "pool (unclaimed)"] + + +def test_pool_cpus_the_host_stopped_reporting_come_last(): + pool = _pool(available=[130, 129]) + + rows = cpu_rows({0: 0, 1: 200}, {0: 0, 200: 1}, pool, {}) + + assert rows[2:] == [ + CpuRow(physical=129, logical=None, node=None, kind=None, state="pool"), + CpuRow(physical=130, logical=None, node=None, kind=None, state="pool"), + ] + + +@pytest.mark.usefixtures("arm64") +def test_table_names_the_id_of_the_architecture(): + out = render(cpu_rows({0: 0, 1: 0x100}, {0: 0, 0x100: 0}, None, {})) + + assert out.splitlines() == [ + "CPU MPIDR NODE STATE", + "0 0x0 0 host (boot)", + "1 0x100 0 host", + ] + + +@pytest.mark.usefixtures("x86") +def test_table_has_a_kind_column_only_where_cpus_differ(): + pool = _pool(available=[1], kinds={0: 0, 1: 1}) + plain = render(cpu_rows({0: 0, 1: 1}, {}, None, {})) + mixed = render(cpu_rows({0: 0, 1: 1}, {}, pool, {})) + + assert plain.splitlines()[0] == "CPU APIC ID NODE STATE" + assert mixed.splitlines() == [ + "CPU APIC ID NODE KIND STATE", + "0 0 - 0 host (boot)", + "1 1 - 1 pool", + ] + + +def _run(monkeypatch, physical_of, pool=None, owners=None): + monkeypatch.setattr(main, "logical_to_physical", lambda: physical_of) + monkeypatch.setattr(main, "cpu_numa_nodes", lambda: {cpu: 0 for cpu in physical_of.values()}) + monkeypatch.setattr(main, "read_current_pool", lambda manager: pool) + monkeypatch.setattr(main, "instance_cpus", lambda: owners or {}) + return CliRunner().invoke(main.cpus) + + +@pytest.mark.usefixtures("arm64") +def test_command_lists_the_host_before_any_pool_exists(monkeypatch): + result = _run(monkeypatch, {0: 0, 1: 1}) + + assert result.exit_code == 0 + assert result.output.splitlines()[1:] == ["0 0x0 0 host (boot)", "1 0x1 0 host"] + + +@pytest.mark.usefixtures("arm64") +def test_command_lists_the_pool_and_its_instances(monkeypatch): + pool = _pool(available=[0x100, 0x101], available_free=[0x101]) + + result = _run(monkeypatch, {0: 0, 4: 0x100, 5: 0x101}, pool, {0x100: "web"}) + + assert result.exit_code == 0 + assert result.output.splitlines()[2:] == ["4 0x100 0 web", "5 0x101 0 pool"] + + +def test_command_fails_where_no_cpu_id_can_be_read(monkeypatch): + result = _run(monkeypatch, {}) + + assert result.exit_code == 1 + assert "Could not read the physical CPU IDs" in result.output From b56150857ccf7845ee47b4b94255594f9d35449e Mon Sep 17 00:00:00 2001 From: Cong Wang Date: Sun, 29 Nov 2026 15:42:08 -0800 Subject: [PATCH 2/2] Read and write MPIDRs in hex An MPIDR packs one affinity level per byte, so 0x10100 says cluster and core where 65792 says nothing, and hex is how the device tree, the MADT and the kernel log all write it. Yet --cpus took decimal only, and every list of CPUs that kerf printed was decimal too. Take a physical CPU ID in decimal or 0x-prefixed hex wherever --cpus is parsed, on any architecture. Write the IDs in hex where they are MPIDRs, in kerf show, in the reports and in the error messages; APIC IDs and hart IDs stay decimal. A range needed a new meaning as well. It used to be every number from its first to its last, which for MPIDRs is mostly CPUs that do not exist: 0x0-0x103 names 8 CPUs of a machine with two clusters of 4, and 252 numbers that are not. A range now takes the CPUs that exist in it, those of the host and of the pool. Its two ends are kept either way, so a mistyped one is still reported as invalid. Where the IDs are consecutive nothing changes. The parser therefore returns the ranges, and init, create and update expand them once they know the CPUs of the machine. Signed-off-by: Cong Wang --- README.md | 3 +- src/kerf/create/main.py | 86 ++++++++++++++--------- src/kerf/dtc/reporter.py | 7 +- src/kerf/dtc/validator.py | 20 +++--- src/kerf/init/main.py | 42 ++++++----- src/kerf/resources.py | 20 ++++-- src/kerf/show/main.py | 17 ++--- src/kerf/topology.py | 5 ++ src/kerf/update/main.py | 22 +++--- tests/conftest.py | 6 ++ tests/test_cpu_spec.py | 125 +++++++++++++++++++++++++++++++++ tests/test_init_memory_spec.py | 4 +- 12 files changed, 271 insertions(+), 86 deletions(-) create mode 100644 tests/test_cpu_spec.py diff --git a/README.md b/README.md index ae84f67..205fa3b 100644 --- a/README.md +++ b/README.md @@ -371,7 +371,8 @@ pip install -e . kerf --help kerf init --help -# Find the physical IDs of the CPUs to hand over +# Find the physical IDs of the CPUs to hand over. On arm64 they are MPIDRs, +# written in hex: --cpus=0x100-0x103 takes the CPUs that exist in that range kerf cpus # Carve a pool out of the host: 7 CPUs (by APIC ID) and 1GB on their NUMA node diff --git a/src/kerf/create/main.py b/src/kerf/create/main.py index 2023452..4cf111b 100644 --- a/src/kerf/create/main.py +++ b/src/kerf/create/main.py @@ -24,7 +24,7 @@ import sys import traceback from pathlib import Path -from typing import List, Optional +from typing import Iterable, List, Optional, Tuple import click from ..runtime import DeviceTreeManager @@ -33,18 +33,27 @@ from ..resources import ( validate_cpu_allocation, get_available_cpus, + known_cpu_ids, ) from ..exceptions import ValidationError, KernelInterfaceError, ResourceError, ParseError -from ..topology import cpu_id_name +from ..topology import cpu_id_name, format_cpu_id -def parse_cpu_spec(cpu_spec: str) -> List[int]: +def parse_cpu_id(text: str) -> int: + """Parse one physical CPU ID, decimal or 0x-prefixed hex.""" + text = text.strip() + if text.lower().startswith("0x"): + return int(text, 16) + return int(text) + + +def parse_cpu_ranges(cpu_spec: str) -> List[Tuple[int, int]]: """ - Parse CPU specification string into explicit CPU IDs. + Parse a CPU specification into the ranges it spells. Supports formats: - - "4" (single CPU ID 4) - - "4-7" (range of CPUs: 4, 5, 6, 7) + - "4" or "0x100" (single CPU ID) + - "4-7" or "0x100-0x103" (range of CPUs) - "4,5,6,7" (comma-separated list) - "4-7,10-12" (mixed ranges and lists) @@ -52,42 +61,53 @@ def parse_cpu_spec(cpu_spec: str) -> List[int]: cpu_spec: CPU specification string Returns: - List of explicit CPU IDs (sorted) + (first, last) per entry, a single CPU being a range of one Raises: ValueError: If specification is invalid """ - cpu_spec = cpu_spec.strip() - - # Explicit CPU specification - cpus = set() - - # Split by comma - parts = [p.strip() for p in cpu_spec.split(",")] - - for part in parts: + ranges = [] + for part in cpu_spec.strip().split(","): + part = part.strip() if "-" in part: - # Range format: "4-7" try: - start, end = part.split("-", 1) - start = int(start.strip()) - end = int(end.strip()) + first, last = part.split("-", 1) + start, end = parse_cpu_id(first), parse_cpu_id(last) if start > end: raise ValueError(f"Invalid CPU range: {start} > {end}") - cpus.update(range(start, end + 1)) except ValueError as e: raise ValueError(f"Invalid CPU range format '{part}': {e}") from e + ranges.append((start, end)) else: - # Single CPU try: - cpus.add(int(part.strip())) + cpu = parse_cpu_id(part) except ValueError as e: raise ValueError(f"Invalid CPU ID '{part}': {e}") from e + ranges.append((cpu, cpu)) + return ranges + - if not cpus: - raise ValueError("CPU specification must include at least one CPU") +def expand_cpu_ranges(ranges: Iterable[Tuple[int, int]], known: Iterable[int]) -> List[int]: + """ + List the CPUs that ranges of physical IDs select. + + Physical IDs are sparse, MPIDRs with gaps of whole affinity levels, so + a range selects the CPUs that exist between its ends rather than every + number. The ends are kept even if unknown, for validation to name them. + + Args: + ranges: (first, last) pairs from parse_cpu_ranges() + known: Physical IDs of the CPUs that exist - return sorted(list(cpus)) + Returns: + The selected CPU IDs, sorted + """ + known = set(known) + cpus = set() + for start, end in ranges: + cpus.update((start, end)) + cpus.update(cpu for cpu in known if start < cpu < end) + return sorted(cpus) def _find_consecutive_cpus(cpu_list: List[int], count: int) -> Optional[List[int]]: @@ -366,7 +386,8 @@ def dump_overlay_for_debug( "--cpus", "-c", help='Explicit CPU allocation by physical ID, the APIC ID on x86 or the MPIDR on arm64 ' - '(e.g., "128", "128-134" for range, "128,130,132" for list), not logical CPU numbers. ' + '(e.g., "128", "128-134" for range, "128,130,132" for list, "0x100-0x103" in hex), ' + 'not logical CPU numbers; "kerf cpus" lists them. A range takes the CPUs that exist in it. ' 'Mutually exclusive with --cpu-count', ) @click.option( @@ -565,7 +586,7 @@ def create( # pylint: disable=too-many-arguments,too-many-positional-arguments cpu_spec_value = cpu_count else: try: - cpu_spec_value = parse_cpu_spec(cpus) + cpu_spec_value = parse_cpu_ranges(cpus) except ValueError as e: click.echo(f"Error: Invalid {cpu_id_name()} specification '{cpus}': {e}", err=True) sys.exit(2) @@ -643,8 +664,7 @@ def create_instance_operation(current): numa_nodes=numa_node_list, ) else: - # Use explicitly specified CPUs - cpu_list = cpu_spec_value # cpu_spec_value is List[int] + cpu_list = expand_cpu_ranges(cpu_spec_value, known_cpu_ids(modified)) # Validate CPU allocation (against baseline and existing instances) validate_cpu_allocation(modified, cpu_list) @@ -691,10 +711,10 @@ def create_instance_operation(current): click.echo(f"✓ Validation passed for instance '{name}'") if is_count: - cpus_str = ", ".join(map(str, instance.resources.cpus)) + cpus_str = ", ".join(map(format_cpu_id, instance.resources.cpus)) click.echo(f" CPUs: {cpu_spec_value} CPUs auto-allocated: {cpus_str}") else: - click.echo(f" CPUs: {', '.join(map(str, instance.resources.cpus))}") + click.echo(f" CPUs: {', '.join(map(format_cpu_id, instance.resources.cpus))}") if instance.resources.cpu_affinity: click.echo(f" CPU Affinity: {instance.resources.cpu_affinity}") if instance.resources.numa_nodes: @@ -734,7 +754,7 @@ def create_instance_operation(current): if verbose: instance = manager.read_instance(name) click.echo(f" Instance ID: {instance.id}") - click.echo(f" CPUs: {', '.join(map(str, instance.resources.cpus))}") + click.echo(f" CPUs: {', '.join(map(format_cpu_id, instance.resources.cpus))}") if instance.resources.cpu_affinity: click.echo(f" CPU Affinity: {instance.resources.cpu_affinity}") if instance.resources.numa_nodes: diff --git a/src/kerf/dtc/reporter.py b/src/kerf/dtc/reporter.py index 54ee2f3..7bc5517 100644 --- a/src/kerf/dtc/reporter.py +++ b/src/kerf/dtc/reporter.py @@ -18,6 +18,7 @@ from typing import List, Dict, Any from ..models import GlobalDeviceTree, ValidationResult +from ..topology import format_cpu_id class ValidationReporter: @@ -112,10 +113,10 @@ def _format_hardware_inventory(self, tree: GlobalDeviceTree) -> List[str]: lines.append(f" CPUs: {cpus.total} total") lines.append( - f" Host reserved: {cpus.host_reserved[0]}-{cpus.host_reserved[-1]} ({host_count} CPUs, {host_percent:.0f}%)" + f" Host reserved: {format_cpu_id(cpus.host_reserved[0])}-{format_cpu_id(cpus.host_reserved[-1])} ({host_count} CPUs, {host_percent:.0f}%)" ) lines.append( - f" Memory pool: {cpus.available[0]}-{cpus.available[-1]} ({available_count} CPUs, {memory_pool_percent:.0f}%)" + f" Memory pool: {format_cpu_id(cpus.available[0])}-{format_cpu_id(cpus.available[-1])} ({available_count} CPUs, {memory_pool_percent:.0f}%)" ) # Memory information @@ -166,7 +167,7 @@ def _format_instance_allocations(self, tree: GlobalDeviceTree) -> List[str]: # CPU allocation cpu_count = len(instance.resources.cpus) cpu_range = ( - f"{instance.resources.cpus[0]}-{instance.resources.cpus[-1]}" + f"{format_cpu_id(instance.resources.cpus[0])}-{format_cpu_id(instance.resources.cpus[-1])}" if instance.resources.cpus else "none" ) diff --git a/src/kerf/dtc/validator.py b/src/kerf/dtc/validator.py index c23426b..c26c925 100644 --- a/src/kerf/dtc/validator.py +++ b/src/kerf/dtc/validator.py @@ -21,6 +21,7 @@ from typing import List, Dict, Optional from ..models import GlobalDeviceTree, ValidationResult, ResourceUsage from ..resources import chunk_containing, get_pool_chunks_from_iomem +from ..topology import format_cpu_id, format_cpu_ids class MultikernelValidator: @@ -298,8 +299,8 @@ def _validate_cpu_allocation(self, instance, tree: GlobalDeviceTree): error_msg = self._format_error_with_context( error_type="CPU allocation error", instance_name=instance.name, - problem=f"CPU {cpu} does not exist in hardware inventory", - current_state=f"Hardware has CPUs {known}", + problem=f"CPU {format_cpu_id(cpu)} does not exist in hardware inventory", + current_state=f"Hardware has CPUs {format_cpu_ids(known)}", suggestion="Use a CPU from the hardware inventory", alternative="Check hardware inventory configuration", ) @@ -312,9 +313,9 @@ def _validate_cpu_allocation(self, instance, tree: GlobalDeviceTree): error_msg = self._format_error_with_context( error_type="CPU allocation error", instance_name=instance.name, - problem=f"CPUs {sorted(reserved_cpus)} are reserved for host kernel", - current_state=f"Host reserved CPUs: {sorted(host_reserved)}", - suggestion=f"Use available CPUs: {available_cpus}", + problem=f"CPUs {format_cpu_ids(sorted(reserved_cpus))} are reserved for host kernel", + current_state=f"Host reserved CPUs: {format_cpu_ids(sorted(host_reserved))}", + suggestion=f"Use available CPUs: {format_cpu_ids(available_cpus)}", alternative="Modify host-reserved CPU configuration", ) self.errors.append(error_msg) @@ -322,7 +323,7 @@ def _validate_cpu_allocation(self, instance, tree: GlobalDeviceTree): kinds = {cpus.kinds[cpu] for cpu in instance_cpus if cpu in cpus.kinds} if len(kinds) > 1: by_kind = "; ".join( - f"kind {kind}: {sorted(cpu for cpu in instance_cpus if cpus.kinds.get(cpu) == kind)}" + f"kind {kind}: " + format_cpu_ids(sorted(cpu for cpu in instance_cpus if cpus.kinds.get(cpu) == kind)) for kind in sorted(kinds) ) error_msg = self._format_error_with_context( @@ -346,7 +347,7 @@ def _validate_cpu_allocation(self, instance, tree: GlobalDeviceTree): error_type="CPU allocation conflict", instance_name=instance.name, problem=f"CPU overlap with instance '{other_name}'", - current_state=f"Both instances use CPUs: {sorted(overlap)}", + current_state=f"Both instances use CPUs: {format_cpu_ids(sorted(overlap))}", suggestion=f"Assign different CPUs to {instance.name} or {other_name}", alternative="Use CPU ranges instead of individual CPUs", ) @@ -355,7 +356,8 @@ def _validate_cpu_allocation(self, instance, tree: GlobalDeviceTree): available_cpus = set(cpus.available) - instance_cpus - other_cpus if available_cpus: self.suggestions.append( - f"Consider using available CPUs: {sorted(list(available_cpus)[:len(overlap)])}" + "Consider using available CPUs: " + + format_cpu_ids(sorted(list(available_cpus)[:len(overlap)])) ) def _validate_memory_allocation(self, instance, tree: GlobalDeviceTree): @@ -594,7 +596,7 @@ def _validate_numa_constraints(self, instance, tree: GlobalDeviceTree): if cpu_numa_node is not None and cpu_numa_node not in resources.numa_nodes: self.warnings.append( - f"Instance {instance.name}: CPU {cpu} is in NUMA node {cpu_numa_node}, " + f"Instance {instance.name}: CPU {format_cpu_id(cpu)} is in NUMA node {cpu_numa_node}, " f"but instance is configured for NUMA nodes {resources.numa_nodes}. " f"This may cause performance issues due to remote memory access." ) diff --git a/src/kerf/init/main.py b/src/kerf/init/main.py index 44250d7..3a49eea 100644 --- a/src/kerf/init/main.py +++ b/src/kerf/init/main.py @@ -37,7 +37,7 @@ pyudev = None from ..baseline import BaselineManager -from ..create.main import parse_cpu_spec, parse_device_list, parse_memory_spec +from ..create.main import expand_cpu_ranges, parse_cpu_ranges, parse_device_list, parse_memory_spec from ..dtc.parser import DeviceTreeParser, is_dts_text from ..dtc.reporter import ValidationReporter from ..dtc.validator import MultikernelValidator @@ -54,7 +54,14 @@ from ..devices import check_label, default_label, is_partition, pci_node_name, split_name from ..resources import get_busy_chunks_from_iomem, get_park_chunks_from_iomem from ..runtime import DeviceTreeManager -from ..topology import cpu_id_name, cpu_numa_nodes, logical_to_physical, node_for_cpus +from ..topology import ( + cpu_id_name, + cpu_numa_nodes, + format_cpu_id, + format_cpu_ids, + logical_to_physical, + node_for_cpus, +) MULTIKERNEL_MOUNT_POINT = "/sys/fs/multikernel" @@ -377,7 +384,7 @@ def spec_is_empty(spec: str, option: str, synonyms: Tuple[str, ...] = ()) -> boo return True -def parse_cpu_request(spec: str) -> List[int]: +def parse_cpu_request(spec: str) -> List[Tuple[int, int]]: """ Parse the pool CPU request, where "none" asks for no pool CPUs. @@ -385,7 +392,7 @@ def parse_cpu_request(spec: str) -> List[int]: spec: APIC ID specification, or "none" Returns: - The requested APIC IDs, empty for "none" + The requested ranges of APIC IDs, empty for "none" Raises: ValueError: If the specification is malformed @@ -393,7 +400,7 @@ def parse_cpu_request(spec: str) -> List[int]: if spec_is_empty(spec, "--cpus"): return [] try: - return parse_cpu_spec(spec) + return parse_cpu_ranges(spec) except ValueError as e: raise ValueError(f"Invalid CPU specification '{spec}': {e}") from e @@ -499,7 +506,9 @@ def _cpu_ranges(cpus: List[int]) -> str: parts[-1][1] = cpu else: parts.append([cpu, cpu]) - return ",".join(str(a) if a == b else f"{a}-{b}" for a, b in parts) + return ",".join( + format_cpu_id(a) if a == b else f"{format_cpu_id(a)}-{format_cpu_id(b)}" for a, b in parts + ) def pick_memory_node(cpu_list: List[int], @@ -606,7 +615,7 @@ def build_baseline_from_cmdline( ValueError: If the CPU or memory specification is invalid KernelInterfaceError: If the system topology cannot be read """ - cpu_list = sorted(set(parse_cpu_request(cpus)) | set(unclaimed or ())) + cpu_ranges = parse_cpu_request(cpus) # Silence about memory would otherwise read as "give it all back". if not memory: @@ -624,12 +633,13 @@ def build_baseline_from_cmdline( # The host stops listing a CPU in /proc/cpuinfo once the pool takes it, # so a re-init has to count the pool's own CPUs as valid. valid_apic_ids = valid_apic_ids | set(pool_cpus or ()) + cpu_list = sorted(set(expand_cpu_ranges(cpu_ranges, valid_apic_ids)) | set(unclaimed or ())) invalid_cpus = set(cpu_list) - valid_apic_ids if invalid_cpus: raise ValueError( - f"Invalid {cpu_id_name()}(s) specified: {sorted(invalid_cpus)}. " - f"Valid {cpu_id_name()}s on this system: {sorted(valid_apic_ids)}. " + f"Invalid {cpu_id_name()}(s) specified: {format_cpu_ids(sorted(invalid_cpus))}. " + f"Valid {cpu_id_name()}s on this system: {format_cpu_ids(sorted(valid_apic_ids))}. " "'kerf cpus' lists them." ) @@ -637,7 +647,7 @@ def build_baseline_from_cmdline( # Host reserved are all valid APIC IDs not in the available list boot_cpu = get_boot_cpu_from_system() if boot_cpu in cpu_list: - click.echo(f"Warning: {cpu_id_name()} {boot_cpu} is the host's boot CPU and stays with the host.", err=True) + click.echo(f"Warning: {cpu_id_name()} {format_cpu_id(boot_cpu)} is the host's boot CPU and stays with the host.", err=True) cpu_list = [cpu for cpu in cpu_list if cpu != boot_cpu] host_reserved_cpus = sorted(valid_apic_ids - set(cpu_list)) @@ -648,9 +658,9 @@ def build_baseline_from_cmdline( total_bytes = sum(requested.values()) if verbose: click.echo(f"Parsed {cpu_id_name()} specification: {cpus}") - click.echo(f" Valid {cpu_id_name()}s on system: {sorted(valid_apic_ids)}") - click.echo(f" Host-reserved {cpu_id_name()}s: {host_reserved_cpus}") - click.echo(f" Available {cpu_id_name()}s: {cpu_list}") + click.echo(f" Valid {cpu_id_name()}s on system: {format_cpu_ids(sorted(valid_apic_ids))}") + click.echo(f" Host-reserved {cpu_id_name()}s: {format_cpu_ids(host_reserved_cpus)}") + click.echo(f" Available {cpu_id_name()}s: {format_cpu_ids(cpu_list)}") click.echo("Requested pool memory:") for node, size in sorted(requested.items()): click.echo(f" node {node}: {size} bytes ({size / (1024**3):.2f} GB)") @@ -829,8 +839,8 @@ def line(label, items): if items: click.echo(f" {label}: {', '.join(str(i) for i in items)}") - line("CPUs to pool", diff.cpus_to_pool) - line("CPUs to host", diff.cpus_to_host) + line("CPUs to pool", [format_cpu_id(cpu) for cpu in diff.cpus_to_pool]) + line("CPUs to host", [format_cpu_id(cpu) for cpu in diff.cpus_to_host]) line("Memory to pool", [ f"{size >> 20} MB" + ("" if node == ANY_NODE else f" on node {node}") for node, size in diff.memory_to_pool @@ -964,7 +974,7 @@ def _dump_baseline_dts(baseline_mgr: BaselineManager, tree: GlobalDeviceTree) -> @click.command() @click.pass_context @click.option('--input', '-i', help='Baseline DTB to replay, as written by "kerf dump". Mutually exclusive with --cpus, --memory and --devices.') -@click.option('--cpus', '-c', help='Physical CPU IDs for baseline, the APIC ID on x86 or the MPIDR on arm64 (e.g., "128-134" or "128,130,132"), or "none" for no pool CPUs. Not logical CPU numbers. Mutually exclusive with --input.') +@click.option('--cpus', '-c', help='Physical CPU IDs for baseline, the APIC ID on x86 or the MPIDR on arm64 (e.g., "128-134", "128,130,132" or "0x100-0x103"), or "none" for no pool CPUs. Not logical CPU numbers; "kerf cpus" lists them. A range takes the CPUs that exist in it. Mutually exclusive with --input.') @click.option('--memory', '-m', help='Pool memory: SIZE (e.g. "2GB") on the node of the requested CPUs, per-node "8GB@0,8GB@1", or "none" for no pool memory. Required with --cpus, mutually exclusive with --input.') @click.option('--devices', '-d', help='Host device names or PCI addresses to pool, each with an optional "=name" every kernel names the device by (comma-separated, e.g. "nvme0n1,enP1s1f1,0000:4f:01.0=nvme1"), or "none" for no devices. By default an NVMe keeps its controller name and a network device keeps its interface name. Mutually exclusive with --input.') @click.option('--dry-run', is_flag=True, help='Report the plan without applying it. Still reads the pool from the kernel, so it needs root.') diff --git a/src/kerf/resources.py b/src/kerf/resources.py index 8a12a77..70e30c6 100644 --- a/src/kerf/resources.py +++ b/src/kerf/resources.py @@ -28,7 +28,7 @@ from .models import GlobalDeviceTree, PoolMemoryRegion from .exceptions import ResourceError -from .topology import cpu_id_name +from .topology import cpu_id_name, format_cpu_ids, logical_to_physical IOMEM_PATH = "/proc/iomem" @@ -277,6 +277,16 @@ def get_available_cpus(tree: GlobalDeviceTree) -> Set[int]: return set(tree.hardware.cpus.available) - allocated +def known_cpu_ids(tree: GlobalDeviceTree) -> Set[int]: + """ + Physical IDs of every CPU of the machine. + + The host stops reporting the CPUs it gave to the pool on x86, so both + have to be asked. + """ + return set(logical_to_physical().values()) | set(tree.hardware.cpus.available) + + def get_allocated_cpus(tree: GlobalDeviceTree) -> Set[int]: """ Get set of CPUs currently allocated to instances. @@ -382,8 +392,8 @@ def validate_cpu_allocation( invalid_cpus = requested_set - hardware_cpus if invalid_cpus: raise ResourceError( - f"Invalid {cpu_id_name()}s requested: {sorted(invalid_cpus)}. " - f"Available {cpu_id_name()}s: {sorted(hardware_cpus)}" + f"Invalid {cpu_id_name()}s requested: {format_cpu_ids(sorted(invalid_cpus))}. " + f"Available {cpu_id_name()}s: {format_cpu_ids(sorted(hardware_cpus))}" ) # Check APIC IDs are available @@ -396,10 +406,10 @@ def validate_cpu_allocation( continue conflict_cpus = set(instance.resources.cpus) & unavailable if conflict_cpus: - conflicts.append(f"{instance.name} uses {cpu_id_name()}s {sorted(conflict_cpus)}") + conflicts.append(f"{instance.name} uses {cpu_id_name()}s {format_cpu_ids(sorted(conflict_cpus))}") conflict_msg = ", ".join(conflicts) if conflicts else "allocated to other instances" - raise ResourceError(f"{cpu_id_name()}s {sorted(unavailable)} are not available ({conflict_msg})") + raise ResourceError(f"{cpu_id_name()}s {format_cpu_ids(sorted(unavailable))} are not available ({conflict_msg})") def find_next_instance_id(tree: GlobalDeviceTree) -> int: diff --git a/src/kerf/show/main.py b/src/kerf/show/main.py index 99cc215..90f101f 100644 --- a/src/kerf/show/main.py +++ b/src/kerf/show/main.py @@ -36,6 +36,7 @@ from ..models import DeviceInfo, GlobalDeviceTree from ..pool_diff import ANY_NODE from ..resources import get_pool_allocated_bytes +from ..topology import format_cpu_id, format_cpu_ids from ..utils import get_instance_id_from_name, get_instance_status, resolve_instance @@ -168,34 +169,34 @@ def display_baseline_info(tree: GlobalDeviceTree, verbose: bool = False): # it carries no host-reserved list worth a line. if hardware.cpus.host_reserved: click.echo( - f" Host Reserved: {len(hardware.cpus.host_reserved)} cpus: {hardware.cpus.host_reserved}" + f" Host Reserved: {len(hardware.cpus.host_reserved)} cpus: {format_cpu_ids(hardware.cpus.host_reserved)}" ) if hardware.cpus.available_free is not None: click.echo( - f" Pool CPUs: {len(hardware.cpus.available)} cpus: {hardware.cpus.available}" + f" Pool CPUs: {len(hardware.cpus.available)} cpus: {format_cpu_ids(hardware.cpus.available)}" ) click.echo( - f" Available CPUs: {len(hardware.cpus.available_free)} cpus: {hardware.cpus.available_free}" + f" Available CPUs: {len(hardware.cpus.available_free)} cpus: {format_cpu_ids(hardware.cpus.available_free)}" ) else: click.echo( - f" Available: {len(hardware.cpus.available)} cpus: {hardware.cpus.available}" + f" Available: {len(hardware.cpus.available)} cpus: {format_cpu_ids(hardware.cpus.available)}" ) if hardware.cpus.unclaimed: click.echo( - f" Unclaimed CPUs: {len(hardware.cpus.unclaimed)} cpus: {hardware.cpus.unclaimed}" + f" Unclaimed CPUs: {len(hardware.cpus.unclaimed)} cpus: {format_cpu_ids(hardware.cpus.unclaimed)}" " (never booted by the host, always in the pool)" ) for kind in sorted(set(hardware.cpus.kinds.values())): of_kind = sorted(cpu for cpu, k in hardware.cpus.kinds.items() if k == kind) - click.echo(f" Kind {kind}: {len(of_kind)} cpus: {of_kind}" + click.echo(f" Kind {kind}: {len(of_kind)} cpus: {format_cpu_ids(of_kind)}" + (" (the host's)" if kind == 0 else "")) if verbose and hardware.cpus.topology: click.echo("\n Topology:") for cpu_id, topo in sorted(hardware.cpus.topology.items()): click.echo( - f" CPU {cpu_id}: NUMA {topo.numa_node}, Socket {topo.socket_id}, Core {topo.core_id}, Thread {topo.thread_id}" + f" CPU {format_cpu_id(cpu_id)}: NUMA {topo.numa_node}, Socket {topo.socket_id}, Core {topo.core_id}, Thread {topo.thread_id}" ) # Memory Information @@ -243,7 +244,7 @@ def display_baseline_info(tree: GlobalDeviceTree, verbose: bool = False): mem_gb = numa_node.memory_size / (1024**3) click.echo(f" Node {node_id}:") click.echo(f" Memory: {mem_gb:.2f} GB (base: 0x{numa_node.memory_base:x})") - click.echo(f" CPUs: {numa_node.cpus}") + click.echo(f" CPUs: {format_cpu_ids(numa_node.cpus)}") click.echo(f" Type: {numa_node.memory_type}") if verbose and numa_node.distance_matrix: click.echo(" Distance:") diff --git a/src/kerf/topology.py b/src/kerf/topology.py index 151498f..46394e1 100644 --- a/src/kerf/topology.py +++ b/src/kerf/topology.py @@ -60,6 +60,11 @@ def format_cpu_id(cpu: int) -> str: return str(cpu) +def format_cpu_ids(cpus: Iterable[int]) -> str: + """Write a list of physical CPU IDs, in the order given.""" + return "[" + ", ".join(format_cpu_id(cpu) for cpu in cpus) + "]" + + def _parse_cpulist(text: str) -> List[int]: """Expand a sysfs cpulist ("0-3,8") into logical CPU numbers.""" cpus: List[int] = [] diff --git a/src/kerf/update/main.py b/src/kerf/update/main.py index 83a392f..4c811a0 100644 --- a/src/kerf/update/main.py +++ b/src/kerf/update/main.py @@ -29,7 +29,7 @@ from typing import Optional, List, Tuple import click -from ..create.main import parse_cpu_spec, parse_memory_spec +from ..create.main import expand_cpu_ranges, parse_cpu_ranges, parse_memory_spec from ..dtc.parser import DeviceTreeParser from ..exceptions import KernelInterfaceError, ParseError, ResourceError, ValidationError from ..init.main import spec_is_empty @@ -38,9 +38,11 @@ find_free_range_from_iomem, get_memory_granule, get_instance_regions_from_iomem, + known_cpu_ids, validate_cpu_allocation, ) from ..runtime import DeviceTreeManager +from ..topology import format_cpu_id, format_cpu_ids from ..utils import get_instance_id_from_name @@ -179,10 +181,10 @@ def update( click.echo(f"Error: Instance '{name}' does not exist", err=True) sys.exit(1) - cpu_list = None + cpu_ranges = None if cpus: try: - cpu_list = parse_cpu_spec(cpus) + cpu_ranges = parse_cpu_ranges(cpus) except ValueError as e: click.echo(f"Error: Invalid CPU specification '{cpus}': {e}", err=True) sys.exit(2) @@ -232,7 +234,9 @@ def update_instance_operation(current): modified = copy.deepcopy(current) modified.instances[instance_node_name] = copy.deepcopy(existing_instance) - if cpu_list is not None: + cpu_list = None + if cpu_ranges is not None: + cpu_list = expand_cpu_ranges(cpu_ranges, known_cpu_ids(modified)) current_cpus = set(existing_instance.resources.cpus) requested_cpus = set(cpu_list) new_cpus = requested_cpus - current_cpus @@ -257,8 +261,8 @@ def update_instance_operation(current): old_instance, new_instance = update_instance_operation(current) click.echo(f"✓ Validation passed for updating instance '{name}'") - if cpu_list is not None: - click.echo(f" CPUs: {', '.join(map(str, new_instance.resources.cpus))}") + if cpu_ranges is not None: + click.echo(f" CPUs: {', '.join(map(format_cpu_id, new_instance.resources.cpus))}") if memory_bytes is not None: click.echo(f" Memory: {memory}") @@ -281,8 +285,8 @@ def update_instance_operation(current): if debug: current = manager.read_baseline() old_instance, new_instance = update_instance_operation(current) - click.echo(f"\nDebug: Old instance: CPUs={old_instance.resources.cpus}, Devices={old_instance.resources.devices}") - click.echo(f"Debug: New instance: CPUs={new_instance.resources.cpus}, Devices={new_instance.resources.devices}") + click.echo(f"\nDebug: Old instance: CPUs={format_cpu_ids(old_instance.resources.cpus)}, Devices={old_instance.resources.devices}") + click.echo(f"Debug: New instance: CPUs={format_cpu_ids(new_instance.resources.cpus)}, Devices={new_instance.resources.devices}") dump_overlay_for_debug(manager, name, old_instance, new_instance, pci_ids=pci_ids) def apply_update_operation(current): @@ -303,7 +307,7 @@ def apply_update_operation(current): current = manager.read_baseline() _, new_instance = update_instance_operation(current) click.echo(f" Instance ID: {new_instance.id}") - click.echo(f" CPUs: {', '.join(map(str, new_instance.resources.cpus))}") + click.echo(f" CPUs: {', '.join(map(format_cpu_id, new_instance.resources.cpus))}") click.echo(f" Memory: {new_instance.resources.memory_bytes} bytes") except ResourceError as e: click.echo(f"Error: Resource allocation failed: {e}", err=True) diff --git a/tests/conftest.py b/tests/conftest.py index 72d7a23..6c8849c 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -50,6 +50,12 @@ def boot_cpu_is_zero(monkeypatch): monkeypatch.setattr(init_main, "get_boot_cpu_from_system", lambda: 0) +@pytest.fixture(autouse=True) +def on_x86(monkeypatch): + """Physical CPU IDs are written per architecture; a test of another one asks for it.""" + monkeypatch.setattr("platform.machine", lambda: "x86_64") + + @pytest.fixture def sample_hardware(): """Create sample hardware inventory for testing.""" diff --git a/tests/test_cpu_spec.py b/tests/test_cpu_spec.py new file mode 100644 index 0000000..476798f --- /dev/null +++ b/tests/test_cpu_spec.py @@ -0,0 +1,125 @@ +# Copyright 2026 Multikernel Technologies, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Tests for how physical CPU IDs are read from --cpus and written back. +""" + +import pytest + +from kerf import resources +from kerf.create.main import expand_cpu_ranges, parse_cpu_id, parse_cpu_ranges +from kerf.exceptions import ResourceError +from kerf.init import main as init +from kerf.models import CPUAllocation, GlobalDeviceTree, HardwareInventory, MemoryAllocation +from kerf.show.main import display_baseline_info +from kerf.topology import format_cpu_ids + +SPARSE = {0x0, 0x1, 0x100, 0x101, 0x200, 0x201} + + +def _tree(available): + cpus = CPUAllocation(total=len(SPARSE), host_reserved=[0x0], available=list(available)) + memory = MemoryAllocation(total_bytes=0, host_reserved_bytes=0) + hardware = HardwareInventory(cpus=cpus, memory=memory, devices={}) + return GlobalDeviceTree(hardware=hardware, instances={}, device_references={}) + + +@pytest.fixture(name="arm64") +def _arm64(monkeypatch): + monkeypatch.setattr("platform.machine", lambda: "aarch64") + + +@pytest.fixture(name="sparse_host") +def _sparse_host(monkeypatch): + monkeypatch.setattr(init, "get_valid_apic_ids_from_system", lambda: set(SPARSE)) + monkeypatch.setattr(init, "get_boot_cpu_from_system", lambda: 0x0) + + +@pytest.mark.parametrize("text, cpu", [("128", 128), ("0x100", 256), ("0X1a0100", 0x1A0100), (" 7 ", 7)]) +def test_a_cpu_id_is_decimal_or_hex(text, cpu): + assert parse_cpu_id(text) == cpu + + +@pytest.mark.parametrize("text", ["", "x100", "0x", "1a", "0x1g"]) +def test_a_malformed_cpu_id_is_rejected(text): + with pytest.raises(ValueError): + parse_cpu_id(text) + + +def test_a_spec_is_parsed_into_its_ranges(): + assert parse_cpu_ranges("0x100-0x103, 8,4-7") == [(0x100, 0x103), (8, 8), (4, 7)] + + +@pytest.mark.parametrize("spec", ["7-4", "0x101-0x100", "4-", "4,,5", "4-5-6", "cpu4"]) +def test_a_malformed_spec_is_rejected(spec): + with pytest.raises(ValueError): + parse_cpu_ranges(spec) + + +def test_a_range_takes_the_cpus_that_exist_in_it(): + assert expand_cpu_ranges([(0x1, 0x200)], SPARSE) == [0x1, 0x100, 0x101, 0x200] + + +def test_a_range_of_consecutive_ids_is_every_one_of_them(): + assert expand_cpu_ranges([(4, 7), (9, 9)], range(16)) == [4, 5, 6, 7, 9] + + +def test_the_ends_of_a_range_are_kept_for_validation_to_name(): + assert expand_cpu_ranges([(0x100, 0x103)], SPARSE) == [0x100, 0x101, 0x103] + + +@pytest.mark.usefixtures("sparse_host") +def test_init_takes_a_hex_range_of_sparse_ids(): + tree = init.build_baseline_from_cmdline("0x100-0x201", memory="none") + + assert tree.hardware.cpus.available == [0x100, 0x101, 0x200, 0x201] + assert tree.hardware.cpus.host_reserved == [0x0, 0x1] + + +@pytest.mark.usefixtures("sparse_host", "arm64") +def test_init_names_a_wrong_mpidr_in_hex(): + with pytest.raises(ValueError, match=r"Invalid MPIDR\(s\) specified: \[0x103\]\. " + r"Valid MPIDRs on this system: \[0x0, 0x1, 0x100,"): + init.build_baseline_from_cmdline("0x100-0x103", memory="none") + + +@pytest.mark.usefixtures("arm64") +def test_mpidr_lists_are_written_in_hex(): + assert format_cpu_ids([0x0, 0x100]) == "[0x0, 0x100]" + + +def test_other_id_lists_are_written_as_before(monkeypatch): + monkeypatch.setattr("platform.machine", lambda: "x86_64") + assert format_cpu_ids([4, 128]) == str([4, 128]) + + +@pytest.mark.usefixtures("arm64") +def test_show_writes_mpidrs_in_hex(capsys): + display_baseline_info(_tree([0x100, 0x101])) + + assert "Available: 2 cpus: [0x100, 0x101]" in capsys.readouterr().out + + +@pytest.mark.usefixtures("arm64") +def test_a_cpu_outside_the_pool_is_named_in_hex(): + with pytest.raises(ResourceError, match=r"Invalid MPIDRs requested: \[0x200\]\. " + r"Available MPIDRs: \[0x100, 0x101\]"): + resources.validate_cpu_allocation(_tree([0x100, 0x101]), [0x200]) + + +def test_known_cpus_are_the_hosts_and_the_pools(monkeypatch): + monkeypatch.setattr(resources, "logical_to_physical", lambda: {0: 0x0, 1: 0x1}) + + assert resources.known_cpu_ids(_tree([0x100, 0x101])) == {0x0, 0x1, 0x100, 0x101} diff --git a/tests/test_init_memory_spec.py b/tests/test_init_memory_spec.py index d3749ac..1fe2237 100644 --- a/tests/test_init_memory_spec.py +++ b/tests/test_init_memory_spec.py @@ -73,11 +73,11 @@ def test_memory_none_cannot_be_mixed(spec): @pytest.mark.parametrize("spec", ["none", "NONE", " none "]) def test_cpus_none_asks_for_nothing(spec): - assert parse_cpu_request(spec) == [] + assert not parse_cpu_request(spec) def test_cpus_are_still_parsed(): - assert parse_cpu_request("1-3,8") == [1, 2, 3, 8] + assert parse_cpu_request("1-3,8") == [(1, 3), (8, 8)] @pytest.mark.parametrize("spec", ["none,4", "4,none", "none,0"])