1 // SPDX-License-Identifier: GPL-2.0
8 #include <linux/refcount.h>
12 struct rb_node rb_node;
16 /* Should perhaps be moved to struct machine */
17 static struct rb_root comm_str_root;
19 static struct comm_str *comm_str__get(struct comm_str *cs)
21 if (cs && refcount_inc_not_zero(&cs->refcnt))
27 static void comm_str__put(struct comm_str *cs)
29 if (cs && refcount_dec_and_test(&cs->refcnt)) {
30 rb_erase(&cs->rb_node, &comm_str_root);
36 static struct comm_str *comm_str__alloc(const char *str)
40 cs = zalloc(sizeof(*cs));
44 cs->str = strdup(str);
50 refcount_set(&cs->refcnt, 1);
55 static struct comm_str *comm_str__findnew(const char *str, struct rb_root *root)
57 struct rb_node **p = &root->rb_node;
58 struct rb_node *parent = NULL;
59 struct comm_str *iter, *new;
64 iter = rb_entry(parent, struct comm_str, rb_node);
67 * If we race with comm_str__put, iter->refcnt is 0
68 * and it will be removed within comm_str__put call
69 * shortly, ignore it in this search.
71 cmp = strcmp(str, iter->str);
72 if (!cmp && comm_str__get(iter))
81 new = comm_str__alloc(str);
85 rb_link_node(&new->rb_node, parent, p);
86 rb_insert_color(&new->rb_node, root);
91 struct comm *comm__new(const char *str, u64 timestamp, bool exec)
93 struct comm *comm = zalloc(sizeof(*comm));
98 comm->start = timestamp;
101 comm->comm_str = comm_str__findnew(str, &comm_str_root);
102 if (!comm->comm_str) {
110 int comm__override(struct comm *comm, const char *str, u64 timestamp, bool exec)
112 struct comm_str *new, *old = comm->comm_str;
114 new = comm_str__findnew(str, &comm_str_root);
119 comm->comm_str = new;
120 comm->start = timestamp;
127 void comm__free(struct comm *comm)
129 comm_str__put(comm->comm_str);
133 const char *comm__str(const struct comm *comm)
135 return comm->comm_str->str;