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 static int sysfs_topology_read_file(unsigned int cpu
, const char *fname
, int *result
)
25 char linebuf
[MAX_LINE_LEN
];
27 char path
[SYSFS_PATH_MAX
];
29 snprintf(path
, sizeof(path
), PATH_TO_CPU
"cpu%u/topology/%s",
31 if (sysfs_read_file(path
, linebuf
, MAX_LINE_LEN
) == 0)
33 *result
= strtol(linebuf
, &endp
, 0);
34 if (endp
== linebuf
|| errno
== ERANGE
)
39 static int __compare(const void *t1
, const void *t2
)
41 struct cpuid_core_info
*top1
= (struct cpuid_core_info
*)t1
;
42 struct cpuid_core_info
*top2
= (struct cpuid_core_info
*)t2
;
43 if (top1
->pkg
< top2
->pkg
)
45 else if (top1
->pkg
> top2
->pkg
)
47 else if (top1
->core
< top2
->core
)
49 else if (top1
->core
> top2
->core
)
51 else if (top1
->cpu
< top2
->cpu
)
53 else if (top1
->cpu
> top2
->cpu
)
60 * Returns amount of cpus, negative on error, cpu_top must be
61 * passed to cpu_topology_release to free resources
63 * Array is sorted after ->pkg, ->core, then ->cpu
65 int get_cpu_topology(struct cpupower_topology
*cpu_top
)
67 int cpu
, last_pkg
, cpus
= sysconf(_SC_NPROCESSORS_CONF
);
69 cpu_top
->core_info
= malloc(sizeof(struct cpuid_core_info
) * cpus
);
70 if (cpu_top
->core_info
== NULL
)
72 cpu_top
->pkgs
= cpu_top
->cores
= 0;
73 for (cpu
= 0; cpu
< cpus
; cpu
++) {
74 cpu_top
->core_info
[cpu
].cpu
= cpu
;
75 cpu_top
->core_info
[cpu
].is_online
= sysfs_is_cpu_online(cpu
);
76 if(sysfs_topology_read_file(
78 "physical_package_id",
79 &(cpu_top
->core_info
[cpu
].pkg
)) < 0)
81 if(sysfs_topology_read_file(
84 &(cpu_top
->core_info
[cpu
].core
)) < 0)
88 qsort(cpu_top
->core_info
, cpus
, sizeof(struct cpuid_core_info
),
91 /* Count the number of distinct pkgs values. This works
92 because the primary sort of the core_info struct was just
94 last_pkg
= cpu_top
->core_info
[0].pkg
;
95 for(cpu
= 1; cpu
< cpus
; cpu
++) {
96 if(cpu_top
->core_info
[cpu
].pkg
!= last_pkg
) {
97 last_pkg
= cpu_top
->core_info
[cpu
].pkg
;
103 /* Intel's cores count is not consecutively numbered, there may
104 * be a core_id of 3, but none of 2. Assume there always is 0
105 * Get amount of cores by counting duplicates in a package
106 for (cpu = 0; cpu_top->core_info[cpu].pkg = 0 && cpu < cpus; cpu++) {
107 if (cpu_top->core_info[cpu].core == 0)
113 void cpu_topology_release(struct cpupower_topology cpu_top
)
115 free(cpu_top
.core_info
);