1 /*
2 *
3 * Copyright (c) Novell Inc. 2011
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms in version 2 of the GNU General Public License as
7 * published by the Free Software Foundation.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
12 * the GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17 *
18 * Author: Peter W. Morreale <pmorreale AT novell DOT com>
19 * Date: 11/08/2011
20 */
21
22 /*
23 * Must be ported to OS's other than Linux
24 */
25
26 #ifdef __linux__
27 # define _GNU_SOURCE
28 # include <sched.h>
29 # include <stdio.h>
30
set_affinity(int cpu)31 static int set_affinity(int cpu)
32 {
33 cpu_set_t mask;
34
35 CPU_ZERO(&mask);
36 CPU_SET(cpu, &mask);
37
38 return (sched_setaffinity(0, sizeof(cpu_set_t), &mask));
39 }
40
get_online_cpu_from_sysfs(void)41 static int get_online_cpu_from_sysfs(void)
42 {
43 FILE *f;
44 int cpu = -1;
45
46 f = fopen("/sys/devices/system/cpu/online", "r");
47 if (!f)
48 return -1;
49 fscanf(f, "%d", &cpu);
50 fclose(f);
51
52 return cpu;
53 }
54
get_online_cpu_from_cpuinfo(void)55 static int get_online_cpu_from_cpuinfo(void)
56 {
57 FILE *f;
58 int cpu = -1;
59 char line[4096];
60
61 f = fopen("/proc/cpuinfo", "r");
62 if (!f)
63 return -1;
64
65 while (!feof(f)) {
66 if (!fgets(line, sizeof(line), f))
67 return -1;
68 /*
69 * cpuinfo output is not consistent across all archictures,
70 * it can be "processor : N", but for example on s390
71 * it's: "processor N: ...", so ignore any non-number
72 * after "processor"
73 */
74 if (sscanf(line, "processor%*[^0123456789]%d", &cpu) == 1)
75 break;
76 }
77 fclose(f);
78
79 return cpu;
80 }
81
set_affinity_single(void)82 static int set_affinity_single(void)
83 {
84 int cpu;
85
86 cpu = get_online_cpu_from_sysfs();
87 if (cpu >= 0)
88 goto set_affinity;
89
90 cpu = get_online_cpu_from_cpuinfo();
91 if (cpu >= 0)
92 goto set_affinity;
93
94 fprintf(stderr, "WARNING: Failed to detect online cpu, using cpu=0\n");
95 cpu = 0;
96 set_affinity:
97 return set_affinity(cpu);
98 }
99
100 #else
101 #include <errno.h>
102
set_affinity_single(void)103 static int set_affinity_single(void)
104 {
105 errno = ENOSYS;
106 return -1;
107 }
108 #endif
109