]> git.ipfire.org Git - thirdparty/util-linux.git/blob - sys-utils/lscpu-cpu.c
sys-utils: cleanup license lines, add SPDX
[thirdparty/util-linux.git] / sys-utils / lscpu-cpu.c
1 /*
2 * SPDX-License-Identifier: GPL-2.0-or-later
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * Copyright (C) 2020 Karel Zak <kzak@redhat.com>
10 */
11 #include "lscpu.h"
12
13 struct lscpu_cpu *lscpu_new_cpu(int id)
14 {
15 struct lscpu_cpu *cpu;
16
17 cpu = xcalloc(1, sizeof(struct lscpu_cpu));
18 cpu->refcount = 1;
19 cpu->logical_id = id;
20 cpu->coreid = -1;
21 cpu->socketid = -1;
22 cpu->bookid = -1;
23 cpu->bookid = -1;
24 cpu->address = -1;
25 cpu->configured = -1;
26
27 DBG(CPU, ul_debugobj(cpu, "alloc"));
28 return cpu;
29 }
30
31 void lscpu_ref_cpu(struct lscpu_cpu *cpu)
32 {
33 if (cpu)
34 cpu->refcount++;
35 }
36
37 void lscpu_unref_cpu(struct lscpu_cpu *cpu)
38 {
39 if (!cpu)
40 return;
41
42 if (--cpu->refcount <= 0) {
43 DBG(CPU, ul_debugobj(cpu, " freeing #%d", cpu->logical_id));
44 lscpu_unref_cputype(cpu->type);
45 cpu->type = NULL;
46 free(cpu->dynamic_mhz);
47 free(cpu->static_mhz);
48 free(cpu->mhz);
49 free(cpu->bogomips);
50 free(cpu);
51 }
52 }
53
54 /*
55 * Create and initialize array with CPU structs according to @cpuset.
56 */
57 int lscpu_create_cpus(struct lscpu_cxt *cxt, cpu_set_t *cpuset, size_t setsize)
58 {
59 size_t n, i;
60
61 assert(!cxt->cpus);
62
63 cxt->npossibles = CPU_COUNT_S(setsize, cpuset);
64 cxt->cpus = xcalloc(1, cxt->npossibles * sizeof(struct lscpu_cpu *));
65
66 for (n = 0, i = 0; n < (size_t) cxt->maxcpus && i < cxt->npossibles; n++) {
67 if (CPU_ISSET_S(n, setsize, cpuset))
68 cxt->cpus[i++] = lscpu_new_cpu(n);
69 }
70
71 return 0;
72 }
73
74 int lscpu_cpu_set_type(struct lscpu_cpu *cpu, struct lscpu_cputype *type)
75 {
76 if (cpu->type == type)
77 return 0;
78
79 lscpu_unref_cputype(cpu->type);
80 cpu->type = type;
81 lscpu_ref_cputype(type);
82
83 DBG(CPU, ul_debugobj(cpu, "cputype set to %s", type ? type->vendor : NULL));
84 return 0;
85 }
86
87 /* don't forget lscpu_ref_cpu() ! */
88 struct lscpu_cpu *lscpu_get_cpu(struct lscpu_cxt *cxt, int logical_id)
89 {
90 size_t i;
91
92 for (i = 0; i < cxt->npossibles; i++) {
93 struct lscpu_cpu *cpu = cxt->cpus[i];
94
95 if (cpu && cpu->logical_id == logical_id)
96 return cpu;
97 }
98
99 return NULL;
100 }