threadmap.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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>
  9. static void perf_thread_map__reset(struct perf_thread_map *map, int start, int nr)
  10. {
  11. size_t size = (nr - start) * sizeof(map->map[0]);
  12. memset(&map->map[start], 0, size);
  13. map->err_thread = -1;
  14. }
  15. struct perf_thread_map *perf_thread_map__realloc(struct perf_thread_map *map, int nr)
  16. {
  17. size_t size = sizeof(*map) + sizeof(map->map[0]) * nr;
  18. int start = map ? map->nr : 0;
  19. map = realloc(map, size);
  20. /*
  21. * We only realloc to add more items, let's reset new items.
  22. */
  23. if (map)
  24. perf_thread_map__reset(map, start, nr);
  25. return map;
  26. }
  27. #define thread_map__alloc(__nr) perf_thread_map__realloc(NULL, __nr)
  28. void perf_thread_map__set_pid(struct perf_thread_map *map, int idx, pid_t pid)
  29. {
  30. map->map[idx].pid = pid;
  31. }
  32. char *perf_thread_map__comm(struct perf_thread_map *map, int idx)
  33. {
  34. return map->map[idx].comm;
  35. }
  36. struct perf_thread_map *perf_thread_map__new_array(int nr_threads, pid_t *array)
  37. {
  38. struct perf_thread_map *threads = thread_map__alloc(nr_threads);
  39. int i;
  40. if (!threads)
  41. return NULL;
  42. for (i = 0; i < nr_threads; i++)
  43. perf_thread_map__set_pid(threads, i, array ? array[i] : -1);
  44. threads->nr = nr_threads;
  45. refcount_set(&threads->refcnt, 1);
  46. return threads;
  47. }
  48. struct perf_thread_map *perf_thread_map__new_dummy(void)
  49. {
  50. return perf_thread_map__new_array(1, NULL);
  51. }
  52. static void perf_thread_map__delete(struct perf_thread_map *threads)
  53. {
  54. if (threads) {
  55. int i;
  56. WARN_ONCE(refcount_read(&threads->refcnt) != 0,
  57. "thread map refcnt unbalanced\n");
  58. for (i = 0; i < threads->nr; i++)
  59. free(perf_thread_map__comm(threads, i));
  60. free(threads);
  61. }
  62. }
  63. struct perf_thread_map *perf_thread_map__get(struct perf_thread_map *map)
  64. {
  65. if (map)
  66. refcount_inc(&map->refcnt);
  67. return map;
  68. }
  69. void perf_thread_map__put(struct perf_thread_map *map)
  70. {
  71. if (map && refcount_dec_and_test(&map->refcnt))
  72. perf_thread_map__delete(map);
  73. }
  74. int perf_thread_map__nr(struct perf_thread_map *threads)
  75. {
  76. return threads ? threads->nr : 1;
  77. }
  78. pid_t perf_thread_map__pid(struct perf_thread_map *map, int idx)
  79. {
  80. return map->map[idx].pid;
  81. }