kerf-multikernel 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
kerf/kill/__init__.py ADDED
@@ -0,0 +1,21 @@
1
+ # Copyright 2025 Multikernel Technologies, Inc.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ Kernel shutdown subcommand implementation.
17
+ """
18
+
19
+ from .main import kill_cmd
20
+
21
+ __all__ = ['kill_cmd']
kerf/kill/main.py ADDED
@@ -0,0 +1,275 @@
1
+ # Copyright 2025 Multikernel Technologies, Inc.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ Kernel shutdown subcommand implementation using reboot syscall with MULTIKERNEL_HALT command.
17
+ """
18
+
19
+ import ctypes
20
+ import os
21
+ import platform
22
+ import sys
23
+ from pathlib import Path
24
+ from typing import Optional
25
+
26
+ import click
27
+
28
+ from ..models import InstanceState
29
+ from ..utils import get_instance_id_from_name
30
+
31
+
32
+ LINUX_REBOOT_MAGIC1 = 0xfee1dead
33
+ LINUX_REBOOT_MAGIC2 = 672274793 # 0x28121969
34
+ LINUX_REBOOT_CMD_MULTIKERNEL_HALT = 0x4D4B4C48
35
+ LINUX_REBOOT_CMD_MULTIKERNEL_HALT_FORCE = 0x4D4B4C46
36
+
37
+ SYS_REBOOT_X86_64 = 169
38
+ SYS_REBOOT_ARM64 = 142
39
+ SYS_REBOOT_ARM = 88
40
+ SYS_REBOOT_X86 = 88
41
+
42
+
43
+ def get_reboot_syscall():
44
+ """Get the reboot syscall number for current architecture."""
45
+ arch = platform.machine().lower()
46
+ if arch in ('x86_64', 'amd64'):
47
+ return SYS_REBOOT_X86_64
48
+ if arch in ('aarch64', 'arm64'):
49
+ return SYS_REBOOT_ARM64
50
+ if arch.startswith('arm'):
51
+ return SYS_REBOOT_ARM
52
+ if arch in ('i386', 'i686', 'x86'):
53
+ return SYS_REBOOT_X86
54
+ click.echo(
55
+ f"Warning: Unknown architecture '{arch}', assuming x86_64 syscall number",
56
+ err=True
57
+ )
58
+ return SYS_REBOOT_X86_64
59
+
60
+
61
+ class MultikernelBootArgs(ctypes.Structure):
62
+ """Structure for multikernel boot arguments."""
63
+ _fields_ = [
64
+ ("mk_id", ctypes.c_int),
65
+ ]
66
+
67
+ def __init__(self):
68
+ super().__init__()
69
+ self.mk_id = 0
70
+
71
+
72
+ def halt_multikernel(mk_id: int, force: bool = False) -> int:
73
+ libc = ctypes.CDLL(None, use_errno=True)
74
+ syscall_fn = libc.syscall
75
+
76
+ syscall_num = get_reboot_syscall()
77
+
78
+ args = MultikernelBootArgs()
79
+ args.mk_id = mk_id
80
+
81
+ cmd = LINUX_REBOOT_CMD_MULTIKERNEL_HALT_FORCE if force else LINUX_REBOOT_CMD_MULTIKERNEL_HALT
82
+
83
+ syscall_fn.argtypes = [
84
+ ctypes.c_long, # syscall number
85
+ ctypes.c_ulong, # LINUX_REBOOT_MAGIC1
86
+ ctypes.c_ulong, # LINUX_REBOOT_MAGIC2
87
+ ctypes.c_ulong, # LINUX_REBOOT_CMD_MULTIKERNEL_HALT[_FORCE]
88
+ ctypes.POINTER(MultikernelBootArgs)
89
+ ]
90
+ syscall_fn.restype = ctypes.c_long
91
+
92
+ result = syscall_fn(
93
+ syscall_num,
94
+ LINUX_REBOOT_MAGIC1,
95
+ LINUX_REBOOT_MAGIC2,
96
+ cmd,
97
+ ctypes.byref(args)
98
+ )
99
+
100
+ if result < 0:
101
+ errno_value = ctypes.get_errno()
102
+ raise OSError(errno_value, os.strerror(errno_value))
103
+
104
+ return result
105
+
106
+
107
+ @click.command(name='kill')
108
+ @click.argument('name', required=False)
109
+ @click.option('--id', type=int, help='Multikernel instance ID to shutdown (alternative to name)')
110
+ @click.option('--force', '-f', is_flag=True, help='Force shutdown without graceful termination')
111
+ @click.option('--verbose', '-v', is_flag=True, help='Verbose output')
112
+ def kill_cmd(name: Optional[str], id: Optional[int], force: bool, verbose: bool):
113
+ """
114
+ Shutdown a multikernel instance using the reboot syscall.
115
+
116
+ This command shuts down a running multikernel instance by name or ID using
117
+ the reboot syscall with the MULTIKERNEL_HALT command.
118
+
119
+ Examples:
120
+
121
+ kerf kill web-server
122
+ kerf kill --id=1
123
+ kerf kill --force web-server
124
+ """
125
+ try:
126
+ if not name and id is None:
127
+ click.echo(
128
+ "Error: Either instance name or --id must be provided",
129
+ err=True
130
+ )
131
+ click.echo(
132
+ "Usage: kerf kill <name> or kerf kill --id=<id>",
133
+ err=True
134
+ )
135
+ sys.exit(2)
136
+
137
+ instance_name = None
138
+ instance_id = None
139
+
140
+ if name:
141
+ instance_name = name
142
+ instance_id = get_instance_id_from_name(name)
143
+
144
+ if instance_id is None:
145
+ click.echo(
146
+ f"Error: Instance '{name}' not found",
147
+ err=True
148
+ )
149
+ click.echo(
150
+ "Check available instances in /sys/fs/multikernel/instances/",
151
+ err=True
152
+ )
153
+ sys.exit(1)
154
+
155
+ if verbose:
156
+ click.echo(f"Instance name: {name} (ID: {instance_id})")
157
+ else:
158
+ instance_id = id
159
+
160
+ if instance_id < 1 or instance_id > 511:
161
+ click.echo(
162
+ f"Error: --id must be between 1 and 511 (got {instance_id})",
163
+ err=True
164
+ )
165
+ sys.exit(2)
166
+
167
+ instances_dir = Path('/sys/fs/multikernel/instances')
168
+ if instances_dir.exists():
169
+ for inst_dir in instances_dir.iterdir():
170
+ if inst_dir.is_dir():
171
+ found_id = get_instance_id_from_name(inst_dir.name)
172
+ if found_id == instance_id:
173
+ instance_name = inst_dir.name
174
+ break
175
+
176
+ if not instance_name:
177
+ click.echo(
178
+ f"Error: Instance with ID {instance_id} not found",
179
+ err=True
180
+ )
181
+ click.echo(
182
+ "Check available instances in /sys/fs/multikernel/instances/",
183
+ err=True
184
+ )
185
+ sys.exit(1)
186
+
187
+ status_path = Path(f'/sys/fs/multikernel/instances/{instance_name}/status')
188
+ if verbose:
189
+ click.echo(f"Checking status for instance '{instance_name}'...")
190
+ click.echo(f"Status file: {status_path}")
191
+
192
+ if not status_path.exists():
193
+ click.echo(
194
+ f"Error: Instance '{instance_name}' status file not found",
195
+ err=True
196
+ )
197
+ sys.exit(1)
198
+
199
+ try:
200
+ with open(status_path, 'r', encoding='utf-8') as f:
201
+ status = f.read().strip()
202
+
203
+ status_lower = status.lower()
204
+ # A force halt is also valid on a 'loaded' instance: a previous
205
+ # halt settles the state before every CPU is confirmed parked,
206
+ # and rerunning it is how CPUs missed the first time are rescued.
207
+ allowed = {InstanceState.ACTIVE.value}
208
+ if force:
209
+ allowed.add(InstanceState.LOADED.value)
210
+ if status_lower not in allowed:
211
+ click.echo(
212
+ f"Error: Instance '{instance_name}' (ID: {instance_id}) is not running",
213
+ err=True
214
+ )
215
+ click.echo(
216
+ f"Current status: '{status}' (expected: {' or '.join(sorted(allowed))})",
217
+ err=True
218
+ )
219
+ sys.exit(1)
220
+
221
+ if verbose:
222
+ click.echo(f"Instance status: '{status}'")
223
+ except (OSError, IOError) as e:
224
+ click.echo(
225
+ f"Error: Failed to read status file: {e}",
226
+ err=True
227
+ )
228
+ sys.exit(1)
229
+
230
+ halt_cmd = LINUX_REBOOT_CMD_MULTIKERNEL_HALT_FORCE if force else LINUX_REBOOT_CMD_MULTIKERNEL_HALT
231
+ if verbose:
232
+ click.echo(f"✓ Instance '{instance_name}' is running")
233
+ click.echo(f"Instance ID to shutdown: {instance_id}")
234
+ click.echo(f"Using reboot syscall with command: 0x{halt_cmd:x}{' (force)' if force else ''}")
235
+ click.echo("Calling reboot syscall...")
236
+ else:
237
+ force_str = " (force)" if force else ""
238
+ click.echo(f"Shutting down instance '{instance_name}' (ID: {instance_id}){force_str}...")
239
+
240
+ result = halt_multikernel(instance_id, force=force)
241
+
242
+ if verbose:
243
+ click.echo(f"✓ Shutdown command executed successfully (result: {result})")
244
+ else:
245
+ click.echo("✓ Shutdown command executed successfully")
246
+
247
+ except OSError as e:
248
+ click.echo(f"Error: reboot syscall failed: {e}", err=True)
249
+ if e.errno == 1: # EPERM
250
+ click.echo(
251
+ "Note: This operation requires root privileges",
252
+ err=True
253
+ )
254
+ elif e.errno == 22: # EINVAL
255
+ click.echo(
256
+ f"Error: Invalid arguments for instance '{instance_name}' (ID: {instance_id})",
257
+ err=True
258
+ )
259
+ click.echo(
260
+ "The kernel may not support the MULTIKERNEL_HALT reboot command, or the instance ID is invalid.",
261
+ err=True
262
+ )
263
+ elif e.errno == 3: # ESRCH
264
+ click.echo(
265
+ "Note: Multikernel instance not found or not running.",
266
+ err=True
267
+ )
268
+ sys.exit(1)
269
+
270
+ except Exception as exc:
271
+ click.echo(f"Unexpected error: {exc}", err=True)
272
+ if verbose:
273
+ import traceback
274
+ traceback.print_exc()
275
+ sys.exit(1)
kerf/lazy_cma.py ADDED
@@ -0,0 +1,132 @@
1
+ # Copyright 2026 Multikernel Technologies, Inc.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ Client for the lazy_cma runtime contiguous memory allocator.
17
+
18
+ kerf allocates the multikernel memory pool at runtime through
19
+ /dev/lazy_cma instead of requiring a boot-time reservation. Allocating
20
+ under the canonical resource name ("Multikernel Memory Pool") makes the
21
+ pool discoverable in /proc/iomem, which is where kerf and the kernel
22
+ tooling look it up.
23
+ """
24
+
25
+ import fcntl
26
+ import os
27
+ import struct
28
+
29
+ from .exceptions import KernelInterfaceError
30
+
31
+ LAZY_CMA_DEVICE = "/dev/lazy_cma"
32
+
33
+ #: iomem resource name the multikernel stack discovers the pool by.
34
+ MULTIKERNEL_POOL_NAME = "Multikernel Memory Pool"
35
+
36
+ _LAZY_CMA_IOC_MAGIC = ord("H")
37
+ _LAZY_CMA_NAME_MAX = 64
38
+
39
+ # struct lazy_cma_allocation_data {
40
+ # __u64 len;
41
+ # __u64 phys_addr; /* out */
42
+ # __s32 node; /* NUMA node; -1 = any */
43
+ # __u32 pad;
44
+ # char name[64]; /* iomem resource name */
45
+ # };
46
+ _ALLOC_FORMAT = f"<QQiI{_LAZY_CMA_NAME_MAX}s"
47
+ _ALLOC_SIZE = struct.calcsize(_ALLOC_FORMAT)
48
+
49
+ _IOC_WRITE = 1
50
+ _IOC_READ = 2
51
+
52
+
53
+ def _ioc(direction: int, nr: int, size: int) -> int:
54
+ """Encode an ioctl request number (matches the kernel's _IOC macro)."""
55
+ return (direction << 30) | (size << 16) | (_LAZY_CMA_IOC_MAGIC << 8) | nr
56
+
57
+
58
+ LAZY_CMA_IOCTL_ALLOC = _ioc(_IOC_READ | _IOC_WRITE, 0x0, _ALLOC_SIZE)
59
+
60
+
61
+ def allocate(size_bytes: int, name: str, node: int = -1) -> int:
62
+ """
63
+ Allocate physically contiguous memory via /dev/lazy_cma.
64
+
65
+ Args:
66
+ size_bytes: Allocation size in bytes (page granularity in the kernel)
67
+ name: iomem resource name for the allocation
68
+ node: NUMA node to allocate from, or -1 for any node
69
+
70
+ Returns:
71
+ Physical base address of the allocation
72
+
73
+ Raises:
74
+ KernelInterfaceError: If the device is unavailable or allocation fails
75
+ ValueError: If the arguments are invalid
76
+ """
77
+ if size_bytes <= 0:
78
+ raise ValueError(f"Allocation size must be positive, got {size_bytes}")
79
+
80
+ encoded_name = name.encode("utf-8")
81
+ if len(encoded_name) >= _LAZY_CMA_NAME_MAX:
82
+ raise ValueError(
83
+ f"Resource name too long ({len(encoded_name)} bytes, "
84
+ f"max {_LAZY_CMA_NAME_MAX - 1})"
85
+ )
86
+
87
+ request = bytearray(
88
+ struct.pack(_ALLOC_FORMAT, size_bytes, 0, node, 0, encoded_name)
89
+ )
90
+
91
+ try:
92
+ fd = os.open(LAZY_CMA_DEVICE, os.O_RDWR)
93
+ except FileNotFoundError as exc:
94
+ raise KernelInterfaceError(
95
+ f"{LAZY_CMA_DEVICE} not found. Load the lazy_cma kernel module "
96
+ "first (e.g. insmod lazy_cma.ko)."
97
+ ) from exc
98
+ except PermissionError as exc:
99
+ raise KernelInterfaceError(
100
+ f"Permission denied opening {LAZY_CMA_DEVICE}. kerf must run as "
101
+ "root to allocate pool memory."
102
+ ) from exc
103
+
104
+ try:
105
+ fcntl.ioctl(fd, LAZY_CMA_IOCTL_ALLOC, request)
106
+ except OSError as exc:
107
+ raise KernelInterfaceError(
108
+ f"lazy_cma allocation of {size_bytes} bytes failed: "
109
+ f"{os.strerror(exc.errno)} (errno {exc.errno}). "
110
+ "The system may not have enough contiguous free memory; "
111
+ "try a smaller pool size."
112
+ ) from exc
113
+ finally:
114
+ os.close(fd)
115
+
116
+ _, phys_addr, _, _, _ = struct.unpack(_ALLOC_FORMAT, bytes(request))
117
+ if phys_addr == 0:
118
+ raise KernelInterfaceError(
119
+ f"lazy_cma returned physical address 0 for a {size_bytes} byte "
120
+ "allocation"
121
+ )
122
+
123
+ return phys_addr
124
+
125
+
126
+ def allocate_multikernel_pool(size_bytes: int, node: int = -1) -> int:
127
+ """
128
+ Allocate the multikernel memory pool under its canonical iomem name.
129
+
130
+ Returns the physical base address of the pool.
131
+ """
132
+ return allocate(size_bytes, MULTIKERNEL_POOL_NAME, node)
kerf/load/__init__.py ADDED
@@ -0,0 +1,21 @@
1
+ # Copyright 2025 Multikernel Technologies, Inc.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ Kernel loading subcommand implementation.
17
+ """
18
+
19
+ from .main import load
20
+
21
+ __all__ = ["load"]