threadmap.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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 thread, pid_t pid)
  29. {
  30. map->map[thread].pid = pid;
  31. }
  32. char *perf_thread_map__comm(struct perf_thread_map *map, int thread)
  33. {
  34. return map->map[thread].comm;
  35. }
  36. struct perf_thread_map *perf_thread_map__new_dummy(void)
  37. {
  38. struct perf_thread_map *threads = thread_map__alloc(1);
  39. if (threads != NULL) {
  40. perf_thread_map__set_pid(threads, 0, -1);
  41. threads->nr = 1;
  42. refcount_set(&threads->refcnt, 1);
  43. }
  44. return threads;
  45. }
  46. static void perf_thread_map__delete(struct perf_thread_map *threads)
  47. {
  48. if (threads) {
  49. int i;
  50. WARN_ONCE(refcount_read(&threads->refcnt) != 0,
  51. "thread map refcnt unbalanced\n");
  52. for (i = 0; i < threads->nr; i++)
  53. free(perf_thread_map__comm(threads, i));
  54. free(threads);
  55. }
  56. }
  57. struct perf_thread_map *perf_thread_map__get(struct perf_thread_map *map)
  58. {
  59. if (map)
  60. refcount_inc(&map->refcnt);
  61. return map;
  62. }
  63. void perf_thread_map__put(struct perf_thread_map *map)
  64. {
  65. if (map && refcount_dec_and_test(&map->refcnt))
  66. perf_thread_map__delete(map);
  67. }
  68. int perf_thread_map__nr(struct perf_thread_map *threads)
  69. {
  70. return threads ? threads->nr : 1;
  71. }
  72. pid_t perf_thread_map__pid(struct perf_thread_map *map, int thread)
  73. {
  74. return map->map[thread].pid;
  75. }