]> git.ipfire.org Git - thirdparty/util-linux.git/blame - sys-utils/lscpu-cpu.c
sys-utils: cleanup license lines, add SPDX
[thirdparty/util-linux.git] / sys-utils / lscpu-cpu.c
CommitLineData
9abd5e4b
KZ
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 */
095be2c2 11#include "lscpu.h"
855bab2a 12
801b125f 13struct lscpu_cpu *lscpu_new_cpu(int id)
855bab2a
KZ
14{
15 struct lscpu_cpu *cpu;
16
17 cpu = xcalloc(1, sizeof(struct lscpu_cpu));
18 cpu->refcount = 1;
801b125f 19 cpu->logical_id = id;
63c5e7f8
KZ
20 cpu->coreid = -1;
21 cpu->socketid = -1;
22 cpu->bookid = -1;
23 cpu->bookid = -1;
24 cpu->address = -1;
25 cpu->configured = -1;
855bab2a
KZ
26
27 DBG(CPU, ul_debugobj(cpu, "alloc"));
28 return cpu;
29}
30
31void lscpu_ref_cpu(struct lscpu_cpu *cpu)
32{
33 if (cpu)
34 cpu->refcount++;
35}
36
37void lscpu_unref_cpu(struct lscpu_cpu *cpu)
38{
39 if (!cpu)
40 return;
41
42 if (--cpu->refcount <= 0) {
f5d13532 43 DBG(CPU, ul_debugobj(cpu, " freeing #%d", cpu->logical_id));
855bab2a 44 lscpu_unref_cputype(cpu->type);
ee0fabda 45 cpu->type = NULL;
617d8fbe
KZ
46 free(cpu->dynamic_mhz);
47 free(cpu->static_mhz);
48 free(cpu->mhz);
d4cb6a03 49 free(cpu->bogomips);
855bab2a
KZ
50 free(cpu);
51 }
52}
53
801b125f
KZ
54/*
55 * Create and initialize array with CPU structs according to @cpuset.
56 */
57int lscpu_create_cpus(struct lscpu_cxt *cxt, cpu_set_t *cpuset, size_t setsize)
855bab2a 58{
6648a70e 59 size_t n, i;
855bab2a 60
801b125f 61 assert(!cxt->cpus);
855bab2a 62
801b125f
KZ
63 cxt->npossibles = CPU_COUNT_S(setsize, cpuset);
64 cxt->cpus = xcalloc(1, cxt->npossibles * sizeof(struct lscpu_cpu *));
855bab2a 65
6648a70e 66 for (n = 0, i = 0; n < (size_t) cxt->maxcpus && i < cxt->npossibles; n++) {
801b125f 67 if (CPU_ISSET_S(n, setsize, cpuset))
6648a70e 68 cxt->cpus[i++] = lscpu_new_cpu(n);
801b125f
KZ
69 }
70
71 return 0;
72}
73
74int lscpu_cpu_set_type(struct lscpu_cpu *cpu, struct lscpu_cputype *type)
75{
ee0fabda
KZ
76 if (cpu->type == type)
77 return 0;
78
f5d13532 79 lscpu_unref_cputype(cpu->type);
801b125f 80 cpu->type = type;
f5d13532 81 lscpu_ref_cputype(type);
ee0fabda
KZ
82
83 DBG(CPU, ul_debugobj(cpu, "cputype set to %s", type ? type->vendor : NULL));
d234a381
KZ
84 return 0;
85}
801b125f 86
f5d13532 87/* don't forget lscpu_ref_cpu() ! */
801b125f
KZ
88struct 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}