Merge tag 'xtensa-20180225' of git://github.com/jcmvbkbc/linux-xtensa
[cris-mirror.git] / tools / testing / selftests / powerpc / utils.c
blobd46916867a6fbcf627bd1fe2d45574decc8c9de8
1 /*
2 * Copyright 2013-2015, Michael Ellerman, IBM Corp.
3 * Licensed under GPLv2.
4 */
6 #define _GNU_SOURCE /* For CPU_ZERO etc. */
8 #include <elf.h>
9 #include <errno.h>
10 #include <fcntl.h>
11 #include <link.h>
12 #include <sched.h>
13 #include <stdio.h>
14 #include <sys/stat.h>
15 #include <sys/types.h>
16 #include <unistd.h>
18 #include "utils.h"
20 static char auxv[4096];
22 int read_auxv(char *buf, ssize_t buf_size)
24 ssize_t num;
25 int rc, fd;
27 fd = open("/proc/self/auxv", O_RDONLY);
28 if (fd == -1) {
29 perror("open");
30 return -errno;
33 num = read(fd, buf, buf_size);
34 if (num < 0) {
35 perror("read");
36 rc = -EIO;
37 goto out;
40 if (num > buf_size) {
41 printf("overflowed auxv buffer\n");
42 rc = -EOVERFLOW;
43 goto out;
46 rc = 0;
47 out:
48 close(fd);
49 return rc;
52 void *find_auxv_entry(int type, char *auxv)
54 ElfW(auxv_t) *p;
56 p = (ElfW(auxv_t) *)auxv;
58 while (p->a_type != AT_NULL) {
59 if (p->a_type == type)
60 return p;
62 p++;
65 return NULL;
68 void *get_auxv_entry(int type)
70 ElfW(auxv_t) *p;
72 if (read_auxv(auxv, sizeof(auxv)))
73 return NULL;
75 p = find_auxv_entry(type, auxv);
76 if (p)
77 return (void *)p->a_un.a_val;
79 return NULL;
82 int pick_online_cpu(void)
84 cpu_set_t mask;
85 int cpu;
87 CPU_ZERO(&mask);
89 if (sched_getaffinity(0, sizeof(mask), &mask)) {
90 perror("sched_getaffinity");
91 return -1;
94 /* We prefer a primary thread, but skip 0 */
95 for (cpu = 8; cpu < CPU_SETSIZE; cpu += 8)
96 if (CPU_ISSET(cpu, &mask))
97 return cpu;
99 /* Search for anything, but in reverse */
100 for (cpu = CPU_SETSIZE - 1; cpu >= 0; cpu--)
101 if (CPU_ISSET(cpu, &mask))
102 return cpu;
104 printf("No cpus in affinity mask?!\n");
105 return -1;