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 // Test that values in /proc/uptime increment monotonically
17 // while shifting across CPUs.
18 #undef NDEBUG
19 #include <assert.h>
20 #include <unistd.h>
21 #include <sys/syscall.h>
22 #include <stdlib.h>
23 #include <string.h>
24 
25 #include <stdint.h>
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <fcntl.h>
29 
30 #include "proc-uptime.h"
31 
32 static inline int sys_sched_getaffinity(pid_t pid, unsigned int len, unsigned long *m)
33 {
34 	return syscall(SYS_sched_getaffinity, pid, len, m);
35 }
36 
37 static inline int sys_sched_setaffinity(pid_t pid, unsigned int len, unsigned long *m)
38 {
39 	return syscall(SYS_sched_setaffinity, pid, len, m);
40 }
41 
42 int main(void)
43 {
44 	unsigned int len;
45 	unsigned long *m;
46 	unsigned int cpu;
47 	uint64_t u0, u1, i0, i1;
48 	int fd;
49 
50 	/* find out "nr_cpu_ids" */
51 	m = NULL;
52 	len = 0;
53 	do {
54 		len += sizeof(unsigned long);
55 		free(m);
56 		m = malloc(len);
57 	} while (sys_sched_getaffinity(0, len, m) == -EINVAL);
58 
59 	fd = open("/proc/uptime", O_RDONLY);
60 	assert(fd >= 0);
61 
62 	proc_uptime(fd, &u0, &i0);
63 	for (cpu = 0; cpu < len * 8; cpu++) {
64 		memset(m, 0, len);
65 		m[cpu / (8 * sizeof(unsigned long))] |= 1UL << (cpu % (8 * sizeof(unsigned long)));
66 
67 		/* CPU might not exist, ignore error */
68 		sys_sched_setaffinity(0, len, m);
69 
70 		proc_uptime(fd, &u1, &i1);
71 		assert(u1 >= u0);
72 		assert(i1 >= i0);
73 		u0 = u1;
74 		i0 = i1;
75 	}
76 
77 	return 0;
78 }
79