1 #include "lscpu.h"
2
3 struct lscpu_cpu *lscpu_new_cpu(int id)
4 {
5 struct lscpu_cpu *cpu;
6
7 cpu = xcalloc(1, sizeof(struct lscpu_cpu));
8 cpu->refcount = 1;
9 cpu->logical_id = id;
10 cpu->coreid = -1;
11 cpu->socketid = -1;
12 cpu->bookid = -1;
13 cpu->bookid = -1;
14 cpu->address = -1;
15 cpu->configured = -1;
16
17 DBG(CPU, ul_debugobj(cpu, "alloc"));
18 return cpu;
19 }
20
21 void lscpu_ref_cpu(struct lscpu_cpu *cpu)
22 {
23 if (cpu)
24 cpu->refcount++;
25 }
26
27 void lscpu_unref_cpu(struct lscpu_cpu *cpu)
28 {
29 if (!cpu)
30 return;
31
32 if (--cpu->refcount <= 0) {
33 DBG(CPU, ul_debugobj(cpu, " freeing #%d", cpu->logical_id));
34 lscpu_unref_cputype(cpu->type);
35 cpu->type = NULL;
36 free(cpu->dynamic_mhz);
37 free(cpu->static_mhz);
38 free(cpu->mhz);
39 free(cpu->bogomips);
40 free(cpu);
41 }
42 }
43
44 /*
45 * Create and initialize array with CPU structs according to @cpuset.
46 */
47 int lscpu_create_cpus(struct lscpu_cxt *cxt, cpu_set_t *cpuset, size_t setsize)
48 {
49 size_t n, i;
50
51 assert(!cxt->cpus);
52
53 cxt->npossibles = CPU_COUNT_S(setsize, cpuset);
54 cxt->cpus = xcalloc(1, cxt->npossibles * sizeof(struct lscpu_cpu *));
55
56 for (n = 0, i = 0; n < (size_t) cxt->maxcpus && i < cxt->npossibles; n++) {
57 if (CPU_ISSET_S(n, setsize, cpuset))
58 cxt->cpus[i++] = lscpu_new_cpu(n);
59 }
60
61 return 0;
62 }
63
64 int lscpu_cpu_set_type(struct lscpu_cpu *cpu, struct lscpu_cputype *type)
65 {
66 if (cpu->type == type)
67 return 0;
68
69 lscpu_unref_cputype(cpu->type);
70 cpu->type = type;
71 lscpu_ref_cputype(type);
72
73 DBG(CPU, ul_debugobj(cpu, "cputype set to %s", type ? type->vendor : NULL));
74 return 0;
75 }
76
77 /* don't forget lscpu_ref_cpu() ! */
78 struct lscpu_cpu *lscpu_get_cpu(struct lscpu_cxt *cxt, int logical_id)
79 {
80 size_t i;
81
82 for (i = 0; i < cxt->npossibles; i++) {
83 struct lscpu_cpu *cpu = cxt->cpus[i];
84
85 if (cpu && cpu->logical_id == logical_id)
86 return cpu;
87 }
88
89 return NULL;
90 }