xref: /openbmc/linux/tools/testing/selftests/proc/proc-uptime.h (revision ca90578000afb0d8f177ea36f7259a9c3640cf49)
1 /*
2  * Copyright © 2018 Alexey Dobriyan <adobriyan@gmail.com>
3  *
4  * Permission to use, copy, modify, and distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  */
16 #undef NDEBUG
17 #include <assert.h>
18 #include <errno.h>
19 #include <string.h>
20 #include <stdlib.h>
21 #include <unistd.h>
22 
23 static unsigned long long xstrtoull(const char *p, char **end)
24 {
25 	if (*p == '0') {
26 		*end = (char *)p + 1;
27 		return 0;
28 	} else if ('1' <= *p && *p <= '9') {
29 		unsigned long long val;
30 
31 		errno = 0;
32 		val = strtoull(p, end, 10);
33 		assert(errno == 0);
34 		return val;
35 	} else
36 		assert(0);
37 }
38 
39 static void proc_uptime(int fd, uint64_t *uptime, uint64_t *idle)
40 {
41 	uint64_t val1, val2;
42 	char buf[64], *p;
43 	ssize_t rv;
44 
45 	/* save "p < end" checks */
46 	memset(buf, 0, sizeof(buf));
47 	rv = pread(fd, buf, sizeof(buf), 0);
48 	assert(0 <= rv && rv <= sizeof(buf));
49 	buf[sizeof(buf) - 1] = '\0';
50 
51 	p = buf;
52 
53 	val1 = xstrtoull(p, &p);
54 	assert(p[0] == '.');
55 	assert('0' <= p[1] && p[1] <= '9');
56 	assert('0' <= p[2] && p[2] <= '9');
57 	assert(p[3] == ' ');
58 
59 	val2 = (p[1] - '0') * 10 + p[2] - '0';
60 	*uptime = val1 * 100 + val2;
61 
62 	p += 4;
63 
64 	val1 = xstrtoull(p, &p);
65 	assert(p[0] == '.');
66 	assert('0' <= p[1] && p[1] <= '9');
67 	assert('0' <= p[2] && p[2] <= '9');
68 	assert(p[3] == '\n');
69 
70 	val2 = (p[1] - '0') * 10 + p[2] - '0';
71 	*idle = val1 * 100 + val2;
72 
73 	assert(p + 4 == buf + rv);
74 }
75