2 * (C) 2010,2011 Thomas Renninger <trenn@suse.de>, Novell Inc.
4 * Licensed under the terms of the GNU GPL License version 2.
6 * ToDo: Needs to be done more properly for AMD/Intel specifics
9 /* Helper struct for qsort, must be in sync with cpupower_topology.cpu_info */
10 /* Be careful: Need to pass unsigned to the sort, so that offlined cores are
11 in the end, but double check for -1 for offlined cpus at other places */
19 #include <helpers/helpers.h>
20 #include <helpers/sysfs.h>
22 /* returns -1 on failure, 0 on success */
23 int sysfs_topology_read_file(unsigned int cpu, const char *fname)
26 char linebuf[MAX_LINE_LEN];
28 char path[SYSFS_PATH_MAX];
30 snprintf(path, sizeof(path), PATH_TO_CPU "cpu%u/topology/%s",
32 if (sysfs_read_file(path, linebuf, MAX_LINE_LEN) == 0)
34 value = strtoul(linebuf, &endp, 0);
35 if (endp == linebuf || errno == ERANGE)
40 struct cpuid_core_info {
46 static int __compare(const void *t1, const void *t2)
48 struct cpuid_core_info *top1 = (struct cpuid_core_info *)t1;
49 struct cpuid_core_info *top2 = (struct cpuid_core_info *)t2;
50 if (top1->pkg < top2->pkg)
52 else if (top1->pkg > top2->pkg)
54 else if (top1->thread < top2->thread)
56 else if (top1->thread > top2->thread)
58 else if (top1->cpu < top2->cpu)
60 else if (top1->cpu > top2->cpu)
67 * Returns amount of cpus, negative on error, cpu_top must be
68 * passed to cpu_topology_release to free resources
70 * Array is sorted after ->pkg, ->core, then ->cpu
72 int get_cpu_topology(struct cpupower_topology *cpu_top)
74 int cpu, cpus = sysconf(_SC_NPROCESSORS_CONF);
76 cpu_top->core_info = malloc(sizeof(struct cpupower_topology) * cpus);
77 if (cpu_top->core_info == NULL)
79 cpu_top->pkgs = cpu_top->cores = 0;
80 for (cpu = 0; cpu < cpus; cpu++) {
81 cpu_top->core_info[cpu].pkg =
82 sysfs_topology_read_file(cpu, "physical_package_id");
83 if ((int)cpu_top->core_info[cpu].pkg != -1 &&
84 cpu_top->core_info[cpu].pkg > cpu_top->pkgs)
85 cpu_top->pkgs = cpu_top->core_info[cpu].pkg;
86 cpu_top->core_info[cpu].core =
87 sysfs_topology_read_file(cpu, "core_id");
88 cpu_top->core_info[cpu].cpu = cpu;
92 qsort(cpu_top->core_info, cpus, sizeof(struct cpuid_core_info),
95 /* Intel's cores count is not consecutively numbered, there may
96 * be a core_id of 3, but none of 2. Assume there always is 0
97 * Get amount of cores by counting duplicates in a package
98 for (cpu = 0; cpu_top->core_info[cpu].pkg = 0 && cpu < cpus; cpu++) {
99 if (cpu_top->core_info[cpu].core == 0)
105 void cpu_topology_release(struct cpupower_topology cpu_top)
107 free(cpu_top.core_info);