1 // SPDX-License-Identifier: GPL-2.0-only
3 * Copyright (c) 2021, Microsoft Corporation.
6 * Beau Belgrave <beaub@linux.microsoft.com>
9 #include <linux/bitmap.h>
10 #include <linux/cdev.h>
11 #include <linux/hashtable.h>
12 #include <linux/list.h>
14 #include <linux/uio.h>
15 #include <linux/ioctl.h>
16 #include <linux/jhash.h>
17 #include <linux/refcount.h>
18 #include <linux/trace_events.h>
19 #include <linux/tracefs.h>
20 #include <linux/types.h>
21 #include <linux/uaccess.h>
22 /* Reminder to move to uapi when everything works */
23 #ifdef CONFIG_COMPILE_TEST
24 #include <linux/user_events.h>
26 #include <uapi/linux/user_events.h>
29 #include "trace_dynevent.h"
31 #define USER_EVENTS_PREFIX_LEN (sizeof(USER_EVENTS_PREFIX)-1)
33 #define FIELD_DEPTH_TYPE 0
34 #define FIELD_DEPTH_NAME 1
35 #define FIELD_DEPTH_SIZE 2
38 * Limits how many trace_event calls user processes can create:
39 * Must be a power of two of PAGE_SIZE.
41 #define MAX_PAGE_ORDER 0
42 #define MAX_PAGES (1 << MAX_PAGE_ORDER)
43 #define MAX_BYTES (MAX_PAGES * PAGE_SIZE)
44 #define MAX_EVENTS (MAX_BYTES * 8)
46 /* Limit how long of an event name plus args within the subsystem. */
47 #define MAX_EVENT_DESC 512
48 #define EVENT_NAME(user_event) ((user_event)->tracepoint.name)
49 #define MAX_FIELD_ARRAY_SIZE 1024
52 * The MAP_STATUS_* macros are used for taking a index and determining the
53 * appropriate byte and the bit in the byte to set/reset for an event.
55 * The lower 3 bits of the index decide which bit to set.
56 * The remaining upper bits of the index decide which byte to use for the bit.
58 * This is used when an event has a probe attached/removed to reflect live
59 * status of the event wanting tracing or not to user-programs via shared
62 #define MAP_STATUS_BYTE(index) ((index) >> 3)
63 #define MAP_STATUS_MASK(index) BIT((index) & 7)
66 * Internal bits (kernel side only) to keep track of connected probes:
67 * These are used when status is requested in text form about an event. These
68 * bits are compared against an internal byte on the event to determine which
69 * probes to print out to the user.
71 * These do not reflect the mapped bytes between the user and kernel space.
73 #define EVENT_STATUS_FTRACE BIT(0)
74 #define EVENT_STATUS_PERF BIT(1)
75 #define EVENT_STATUS_OTHER BIT(7)
78 * Stores the pages, tables, and locks for a group of events.
79 * Each logical grouping of events has its own group, with a
80 * matching page for status checks within user programs. This
81 * allows for isolation of events to user programs by various
84 struct user_event_group {
86 char *register_page_data;
88 struct hlist_node node;
89 struct mutex reg_mutex;
90 DECLARE_HASHTABLE(register_table, 8);
91 DECLARE_BITMAP(page_bitmap, MAX_EVENTS);
94 /* Group for init_user_ns mapping, top-most group */
95 static struct user_event_group *init_group;
98 * Stores per-event properties, as users register events
99 * within a file a user_event might be created if it does not
100 * already exist. These are globally used and their lifetime
101 * is tied to the refcnt member. These cannot go away until the
102 * refcnt reaches one.
105 struct user_event_group *group;
106 struct tracepoint tracepoint;
107 struct trace_event_call call;
108 struct trace_event_class class;
109 struct dyn_event devent;
110 struct hlist_node node;
111 struct list_head fields;
112 struct list_head validators;
121 * Stores per-file events references, as users register events
122 * within a file this structure is modified and freed via RCU.
123 * The lifetime of this struct is tied to the lifetime of the file.
124 * These are not shared and only accessible by the file that created it.
126 struct user_event_refs {
129 struct user_event *events[];
132 struct user_event_file_info {
133 struct user_event_group *group;
134 struct user_event_refs *refs;
137 #define VALIDATOR_ENSURE_NULL (1 << 0)
138 #define VALIDATOR_REL (1 << 1)
140 struct user_event_validator {
141 struct list_head link;
146 typedef void (*user_event_func_t) (struct user_event *user, struct iov_iter *i,
147 void *tpdata, bool *faulted);
149 static int user_event_parse(struct user_event_group *group, char *name,
150 char *args, char *flags,
151 struct user_event **newuser);
153 static u32 user_event_key(char *name)
155 return jhash(name, strlen(name), 0);
158 static void set_page_reservations(char *pages, bool set)
162 for (page = 0; page < MAX_PAGES; ++page) {
163 void *addr = pages + (PAGE_SIZE * page);
166 SetPageReserved(virt_to_page(addr));
168 ClearPageReserved(virt_to_page(addr));
172 static void user_event_group_destroy(struct user_event_group *group)
174 if (group->register_page_data)
175 set_page_reservations(group->register_page_data, false);
178 __free_pages(group->pages, MAX_PAGE_ORDER);
180 kfree(group->system_name);
184 static char *user_event_group_system_name(struct user_namespace *user_ns)
187 int len = sizeof(USER_EVENTS_SYSTEM) + 1;
189 if (user_ns != &init_user_ns) {
191 * Unexpected at this point:
192 * We only currently support init_user_ns.
193 * When we enable more, this will trigger a failure so log.
195 pr_warn("user_events: Namespace other than init_user_ns!\n");
199 system_name = kmalloc(len, GFP_KERNEL);
204 snprintf(system_name, len, "%s", USER_EVENTS_SYSTEM);
209 static inline struct user_event_group
210 *user_event_group_from_user_ns(struct user_namespace *user_ns)
212 if (user_ns == &init_user_ns)
218 static struct user_event_group *current_user_event_group(void)
220 struct user_namespace *user_ns = current_user_ns();
221 struct user_event_group *group = NULL;
224 group = user_event_group_from_user_ns(user_ns);
229 user_ns = user_ns->parent;
235 static struct user_event_group
236 *user_event_group_create(struct user_namespace *user_ns)
238 struct user_event_group *group;
240 group = kzalloc(sizeof(*group), GFP_KERNEL);
245 group->system_name = user_event_group_system_name(user_ns);
247 if (!group->system_name)
250 group->pages = alloc_pages(GFP_KERNEL | __GFP_ZERO, MAX_PAGE_ORDER);
255 group->register_page_data = page_address(group->pages);
257 set_page_reservations(group->register_page_data, true);
259 /* Zero all bits beside 0 (which is reserved for failures) */
260 bitmap_zero(group->page_bitmap, MAX_EVENTS);
261 set_bit(0, group->page_bitmap);
263 mutex_init(&group->reg_mutex);
264 hash_init(group->register_table);
269 user_event_group_destroy(group);
274 static __always_inline
275 void user_event_register_set(struct user_event *user)
279 user->group->register_page_data[MAP_STATUS_BYTE(i)] |= MAP_STATUS_MASK(i);
282 static __always_inline
283 void user_event_register_clear(struct user_event *user)
287 user->group->register_page_data[MAP_STATUS_BYTE(i)] &= ~MAP_STATUS_MASK(i);
290 static __always_inline __must_check
291 bool user_event_last_ref(struct user_event *user)
293 return refcount_read(&user->refcnt) == 1;
296 static __always_inline __must_check
297 size_t copy_nofault(void *addr, size_t bytes, struct iov_iter *i)
303 ret = copy_from_iter_nocache(addr, bytes, i);
310 static struct list_head *user_event_get_fields(struct trace_event_call *call)
312 struct user_event *user = (struct user_event *)call->data;
314 return &user->fields;
318 * Parses a register command for user_events
319 * Format: event_name[:FLAG1[,FLAG2...]] [field1[;field2...]]
321 * Example event named 'test' with a 20 char 'msg' field with an unsigned int
323 * test char[20] msg;unsigned int id
325 * NOTE: Offsets are from the user data perspective, they are not from the
326 * trace_entry/buffer perspective. We automatically add the common properties
327 * sizes to the offset for the user.
329 * Upon success user_event has its ref count increased by 1.
331 static int user_event_parse_cmd(struct user_event_group *group,
332 char *raw_command, struct user_event **newuser)
334 char *name = raw_command;
335 char *args = strpbrk(name, " ");
341 flags = strpbrk(name, ":");
346 return user_event_parse(group, name, args, flags, newuser);
349 static int user_field_array_size(const char *type)
351 const char *start = strchr(type, '[');
359 if (strscpy(val, start + 1, sizeof(val)) <= 0)
362 bracket = strchr(val, ']');
369 if (kstrtouint(val, 0, &size))
372 if (size > MAX_FIELD_ARRAY_SIZE)
378 static int user_field_size(const char *type)
380 /* long is not allowed from a user, since it's ambigious in size */
381 if (strcmp(type, "s64") == 0)
383 if (strcmp(type, "u64") == 0)
385 if (strcmp(type, "s32") == 0)
387 if (strcmp(type, "u32") == 0)
389 if (strcmp(type, "int") == 0)
391 if (strcmp(type, "unsigned int") == 0)
392 return sizeof(unsigned int);
393 if (strcmp(type, "s16") == 0)
395 if (strcmp(type, "u16") == 0)
397 if (strcmp(type, "short") == 0)
398 return sizeof(short);
399 if (strcmp(type, "unsigned short") == 0)
400 return sizeof(unsigned short);
401 if (strcmp(type, "s8") == 0)
403 if (strcmp(type, "u8") == 0)
405 if (strcmp(type, "char") == 0)
407 if (strcmp(type, "unsigned char") == 0)
408 return sizeof(unsigned char);
409 if (str_has_prefix(type, "char["))
410 return user_field_array_size(type);
411 if (str_has_prefix(type, "unsigned char["))
412 return user_field_array_size(type);
413 if (str_has_prefix(type, "__data_loc "))
415 if (str_has_prefix(type, "__rel_loc "))
418 /* Uknown basic type, error */
422 static void user_event_destroy_validators(struct user_event *user)
424 struct user_event_validator *validator, *next;
425 struct list_head *head = &user->validators;
427 list_for_each_entry_safe(validator, next, head, link) {
428 list_del(&validator->link);
433 static void user_event_destroy_fields(struct user_event *user)
435 struct ftrace_event_field *field, *next;
436 struct list_head *head = &user->fields;
438 list_for_each_entry_safe(field, next, head, link) {
439 list_del(&field->link);
444 static int user_event_add_field(struct user_event *user, const char *type,
445 const char *name, int offset, int size,
446 int is_signed, int filter_type)
448 struct user_event_validator *validator;
449 struct ftrace_event_field *field;
450 int validator_flags = 0;
452 field = kmalloc(sizeof(*field), GFP_KERNEL);
457 if (str_has_prefix(type, "__data_loc "))
460 if (str_has_prefix(type, "__rel_loc ")) {
461 validator_flags |= VALIDATOR_REL;
468 if (strstr(type, "char") != NULL)
469 validator_flags |= VALIDATOR_ENSURE_NULL;
471 validator = kmalloc(sizeof(*validator), GFP_KERNEL);
478 validator->flags = validator_flags;
479 validator->offset = offset;
481 /* Want sequential access when validating */
482 list_add_tail(&validator->link, &user->validators);
487 field->offset = offset;
489 field->is_signed = is_signed;
490 field->filter_type = filter_type;
492 list_add(&field->link, &user->fields);
495 * Min size from user writes that are required, this does not include
496 * the size of trace_entry (common fields).
498 user->min_size = (offset + size) - sizeof(struct trace_entry);
504 * Parses the values of a field within the description
505 * Format: type name [size]
507 static int user_event_parse_field(char *field, struct user_event *user,
510 char *part, *type, *name;
511 u32 depth = 0, saved_offset = *offset;
512 int len, size = -EINVAL;
513 bool is_struct = false;
515 field = skip_spaces(field);
520 /* Handle types that have a space within */
521 len = str_has_prefix(field, "unsigned ");
525 len = str_has_prefix(field, "struct ");
531 len = str_has_prefix(field, "__data_loc unsigned ");
535 len = str_has_prefix(field, "__data_loc ");
539 len = str_has_prefix(field, "__rel_loc unsigned ");
543 len = str_has_prefix(field, "__rel_loc ");
550 field = strpbrk(field + len, " ");
560 while ((part = strsep(&field, " ")) != NULL) {
562 case FIELD_DEPTH_TYPE:
565 case FIELD_DEPTH_NAME:
568 case FIELD_DEPTH_SIZE:
572 if (kstrtou32(part, 10, &size))
580 if (depth < FIELD_DEPTH_SIZE || !name)
583 if (depth == FIELD_DEPTH_SIZE)
584 size = user_field_size(type);
592 *offset = saved_offset + size;
594 return user_event_add_field(user, type, name, saved_offset, size,
595 type[0] != 'u', FILTER_OTHER);
598 static int user_event_parse_fields(struct user_event *user, char *args)
601 u32 offset = sizeof(struct trace_entry);
607 while ((field = strsep(&args, ";")) != NULL) {
608 ret = user_event_parse_field(field, user, &offset);
617 static struct trace_event_fields user_event_fields_array[1];
619 static const char *user_field_format(const char *type)
621 if (strcmp(type, "s64") == 0)
623 if (strcmp(type, "u64") == 0)
625 if (strcmp(type, "s32") == 0)
627 if (strcmp(type, "u32") == 0)
629 if (strcmp(type, "int") == 0)
631 if (strcmp(type, "unsigned int") == 0)
633 if (strcmp(type, "s16") == 0)
635 if (strcmp(type, "u16") == 0)
637 if (strcmp(type, "short") == 0)
639 if (strcmp(type, "unsigned short") == 0)
641 if (strcmp(type, "s8") == 0)
643 if (strcmp(type, "u8") == 0)
645 if (strcmp(type, "char") == 0)
647 if (strcmp(type, "unsigned char") == 0)
649 if (strstr(type, "char[") != NULL)
652 /* Unknown, likely struct, allowed treat as 64-bit */
656 static bool user_field_is_dyn_string(const char *type, const char **str_func)
658 if (str_has_prefix(type, "__data_loc ")) {
659 *str_func = "__get_str";
663 if (str_has_prefix(type, "__rel_loc ")) {
664 *str_func = "__get_rel_str";
670 return strstr(type, "char") != NULL;
673 #define LEN_OR_ZERO (len ? len - pos : 0)
674 static int user_dyn_field_set_string(int argc, const char **argv, int *iout,
675 char *buf, int len, bool *colon)
677 int pos = 0, i = *iout;
681 for (; i < argc; ++i) {
683 pos += snprintf(buf + pos, LEN_OR_ZERO, " ");
685 pos += snprintf(buf + pos, LEN_OR_ZERO, "%s", argv[i]);
687 if (strchr(argv[i], ';')) {
694 /* Actual set, advance i */
701 static int user_field_set_string(struct ftrace_event_field *field,
702 char *buf, int len, bool colon)
706 pos += snprintf(buf + pos, LEN_OR_ZERO, "%s", field->type);
707 pos += snprintf(buf + pos, LEN_OR_ZERO, " ");
708 pos += snprintf(buf + pos, LEN_OR_ZERO, "%s", field->name);
711 pos += snprintf(buf + pos, LEN_OR_ZERO, ";");
716 static int user_event_set_print_fmt(struct user_event *user, char *buf, int len)
718 struct ftrace_event_field *field, *next;
719 struct list_head *head = &user->fields;
720 int pos = 0, depth = 0;
721 const char *str_func;
723 pos += snprintf(buf + pos, LEN_OR_ZERO, "\"");
725 list_for_each_entry_safe_reverse(field, next, head, link) {
727 pos += snprintf(buf + pos, LEN_OR_ZERO, " ");
729 pos += snprintf(buf + pos, LEN_OR_ZERO, "%s=%s",
730 field->name, user_field_format(field->type));
735 pos += snprintf(buf + pos, LEN_OR_ZERO, "\"");
737 list_for_each_entry_safe_reverse(field, next, head, link) {
738 if (user_field_is_dyn_string(field->type, &str_func))
739 pos += snprintf(buf + pos, LEN_OR_ZERO,
740 ", %s(%s)", str_func, field->name);
742 pos += snprintf(buf + pos, LEN_OR_ZERO,
743 ", REC->%s", field->name);
750 static int user_event_create_print_fmt(struct user_event *user)
755 len = user_event_set_print_fmt(user, NULL, 0);
757 print_fmt = kmalloc(len, GFP_KERNEL);
762 user_event_set_print_fmt(user, print_fmt, len);
764 user->call.print_fmt = print_fmt;
769 static enum print_line_t user_event_print_trace(struct trace_iterator *iter,
771 struct trace_event *event)
773 /* Unsafe to try to decode user provided print_fmt, use hex */
774 trace_print_hex_dump_seq(&iter->seq, "", DUMP_PREFIX_OFFSET, 16,
775 1, iter->ent, iter->ent_size, true);
777 return trace_handle_return(&iter->seq);
780 static struct trace_event_functions user_event_funcs = {
781 .trace = user_event_print_trace,
784 static int user_event_set_call_visible(struct user_event *user, bool visible)
787 const struct cred *old_cred;
790 cred = prepare_creds();
796 * While by default tracefs is locked down, systems can be configured
797 * to allow user_event files to be less locked down. The extreme case
798 * being "other" has read/write access to user_events_data/status.
800 * When not locked down, processes may not have permissions to
801 * add/remove calls themselves to tracefs. We need to temporarily
802 * switch to root file permission to allow for this scenario.
804 cred->fsuid = GLOBAL_ROOT_UID;
806 old_cred = override_creds(cred);
809 ret = trace_add_event_call(&user->call);
811 ret = trace_remove_event_call(&user->call);
813 revert_creds(old_cred);
819 static int destroy_user_event(struct user_event *user)
823 /* Must destroy fields before call removal */
824 user_event_destroy_fields(user);
826 ret = user_event_set_call_visible(user, false);
831 dyn_event_remove(&user->devent);
833 user_event_register_clear(user);
834 clear_bit(user->index, user->group->page_bitmap);
835 hash_del(&user->node);
837 user_event_destroy_validators(user);
838 kfree(user->call.print_fmt);
839 kfree(EVENT_NAME(user));
845 static struct user_event *find_user_event(struct user_event_group *group,
846 char *name, u32 *outkey)
848 struct user_event *user;
849 u32 key = user_event_key(name);
853 hash_for_each_possible(group->register_table, user, node, key)
854 if (!strcmp(EVENT_NAME(user), name)) {
855 refcount_inc(&user->refcnt);
862 static int user_event_validate(struct user_event *user, void *data, int len)
864 struct list_head *head = &user->validators;
865 struct user_event_validator *validator;
866 void *pos, *end = data + len;
867 u32 loc, offset, size;
869 list_for_each_entry(validator, head, link) {
870 pos = data + validator->offset;
872 /* Already done min_size check, no bounds check here */
874 offset = loc & 0xffff;
877 if (likely(validator->flags & VALIDATOR_REL))
878 pos += offset + sizeof(loc);
884 if (unlikely(pos > end))
887 if (likely(validator->flags & VALIDATOR_ENSURE_NULL))
888 if (unlikely(*(char *)(pos - 1) != '\0'))
896 * Writes the user supplied payload out to a trace file.
898 static void user_event_ftrace(struct user_event *user, struct iov_iter *i,
899 void *tpdata, bool *faulted)
901 struct trace_event_file *file;
902 struct trace_entry *entry;
903 struct trace_event_buffer event_buffer;
904 size_t size = sizeof(*entry) + i->count;
906 file = (struct trace_event_file *)tpdata;
909 !(file->flags & EVENT_FILE_FL_ENABLED) ||
910 trace_trigger_soft_disabled(file))
913 /* Allocates and fills trace_entry, + 1 of this is data payload */
914 entry = trace_event_buffer_reserve(&event_buffer, file, size);
916 if (unlikely(!entry))
919 if (unlikely(!copy_nofault(entry + 1, i->count, i)))
922 if (!list_empty(&user->validators) &&
923 unlikely(user_event_validate(user, entry, size)))
926 trace_event_buffer_commit(&event_buffer);
931 __trace_event_discard_commit(event_buffer.buffer,
935 #ifdef CONFIG_PERF_EVENTS
937 * Writes the user supplied payload out to perf ring buffer.
939 static void user_event_perf(struct user_event *user, struct iov_iter *i,
940 void *tpdata, bool *faulted)
942 struct hlist_head *perf_head;
944 perf_head = this_cpu_ptr(user->call.perf_events);
946 if (perf_head && !hlist_empty(perf_head)) {
947 struct trace_entry *perf_entry;
948 struct pt_regs *regs;
949 size_t size = sizeof(*perf_entry) + i->count;
952 perf_entry = perf_trace_buf_alloc(ALIGN(size, 8),
955 if (unlikely(!perf_entry))
958 perf_fetch_caller_regs(regs);
960 if (unlikely(!copy_nofault(perf_entry + 1, i->count, i)))
963 if (!list_empty(&user->validators) &&
964 unlikely(user_event_validate(user, perf_entry, size)))
967 perf_trace_buf_submit(perf_entry, size, context,
968 user->call.event.type, 1, regs,
974 perf_swevent_put_recursion_context(context);
980 * Update the register page that is shared between user processes.
982 static void update_reg_page_for(struct user_event *user)
984 struct tracepoint *tp = &user->tracepoint;
987 if (atomic_read(&tp->key.enabled) > 0) {
988 struct tracepoint_func *probe_func_ptr;
989 user_event_func_t probe_func;
991 rcu_read_lock_sched();
993 probe_func_ptr = rcu_dereference_sched(tp->funcs);
995 if (probe_func_ptr) {
997 probe_func = probe_func_ptr->func;
999 if (probe_func == user_event_ftrace)
1000 status |= EVENT_STATUS_FTRACE;
1001 #ifdef CONFIG_PERF_EVENTS
1002 else if (probe_func == user_event_perf)
1003 status |= EVENT_STATUS_PERF;
1006 status |= EVENT_STATUS_OTHER;
1007 } while ((++probe_func_ptr)->func);
1010 rcu_read_unlock_sched();
1014 user_event_register_set(user);
1016 user_event_register_clear(user);
1018 user->status = status;
1022 * Register callback for our events from tracing sub-systems.
1024 static int user_event_reg(struct trace_event_call *call,
1025 enum trace_reg type,
1028 struct user_event *user = (struct user_event *)call->data;
1035 case TRACE_REG_REGISTER:
1036 ret = tracepoint_probe_register(call->tp,
1043 case TRACE_REG_UNREGISTER:
1044 tracepoint_probe_unregister(call->tp,
1049 #ifdef CONFIG_PERF_EVENTS
1050 case TRACE_REG_PERF_REGISTER:
1051 ret = tracepoint_probe_register(call->tp,
1052 call->class->perf_probe,
1058 case TRACE_REG_PERF_UNREGISTER:
1059 tracepoint_probe_unregister(call->tp,
1060 call->class->perf_probe,
1064 case TRACE_REG_PERF_OPEN:
1065 case TRACE_REG_PERF_CLOSE:
1066 case TRACE_REG_PERF_ADD:
1067 case TRACE_REG_PERF_DEL:
1074 refcount_inc(&user->refcnt);
1075 update_reg_page_for(user);
1078 update_reg_page_for(user);
1079 refcount_dec(&user->refcnt);
1083 static int user_event_create(const char *raw_command)
1085 struct user_event_group *group;
1086 struct user_event *user;
1090 if (!str_has_prefix(raw_command, USER_EVENTS_PREFIX))
1093 raw_command += USER_EVENTS_PREFIX_LEN;
1094 raw_command = skip_spaces(raw_command);
1096 name = kstrdup(raw_command, GFP_KERNEL);
1101 group = current_user_event_group();
1106 mutex_lock(&group->reg_mutex);
1108 ret = user_event_parse_cmd(group, name, &user);
1111 refcount_dec(&user->refcnt);
1113 mutex_unlock(&group->reg_mutex);
1121 static int user_event_show(struct seq_file *m, struct dyn_event *ev)
1123 struct user_event *user = container_of(ev, struct user_event, devent);
1124 struct ftrace_event_field *field, *next;
1125 struct list_head *head;
1128 seq_printf(m, "%s%s", USER_EVENTS_PREFIX, EVENT_NAME(user));
1130 head = trace_get_fields(&user->call);
1132 list_for_each_entry_safe_reverse(field, next, head, link) {
1138 seq_printf(m, "%s %s", field->type, field->name);
1140 if (str_has_prefix(field->type, "struct "))
1141 seq_printf(m, " %d", field->size);
1151 static bool user_event_is_busy(struct dyn_event *ev)
1153 struct user_event *user = container_of(ev, struct user_event, devent);
1155 return !user_event_last_ref(user);
1158 static int user_event_free(struct dyn_event *ev)
1160 struct user_event *user = container_of(ev, struct user_event, devent);
1162 if (!user_event_last_ref(user))
1165 return destroy_user_event(user);
1168 static bool user_field_match(struct ftrace_event_field *field, int argc,
1169 const char **argv, int *iout)
1171 char *field_name = NULL, *dyn_field_name = NULL;
1172 bool colon = false, match = false;
1178 dyn_len = user_dyn_field_set_string(argc, argv, iout, dyn_field_name,
1181 len = user_field_set_string(field, field_name, 0, colon);
1186 dyn_field_name = kmalloc(dyn_len, GFP_KERNEL);
1187 field_name = kmalloc(len, GFP_KERNEL);
1189 if (!dyn_field_name || !field_name)
1192 user_dyn_field_set_string(argc, argv, iout, dyn_field_name,
1195 user_field_set_string(field, field_name, len, colon);
1197 match = strcmp(dyn_field_name, field_name) == 0;
1199 kfree(dyn_field_name);
1205 static bool user_fields_match(struct user_event *user, int argc,
1208 struct ftrace_event_field *field, *next;
1209 struct list_head *head = &user->fields;
1212 list_for_each_entry_safe_reverse(field, next, head, link)
1213 if (!user_field_match(field, argc, argv, &i))
1222 static bool user_event_match(const char *system, const char *event,
1223 int argc, const char **argv, struct dyn_event *ev)
1225 struct user_event *user = container_of(ev, struct user_event, devent);
1228 match = strcmp(EVENT_NAME(user), event) == 0 &&
1229 (!system || strcmp(system, USER_EVENTS_SYSTEM) == 0);
1231 if (match && argc > 0)
1232 match = user_fields_match(user, argc, argv);
1237 static struct dyn_event_operations user_event_dops = {
1238 .create = user_event_create,
1239 .show = user_event_show,
1240 .is_busy = user_event_is_busy,
1241 .free = user_event_free,
1242 .match = user_event_match,
1245 static int user_event_trace_register(struct user_event *user)
1249 ret = register_trace_event(&user->call.event);
1254 ret = user_event_set_call_visible(user, true);
1257 unregister_trace_event(&user->call.event);
1263 * Parses the event name, arguments and flags then registers if successful.
1264 * The name buffer lifetime is owned by this method for success cases only.
1265 * Upon success the returned user_event has its ref count increased by 1.
1267 static int user_event_parse(struct user_event_group *group, char *name,
1268 char *args, char *flags,
1269 struct user_event **newuser)
1274 struct user_event *user;
1276 /* Prevent dyn_event from racing */
1277 mutex_lock(&event_mutex);
1278 user = find_user_event(group, name, &key);
1279 mutex_unlock(&event_mutex);
1284 * Name is allocated by caller, free it since it already exists.
1285 * Caller only worries about failure cases for freeing.
1291 index = find_first_zero_bit(group->page_bitmap, MAX_EVENTS);
1293 if (index == MAX_EVENTS)
1296 user = kzalloc(sizeof(*user), GFP_KERNEL);
1301 INIT_LIST_HEAD(&user->class.fields);
1302 INIT_LIST_HEAD(&user->fields);
1303 INIT_LIST_HEAD(&user->validators);
1305 user->group = group;
1306 user->tracepoint.name = name;
1308 ret = user_event_parse_fields(user, args);
1313 ret = user_event_create_print_fmt(user);
1318 user->call.data = user;
1319 user->call.class = &user->class;
1320 user->call.name = name;
1321 user->call.flags = TRACE_EVENT_FL_TRACEPOINT;
1322 user->call.tp = &user->tracepoint;
1323 user->call.event.funcs = &user_event_funcs;
1324 user->class.system = group->system_name;
1326 user->class.fields_array = user_event_fields_array;
1327 user->class.get_fields = user_event_get_fields;
1328 user->class.reg = user_event_reg;
1329 user->class.probe = user_event_ftrace;
1330 #ifdef CONFIG_PERF_EVENTS
1331 user->class.perf_probe = user_event_perf;
1334 mutex_lock(&event_mutex);
1336 ret = user_event_trace_register(user);
1341 user->index = index;
1343 /* Ensure we track self ref and caller ref (2) */
1344 refcount_set(&user->refcnt, 2);
1346 dyn_event_init(&user->devent, &user_event_dops);
1347 dyn_event_add(&user->devent, &user->call);
1348 set_bit(user->index, group->page_bitmap);
1349 hash_add(group->register_table, &user->node, key);
1351 mutex_unlock(&event_mutex);
1356 mutex_unlock(&event_mutex);
1358 user_event_destroy_fields(user);
1359 user_event_destroy_validators(user);
1365 * Deletes a previously created event if it is no longer being used.
1367 static int delete_user_event(struct user_event_group *group, char *name)
1370 struct user_event *user = find_user_event(group, name, &key);
1375 refcount_dec(&user->refcnt);
1377 if (!user_event_last_ref(user))
1380 return destroy_user_event(user);
1384 * Validates the user payload and writes via iterator.
1386 static ssize_t user_events_write_core(struct file *file, struct iov_iter *i)
1388 struct user_event_file_info *info = file->private_data;
1389 struct user_event_refs *refs;
1390 struct user_event *user = NULL;
1391 struct tracepoint *tp;
1392 ssize_t ret = i->count;
1395 if (unlikely(copy_from_iter(&idx, sizeof(idx), i) != sizeof(idx)))
1398 rcu_read_lock_sched();
1400 refs = rcu_dereference_sched(info->refs);
1403 * The refs->events array is protected by RCU, and new items may be
1404 * added. But the user retrieved from indexing into the events array
1405 * shall be immutable while the file is opened.
1407 if (likely(refs && idx < refs->count))
1408 user = refs->events[idx];
1410 rcu_read_unlock_sched();
1412 if (unlikely(user == NULL))
1415 if (unlikely(i->count < user->min_size))
1418 tp = &user->tracepoint;
1421 * It's possible key.enabled disables after this check, however
1422 * we don't mind if a few events are included in this condition.
1424 if (likely(atomic_read(&tp->key.enabled) > 0)) {
1425 struct tracepoint_func *probe_func_ptr;
1426 user_event_func_t probe_func;
1427 struct iov_iter copy;
1431 if (unlikely(fault_in_iov_iter_readable(i, i->count)))
1436 rcu_read_lock_sched();
1438 probe_func_ptr = rcu_dereference_sched(tp->funcs);
1440 if (probe_func_ptr) {
1443 probe_func = probe_func_ptr->func;
1444 tpdata = probe_func_ptr->data;
1445 probe_func(user, ©, tpdata, &faulted);
1446 } while ((++probe_func_ptr)->func);
1449 rcu_read_unlock_sched();
1451 if (unlikely(faulted))
1458 static int user_events_open(struct inode *node, struct file *file)
1460 struct user_event_group *group;
1461 struct user_event_file_info *info;
1463 group = current_user_event_group();
1468 info = kzalloc(sizeof(*info), GFP_KERNEL);
1473 info->group = group;
1475 file->private_data = info;
1480 static ssize_t user_events_write(struct file *file, const char __user *ubuf,
1481 size_t count, loff_t *ppos)
1486 if (unlikely(*ppos != 0))
1489 if (unlikely(import_single_range(WRITE, (char __user *)ubuf,
1493 return user_events_write_core(file, &i);
1496 static ssize_t user_events_write_iter(struct kiocb *kp, struct iov_iter *i)
1498 return user_events_write_core(kp->ki_filp, i);
1501 static int user_events_ref_add(struct user_event_file_info *info,
1502 struct user_event *user)
1504 struct user_event_group *group = info->group;
1505 struct user_event_refs *refs, *new_refs;
1506 int i, size, count = 0;
1508 refs = rcu_dereference_protected(info->refs,
1509 lockdep_is_held(&group->reg_mutex));
1512 count = refs->count;
1514 for (i = 0; i < count; ++i)
1515 if (refs->events[i] == user)
1519 size = struct_size(refs, events, count + 1);
1521 new_refs = kzalloc(size, GFP_KERNEL);
1526 new_refs->count = count + 1;
1528 for (i = 0; i < count; ++i)
1529 new_refs->events[i] = refs->events[i];
1531 new_refs->events[i] = user;
1533 refcount_inc(&user->refcnt);
1535 rcu_assign_pointer(info->refs, new_refs);
1538 kfree_rcu(refs, rcu);
1543 static long user_reg_get(struct user_reg __user *ureg, struct user_reg *kreg)
1548 ret = get_user(size, &ureg->size);
1553 if (size > PAGE_SIZE)
1556 if (size < offsetofend(struct user_reg, write_index))
1559 ret = copy_struct_from_user(kreg, sizeof(*kreg), ureg, size);
1570 * Registers a user_event on behalf of a user process.
1572 static long user_events_ioctl_reg(struct user_event_file_info *info,
1575 struct user_reg __user *ureg = (struct user_reg __user *)uarg;
1576 struct user_reg reg;
1577 struct user_event *user;
1581 ret = user_reg_get(ureg, ®);
1586 name = strndup_user((const char __user *)(uintptr_t)reg.name_args,
1590 ret = PTR_ERR(name);
1594 ret = user_event_parse_cmd(info->group, name, &user);
1601 ret = user_events_ref_add(info, user);
1603 /* No longer need parse ref, ref_add either worked or not */
1604 refcount_dec(&user->refcnt);
1606 /* Positive number is index and valid */
1610 put_user((u32)ret, &ureg->write_index);
1611 put_user(user->index, &ureg->status_bit);
1617 * Deletes a user_event on behalf of a user process.
1619 static long user_events_ioctl_del(struct user_event_file_info *info,
1622 void __user *ubuf = (void __user *)uarg;
1626 name = strndup_user(ubuf, MAX_EVENT_DESC);
1629 return PTR_ERR(name);
1631 /* event_mutex prevents dyn_event from racing */
1632 mutex_lock(&event_mutex);
1633 ret = delete_user_event(info->group, name);
1634 mutex_unlock(&event_mutex);
1642 * Handles the ioctl from user mode to register or alter operations.
1644 static long user_events_ioctl(struct file *file, unsigned int cmd,
1647 struct user_event_file_info *info = file->private_data;
1648 struct user_event_group *group = info->group;
1653 mutex_lock(&group->reg_mutex);
1654 ret = user_events_ioctl_reg(info, uarg);
1655 mutex_unlock(&group->reg_mutex);
1659 mutex_lock(&group->reg_mutex);
1660 ret = user_events_ioctl_del(info, uarg);
1661 mutex_unlock(&group->reg_mutex);
1669 * Handles the final close of the file from user mode.
1671 static int user_events_release(struct inode *node, struct file *file)
1673 struct user_event_file_info *info = file->private_data;
1674 struct user_event_group *group;
1675 struct user_event_refs *refs;
1676 struct user_event *user;
1682 group = info->group;
1685 * Ensure refs cannot change under any situation by taking the
1686 * register mutex during the final freeing of the references.
1688 mutex_lock(&group->reg_mutex);
1696 * The lifetime of refs has reached an end, it's tied to this file.
1697 * The underlying user_events are ref counted, and cannot be freed.
1698 * After this decrement, the user_events may be freed elsewhere.
1700 for (i = 0; i < refs->count; ++i) {
1701 user = refs->events[i];
1704 refcount_dec(&user->refcnt);
1707 file->private_data = NULL;
1709 mutex_unlock(&group->reg_mutex);
1717 static const struct file_operations user_data_fops = {
1718 .open = user_events_open,
1719 .write = user_events_write,
1720 .write_iter = user_events_write_iter,
1721 .unlocked_ioctl = user_events_ioctl,
1722 .release = user_events_release,
1725 static struct user_event_group *user_status_group(struct file *file)
1727 struct seq_file *m = file->private_data;
1736 * Maps the shared page into the user process for checking if event is enabled.
1738 static int user_status_mmap(struct file *file, struct vm_area_struct *vma)
1741 struct user_event_group *group = user_status_group(file);
1742 unsigned long size = vma->vm_end - vma->vm_start;
1744 if (size != MAX_BYTES)
1750 pages = group->register_page_data;
1752 return remap_pfn_range(vma, vma->vm_start,
1753 virt_to_phys(pages) >> PAGE_SHIFT,
1754 size, vm_get_page_prot(VM_READ));
1757 static void *user_seq_start(struct seq_file *m, loff_t *pos)
1765 static void *user_seq_next(struct seq_file *m, void *p, loff_t *pos)
1771 static void user_seq_stop(struct seq_file *m, void *p)
1775 static int user_seq_show(struct seq_file *m, void *p)
1777 struct user_event_group *group = m->private;
1778 struct user_event *user;
1780 int i, active = 0, busy = 0, flags;
1785 mutex_lock(&group->reg_mutex);
1787 hash_for_each(group->register_table, i, user, node) {
1788 status = user->status;
1789 flags = user->flags;
1791 seq_printf(m, "%d:%s", user->index, EVENT_NAME(user));
1793 if (flags != 0 || status != 0)
1797 seq_puts(m, " Used by");
1798 if (status & EVENT_STATUS_FTRACE)
1799 seq_puts(m, " ftrace");
1800 if (status & EVENT_STATUS_PERF)
1801 seq_puts(m, " perf");
1802 if (status & EVENT_STATUS_OTHER)
1803 seq_puts(m, " other");
1811 mutex_unlock(&group->reg_mutex);
1814 seq_printf(m, "Active: %d\n", active);
1815 seq_printf(m, "Busy: %d\n", busy);
1816 seq_printf(m, "Max: %ld\n", MAX_EVENTS);
1821 static const struct seq_operations user_seq_ops = {
1822 .start = user_seq_start,
1823 .next = user_seq_next,
1824 .stop = user_seq_stop,
1825 .show = user_seq_show,
1828 static int user_status_open(struct inode *node, struct file *file)
1830 struct user_event_group *group;
1833 group = current_user_event_group();
1838 ret = seq_open(file, &user_seq_ops);
1841 /* Chain group to seq_file */
1842 struct seq_file *m = file->private_data;
1850 static const struct file_operations user_status_fops = {
1851 .open = user_status_open,
1852 .mmap = user_status_mmap,
1854 .llseek = seq_lseek,
1855 .release = seq_release,
1859 * Creates a set of tracefs files to allow user mode interactions.
1861 static int create_user_tracefs(void)
1863 struct dentry *edata, *emmap;
1865 edata = tracefs_create_file("user_events_data", TRACE_MODE_WRITE,
1866 NULL, NULL, &user_data_fops);
1869 pr_warn("Could not create tracefs 'user_events_data' entry\n");
1873 /* mmap with MAP_SHARED requires writable fd */
1874 emmap = tracefs_create_file("user_events_status", TRACE_MODE_WRITE,
1875 NULL, NULL, &user_status_fops);
1878 tracefs_remove(edata);
1879 pr_warn("Could not create tracefs 'user_events_mmap' entry\n");
1888 static int __init trace_events_user_init(void)
1892 init_group = user_event_group_create(&init_user_ns);
1897 ret = create_user_tracefs();
1900 pr_warn("user_events could not register with tracefs\n");
1901 user_event_group_destroy(init_group);
1906 if (dyn_event_register(&user_event_dops))
1907 pr_warn("user_events could not register with dyn_events\n");
1912 fs_initcall(trace_events_user_init);