Debian Codegraph @

third_party/rust/memtest/src/lib.rs

raw
1 #[cfg(unix)]
2 use unix::{memory_lock, memory_resize_and_lock, PageFaultChecker};
3 #[cfg(windows)]
4 use windows::{memory_lock, memory_resize_and_lock, replace_set_size};
5 use {
6 prelude::*,
7 rand::{seq::SliceRandom, thread_rng},
8 serde::{Deserialize, Serialize},
9 std::{
10 error, fmt,
11 time::{Duration, Instant},
12 },
13 };
14
15 mod memtest;
16 mod prelude;
17
18 pub use memtest::{Error, Failure, Outcome, ParseTestKindError, TestKind, TestResult};
19
20 #[derive(Debug)]
21 pub struct Runner {
22 test_kinds: Vec<TestKind>,
23 timeout: Duration,
24 mem_lock_mode: MemLockMode,
25 #[allow(dead_code)]
26 allow_working_set_resize: bool,
27 allow_multithread: bool,
28 allow_early_termination: bool,
29 }
30
31 // TODO: Replace RunnerArgs with a Builder struct implementing fluent interface
32 /// A set of arguments that define the behavior of Runner
33 #[derive(Serialize, Deserialize, Debug)]
34 pub struct RunnerArgs {
35 /// How long should Runner run the test suite before timing out
36 pub timeout: Duration,
37 /// Whether memory will be locked before testing and whether the requested memory size of
38 /// testing can be reduced to accomodate memory locking
39 /// If memory locking failed but is required, Runner returns with error
40 pub mem_lock_mode: MemLockMode,
41 /// Whether the process working set can be resized to accomodate memory locking
42 /// This argument is only meaningful for Windows
43 pub allow_working_set_resize: bool,
44 /// Whether mulithreading is enabled
45 pub allow_multithread: bool,
46 /// Whether Runner returns immediately if a test fails or continues until all tests are run
47 pub allow_early_termination: bool,
48 }
49
50 #[derive(Debug)]
51 pub enum RunnerError {
52 MemLockFailed(anyhow::Error),
53 Other(anyhow::Error),
54 }
55
56 #[derive(Debug, Serialize, Deserialize)]
57 pub struct TestReportList {
58 pub tested_mem_length: usize,
59 pub mlocked: bool,
60 pub reports: Vec<TestReport>,
61 }
62
63 #[derive(Debug, Serialize, Deserialize)]
64 pub struct TestReport {
65 pub test_kind: TestKind,
66 pub outcome: Result<Outcome, memtest::Error<RuntimeError>>,
67 }
68
69 #[derive(Clone, Copy, Debug, Serialize, Deserialize)]
70 pub enum MemLockMode {
71 Resizable,
72 FixedSize,
73 PageFaultChecking,
74 Disabled,
75 }
76
77 #[derive(Debug, PartialEq, Eq)]
78 pub struct ParseMemLockModeError;
79
80 /// The minimum memory length (in usize) for Runner to run tests on
81 /// On a 64-bit machine, this is the size of a page
82 pub const MIN_MEMORY_LENGTH: usize = 512;
83
84 #[derive(Debug)]
85 struct MemLockGuard {
86 base_ptr: *mut usize,
87 mem_size: usize,
88 }
89
90 #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
91 pub enum RuntimeError {
92 Timeout,
93 PageFault,
94 }
95
96 /// A struct to ensure the test timeouts in a given duration
97 #[derive(Debug)]
98 struct TimeoutChecker {
99 deadline: Instant,
100 state: Option<TimeoutCheckerState>,
101 }
102
103 #[derive(Debug)]
104 struct TimeoutCheckerState {
105 test_start_time: Instant,
106 expected_iter: u64,
107 completed_iter: u64,
108 checkpoint: u64,
109 }
110
111 impl Runner {
112 /// Create a Runner containing all test kinds in random order
113 pub fn all_tests_random_order(args: &RunnerArgs) -> Runner {
114 let mut test_kinds = TestKind::ALL.to_vec();
115 test_kinds.shuffle(&mut thread_rng());
116
117 Self::from_test_kinds(args, test_kinds)
118 }
119
120 /// Create a Runner with specified test kinds
121 pub fn from_test_kinds(args: &RunnerArgs, test_kinds: Vec<TestKind>) -> Runner {
122 Runner {
123 test_kinds,
124 timeout: args.timeout,
125 mem_lock_mode: args.mem_lock_mode,
126 allow_working_set_resize: args.allow_working_set_resize,
127 allow_multithread: args.allow_multithread,
128 allow_early_termination: args.allow_early_termination,
129 }
130 }
131
132 /// Run the tests, possibly after locking the memory
133 pub fn run(&self, memory: &mut [usize]) -> Result<TestReportList, RunnerError> {
134 if memory.len() < MIN_MEMORY_LENGTH {
135 return Err(anyhow!("Insufficient memory length").into());
136 }
137
138 let deadline = Instant::now() + self.timeout;
139
140 if matches!(
141 self.mem_lock_mode,
142 MemLockMode::Disabled | MemLockMode::PageFaultChecking
143 ) {
144 return Ok(TestReportList {
145 tested_mem_length: memory.len(),
146 mlocked: false,
147 reports: self.run_tests(memory, deadline),
148 });
149 }
150
151 #[cfg(windows)]
152 // TODO: When it is MemLockMode::Resizable and working set resize failed, consider shrinking
153 // the memory region and try again
154 let _working_set_resize_guard = if self.allow_working_set_resize {
155 Some(
156 replace_set_size(std::mem::size_of_val(memory))
157 .context("Failed to replace process working set size")?,
158 )
159 } else {
160 None
161 };
162
163 let (memory, _mem_lock_guard) = match self.mem_lock_mode {
164 MemLockMode::FixedSize => memory_lock(memory),
165 MemLockMode::Resizable => memory_resize_and_lock(memory),
166 _ => unreachable!(),
167 }
168 .map_err(RunnerError::MemLockFailed)?;
169
170 Ok(TestReportList {
171 tested_mem_length: memory.len(),
172 mlocked: true,
173 reports: self.run_tests(memory, deadline),
174 })
175 }
176
177 /// Run tests
178 fn run_tests(&self, memory: &mut [usize], deadline: Instant) -> Vec<TestReport> {
179 let mut reports = Vec::new();
180 let mut timed_out = false;
181
182 for test_kind in &self.test_kinds {
183 let test_result = if timed_out {
184 Err(memtest::Error::Observer(RuntimeError::Timeout))
185 } else if self.allow_multithread {
186 std::thread::scope(|scope| {
187 let num_threads = num_cpus::get();
188 let chunk_size = memory.len() / num_threads;
189
190 let mut handles = vec![];
191 for chunk in memory.chunks_exact_mut(chunk_size) {
192 handles.push(scope.spawn(|| self.run_test(*test_kind, chunk, deadline)));
193 }
194
195 #[allow(clippy::manual_try_fold)]
196 handles
197 .into_iter()
198 .map(|handle| {
199 handle
200 .join()
201 .unwrap_or(Err(memtest::Error::Other(anyhow!("Thread panicked"))))
202 })
203 .fold(Ok(Outcome::Pass), |acc, result| {
204 use {memtest::Error::*, Outcome::*};
205 match (acc, result) {
206 (Err(Other(e)), _) | (_, Err(Other(e))) => Err(Other(e)),
207 (Ok(Fail(f)), _) | (_, Ok(Fail(f))) => Ok(Fail(f)),
208 (Err(Observer(e)), _) | (_, Err(Observer(e))) => Err(Observer(e)),
209 _ => Ok(Pass),
210 }
211 })
212 })
213 } else {
214 self.run_test(*test_kind, memory, deadline)
215 };
216 timed_out = matches!(
217 test_result,
218 Err(memtest::Error::Observer(RuntimeError::Timeout))
219 );
220
221 if matches!(test_result, Ok(Outcome::Fail(_))) && self.allow_early_termination {
222 reports.push(TestReport::new(*test_kind, test_result));
223 warn!("Test failed, terminating early");
224 break;
225 }
226 reports.push(TestReport::new(*test_kind, test_result));
227 }
228
229 reports
230 }
231
232 fn run_test(
233 &self,
234 test_kind: TestKind,
235 memory: &mut [usize],
236 deadline: Instant,
237 ) -> Result<Outcome, memtest::Error<RuntimeError>> {
238 let timeout_checker = TimeoutChecker::new(deadline);
239
240 #[cfg(unix)]
241 if matches!(self.mem_lock_mode, MemLockMode::PageFaultChecking) {
242 let runtime_checker = unix::RuntimeChecker::new(
243 timeout_checker,
244 PageFaultChecker::new(memory.as_mut_ptr() as usize, memory.len())
245 .map_err(memtest::Error::Other)?,
246 );
247 test_kind.run(memory, runtime_checker)
248 } else {
249 test_kind.run(memory, timeout_checker)
250 }
251
252 // PageFaultChecker is not implemented for Windows
253 #[cfg(windows)]
254 test_kind.run(memory, timeout_checker)
255 }
256 }
257
258 impl fmt::Display for RunnerError {
259 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
260 write!(f, "{:?}", self)
261 }
262 }
263
264 impl error::Error for RunnerError {
265 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
266 match self {
267 RunnerError::MemLockFailed(err) | RunnerError::Other(err) => Some(err.as_ref()),
268 }
269 }
270 }
271
272 impl From<anyhow::Error> for RunnerError {
273 fn from(err: anyhow::Error) -> RunnerError {
274 RunnerError::Other(err)
275 }
276 }
277
278 impl std::str::FromStr for MemLockMode {
279 type Err = ParseMemLockModeError;
280 fn from_str(s: &str) -> Result<Self, Self::Err> {
281 match s {
282 "resizable" => Ok(Self::Resizable),
283 "fixed_size" => Ok(Self::FixedSize),
284 "page_fault_checking" => Ok(Self::PageFaultChecking),
285 "disabled" => Ok(Self::Disabled),
286 _ => Err(ParseMemLockModeError),
287 }
288 }
289 }
290
291 impl fmt::Display for ParseMemLockModeError {
292 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
293 write!(f, "{:?}", self)
294 }
295 }
296
297 impl error::Error for ParseMemLockModeError {}
298
299 impl fmt::Display for TestReportList {
300 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
301 writeln!(f, "tested_mem_len = {}", self.tested_mem_length)?;
302 writeln!(f, "mlocked = {}", self.mlocked)?;
303 for report in &self.reports {
304 let outcome = match &report.outcome {
305 Ok(outcome) => format!("{}", outcome),
306 Err(e) => format!("{}", e),
307 };
308 writeln!(
309 f,
310 "{:<30} {}",
311 format!("Ran Test: {:?}", report.test_kind),
312 outcome
313 )?;
314 }
315 Ok(())
316 }
317 }
318
319 impl TestReportList {
320 pub fn iter(&self) -> impl Iterator<Item = &TestReport> {
321 self.reports.iter()
322 }
323
324 /// Returns true if all tests were run successfully and all tests passed
325 pub fn all_pass(&self) -> bool {
326 self.reports
327 .iter()
328 .all(|report| matches!(report.outcome, Ok(Outcome::Pass)))
329 }
330 }
331
332 impl TestReport {
333 fn new(
334 test_kind: TestKind,
335 outcome: Result<Outcome, memtest::Error<RuntimeError>>,
336 ) -> TestReport {
337 TestReport { test_kind, outcome }
338 }
339 }
340
341 impl fmt::Display for RuntimeError {
342 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
343 write!(f, "{:?}", self)
344 }
345 }
346
347 impl error::Error for RuntimeError {}
348
349 impl TimeoutChecker {
350 fn new(deadline: Instant) -> TimeoutChecker {
351 TimeoutChecker {
352 deadline,
353 state: None,
354 }
355 }
356 }
357
358 impl memtest::TestObserver for TimeoutChecker {
359 type Error = RuntimeError;
360
361 /// Initialize TimeoutCheckerState
362 /// This function should be called in the beginning of a memtest.
363 fn init(&mut self, expected_iter: u64) {
364 const FIRST_CHECKPOINT: u64 = 8;
365
366 assert!(
367 self.state.is_none(),
368 "init() should only be called once per test"
369 );
370
371 // The first checkpoint is set to 8 to have a more accurate sample of duration per
372 // iteration for determining new checkpoint
373 self.state = Some(TimeoutCheckerState {
374 test_start_time: Instant::now(),
375 expected_iter,
376 completed_iter: 0,
377 checkpoint: FIRST_CHECKPOINT,
378 });
379 }
380
381 /// Check if the current iteration is a checkpoint. If so, check if timeout occurred
382 ///
383 /// This function should be called in every iteration of a memtest.
384 ///
385 /// To reduce overhead, the function only checks for timeout at specific checkpoints, and
386 /// early returns otherwise.
387 ///
388 // It is important to ensure that the "early return" hot path is inlined. This results in a
389 // 100% improvement in performance.
390 #[inline(always)]
391 fn check(&mut self) -> Result<(), Self::Error> {
392 let state = self
393 .state
394 .as_mut()
395 .expect("init() should be called before check()");
396
397 if state.completed_iter < state.checkpoint {
398 state.completed_iter += 1;
399 return Ok(());
400 }
401
402 state.on_checkpoint(self.deadline)
403 }
404 }
405
406 impl TimeoutCheckerState {
407 fn on_checkpoint(&mut self, deadline: Instant) -> Result<(), RuntimeError> {
408 let current_time = Instant::now();
409 if current_time >= deadline {
410 return Err(RuntimeError::Timeout);
411 }
412
413 self.trace_progress();
414 self.set_next_checkpoint(deadline, current_time);
415
416 self.completed_iter += 1;
417 Ok(())
418 }
419
420 // TODO: Consider separating this functionality to a `ProgressTracer`
421 // Note: Because `trace_progress()` is only called in `on_checkpoints()`, not every percent
422 // of the test progress is traced. If memtests are running way ahead of the given deadline, the
423 // progress may only be traced once or twice. Although this makes the logs less comprehensive,
424 // it avoids signficiant perforamnce overhead.
425 fn trace_progress(&mut self) {
426 if tracing::enabled!(tracing::Level::TRACE) {
427 trace!(
428 "Progress on checkpoint: {:.2}%",
429 self.completed_iter as f64 / self.expected_iter as f64 * 100.0
430 );
431 }
432 }
433
434 /// Calculate the remaining time before the deadline and schedule the next check at 75% of that
435 /// interval, then estimate the number of iterations to get there and set as next checkpoint
436 fn set_next_checkpoint(&mut self, deadline: Instant, current_time: Instant) {
437 const DEADLINE_CHECK_RATIO: f64 = 0.75;
438
439 let duration_until_next_checkpoint = {
440 let duration_until_deadline = deadline - current_time;
441 duration_until_deadline.mul_f64(DEADLINE_CHECK_RATIO)
442 };
443
444 let avg_iter_duration = {
445 let test_elapsed = current_time - self.test_start_time;
446 test_elapsed.div_f64(self.completed_iter as f64)
447 };
448
449 let iter_until_next_checkpoint = {
450 let x =
451 Self::div_duration_f64(duration_until_next_checkpoint, avg_iter_duration) as u64;
452 u64::max(x, 1)
453 };
454
455 self.checkpoint += iter_until_next_checkpoint;
456 }
457
458 // This is equivalent to `Duration::div_duration_f64`, but that is not stable on Rust 1.76
459 fn div_duration_f64(lhs: Duration, rhs: Duration) -> f64 {
460 const NANOS_PER_SEC: u32 = 1_000_000_000;
461 let lhs_nanos =
462 (lhs.as_secs() as f64) * (NANOS_PER_SEC as f64) + (lhs.subsec_nanos() as f64);
463 let rhs_nanos =
464 (rhs.as_secs() as f64) * (NANOS_PER_SEC as f64) + (rhs.subsec_nanos() as f64);
465 lhs_nanos / rhs_nanos
466 }
467 }
468
469 #[cfg(windows)]
470 mod windows {
471 use {
472 crate::{prelude::*, MemLockGuard},
473 std::mem::{size_of, size_of_val},
474 windows::Win32::{
475 Foundation::ERROR_WORKING_SET_QUOTA,
476 System::{
477 Memory::{VirtualLock, VirtualUnlock},
478 SystemInformation::{
479 GetNativeSystemInfo, GlobalMemoryStatusEx, MEMORYSTATUSEX, SYSTEM_INFO,
480 },
481 Threading::{
482 GetCurrentProcess, GetProcessWorkingSetSize, SetProcessWorkingSetSize,
483 },
484 },
485 },
486 };
487
488 #[derive(Debug)]
489 pub struct WorkingSetResizeGuard {
490 min_set_size: usize,
491 max_set_size: usize,
492 }
493
494 // TODO: Consider verifying that the process memory is properly sized by using
495 // `GetProcessMemoryInfo` during memtests to retrieve the number of page faults this process is
496 // causing. If it's suddenly a very high number, it indicates the set size might be too small
497 pub(super) fn replace_set_size(memsize: usize) -> anyhow::Result<WorkingSetResizeGuard> {
498 const ESTIMATED_TEST_MEM_USAGE: usize = 1024 * 1024; // 1MiB
499 let (min_set_size, max_set_size) = get_set_size()?;
500 let new_min_set_size = memsize + ESTIMATED_TEST_MEM_USAGE;
501 let new_max_set_size: usize = get_physical_memory_size()
502 .context("Failed to get physical memory size")?
503 .try_into()
504 .unwrap_or(usize::MAX);
505 unsafe {
506 SetProcessWorkingSetSize(GetCurrentProcess(), new_min_set_size, new_max_set_size)
507 .context("Failed to set process working set size")?;
508 }
509 Ok(WorkingSetResizeGuard {
510 min_set_size,
511 max_set_size,
512 })
513 }
514
515 impl Drop for WorkingSetResizeGuard {
516 fn drop(&mut self) {
517 unsafe {
518 if let Err(e) = SetProcessWorkingSetSize(
519 GetCurrentProcess(),
520 self.min_set_size,
521 self.max_set_size,
522 ) {
523 warn!("Failed to restore process working set: {e}");
524 }
525 }
526 }
527 }
528
529 pub(super) fn memory_lock(
530 memory: &mut [usize],
531 ) -> anyhow::Result<(&mut [usize], MemLockGuard)> {
532 let base_ptr = memory.as_mut_ptr();
533 let mem_size = size_of_val(memory);
534
535 unsafe {
536 VirtualLock(base_ptr.cast(), mem_size).context("VirtualLock failed")?;
537 }
538 info!("Successfully locked {}MB", mem_size);
539 Ok((memory, MemLockGuard { base_ptr, mem_size }))
540 }
541
542 pub(super) fn memory_resize_and_lock(
543 mut memory: &mut [usize],
544 ) -> anyhow::Result<(&mut [usize], MemLockGuard)> {
545 // Resizing to system limit first is more efficient than only decrementing by page
546 // size and retry locking.
547 let min_set_size_usize = get_set_size()?.0 / size_of::<usize>();
548 if memory.len() > min_set_size_usize {
549 memory = &mut memory[0..min_set_size_usize];
550 warn!(
551 "Resized memory to system limit ({} bytes)",
552 size_of_val(memory)
553 );
554 }
555
556 let usize_per_page = get_page_size()? / std::mem::size_of::<usize>();
557 loop {
558 let base_ptr = memory.as_mut_ptr();
559 let mem_size = size_of_val(memory);
560
561 let res = unsafe { VirtualLock(base_ptr.cast(), mem_size) };
562 let Err(e) = res else {
563 info!("Successfully locked {} bytes", mem_size);
564 return Ok((memory, MemLockGuard { base_ptr, mem_size }));
565 };
566
567 ensure!(
568 e == ERROR_WORKING_SET_QUOTA.into(),
569 anyhow!(e).context("VirtualLock failed")
570 );
571
572 // Locking with the system limit can still fail as the memory to be locked may not be
573 // page aligned. In that case retry locking after decrement memory size by a page.
574 let new_len = memory
575 .len()
576 .checked_sub(usize_per_page)
577 .context("Failed to lock any memory, memory size has been decremented to 0")?;
578
579 memory = &mut memory[0..new_len];
580 warn!(
581 "Decremented memory size to {} bytes, retry memory locking",
582 new_len * usize_per_page
583 );
584 }
585 }
586
587 impl Drop for MemLockGuard {
588 fn drop(&mut self) {
589 unsafe {
590 if let Err(e) = VirtualUnlock(self.base_ptr.cast(), self.mem_size) {
591 warn!("Failed to unlock memory: {e}")
592 }
593 }
594 }
595 }
596
597 fn get_set_size() -> anyhow::Result<(usize, usize)> {
598 let (mut min_set_size, mut max_set_size) = (0, 0);
599 unsafe {
600 GetProcessWorkingSetSize(GetCurrentProcess(), &mut min_set_size, &mut max_set_size)
601 .context("Failed to get process working set")?;
602 }
603 Ok((min_set_size, max_set_size))
604 }
605
606 fn get_page_size() -> anyhow::Result<usize> {
607 Ok((unsafe {
608 let mut sysinfo: SYSTEM_INFO = std::mem::zeroed();
609 GetNativeSystemInfo(&mut sysinfo);
610 sysinfo.dwPageSize
611 })
612 .try_into()
613 .unwrap())
614 }
615
616 fn get_physical_memory_size() -> anyhow::Result<u64> {
617 let mut memory_status = MEMORYSTATUSEX::default();
618 memory_status.dwLength = std::mem::size_of_val(&memory_status).try_into().unwrap();
619 unsafe {
620 GlobalMemoryStatusEx(&mut memory_status)
621 .context("Failed to get global memory status")?
622 };
623 Ok(memory_status.ullTotalPhys)
624 }
625 }
626
627 #[cfg(unix)]
628 mod unix {
629 use {
630 crate::{memtest::TestObserver, prelude::*, MemLockGuard, RuntimeError, TimeoutChecker},
631 libc::{getrlimit, mlock, munlock, rlimit, sysconf, RLIMIT_MEMLOCK, _SC_PAGESIZE},
632 std::{
633 borrow::BorrowMut,
634 io::{self, ErrorKind},
635 mem::{size_of, size_of_val},
636 },
637 };
638
639 #[derive(Debug)]
640 pub(super) struct RuntimeChecker {
641 timeout_checker: TimeoutChecker,
642 page_fault_checker: PageFaultChecker,
643 }
644
645 #[derive(Debug)]
646 pub(super) struct PageFaultChecker {
647 address: usize,
648 len: usize,
649 page_size: usize,
650 state: Option<PageFaultCheckerState>,
651 }
652
653 #[derive(Debug)]
654 struct PageFaultCheckerState {
655 completed_iter: u64,
656 checkpoint: u64,
657 checkpoint_step: u64,
658 }
659
660 pub(super) fn memory_lock(
661 memory: &mut [usize],
662 ) -> anyhow::Result<(&mut [usize], MemLockGuard)> {
663 let base_ptr = memory.as_mut_ptr();
664 let mem_size = size_of_val(memory);
665 if unsafe { mlock(base_ptr.cast(), mem_size) } == 0 {
666 info!("Successfully locked {} bytes", mem_size);
667 Ok((
668 memory,
669 MemLockGuard {
670 base_ptr: base_ptr.cast(),
671 mem_size,
672 },
673 ))
674 } else {
675 Err(anyhow!(io::Error::last_os_error()).context("mlock failed"))
676 }
677 }
678
679 pub(super) fn memory_resize_and_lock(
680 mut memory: &mut [usize],
681 ) -> anyhow::Result<(&mut [usize], MemLockGuard)> {
682 // Note: Resizing to system limit first is more efficient than only decrementing by page
683 // size and retry locking, but this may not work as intended when running as a priviledged
684 // process, since priviledged processes do not need to respect the limit.
685 let max_mem_lock_usize = get_max_mem_lock()? / size_of::<usize>();
686 if memory.len() > max_mem_lock_usize {
687 memory = &mut memory[0..max_mem_lock_usize];
688 warn!(
689 "Resized memory to system limit ({} bytes)",
690 size_of_val(memory)
691 );
692 }
693
694 let usize_per_page = get_page_size()? / std::mem::size_of::<usize>();
695 loop {
696 let base_ptr = memory.as_mut_ptr();
697 let mem_size = size_of_val(memory);
698 if unsafe { mlock(base_ptr.cast(), mem_size) } == 0 {
699 info!("Successfully locked {} bytes", mem_size);
700 return Ok((memory, MemLockGuard { base_ptr, mem_size }));
701 }
702
703 let e = io::Error::last_os_error();
704 ensure!(
705 e.kind() == ErrorKind::OutOfMemory,
706 anyhow!(e).context("mlock failed")
707 );
708
709 // Locking with the system limit can still fail as the memory to be locked may not be
710 // page aligned. In that case retry locking after decrement memory size by a page.
711 let new_len = memory
712 .len()
713 .checked_sub(usize_per_page)
714 .context("Failed to lock any memory, memory size has been decremented to 0")?;
715 memory = &mut memory[0..new_len];
716 warn!(
717 "Decremented memory size to {} bytes, retry memory locking",
718 size_of_val(memory)
719 );
720 }
721 }
722
723 impl Drop for MemLockGuard {
724 fn drop(&mut self) {
725 unsafe {
726 if munlock(self.base_ptr.cast(), self.mem_size) != 0 {
727 warn!("Failed to unlock memory: {}", io::Error::last_os_error())
728 }
729 }
730 }
731 }
732
733 fn get_max_mem_lock() -> anyhow::Result<usize> {
734 unsafe {
735 let mut rlim: rlimit = std::mem::zeroed();
736 ensure!(
737 getrlimit(RLIMIT_MEMLOCK, rlim.borrow_mut()) == 0,
738 anyhow!(io::Error::last_os_error()).context("Failed to get RLIMIT_MEMLOCK")
739 );
740 Ok(rlim.rlim_cur.try_into().unwrap())
741 }
742 }
743
744 fn get_page_size() -> anyhow::Result<usize> {
745 (unsafe { sysconf(_SC_PAGESIZE) })
746 .try_into()
747 .context("Failed to get page size")
748 }
749
750 impl RuntimeChecker {
751 pub(super) fn new(
752 timeout_checker: TimeoutChecker,
753 page_fault_checker: PageFaultChecker,
754 ) -> RuntimeChecker {
755 RuntimeChecker {
756 timeout_checker,
757 page_fault_checker,
758 }
759 }
760 }
761
762 impl TestObserver for RuntimeChecker {
763 type Error = RuntimeError;
764
765 /// This function should be called in the beginning of a memtest.
766 fn init(&mut self, expected_iter: u64) {
767 self.timeout_checker.init(expected_iter);
768 self.page_fault_checker.init(expected_iter);
769 }
770
771 #[inline(always)]
772 fn check(&mut self) -> Result<(), Self::Error> {
773 self.timeout_checker
774 .check()
775 .map_err(|_| RuntimeError::Timeout)?;
776 self.page_fault_checker
777 .check()
778 .map_err(|_| RuntimeError::PageFault)?;
779 Ok(())
780 }
781 }
782
783 impl PageFaultChecker {
784 pub(super) fn new(address: usize, len: usize) -> anyhow::Result<PageFaultChecker> {
785 Ok(PageFaultChecker {
786 address,
787 len,
788 page_size: get_page_size()?,
789 state: None,
790 })
791 }
792 }
793
794 impl TestObserver for PageFaultChecker {
795 type Error = RuntimeError;
796
797 // TODO: Currently NUM_CHECKS is an arbitrary number
798 fn init(&mut self, expected_iter: u64) {
799 const FIRST_CHECKPOINT: u64 = 0;
800 const NUM_CHECKS: u64 = 100;
801
802 assert!(
803 self.state.is_none(),
804 "init() should only be called once per test"
805 );
806
807 self.state = Some(PageFaultCheckerState {
808 completed_iter: 0,
809 checkpoint: FIRST_CHECKPOINT,
810 checkpoint_step: expected_iter / NUM_CHECKS,
811 });
812 }
813
814 #[inline(always)]
815 fn check(&mut self) -> Result<(), Self::Error> {
816 let state = self
817 .state
818 .as_mut()
819 .expect("init() should be called before check()");
820
821 if state.completed_iter < state.checkpoint {
822 state.completed_iter += 1;
823 return Ok(());
824 }
825
826 state.on_checkpoint(self.address, self.len, self.page_size)
827 }
828 }
829
830 impl PageFaultCheckerState {
831 fn on_checkpoint(
832 &mut self,
833 address: usize,
834 len: usize,
835 page_size: usize,
836 ) -> Result<(), RuntimeError> {
837 use libc::mincore;
838
839 let mem_size = len * size_of::<usize>();
840
841 let aligned_address = address / page_size * page_size;
842 let aligned_mem_size = mem_size + (address - aligned_address);
843
844 // buf needs to be at least (aligned_mem_size + page_size - 1) / page_size
845 let mut buf: Vec<u8> = vec![0; aligned_mem_size.div_ceil(page_size)];
846 assert_eq!(
847 unsafe {
848 mincore(
849 aligned_address as *mut std::ffi::c_void,
850 aligned_mem_size,
851 buf.as_mut_ptr().cast(),
852 )
853 },
854 0,
855 "mincore did not return 0"
856 );
857 if buf.iter().any(|n| *n & 1 == 0) {
858 trace!("Detected page fault");
859 return Err(RuntimeError::PageFault);
860 }
861
862 self.set_next_checkpoint();
863 self.completed_iter += 1;
864
865 Ok(())
866 }
867
868 /// Calculate the remaining time before the deadline and schedule the next check at 75% of that
869 /// interval, then estimate the number of iterations to get there and set as next checkpoint
870 fn set_next_checkpoint(&mut self) {
871 self.checkpoint += self.checkpoint_step;
872 }
873 }
874 }