xref: /aosp_15_r20/external/flashrom/tests/udelay.c (revision 0d6140be3aa665ecc836e8907834fcd3e3b018fc)
1 /*
2  * This file is part of the flashrom project.
3  *
4  * Copyright 2024 Google LLC
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; version 2 of the License.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  */
15 #include <include/test.h>
16 #include <stdint.h>
17 #include <sys/time.h>
18 #include <time.h>
19 
20 #include "programmer.h"
21 #include "tests.h"
22 
now_us(void)23 static uint64_t now_us(void) {
24 #if HAVE_CLOCK_GETTIME == 1
25     struct timespec ts;
26 
27     clock_gettime(CLOCK_MONOTONIC, &ts);
28     return (ts.tv_nsec / 1000) + (ts.tv_sec * 1000000);
29 #else
30     struct timeval tv;
31 
32     gettimeofday(&tv, NULL);
33     return tv.tv_usec + (tv.tv_sec * 1000000);
34 #endif
35 }
36 
37 static const int64_t min_sleep = CONFIG_DELAY_MINIMUM_SLEEP_US;
38 
39 /*
40  * A short delay should delay for at least as long as requested,
41  * and more than 10x as long would be worrisome.
42  *
43  * This test could fail spuriously on a heavily-loaded system, or if we need
44  * to use gettimeofday() and a time change (such as DST) occurs during the
45  * test.
46  */
udelay_test_short(void ** state)47 void udelay_test_short(void **state) {
48     /*
49      * Delay for 100 microseconds, or short enough that we won't sleep.
50      * It's not useful to test the sleep path because we assume the OS won't
51      * sleep for less time than we ask.
52      */
53     int64_t delay_us = 100;
54     if (delay_us >= min_sleep)
55       delay_us = min_sleep - 1;
56     /* No point in running this test if delay always sleeps. */
57     if (delay_us <= 0)
58       skip();
59 
60     uint64_t start = now_us();
61     default_delay(delay_us);
62     uint64_t elapsed = now_us() - start;
63 
64     assert_in_range(elapsed, delay_us, 10 * delay_us);
65 }
66