1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 Fábio Henrique de Lima Silva (fhl.bsb@gmail.com) All rights reserved.
// SAFETY: Low-level virtual memory manipulation (mmap/ftruncate) with checked parameters.
#![warn(clippy::undocumented_unsafe_blocks)]
use super::{
HUGEPAGE_STATE_HUGETLB, HUGEPAGE_STATE_THP, MIRROR_BUF_HUGEPAGE_STATE, MirroredBuffer,
SIMULATE_FAIL,
};
use crate::math::common::huge_alloc::{HUGE_PAGE_2M, create_backing_fd, try_mmap_huge};
use libc::{
MADV_HUGEPAGE, MAP_FAILED, MAP_FIXED, MAP_SHARED, PROT_READ, PROT_WRITE, c_void, mmap, munmap,
sysconf,
};
use std::marker::PhantomData;
use std::ptr;
const fn gcd(mut a: usize, mut b: usize) -> usize {
while b != 0 {
let t = b;
b = a % b;
a = t;
}
a
}
const fn lcm(a: usize, b: usize) -> Option<usize> {
let g = gcd(a, b);
let a_div_g = a / g;
a_div_g.checked_mul(b)
}
/// Rounds `value` up to the closest multiple of `align`.
/// Panics if `align` is zero.
fn round_up_to_multiple(value: usize, align: usize) -> Option<usize> {
let padded = value.checked_add(align - 1)?;
Some(padded - (padded % align))
}
impl<T> MirroredBuffer<T> {
/// Creates a new mirrored buffer with huge-page preference.
///
/// The `requested_size` (in elements) will be rounded up to the next
/// multiple of the system page size (2 MB for huge pages, 4 KB for standard).
/// Equivalent to `new_aligned(requested_size, 1)`.
#[cold]
pub fn new(requested_size: usize) -> std::io::Result<Self> {
Self::new_aligned(requested_size, 1)
}
/// Creates a mirrored buffer guaranteeing `size_elements % elem_multiple == 0`.
///
/// Rounds `size_bytes` up to the least common multiple of the system page
/// size and `elem_multiple * size_of::<T>()`. This ensures both the mmap
/// mirror invariant (size is page-aligned) and divisibility by `elem_multiple`
/// — essential for ring-buffer wrap arithmetic in multi-channel DSP.
///
/// For huge-page path, rounds to `lcm(2 MiB, elem_multiple * size_of::<T>())`.
///
/// Cost is negligible: e.g. CH=12 (48 B stride) adds at most 12 KiB on 4 KB
/// pages, or up to 6 MiB on huge pages — all cold, during model load.
#[cold]
pub fn new_aligned(requested_size: usize, elem_multiple: usize) -> std::io::Result<Self> {
// SAFETY: Low-level virtual memory manipulation (mmap/ftruncate) with checked parameters.
let page_size = unsafe { sysconf(libc::_SC_PAGESIZE) } as usize;
let element_size = std::mem::size_of::<T>();
if element_size == 0 {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"MirroredBuffer does not support Zero Sized Types",
));
}
if requested_size == 0 {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"requested_size must be greater than zero",
));
}
if elem_multiple == 0 {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"elem_multiple must be greater than zero",
));
}
let requested_bytes = match requested_size.checked_mul(element_size) {
Some(val) => val,
None => {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"requested_size * element_size overflowed",
));
}
};
let total_chunk = match requested_bytes.checked_mul(2) {
Some(val) => val,
None => {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"requested_bytes * 2 overflowed",
));
}
};
let elem_stride = match elem_multiple.checked_mul(element_size) {
Some(val) => val,
None => {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"elem_multiple * element_size overflowed",
));
}
};
if total_chunk >= HUGE_PAGE_2M {
let huge_res = Self::try_new_huge_aligned(requested_bytes, HUGE_PAGE_2M, elem_stride);
if let Ok(buf) = huge_res {
MIRROR_BUF_HUGEPAGE_STATE
.store(HUGEPAGE_STATE_HUGETLB, std::sync::atomic::Ordering::Relaxed);
return Ok(buf);
}
}
let align_bytes = match lcm(page_size, elem_stride) {
Some(val) => val,
None => {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"lcm(page_size, elem_stride) overflowed",
));
}
};
let size_bytes = match round_up_to_multiple(requested_bytes, align_bytes) {
Some(v) => v,
None => {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"size_bytes calculation overflowed",
));
}
};
let size_elements = size_bytes / element_size;
assert!(
requested_size > 0,
"requested_size must be greater than zero"
);
// 1. Create backing store (memfd on Linux, stub fallback on other platforms)
// SAFETY: Low-level virtual memory manipulation (mmap/ftruncate) with checked parameters.
let fd = unsafe {
#[cfg(target_os = "linux")]
{
if SIMULATE_FAIL.with(|f| f.get()) {
*libc::__errno_location() = libc::ENOMEM;
return Err(std::io::Error::last_os_error());
}
}
create_backing_fd(size_bytes, false)?
};
// 2. Reserve contiguous virtual space (2x size)
let total_size = size_bytes * 2;
// SAFETY: Low-level virtual memory manipulation (mmap/ftruncate) with checked parameters.
let base_ptr = unsafe {
if SIMULATE_FAIL.with(|f| f.get()) {
*libc::__errno_location() = libc::ENOMEM;
MAP_FAILED
} else {
try_mmap_huge(ptr::null_mut(), total_size, -1, 0, false)
}
};
if base_ptr == MAP_FAILED {
let err = std::io::Error::last_os_error();
// SAFETY: Low-level virtual memory manipulation (mmap/ftruncate) with checked parameters.
unsafe { libc::close(fd) };
return Err(err);
}
// 3. Map the first half
// SAFETY: Low-level virtual memory manipulation (mmap/ftruncate) with checked parameters.
let ptr1 = unsafe {
mmap(
base_ptr,
size_bytes,
PROT_READ | PROT_WRITE,
MAP_FIXED | MAP_SHARED,
fd,
0,
)
};
if ptr1 != base_ptr {
let err = std::io::Error::last_os_error();
// SAFETY: Low-level virtual memory manipulation (mmap/ftruncate) with checked parameters.
unsafe {
munmap(base_ptr, total_size);
libc::close(fd);
}
return Err(err);
}
// 4. Map the second half (mirror)
// SAFETY: Low-level virtual memory manipulation (mmap/ftruncate) with checked parameters.
let ptr2 = unsafe {
mmap(
(base_ptr as *mut u8).add(size_bytes) as *mut c_void,
size_bytes,
PROT_READ | PROT_WRITE,
MAP_FIXED | MAP_SHARED,
fd,
0,
)
};
// SAFETY: Low-level virtual memory manipulation (mmap/ftruncate) with checked parameters.
if ptr2 != unsafe { (base_ptr as *mut u8).add(size_bytes) as *mut c_void } {
let err = std::io::Error::last_os_error();
// SAFETY: Low-level virtual memory manipulation (mmap/ftruncate) with checked parameters.
unsafe {
munmap(base_ptr, total_size);
libc::close(fd);
}
return Err(err);
}
// Hint THP promotion for the data regions, then force synchronous collapse.
// Only report THP active if the kernel confirms success (return 0).
// SAFETY: base_ptr and size_bytes are valid mapped regions.
let collapse_rc = unsafe {
libc::madvise(base_ptr, size_bytes, MADV_HUGEPAGE);
libc::madvise(base_ptr, size_bytes, libc::MADV_COLLAPSE)
};
if collapse_rc == 0 {
MIRROR_BUF_HUGEPAGE_STATE
.store(HUGEPAGE_STATE_THP, std::sync::atomic::Ordering::Relaxed);
}
// SAFETY: Low-level virtual memory manipulation (mmap/ftruncate) with checked parameters.
unsafe { libc::close(fd) };
Ok(Self {
ptr: base_ptr as *mut T,
size_elements,
_marker: PhantomData,
})
}
/// Attempts creation with explicit 2 MB huge pages, honouring element alignment.
#[cold]
fn try_new_huge_aligned(
requested_bytes: usize,
huge_page_size: usize,
elem_stride: usize,
) -> std::io::Result<Self> {
let element_size = std::mem::size_of::<T>();
let align_bytes = match lcm(huge_page_size, elem_stride) {
Some(val) => val,
None => {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"lcm(huge_page_size, elem_stride) overflowed",
));
}
};
let size_bytes = match round_up_to_multiple(requested_bytes, align_bytes) {
Some(v) => v,
None => {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"size_bytes calculation overflowed",
));
}
};
let size_elements = size_bytes / element_size;
// 1. Create HugeTLB-backed memfd (falls back to regular memfd)
// SAFETY: Low-level virtual memory manipulation (mmap/ftruncate) with checked parameters.
let fd = unsafe {
if SIMULATE_FAIL.with(|f| f.get()) {
*libc::__errno_location() = libc::ENOMEM;
return Err(std::io::Error::last_os_error());
}
create_backing_fd(size_bytes, true)?
};
let total_size = size_bytes * 2;
// 2. Reserve 2x virtual space with MAP_HUGETLB
// SAFETY: Low-level virtual memory manipulation (mmap/ftruncate) with checked parameters.
let base_ptr = unsafe { try_mmap_huge(ptr::null_mut(), total_size, -1, 0, true) };
if base_ptr == MAP_FAILED {
let err = std::io::Error::last_os_error();
// SAFETY: Low-level virtual memory manipulation (mmap/ftruncate) with checked parameters.
unsafe { libc::close(fd) };
return Err(err);
}
// 3. Map the first half
let map_flags = MAP_FIXED | MAP_SHARED;
// SAFETY: Low-level virtual memory manipulation (mmap/ftruncate) with checked parameters.
let ptr1 = unsafe {
mmap(
base_ptr,
size_bytes,
PROT_READ | PROT_WRITE,
map_flags,
fd,
0,
)
};
if ptr1 != base_ptr {
let err = std::io::Error::last_os_error();
// SAFETY: Low-level virtual memory manipulation (mmap/ftruncate) with checked parameters.
unsafe {
munmap(base_ptr, total_size);
libc::close(fd);
}
return Err(err);
}
// 4. Map the second half (mirror)
// SAFETY: Low-level virtual memory manipulation (mmap/ftruncate) with checked parameters.
let ptr2 = unsafe {
mmap(
(base_ptr as *mut u8).add(size_bytes) as *mut c_void,
size_bytes,
PROT_READ | PROT_WRITE,
map_flags,
fd,
0,
)
};
// SAFETY: Low-level virtual memory manipulation (mmap/ftruncate) with checked parameters.
if ptr2 != unsafe { (base_ptr as *mut u8).add(size_bytes) as *mut c_void } {
let err = std::io::Error::last_os_error();
// SAFETY: Low-level virtual memory manipulation (mmap/ftruncate) with checked parameters.
unsafe {
munmap(base_ptr, total_size);
libc::close(fd);
}
return Err(err);
}
// SAFETY: Low-level virtual memory manipulation (mmap/ftruncate) with checked parameters.
unsafe { libc::close(fd) };
Ok(Self {
ptr: base_ptr as *mut T,
size_elements,
_marker: PhantomData,
})
}
}