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
use super::*;
use std::{
mem,
hash,
num::NonZeroUsize,
fs,
path::{Path, PathBuf},
fmt, error,
};
use libc::{
c_int,
MAP_HUGE_SHIFT,
};
pub const HUGEPAGE_LOCATION: &'static str = "/sys/kernel/mm/hugepages/";
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Copy)]
#[repr(transparent)]
pub struct MapHugeFlag(c_int);
#[derive(Debug)]
pub struct HugePageCalcErr(());
impl TryFrom<HugePage> for MapHugeFlag
{
type Error = HugePageCalcErr;
#[inline]
fn try_from(from: HugePage) -> Result<Self, Self::Error>
{
from.compute_huge().ok_or(HugePageCalcErr(()))
}
}
impl error::Error for HugePageCalcErr{}
impl fmt::Display for HugePageCalcErr
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
{
f.write_str("Invalid huge-page specification")
}
}
impl Default for MapHugeFlag
{
#[inline]
fn default() -> Self {
Self(MAP_HUGE_SHIFT)
}
}
#[inline(always)]
const fn log2(n: usize) -> usize
{
usize::BITS as usize - n.leading_zeros() as usize - 1
}
impl MapHugeFlag
{
#[inline]
pub const unsafe fn from_mask_unchecked(flag: c_int) -> Self
{
Self(flag)
}
pub const HUGE_DEFAULT: Self = Self(MAP_HUGE_SHIFT);
pub const HUGE_2MB: Self = Self(libc::MAP_HUGE_2MB);
pub const HUGE_1GB: Self = Self(libc::MAP_HUGE_1GB);
#[inline(always)]
pub const fn calculate(kilobytes: NonZeroUsize) -> Self
{
Self((log2(kilobytes.get()) << (MAP_HUGE_SHIFT as usize)) as c_int)
}
#[inline]
pub const fn try_calculate(kilobytes: usize) -> Option<Self>
{
match kilobytes {
0 => None,
kilobytes => {
if let Some(shift) = log2(kilobytes).checked_shl(MAP_HUGE_SHIFT as u32) {
if shift <= c_int::MAX as usize {
return Some(Self(shift as c_int));
}
}
None
}
}
}
#[inline]
pub const fn calculate_or_default(kilobytes: usize) -> Self
{
match Self::try_calculate(kilobytes) {
None => Self::HUGE_DEFAULT,
Some(x) => x,
}
}
#[inline]
pub const fn is_default(&self) -> bool
{
self.0 == Self::HUGE_DEFAULT.0
}
#[inline(always)]
pub const fn get_mask(self) -> c_int
{
self.0
}
}
impl From<MapHugeFlag> for c_int
{
#[inline]
fn from(from: MapHugeFlag) -> Self
{
from.0
}
}
#[derive(Default, Clone, Copy)]
pub enum HugePage {
Static(MapHugeFlag),
Dynamic{ kilobytes: usize },
#[default]
Smallest,
Largest,
Selected(for<'r> fn (&'r [usize]) -> Option<&'r usize>),
}
impl hash::Hash for HugePage {
#[inline]
fn hash<H: hash::Hasher>(&self, state: &mut H) {
mem::discriminant(self).hash(state);
match self {
Self::Static(hpf) => hpf.hash(state),
Self::Dynamic { kilobytes } => kilobytes.hash(state),
Self::Selected(func) => ptr::hash(func as *const _, state),
_ => (),
};
}
}
impl fmt::Debug for HugePage
{
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
{
f.debug_tuple("HugePage")
.field({
let v: &dyn fmt::Debug = match &self {
Self::Static(ref huge) => huge,
Self::Dynamic { ref kilobytes } => kilobytes,
Self::Smallest => &"<smallest>",
Self::Largest => &"<largest>",
Self::Selected(_) => &"<selector>",
};
v
})
.finish()
}
}
impl Eq for HugePage {}
impl PartialEq for HugePage
{
#[inline]
fn eq(&self, other: &Self) -> bool
{
match (self, other) {
(Self::Static(hpf), Self::Static(hpf2)) => hpf == hpf2,
(Self::Dynamic { kilobytes }, Self::Dynamic { kilobytes: kilobytes2 }) => kilobytes == kilobytes2,
(Self::Selected(func), Self::Selected(func2)) => ptr::eq(func, func2),
_ => mem::discriminant(self) == mem::discriminant(other),
}
}
}
impl HugePage
{
#[inline] pub fn compute_huge(self) -> Option<MapHugeFlag>
{
use HugePage::*;
match self {
Dynamic { kilobytes: 0 } |
Smallest |
Static(MapHugeFlag::HUGE_DEFAULT) => Some(MapHugeFlag::HUGE_DEFAULT),
Static(mask) => Some(mask),
Dynamic { kilobytes } => {
MapHugeFlag::try_calculate(kilobytes) },
Largest => Self::Selected(|sizes| sizes.iter().max()).compute_huge(),
Selected(func) => {
fn compute_selected(func: for<'r> fn (&'r [usize]) -> Option<&'r usize>) -> Option<MapHugeFlag>
{
use std::borrow::Cow;
let mask = match SYSTEM_HUGEPAGE_SIZES.as_ref() {
Ok(avail) => Cow::Borrowed(&avail[..]),
Err(_) => {
#[cold]
fn rescan() -> io::Result<Vec<usize>>
{
scan_hugepages().and_then(|x| x.into_iter().collect())
}
let v = rescan();
let mut v = if cfg!(debug_assertions) {
v.expect("Failed to compute available hugetlb sizes")
} else {
v.ok()?
};
v.sort_unstable();
Cow::Owned(v)
},
};
match func(mask.as_ref()) {
Some(mask) => Dynamic { kilobytes: *mask }.compute_huge(),
None => Some(MapHugeFlag::HUGE_DEFAULT),
}
}
compute_selected(func)
},
}
}
}
lazy_static! {
pub(crate) static ref SYSTEM_HUGEPAGE_SIZES: io::Result<Vec<usize>> = {
let mut val: io::Result<Vec<usize>> = scan_hugepages().and_then(|x| x.into_iter().collect());
if let Ok(ref mut arr) = val.as_mut() {
arr.sort_unstable();
};
val
};
pub static ref SYSTEM_HUGEPAGES: io::Result<Vec<MapHugeFlag>> =
SYSTEM_HUGEPAGE_SIZES.as_ref()
.map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, format!("SYSTEM_HUGEPAGES failed with error {err}")))
.map(|vec| vec.iter().map(|&size| MapHugeFlag::calculate_or_default(size)).collect());
}
pub fn scan_hugepages() -> io::Result<impl IntoIterator<Item=io::Result<usize>> + Send + Sync + 'static>
{
let path = Path::new(HUGEPAGE_LOCATION);
let dir = fs::read_dir(path)?;
#[derive(Debug)]
struct FilteredIterator(fs::ReadDir);
impl Iterator for FilteredIterator
{
type Item = io::Result<usize>;
fn next(&mut self) -> Option<Self::Item> {
loop {
break if let Some(next) = self.0.next() {
let path = match next {
Ok(next) => next.file_name(),
Err(err) => return Some(Err(err)),
};
let kbs = if let Some(dash) = memchr::memchr(b'-', path.as_bytes()) {
let name = &path.as_bytes()[(dash+1)..];
if let Some(k_loc) = memchr::memrchr(b'k', &name) {
&name[..k_loc]
} else {
continue
}
} else {
continue
};
let kb = if let Ok(kbs) = std::str::from_utf8(kbs) {
kbs.parse::<usize>().ok()
} else {
continue
};
match kb {
None => continue,
valid => valid.map(Ok)
}
} else {
None
}
}
}
}
Ok(FilteredIterator(dir))
}