at v4.14-rc8 130 lines 2.3 kB view raw
1// SPDX-License-Identifier: GPL-2.0 2#include "comm.h" 3#include "util.h" 4#include <errno.h> 5#include <stdlib.h> 6#include <stdio.h> 7#include <string.h> 8#include <linux/refcount.h> 9 10struct comm_str { 11 char *str; 12 struct rb_node rb_node; 13 refcount_t refcnt; 14}; 15 16/* Should perhaps be moved to struct machine */ 17static struct rb_root comm_str_root; 18 19static struct comm_str *comm_str__get(struct comm_str *cs) 20{ 21 if (cs) 22 refcount_inc(&cs->refcnt); 23 return cs; 24} 25 26static void comm_str__put(struct comm_str *cs) 27{ 28 if (cs && refcount_dec_and_test(&cs->refcnt)) { 29 rb_erase(&cs->rb_node, &comm_str_root); 30 zfree(&cs->str); 31 free(cs); 32 } 33} 34 35static struct comm_str *comm_str__alloc(const char *str) 36{ 37 struct comm_str *cs; 38 39 cs = zalloc(sizeof(*cs)); 40 if (!cs) 41 return NULL; 42 43 cs->str = strdup(str); 44 if (!cs->str) { 45 free(cs); 46 return NULL; 47 } 48 49 refcount_set(&cs->refcnt, 1); 50 51 return cs; 52} 53 54static struct comm_str *comm_str__findnew(const char *str, struct rb_root *root) 55{ 56 struct rb_node **p = &root->rb_node; 57 struct rb_node *parent = NULL; 58 struct comm_str *iter, *new; 59 int cmp; 60 61 while (*p != NULL) { 62 parent = *p; 63 iter = rb_entry(parent, struct comm_str, rb_node); 64 65 cmp = strcmp(str, iter->str); 66 if (!cmp) 67 return comm_str__get(iter); 68 69 if (cmp < 0) 70 p = &(*p)->rb_left; 71 else 72 p = &(*p)->rb_right; 73 } 74 75 new = comm_str__alloc(str); 76 if (!new) 77 return NULL; 78 79 rb_link_node(&new->rb_node, parent, p); 80 rb_insert_color(&new->rb_node, root); 81 82 return new; 83} 84 85struct comm *comm__new(const char *str, u64 timestamp, bool exec) 86{ 87 struct comm *comm = zalloc(sizeof(*comm)); 88 89 if (!comm) 90 return NULL; 91 92 comm->start = timestamp; 93 comm->exec = exec; 94 95 comm->comm_str = comm_str__findnew(str, &comm_str_root); 96 if (!comm->comm_str) { 97 free(comm); 98 return NULL; 99 } 100 101 return comm; 102} 103 104int comm__override(struct comm *comm, const char *str, u64 timestamp, bool exec) 105{ 106 struct comm_str *new, *old = comm->comm_str; 107 108 new = comm_str__findnew(str, &comm_str_root); 109 if (!new) 110 return -ENOMEM; 111 112 comm_str__put(old); 113 comm->comm_str = new; 114 comm->start = timestamp; 115 if (exec) 116 comm->exec = true; 117 118 return 0; 119} 120 121void comm__free(struct comm *comm) 122{ 123 comm_str__put(comm->comm_str); 124 free(comm); 125} 126 127const char *comm__str(const struct comm *comm) 128{ 129 return comm->comm_str->str; 130}