Merge tag 'trace-printf-v6.13' of git://git.kernel.org/pub/scm/linux/kernel/git/trace...
[drm/drm-misc.git] / tools / lib / perf / threadmap.c
blob07968f3ea0931ceb0a4358f14a75f416e55db484
1 // SPDX-License-Identifier: GPL-2.0
2 #include <perf/threadmap.h>
3 #include <stdlib.h>
4 #include <linux/refcount.h>
5 #include <internal/threadmap.h>
6 #include <string.h>
7 #include <asm/bug.h>
8 #include <stdio.h>
10 static void perf_thread_map__reset(struct perf_thread_map *map, int start, int nr)
12 size_t size = (nr - start) * sizeof(map->map[0]);
14 memset(&map->map[start], 0, size);
15 map->err_thread = -1;
18 struct perf_thread_map *perf_thread_map__realloc(struct perf_thread_map *map, int nr)
20 size_t size = sizeof(*map) + sizeof(map->map[0]) * nr;
21 int start = map ? map->nr : 0;
23 map = realloc(map, size);
25 * We only realloc to add more items, let's reset new items.
27 if (map)
28 perf_thread_map__reset(map, start, nr);
30 return map;
33 #define thread_map__alloc(__nr) perf_thread_map__realloc(NULL, __nr)
35 void perf_thread_map__set_pid(struct perf_thread_map *map, int idx, pid_t pid)
37 map->map[idx].pid = pid;
40 char *perf_thread_map__comm(struct perf_thread_map *map, int idx)
42 return map->map[idx].comm;
45 struct perf_thread_map *perf_thread_map__new_array(int nr_threads, pid_t *array)
47 struct perf_thread_map *threads = thread_map__alloc(nr_threads);
48 int i;
50 if (!threads)
51 return NULL;
53 for (i = 0; i < nr_threads; i++)
54 perf_thread_map__set_pid(threads, i, array ? array[i] : -1);
56 threads->nr = nr_threads;
57 refcount_set(&threads->refcnt, 1);
59 return threads;
62 struct perf_thread_map *perf_thread_map__new_dummy(void)
64 return perf_thread_map__new_array(1, NULL);
67 static void perf_thread_map__delete(struct perf_thread_map *threads)
69 if (threads) {
70 int i;
72 WARN_ONCE(refcount_read(&threads->refcnt) != 0,
73 "thread map refcnt unbalanced\n");
74 for (i = 0; i < threads->nr; i++)
75 free(perf_thread_map__comm(threads, i));
76 free(threads);
80 struct perf_thread_map *perf_thread_map__get(struct perf_thread_map *map)
82 if (map)
83 refcount_inc(&map->refcnt);
84 return map;
87 void perf_thread_map__put(struct perf_thread_map *map)
89 if (map && refcount_dec_and_test(&map->refcnt))
90 perf_thread_map__delete(map);
93 int perf_thread_map__nr(struct perf_thread_map *threads)
95 return threads ? threads->nr : 1;
98 pid_t perf_thread_map__pid(struct perf_thread_map *map, int idx)
100 return map->map[idx].pid;