Debian Codegraph @

third_party/rust/memtest/src/memtest.rs

raw
1 use {
2 crate::prelude::*,
3 rand::random,
4 serde::{Deserialize, Deserializer, Serialize, Serializer},
5 std::{error, fmt},
6 };
7
8 // TODO: Intend to convert this module to a standalone `no_std` crate
9
10 pub type TestResult<O> = Result<Outcome, Error<<O as TestObserver>::Error>>;
11
12 #[derive(Debug, Serialize, Deserialize)]
13 #[must_use]
14 pub enum Outcome {
15 Pass,
16 Fail(Failure),
17 }
18
19 #[derive(Serialize, Deserialize)]
20 pub enum Failure {
21 /// Failure due to the actual value read being different from the expected value
22 UnexpectedValue {
23 address: usize,
24 expected: usize,
25 actual: usize,
26 },
27 /// Failure due to the two memory locations being compared returning two different values
28 /// This is used by tests where memory is split in two and values are written in pairs
29 MismatchedValues {
30 address1: usize,
31 value1: usize,
32 address2: usize,
33 value2: usize,
34 },
35 }
36
37 pub trait TestObserver {
38 type Error: error::Error;
39 fn init(&mut self, expected_iter: u64);
40 fn check(&mut self) -> Result<(), Self::Error>;
41 }
42
43 #[derive(Debug, Serialize, Deserialize)]
44 pub enum Error<E> {
45 Observer(E),
46 #[serde(
47 serialize_with = "serialize_error_other",
48 deserialize_with = "deserialize_error_other"
49 )]
50 Other(anyhow::Error),
51 }
52
53 macro_rules! test_kinds {{
54 $($variant: ident),* $(,)?
55 } => {
56 #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
57 pub enum TestKind {
58 $($variant,)*
59 }
60
61 impl TestKind {
62 pub const ALL: &'static [Self] = &[
63 $(Self::$variant),*
64 ];
65 }
66
67 impl std::str::FromStr for TestKind {
68 type Err = ParseTestKindError;
69 fn from_str(s: &str) -> Result<Self, Self::Err> {
70 match s {
71 $(
72 stringify!($variant) => Ok(Self::$variant),
73 )*
74 _ => Err(ParseTestKindError),
75 }
76 }
77 }
78 }}
79
80 test_kinds! {
81 OwnAddressBasic,
82 OwnAddressRepeat,
83 RandomVal,
84 Xor,
85 Sub,
86 Mul,
87 Div,
88 Or,
89 And,
90 SeqInc,
91 SolidBits,
92 Checkerboard,
93 BlockSeq,
94 MovInvFixedBlock,
95 MovInvFixedBit,
96 MovInvFixedRandom,
97 MovInvWalk,
98 BlockMove,
99 MovInvRandom,
100 Modulo20,
101 }
102
103 #[derive(Debug, PartialEq, Eq)]
104 pub struct ParseTestKindError;
105
106 impl TestKind {
107 pub fn run<O: TestObserver>(&self, memory: &mut [usize], observer: O) -> TestResult<O> {
108 use two_region::{
109 run_two_region_test_algorithm, And, BlockSeq, Checkerboard, Div, Mul, Or, RandomVal,
110 SeqInc, SolidBits, Sub, Xor,
111 };
112
113 match self {
114 Self::OwnAddressBasic => {
115 run_test_algorithm(OwnAddressBasic::default(), memory, observer)
116 }
117 Self::OwnAddressRepeat => {
118 run_test_algorithm(OwnAddressRepeat::default(), memory, observer)
119 }
120 Self::RandomVal => {
121 run_two_region_test_algorithm(RandomVal::default(), memory, observer)
122 }
123 Self::Xor => run_two_region_test_algorithm(Xor::default(), memory, observer),
124 Self::Sub => run_two_region_test_algorithm(Sub::default(), memory, observer),
125 Self::Mul => run_two_region_test_algorithm(Mul::default(), memory, observer),
126 Self::Div => run_two_region_test_algorithm(Div::default(), memory, observer),
127 Self::Or => run_two_region_test_algorithm(Or::default(), memory, observer),
128 Self::And => run_two_region_test_algorithm(And::default(), memory, observer),
129 Self::SeqInc => run_two_region_test_algorithm(SeqInc::default(), memory, observer),
130 Self::SolidBits => {
131 run_two_region_test_algorithm(SolidBits::default(), memory, observer)
132 }
133 Self::Checkerboard => {
134 run_two_region_test_algorithm(Checkerboard::default(), memory, observer)
135 }
136 Self::BlockSeq => run_two_region_test_algorithm(BlockSeq::default(), memory, observer),
137 Self::MovInvFixedBlock => {
138 run_test_algorithm(mov_inv::FixedBlock::default(), memory, observer)
139 }
140 Self::MovInvFixedBit => {
141 run_test_algorithm(mov_inv::FixedBit::default(), memory, observer)
142 }
143 Self::MovInvFixedRandom => {
144 run_test_algorithm(mov_inv::FixedRandom::default(), memory, observer)
145 }
146 Self::MovInvWalk => run_test_algorithm(mov_inv::Walk::default(), memory, observer),
147 Self::BlockMove => run_block_move(memory, observer),
148 Self::MovInvRandom => run_test_algorithm(mov_inv::Random::default(), memory, observer),
149 Self::Modulo20 => run_modulo_20(memory, observer),
150 }
151 }
152 }
153
154 /// A pass can be done forward (default) or reversed
155 #[derive(Debug, Default)]
156 enum PassDirection {
157 #[default]
158 Forward,
159 Reverse,
160 }
161
162 type PassFn<T> = fn(&mut T, direction: &mut PassDirection) -> IterFn<T>;
163 type IterFn<T> = fn(&mut T, &mut usize) -> Result<(), Failure>;
164
165 trait TestAlgorithm: fmt::Debug {
166 /// The number of runs the algorithm needs. Most tests can just accept the default of '1'
167 fn num_runs(&self) -> u64 {
168 1
169 }
170 /// Initialize the state for the run given by `run_idx`. Most tests don't need to do anything.
171 fn start_run(&mut self, _run_idx: u64) {}
172 /// Return a list of functions defining the behavior of the passes
173 ///
174 /// Each function receives a mutable reference to `direction`, which will always be set to
175 /// the default of `Forward`. If a pass wants the direction reversed, it can set it to
176 /// `Reverse`.
177 ///
178 /// Each function must return the iteration function for the pass. This is the function that
179 /// will be run for each memory address.
180 ///
181 /// The iteration function itself takes a mutable reference to each memory address and
182 /// returns either `Ok(())` or `Err(Failure)`.
183 fn passes(&self) -> Vec<PassFn<Self>>;
184 }
185
186 #[tracing::instrument(skip(memory, observer))]
187 fn run_test_algorithm<T: TestAlgorithm, O: TestObserver>(
188 mut test: T,
189 memory: &mut [usize],
190 mut observer: O,
191 ) -> TestResult<O> {
192 let expected_iter = u64::try_from(memory.len())
193 .ok()
194 .and_then(|count| count.checked_mul(test.num_runs()))
195 .and_then(|count| count.checked_mul(u64::try_from(test.passes().len()).ok()?))
196 .context("Total number of iterations overflowed")?;
197 observer.init(expected_iter);
198
199 for i in 0..test.num_runs() {
200 test.start_run(i);
201 for pass_fn in test.passes() {
202 let mut direction = PassDirection::default();
203 let iter_fn = pass_fn(&mut test, &mut direction);
204
205 let mem_iter: Box<dyn Iterator<Item = &mut usize>> = match direction {
206 PassDirection::Forward => Box::new(memory.iter_mut()),
207 PassDirection::Reverse => Box::new(memory.iter_mut().rev()),
208 };
209
210 for mem_ref in mem_iter {
211 observer.check().map_err(Error::Observer)?;
212 if let Err(f) = iter_fn(&mut test, mem_ref) {
213 return Ok(Outcome::Fail(f));
214 }
215 }
216 }
217 }
218 Ok(Outcome::Pass)
219 }
220
221 fn check_expected_value(address: usize, expected: usize, actual: usize) -> Result<(), Failure> {
222 if actual != expected {
223 info!("Test failed at 0x{address:x}");
224 Err(Failure::UnexpectedValue {
225 address,
226 expected,
227 actual,
228 })
229 } else {
230 Ok(())
231 }
232 }
233
234 /// Write the address of each memory location to itself, then read back the value and check that it
235 /// matches the expected address.
236 #[derive(Debug, Default)]
237 struct OwnAddressBasic {}
238
239 impl TestAlgorithm for OwnAddressBasic {
240 fn passes(&self) -> Vec<PassFn<Self>> {
241 vec![Self::pass_0, Self::pass_1]
242 }
243 }
244
245 impl OwnAddressBasic {
246 fn pass_0(&mut self, _direction: &mut PassDirection) -> IterFn<Self> {
247 |_state, mem_ref| {
248 write_volatile_safe(mem_ref, address_from_ref(mem_ref));
249 Ok(())
250 }
251 }
252
253 fn pass_1(&mut self, _direction: &mut PassDirection) -> IterFn<Self> {
254 |_state, mem_ref| {
255 check_expected_value(
256 address_from_ref(mem_ref),
257 address_from_ref(mem_ref),
258 read_volatile_safe(mem_ref),
259 )
260 }
261 }
262 }
263
264 /// Write the address of each memory location (or its complement) to itself, then read back the
265 /// value and check that it matches the expected address.
266 /// This procedure is repeated 16 times.
267 #[derive(Debug, Default)]
268 struct OwnAddressRepeat {
269 complement: bool,
270 run_idx: u64,
271 }
272
273 impl TestAlgorithm for OwnAddressRepeat {
274 fn num_runs(&self) -> u64 {
275 16
276 }
277 fn start_run(&mut self, run_idx: u64) {
278 self.run_idx = run_idx;
279 }
280 fn passes(&self) -> Vec<PassFn<Self>> {
281 vec![Self::pass_0, Self::pass_1]
282 }
283 }
284
285 impl OwnAddressRepeat {
286 fn pass_0(&mut self, _direction: &mut PassDirection) -> IterFn<Self> {
287 self.init_complement();
288
289 |state, mem_ref| {
290 write_volatile_safe(mem_ref, state.val_to_write(mem_ref));
291
292 state.complement = !state.complement;
293 Ok(())
294 }
295 }
296
297 fn pass_1(&mut self, _direction: &mut PassDirection) -> IterFn<Self> {
298 self.init_complement();
299
300 |state, mem_ref| {
301 check_expected_value(
302 address_from_ref(mem_ref),
303 state.val_to_write(mem_ref),
304 read_volatile_safe(mem_ref),
305 )?;
306
307 state.complement = !state.complement;
308 Ok(())
309 }
310 }
311
312 fn init_complement(&mut self) {
313 self.complement = self.run_idx % 2 != 0;
314 }
315
316 fn val_to_write(&self, mem_ref: &usize) -> usize {
317 if self.complement {
318 !address_from_ref(mem_ref)
319 } else {
320 address_from_ref(mem_ref)
321 }
322 }
323 }
324
325 mod two_region {
326 use {
327 super::{
328 address_from_ref, mem_reset, read_volatile_safe, split_slice_in_half,
329 usize_filled_from_byte, write_volatile_safe, Error, Failure, Outcome, TestObserver,
330 TestResult,
331 },
332 crate::prelude::*,
333 rand::random,
334 std::fmt,
335 };
336
337 type TwoRegionWriteFn<T> = fn(&mut T, &mut usize, &mut usize);
338
339 /// A two region test has to passes of memory for every run. The test splits memory into
340 /// two halves. The first pass iterates through memory and writes some memory pattern to each
341 /// pair of locations. The second pass reads through and compare the two halves.
342 trait TwoRegionTestAlgorithm: fmt::Debug + Default {
343 /// The number of runs the algorithm needs. Most tests can just accept the default of '1'
344 fn num_runs(&self) -> u64 {
345 1
346 }
347 /// Initialize the state for the run given by `run_idx`. Most tests don't need to do anything.
348 fn start_run(&mut self, _run_idx: u64) {}
349
350 /// Returns whether a memory reset is needed at the start of each run
351 /// If true, the algorithm will reset all bits to 1.
352 fn reset_before_run(&self) -> bool;
353
354 /// Returns the function that is called for every iteration of the first pass to write to
355 /// memory.
356 fn write_fn(&self) -> TwoRegionWriteFn<Self>;
357 }
358
359 #[tracing::instrument(skip(memory, observer))]
360 pub(super) fn run_two_region_test_algorithm<T: TwoRegionTestAlgorithm, O: TestObserver>(
361 mut test: T,
362 memory: &mut [usize],
363 mut observer: O,
364 ) -> TestResult<O> {
365 if test.reset_before_run() {
366 mem_reset(memory);
367 }
368 let (first_half, second_half) = split_slice_in_half(memory)?;
369 let expected_iter = u64::try_from(first_half.len())
370 .ok()
371 .and_then(|count| count.checked_mul(2))
372 .and_then(|count| count.checked_mul(test.num_runs()))
373 .context("Total number of iterations overflowed")?;
374 observer.init(expected_iter);
375
376 for i in 0..test.num_runs() {
377 test.start_run(i);
378
379 let write_fn = test.write_fn();
380 for (first_ref, second_ref) in first_half.iter_mut().zip(second_half.iter_mut()) {
381 observer.check().map_err(Error::Observer)?;
382 write_fn(&mut test, first_ref, second_ref);
383 }
384
385 for (first_ref, second_ref) in first_half.iter().zip(second_half.iter()) {
386 observer.check().map_err(Error::Observer)?;
387 if let Err(f) = check_matching_values(
388 address_from_ref(first_ref),
389 read_volatile_safe(first_ref),
390 address_from_ref(second_ref),
391 read_volatile_safe(second_ref),
392 ) {
393 return Ok(Outcome::Fail(f));
394 }
395 }
396 }
397
398 Ok(Outcome::Pass)
399 }
400
401 fn check_matching_values(
402 address1: usize,
403 value1: usize,
404 address2: usize,
405 value2: usize,
406 ) -> Result<(), Failure> {
407 if value1 != value2 {
408 info!("Test failed at 0x{address1:x} compared to 0x{address2:x}");
409 Err(Failure::MismatchedValues {
410 address1,
411 value1,
412 address2,
413 value2,
414 })
415 } else {
416 Ok(())
417 }
418 }
419
420 /// Split given memory into two halves and iterate through memory locations in pairs. For each
421 /// pair, write a random value. After all locations are written, read and compare the two halves.
422 #[derive(Debug, Default)]
423 pub(super) struct RandomVal {}
424 impl TwoRegionTestAlgorithm for RandomVal {
425 fn reset_before_run(&self) -> bool {
426 false
427 }
428
429 fn write_fn(&self) -> TwoRegionWriteFn<Self> {
430 |_state, first_ref, second_ref| {
431 let val = random();
432 write_volatile_safe(first_ref, val);
433 write_volatile_safe(second_ref, val);
434 }
435 }
436 }
437
438 macro_rules! two_region_write_fn_with_transform_fn {
439 ($transform_fn:expr) => {
440 |_state, first_ref, second_ref| {
441 let mixing_val: usize = random();
442
443 let val = read_volatile_safe(first_ref);
444 let new_val = $transform_fn(val, mixing_val);
445 write_volatile_safe(first_ref, new_val);
446
447 let val = read_volatile_safe(second_ref);
448 let new_val = $transform_fn(val, mixing_val);
449 write_volatile_safe(second_ref, new_val);
450 }
451 };
452 }
453
454 /// Reset all bits in given memory to 1s. Split given memory into two halves and iterate through
455 /// memory locations in pairs. For each pair, write the XOR result of a random value and the value
456 /// read from the location. After all locations are written, read and compare the two halves.
457 #[derive(Debug, Default)]
458 pub(super) struct Xor {}
459 impl TwoRegionTestAlgorithm for Xor {
460 fn reset_before_run(&self) -> bool {
461 true
462 }
463 fn write_fn(&self) -> TwoRegionWriteFn<Self> {
464 two_region_write_fn_with_transform_fn!(std::ops::BitXor::bitxor)
465 }
466 }
467
468 /// Reset all bits in given memory to 1s. Split given memory into two halves and iterate through
469 /// memory locations in pairs. For each pair, write the result of subtracting a random value from
470 /// the value read from the location. After all locations are written, read and compare the two
471 /// halves.
472 #[derive(Debug, Default)]
473 pub(super) struct Sub {}
474 impl TwoRegionTestAlgorithm for Sub {
475 fn reset_before_run(&self) -> bool {
476 true
477 }
478 fn write_fn(&self) -> TwoRegionWriteFn<Self> {
479 two_region_write_fn_with_transform_fn!(usize::wrapping_sub)
480 }
481 }
482
483 /// Reset all bits in given memory to 1s. Split given memory into two halves and iterate through
484 /// memory locations in pairs. For each pair, write the result of multiplying a random value with
485 /// the value read from the location. After all locations are written, read and compare the two
486 /// halves.
487 #[derive(Debug, Default)]
488 pub(super) struct Mul {}
489 impl TwoRegionTestAlgorithm for Mul {
490 fn reset_before_run(&self) -> bool {
491 true
492 }
493 fn write_fn(&self) -> TwoRegionWriteFn<Self> {
494 two_region_write_fn_with_transform_fn!(usize::wrapping_mul)
495 }
496 }
497
498 /// Reset all bits in given memory to 1s. Split given memory into two halves and iterate through
499 /// memory locations in pairs. For each pair, write the result of dividing the value read from the
500 /// location with a random value. After all locations are written, read and compare the two halves.
501 #[derive(Debug, Default)]
502 pub(super) struct Div {}
503 impl TwoRegionTestAlgorithm for Div {
504 fn reset_before_run(&self) -> bool {
505 true
506 }
507 fn write_fn(&self) -> TwoRegionWriteFn<Self> {
508 two_region_write_fn_with_transform_fn!(
509 |n: usize, d: usize| n.wrapping_div(usize::max(d, 1))
510 )
511 }
512 }
513
514 /// Reset all bits in given memory to 1s. Split given memory into two halves and iterate through
515 /// memory locations in pairs. For each pair, write the OR result of a random value and the value
516 /// read from the location. After all locations are written, read and compare the two halves.
517 #[derive(Debug, Default)]
518 pub(super) struct Or {}
519 impl TwoRegionTestAlgorithm for Or {
520 fn reset_before_run(&self) -> bool {
521 true
522 }
523 fn write_fn(&self) -> TwoRegionWriteFn<Self> {
524 two_region_write_fn_with_transform_fn!(std::ops::BitOr::bitor)
525 }
526 }
527
528 /// Reset all bits in given memory to 1s. Split given memory into two halves and iterate through
529 /// memory locations in pairs. For each pair, write the AND result of a random value and the value
530 /// read from the location. After all locations are written, read and compare the two halves.
531 #[derive(Debug, Default)]
532 pub(super) struct And {}
533 impl TwoRegionTestAlgorithm for And {
534 fn reset_before_run(&self) -> bool {
535 true
536 }
537 fn write_fn(&self) -> TwoRegionWriteFn<Self> {
538 two_region_write_fn_with_transform_fn!(std::ops::BitAnd::bitand)
539 }
540 }
541
542 /// Split given memory into two halves and iterate through memory locations in pairs. Generate a
543 /// random value at the start. For each pair, write the result of adding the random value and the
544 /// index of iteration. After all locations are written, read and compare the two halves.
545 #[derive(Debug, Default)]
546 pub(super) struct SeqInc {
547 val: usize,
548 }
549 impl TwoRegionTestAlgorithm for SeqInc {
550 fn reset_before_run(&self) -> bool {
551 false
552 }
553 fn write_fn(&self) -> TwoRegionWriteFn<Self> {
554 |state, first_ref, second_ref| {
555 state.val = state.val.wrapping_add(1);
556 write_volatile_safe(first_ref, state.val);
557 write_volatile_safe(second_ref, state.val);
558 }
559 }
560 }
561
562 /// Split given memory into two halves and iterate through memory locations in pairs. For each
563 /// pair, write to all bits as either 1s or 0s, alternating after each memory location pair.
564 /// After all locations are written, read and compare the two halves.
565 /// This procedure is repeated 64 times.
566 #[derive(Debug)]
567 pub(super) struct SolidBits {
568 solid_bits: usize,
569 val: usize,
570 }
571
572 impl Default for SolidBits {
573 fn default() -> Self {
574 SolidBits {
575 solid_bits: !0,
576 val: usize::default(),
577 }
578 }
579 }
580
581 impl TwoRegionTestAlgorithm for SolidBits {
582 fn num_runs(&self) -> u64 {
583 64
584 }
585
586 fn start_run(&mut self, _run_idx: u64) {
587 self.solid_bits = !self.solid_bits;
588 self.val = self.solid_bits;
589 }
590
591 fn reset_before_run(&self) -> bool {
592 false
593 }
594
595 fn write_fn(&self) -> TwoRegionWriteFn<Self> {
596 |state, first_ref, second_ref| {
597 state.val = !state.val;
598 write_volatile_safe(first_ref, state.val);
599 write_volatile_safe(second_ref, state.val);
600 }
601 }
602 }
603
604 /// Split given memory into two halves and iterate through memory locations in pairs. For each pair,
605 /// write to a pattern of alternating 1s and 0s (in bytes it is either 0x55 or 0xaa, and alternating
606 /// after each memory location pair). After all locations are written, read and compare the two
607 /// halves.
608 /// This procedure is repeated 64 times.
609 #[derive(Debug)]
610 pub(super) struct Checkerboard {
611 checker_board: usize,
612 val: usize,
613 }
614
615 impl Default for Checkerboard {
616 fn default() -> Self {
617 Checkerboard {
618 checker_board: usize_filled_from_byte(0xaa),
619 val: usize::default(),
620 }
621 }
622 }
623
624 impl TwoRegionTestAlgorithm for Checkerboard {
625 fn num_runs(&self) -> u64 {
626 64
627 }
628
629 fn start_run(&mut self, _run_idx: u64) {
630 self.checker_board = !self.checker_board;
631 self.val = self.checker_board;
632 }
633
634 fn reset_before_run(&self) -> bool {
635 false
636 }
637
638 fn write_fn(&self) -> TwoRegionWriteFn<Self> {
639 |state, first_ref, second_ref| {
640 state.val = !state.val;
641 write_volatile_safe(first_ref, state.val);
642 write_volatile_safe(second_ref, state.val);
643 }
644 }
645 }
646
647 /// Split given memory into two halves and iterate through memory locations in pairs. For each pair,
648 /// write to all bytes with the value i. After all locations are written, read and compare the two
649 /// halves.
650 /// This procedure is repeated 256 times, with i corresponding to the iteration number 0-255.
651 #[derive(Debug, Default)]
652 pub(super) struct BlockSeq {
653 val: usize,
654 }
655
656 impl TwoRegionTestAlgorithm for BlockSeq {
657 fn num_runs(&self) -> u64 {
658 256
659 }
660
661 fn start_run(&mut self, run_idx: u64) {
662 self.val = usize_filled_from_byte(run_idx.try_into().unwrap());
663 }
664
665 fn reset_before_run(&self) -> bool {
666 false
667 }
668
669 fn write_fn(&self) -> TwoRegionWriteFn<Self> {
670 |state, first_ref, second_ref| {
671 write_volatile_safe(first_ref, state.val);
672 write_volatile_safe(second_ref, state.val);
673 }
674 }
675 }
676 }
677
678 mod mov_inv {
679 use {
680 super::{
681 address_from_ref, check_expected_value, read_volatile_safe, usize_filled_from_byte,
682 write_volatile_safe, IterFn, PassDirection, PassFn, TestAlgorithm,
683 },
684 rand::{random, rngs::SmallRng, Rng, SeedableRng},
685 std::{
686 fmt,
687 time::{SystemTime, UNIX_EPOCH},
688 },
689 };
690
691 /// These tests adapt the moving inversion algorithm implemented by [memtest86+](https://github.com/
692 /// memtest86plus/memtest86plus). As described in the the [Memtest86+ Test Algorithm Section](https://github.com/
693 /// memtest86plus/memtest86plus?tab=readme-ov-file#memtest86-test-algorithms),
694 ///
695 /// "The moving inversion tests work as follows:
696 /// 1. Fill memory with a pattern
697 /// 2. Starting at the lowest address
698 /// i. check that the pattern has not changed
699 /// ii. write the pattern's complement
700 /// iii. increment the address
701 /// iv. repeat 2.1 to 2.3
702 /// 3. Starting at the highest address
703 /// i. check that the pattern has not changed
704 /// ii. write the pattern's complement
705 /// iii. decrement the address
706 /// iv. repeat 3.1 to 3.3 "
707 pub(super) trait MovInvAlgorithm: fmt::Debug + Default {
708 fn num_runs(&self) -> u64;
709
710 fn start_run(&mut self, _run_idx: u64);
711
712 fn start_pass(&mut self, _pass_idx: u64) {}
713
714 fn generate_pattern(&mut self) -> usize;
715
716 fn backtrack_pattern(&mut self) -> usize;
717
718 fn passes(&self) -> Vec<PassFn<Self>> {
719 vec![Self::pass_0, Self::pass_1, Self::pass_2]
720 }
721
722 fn pass_0(&mut self, _direction: &mut PassDirection) -> IterFn<Self> {
723 self.start_pass(0);
724 |state, mem_ref| {
725 let pattern = state.generate_pattern();
726 write_volatile_safe(mem_ref, pattern);
727 Ok(())
728 }
729 }
730
731 fn pass_1(&mut self, _direction: &mut PassDirection) -> IterFn<Self> {
732 self.start_pass(1);
733
734 |state, mem_ref| {
735 let pattern = state.generate_pattern();
736 check_expected_value(
737 address_from_ref(mem_ref),
738 pattern,
739 read_volatile_safe(mem_ref),
740 )?;
741
742 write_volatile_safe(mem_ref, !pattern);
743 Ok(())
744 }
745 }
746
747 fn pass_2(&mut self, direction: &mut PassDirection) -> IterFn<Self> {
748 *direction = PassDirection::Reverse;
749
750 self.start_pass(2);
751
752 |state, mem_ref| {
753 let pattern = !state.backtrack_pattern();
754 check_expected_value(
755 address_from_ref(mem_ref),
756 pattern,
757 read_volatile_safe(mem_ref),
758 )?;
759
760 write_volatile_safe(mem_ref, !pattern);
761 Ok(())
762 }
763 }
764 }
765
766 impl<T: MovInvAlgorithm> TestAlgorithm for T {
767 fn num_runs(&self) -> u64 {
768 T::num_runs(self)
769 }
770 fn start_run(&mut self, run_idx: u64) {
771 T::start_run(self, run_idx)
772 }
773 fn passes(&self) -> Vec<PassFn<Self>> {
774 T::passes(self)
775 }
776 }
777
778 #[derive(Debug, Default)]
779 pub(super) struct FixedBlock {
780 run_idx: u64,
781 }
782
783 /// This test runs the moving inversion algorithm with fixed patterns of all bits as 1s or 0s.
784 impl MovInvAlgorithm for FixedBlock {
785 fn num_runs(&self) -> u64 {
786 2
787 }
788
789 fn start_run(&mut self, run_idx: u64) {
790 self.run_idx = run_idx;
791 }
792
793 fn generate_pattern(&mut self) -> usize {
794 self.pattern()
795 }
796
797 fn backtrack_pattern(&mut self) -> usize {
798 self.pattern()
799 }
800 }
801
802 impl FixedBlock {
803 fn pattern(&mut self) -> usize {
804 if self.run_idx == 0 {
805 0
806 } else {
807 !0
808 }
809 }
810 }
811
812 /// This test runs the moving inversion algorithm with fixed 8-bit patterns where 1 bit is 1/0 and the
813 /// other 7 bits are 0/1s. The procedure is repeated 8 times with the pattern rotated by 1 bit each
814 /// time to test all bits in a byte.
815 #[derive(Debug)]
816 pub(super) struct FixedBit {
817 run_idx: u64,
818 pattern: usize,
819 }
820
821 impl Default for FixedBit {
822 fn default() -> Self {
823 FixedBit {
824 run_idx: u64::default(),
825 pattern: usize_filled_from_byte(0x01),
826 }
827 }
828 }
829
830 impl MovInvAlgorithm for FixedBit {
831 fn num_runs(&self) -> u64 {
832 16
833 }
834
835 fn start_run(&mut self, run_idx: u64) {
836 self.run_idx = run_idx;
837 if run_idx % 2 == 0 {
838 self.pattern = self.pattern.rotate_right(1);
839 }
840 }
841
842 fn generate_pattern(&mut self) -> usize {
843 self.pattern()
844 }
845
846 fn backtrack_pattern(&mut self) -> usize {
847 self.pattern()
848 }
849 }
850
851 impl FixedBit {
852 fn pattern(&mut self) -> usize {
853 if self.run_idx % 2 == 0 {
854 self.pattern
855 } else {
856 !self.pattern
857 }
858 }
859 }
860
861 /// This test runs the moving inversion algorithm with a random fixed pattern.
862 #[derive(Debug)]
863 pub(super) struct FixedRandom {
864 run_idx: u64,
865 pattern: usize,
866 }
867
868 impl Default for FixedRandom {
869 fn default() -> Self {
870 FixedRandom {
871 run_idx: u64::default(),
872 pattern: random(),
873 }
874 }
875 }
876
877 impl MovInvAlgorithm for FixedRandom {
878 fn num_runs(&self) -> u64 {
879 2
880 }
881
882 fn start_run(&mut self, run_idx: u64) {
883 self.run_idx = run_idx;
884 }
885
886 fn generate_pattern(&mut self) -> usize {
887 self.pattern()
888 }
889
890 fn backtrack_pattern(&mut self) -> usize {
891 self.pattern()
892 }
893 }
894
895 impl FixedRandom {
896 fn pattern(&mut self) -> usize {
897 if self.run_idx % 2 == 0 {
898 self.pattern
899 } else {
900 !self.pattern
901 }
902 }
903 }
904
905 #[derive(Debug, Default)]
906 pub(super) struct Walk {
907 run_idx: u64,
908 starting_pattern: usize,
909 pattern: usize,
910 }
911
912 /// This test runs the moving inversion algorithm with a "walking" bit pattern. The algorithm starts
913 /// with 0x1 (or the compliment of 0x1) and "walks" the bit by shifting left for every new memory
914 /// location.
915 /// The procedure is repeated with offsets 0-31 or 0-63 depending on the size of `usize` to test all
916 /// bits in a memory location.
917 impl MovInvAlgorithm for Walk {
918 fn num_runs(&self) -> u64 {
919 u64::from(usize::BITS) * 2
920 }
921
922 fn start_run(&mut self, run_idx: u64) {
923 self.run_idx = run_idx;
924 self.starting_pattern = 1 << (run_idx / 2);
925 }
926
927 fn start_pass(&mut self, pass_idx: u64) {
928 // For pass_idx == 2, pattern is not reset
929 if pass_idx == 0 || pass_idx == 1 {
930 self.pattern = self.starting_pattern;
931 }
932 }
933
934 fn generate_pattern(&mut self) -> usize {
935 let pattern = if self.run_idx % 2 == 0 {
936 self.pattern
937 } else {
938 !self.pattern
939 };
940 self.pattern = self.pattern.rotate_left(1);
941 pattern
942 }
943
944 fn backtrack_pattern(&mut self) -> usize {
945 self.pattern = self.pattern.rotate_right(1);
946 if self.run_idx % 2 == 0 {
947 self.pattern
948 } else {
949 !self.pattern
950 }
951 }
952 }
953
954 // Despite its name MovInvRandom, this implementation (which follows the Memtest86+
955 // implementation) is not similar to other moving inversion tests. Due to its nature of using
956 // random numbers for each address, pass 2 does not traverse the memory in reverse.
957 // TODO: Consider using a reversible RNG to match other moving inversion tests
958 // See https://stackoverflow.com/questions/31513168/finding-inverse-operation-to-george-marsaglias-xorshift-rng
959 // and https://stackoverflow.com/questions/31521910/simplify-the-inverse-of-z-x-x-y-function/31522122#31522122
960 // for XORshift, which is the RNG used in Memtest86+
961 #[derive(Debug)]
962 pub(super) struct Random {
963 seed: u64,
964 rng: SmallRng,
965 }
966
967 impl Default for Random {
968 fn default() -> Self {
969 let seed = SystemTime::now()
970 .duration_since(UNIX_EPOCH)
971 .unwrap()
972 .as_millis() as u64;
973 Random {
974 seed,
975 rng: SmallRng::seed_from_u64(seed),
976 }
977 }
978 }
979
980 impl TestAlgorithm for Random {
981 fn passes(&self) -> Vec<PassFn<Self>> {
982 vec![Self::pass_0, Self::pass_1, Self::pass_2]
983 }
984 }
985
986 impl Random {
987 fn pass_0(&mut self, _direction: &mut PassDirection) -> IterFn<Self> {
988 self.reset_rng();
989
990 |state, mem_ref| {
991 let pattern = state.rng.gen();
992 write_volatile_safe(mem_ref, pattern);
993
994 Ok(())
995 }
996 }
997
998 fn pass_1(&mut self, _direction: &mut PassDirection) -> IterFn<Self> {
999 self.reset_rng();
1000
1001 |state, mem_ref| {
1002 let pattern = state.rng.gen();
1003 check_expected_value(
1004 address_from_ref(mem_ref),
1005 pattern,
1006 read_volatile_safe(mem_ref),
1007 )?;
1008
1009 write_volatile_safe(mem_ref, !pattern);
1010 Ok(())
1011 }
1012 }
1013
1014 fn pass_2(&mut self, _direction: &mut PassDirection) -> IterFn<Self> {
1015 self.reset_rng();
1016
1017 |state, mem_ref| {
1018 let pattern = !state.rng.gen::<usize>();
1019 check_expected_value(
1020 address_from_ref(mem_ref),
1021 pattern,
1022 read_volatile_safe(mem_ref),
1023 )?;
1024
1025 write_volatile_safe(mem_ref, !pattern);
1026 Ok(())
1027 }
1028 }
1029
1030 fn reset_rng(&mut self) {
1031 self.rng = SmallRng::seed_from_u64(self.seed);
1032 }
1033 }
1034 }
1035 /// This test adapts the block move test algorithm implemented by [memtest86+](https://github.com/
1036 /// memtest86plus/memtest86plus). For a detailed explanation of the algorithm, please refer to
1037 /// the description available at the [Memtest86+ Test Algorithm Section](https://github.com/
1038 /// memtest86plus/memtest86plus?tab=readme-ov-file#memtest86-test-algorithms)
1039 ///
1040 /// The test aims to stress test the memory by moving blocks of memory, such as with the `movs` instruction.
1041 /// It first initializes the memory with an irregular shifting pattern. Then it performs 3 memory block moves.
1042 /// 1. Copy the first half of the memory region to the second half
1043 /// 2. Copy the second half of the memory region back to the first half, offset by 8 locations.
1044 /// ie. Copy the second half - the last 8 locations, to the first half's original location + 8
1045 /// 3. Copy the second half's last 8 locations to the first half's first 8 locations
1046 /// Finally, the test verifies that the second half has the values of the original first half, and
1047 /// the first half's values are right rotated by 8 locations
1048 ///
1049 /// Note that the original implementation in Memtest86+ only verifies the values by comparing
1050 /// neighbouring pairs of memory location. Instead of that, this implementation verifies by
1051 /// recalculating the expected pattern in each location.
1052 ///
1053 /// Also note that unlike the other memory tests, `Observer::check()` is only called in the initial
1054 /// loop for initalizing memory and the final loop for verifying values. It is not called during the
1055 /// memory block moves, as it intefere with the stress testing of memory. Unfortunately, this means
1056 /// that `Observer::check()` will not be called for a siginficant duration of the test run time.
1057 #[tracing::instrument(skip_all)]
1058 pub fn run_block_move<O: TestObserver>(memory: &mut [usize], mut observer: O) -> TestResult<O> {
1059 const CHUNK_SIZE: usize = 16;
1060 const OFFSET: usize = 8;
1061 if memory.len() < CHUNK_SIZE {
1062 Err(anyhow!("Insufficient memory length for Block Move Test"))?;
1063 }
1064
1065 let expected_iter = u64::try_from(memory.len())
1066 .ok()
1067 .and_then(|count| count.checked_mul(2))
1068 .context("Total number of iterations overflowed")?;
1069 observer.init(expected_iter);
1070
1071 let val_to_write = |pattern: usize, idx| match idx {
1072 4 | 5 | 10 | 11 | 14 | 15 => !pattern,
1073 _ => pattern,
1074 };
1075
1076 // Set up initial pattern in memory
1077 let mut pattern = 1;
1078 for chunk in memory.chunks_exact_mut(CHUNK_SIZE) {
1079 for (i, mem_ref) in chunk.iter_mut().enumerate() {
1080 observer.check().map_err(Error::Observer)?;
1081
1082 let val = val_to_write(pattern, i);
1083 write_volatile_safe(mem_ref, val);
1084 }
1085 pattern = pattern.rotate_left(1);
1086 }
1087
1088 // Move blocks of memory around
1089 let (first_half, second_half) = split_slice_in_half(memory)?;
1090 let half_len = first_half.len();
1091 volatile_copy_slice(second_half, first_half);
1092 volatile_copy_slice(
1093 &mut first_half[OFFSET..],
1094 &second_half[..(half_len - OFFSET)],
1095 );
1096 volatile_copy_slice(
1097 &mut first_half[..OFFSET],
1098 &second_half[(half_len - OFFSET)..],
1099 );
1100
1101 // Verify that values stored after block move are as expected, by traversing both halves at the
1102 // same time (with first half rotated by OFFSET), as they have the same expected values
1103 let mut pattern = 1;
1104 for (chunk1, chunk2) in [&first_half[OFFSET..], &first_half[..OFFSET]]
1105 .concat()
1106 .chunks(CHUNK_SIZE)
1107 .zip(second_half.chunks(CHUNK_SIZE))
1108 {
1109 for (i, (mem_ref1, mem_ref2)) in chunk1.iter().zip(chunk2.iter()).enumerate() {
1110 let expected = val_to_write(pattern, i);
1111
1112 for mem_ref in [mem_ref1, mem_ref2] {
1113 observer.check().map_err(Error::Observer)?;
1114
1115 if let Err(f) = check_expected_value(
1116 address_from_ref(mem_ref),
1117 expected,
1118 read_volatile_safe(mem_ref),
1119 ) {
1120 return Ok(Outcome::Fail(f));
1121 }
1122 }
1123 }
1124 pattern = pattern.rotate_left(1);
1125 }
1126
1127 Ok(Outcome::Pass)
1128 }
1129
1130 // TODO: In Memtest86+, block move is achieved with the `movs` assembly instruction
1131 fn volatile_copy_slice<T: Copy>(dst: &mut [T], src: &[T]) {
1132 assert_eq!(
1133 dst.len(),
1134 src.len(),
1135 "length of dst and src should be equal"
1136 );
1137
1138 for (dst_ref, src_ref) in dst.iter_mut().zip(src.iter()) {
1139 let val = read_volatile_safe(src_ref);
1140 write_volatile_safe(dst_ref, val);
1141 }
1142 }
1143
1144 /// This test uses the Modulo-20 algorithm implemented by [memtest86+](https://github.com/
1145 /// memtest86plus/memtest86plus), which is designed to avoid effects of caching and buffering.
1146 ///
1147 /// The test generates a random value, then write the value to every 20th memory location.
1148 /// Afterwards write the complement of the value to all other locations one or more times (twice in
1149 /// this case). Then verify that the values stored in every 20th location is unchanged.
1150 ///
1151 /// The procedure is repeated with offsets 0-19 to test all memory locations.
1152 #[tracing::instrument(skip_all)]
1153 pub fn run_modulo_20<O: TestObserver>(memory: &mut [usize], mut observer: O) -> TestResult<O> {
1154 const STEP: usize = 20;
1155 (memory.len() > STEP)
1156 .then_some(())
1157 .context("Insufficient memory length for two-regions memtest")?;
1158 let expected_iter = u64::try_from(memory.len())
1159 .ok()
1160 .and_then(|count| count.checked_mul((STEP * 2).try_into().unwrap()))
1161 .context("Total number of iterations overflowed")?;
1162 observer.init(expected_iter);
1163
1164 let pattern = random();
1165 for offset in 0..STEP {
1166 for mem_ref in memory.iter_mut().skip(offset).step_by(STEP) {
1167 observer.check().map_err(Error::Observer)?;
1168 write_volatile_safe(mem_ref, pattern);
1169 }
1170
1171 for _ in 0..2 {
1172 for (i, mem_ref) in memory.iter_mut().enumerate() {
1173 if i % STEP == offset {
1174 continue;
1175 }
1176 observer.check().map_err(Error::Observer)?;
1177 write_volatile_safe(mem_ref, !pattern);
1178 }
1179 }
1180
1181 for mem_ref in memory.iter().skip(offset).step_by(STEP) {
1182 observer.check().map_err(Error::Observer)?;
1183
1184 if let Err(f) = check_expected_value(
1185 address_from_ref(mem_ref),
1186 pattern,
1187 read_volatile_safe(mem_ref),
1188 ) {
1189 return Ok(Outcome::Fail(f));
1190 }
1191 }
1192 }
1193
1194 Ok(Outcome::Pass)
1195 }
1196
1197 fn read_volatile_safe<T: Copy>(src: &T) -> T {
1198 unsafe { std::ptr::read_volatile(src) }
1199 }
1200
1201 fn write_volatile_safe<T: Copy>(dst: &mut T, src: T) {
1202 unsafe { std::ptr::write_volatile(dst, src) }
1203 }
1204
1205 fn split_slice_in_half(slice: &mut [usize]) -> anyhow::Result<(&mut [usize], &mut [usize])> {
1206 let mut it = slice.chunks_exact_mut(slice.len() / 2);
1207 let (Some(first), Some(second)) = (it.next(), it.next()) else {
1208 bail!("Insufficient memory length for two-regions memtest");
1209 };
1210 Ok((first, second))
1211 }
1212
1213 fn mem_reset(memory: &mut [usize]) {
1214 for mem_ref in memory.iter_mut() {
1215 write_volatile_safe(mem_ref, !0);
1216 }
1217 }
1218
1219 fn address_from_ref(r: &usize) -> usize {
1220 std::ptr::from_ref(r) as usize
1221 }
1222
1223 /// Return a usize where all bytes are set to to value of `byte`
1224 fn usize_filled_from_byte(byte: u8) -> usize {
1225 let mut val = 0;
1226 unsafe { std::ptr::write_bytes(&mut val, byte, 1) }
1227 val
1228 }
1229
1230 impl fmt::Debug for Failure {
1231 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1232 match self {
1233 Self::UnexpectedValue {
1234 address,
1235 expected,
1236 actual,
1237 } => f
1238 .debug_struct("UnexpectedValue")
1239 .field("address", &format_args!("0x{address:x}"))
1240 .field("expected", &format_args!("0x{expected:x}"))
1241 .field("actual", &format_args!("0x{actual:x}"))
1242 .finish(),
1243 Self::MismatchedValues {
1244 address1,
1245 value1,
1246 address2,
1247 value2,
1248 } => f
1249 .debug_struct("MismatchedValues")
1250 .field("address1", &format_args!("0x{address1:x}"))
1251 .field("value1", &format_args!("0x{value1:x}"))
1252 .field("address2", &format_args!("0x{address2:x}"))
1253 .field("value2", &format_args!("0x{value2:x}"))
1254 .finish(),
1255 }
1256 }
1257 }
1258
1259 impl fmt::Display for ParseTestKindError {
1260 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1261 write!(f, "{:?}", self)
1262 }
1263 }
1264
1265 impl error::Error for ParseTestKindError {}
1266
1267 impl fmt::Display for Outcome {
1268 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1269 write!(f, "Outcome: {:?}", self)
1270 }
1271 }
1272
1273 impl<E: fmt::Debug> fmt::Display for Error<E> {
1274 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1275 write!(f, "Error: {:?}", self)
1276 }
1277 }
1278
1279 impl<E: error::Error + 'static> error::Error for Error<E> {
1280 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
1281 match self {
1282 Error::Observer(err) => Some(err),
1283 Error::Other(err) => Some(err.as_ref()),
1284 }
1285 }
1286 }
1287
1288 impl<E> From<anyhow::Error> for Error<E> {
1289 fn from(err: anyhow::Error) -> Error<E> {
1290 Error::Other(err)
1291 }
1292 }
1293
1294 fn serialize_error_other<S>(error: &anyhow::Error, serializer: S) -> Result<S::Ok, S::Error>
1295 where
1296 S: Serializer,
1297 {
1298 serializer.serialize_str(&format!("{:?}", error))
1299 }
1300
1301 fn deserialize_error_other<'de, D>(deserializer: D) -> Result<anyhow::Error, D::Error>
1302 where
1303 D: Deserializer<'de>,
1304 {
1305 let str = String::deserialize(deserializer)?;
1306 Ok(anyhow!(str))
1307 }
1308
1309 #[cfg(test)]
1310 mod test {
1311 use {
1312 super::{Outcome, TestKind, TestObserver},
1313 std::convert::Infallible,
1314 };
1315
1316 #[derive(Debug)]
1317 struct IterationCounter {
1318 expected_iter: Option<u64>,
1319 completed_iter: u64,
1320 }
1321
1322 impl TestObserver for &mut IterationCounter {
1323 type Error = Infallible;
1324
1325 fn init(&mut self, expected_iter: u64) {
1326 assert!(
1327 self.expected_iter.is_none(),
1328 "init() should only be called once per test"
1329 );
1330
1331 self.expected_iter = Some(expected_iter);
1332 }
1333
1334 #[inline(always)]
1335 fn check(&mut self) -> Result<(), Self::Error> {
1336 self.completed_iter += 1;
1337 Ok(())
1338 }
1339 }
1340
1341 impl IterationCounter {
1342 fn new() -> IterationCounter {
1343 IterationCounter {
1344 expected_iter: None,
1345 completed_iter: 0,
1346 }
1347 }
1348
1349 fn assert_count(self) {
1350 let expected_iter = self.expected_iter.expect("init() should be called");
1351 assert_eq!(expected_iter, self.completed_iter);
1352 }
1353 }
1354
1355 #[test]
1356 fn test_memtest_expected_iter() {
1357 let mut memory = vec![0; 512];
1358 for test_kind in TestKind::ALL {
1359 let mut counter = IterationCounter::new();
1360 assert!(
1361 matches!(test_kind.run(&mut memory, &mut counter), Ok(Outcome::Pass),),
1362 "{:?} should pass",
1363 test_kind
1364 );
1365 counter.assert_count();
1366 }
1367 }
1368 }