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 #include <linux/highmem.h>
23 #include <linux/init.h>
24 #include <linux/user_events.h>
25 #include "trace_dynevent.h"
26 #include "trace_output.h"
29 #define USER_EVENTS_PREFIX_LEN (sizeof(USER_EVENTS_PREFIX)-1)
31 #define FIELD_DEPTH_TYPE 0
32 #define FIELD_DEPTH_NAME 1
33 #define FIELD_DEPTH_SIZE 2
35 /* Limit how long of an event name plus args within the subsystem. */
36 #define MAX_EVENT_DESC 512
37 #define EVENT_NAME(user_event) ((user_event)->tracepoint.name)
38 #define MAX_FIELD_ARRAY_SIZE 1024
41 * Internal bits (kernel side only) to keep track of connected probes:
42 * These are used when status is requested in text form about an event. These
43 * bits are compared against an internal byte on the event to determine which
44 * probes to print out to the user.
46 * These do not reflect the mapped bytes between the user and kernel space.
48 #define EVENT_STATUS_FTRACE BIT(0)
49 #define EVENT_STATUS_PERF BIT(1)
50 #define EVENT_STATUS_OTHER BIT(7)
53 * Stores the system name, tables, and locks for a group of events. This
54 * allows isolation for events by various means.
56 struct user_event_group {
58 struct hlist_node node;
59 struct mutex reg_mutex;
60 DECLARE_HASHTABLE(register_table, 8);
63 /* Group for init_user_ns mapping, top-most group */
64 static struct user_event_group *init_group;
66 /* Max allowed events for the whole system */
67 static unsigned int max_user_events = 32768;
69 /* Current number of events on the whole system */
70 static unsigned int current_user_events;
73 * Stores per-event properties, as users register events
74 * within a file a user_event might be created if it does not
75 * already exist. These are globally used and their lifetime
76 * is tied to the refcnt member. These cannot go away until the
80 struct user_event_group *group;
81 struct tracepoint tracepoint;
82 struct trace_event_call call;
83 struct trace_event_class class;
84 struct dyn_event devent;
85 struct hlist_node node;
86 struct list_head fields;
87 struct list_head validators;
94 * Stores per-mm/event properties that enable an address to be
95 * updated properly for each task. As tasks are forked, we use
96 * these to track enablement sites that are tied to an event.
98 struct user_event_enabler {
99 struct list_head link;
100 struct user_event *event;
103 /* Track enable bit, flags, etc. Aligned for bitops. */
107 /* Bits 0-5 are for the bit to update upon enable/disable (0-63 allowed) */
108 #define ENABLE_VAL_BIT_MASK 0x3F
110 /* Bit 6 is for faulting status of enablement */
111 #define ENABLE_VAL_FAULTING_BIT 6
113 /* Bit 7 is for freeing status of enablement */
114 #define ENABLE_VAL_FREEING_BIT 7
116 /* Only duplicate the bit value */
117 #define ENABLE_VAL_DUP_MASK ENABLE_VAL_BIT_MASK
119 #define ENABLE_BITOPS(e) ((unsigned long *)&(e)->values)
121 /* Used for asynchronous faulting in of pages */
122 struct user_event_enabler_fault {
123 struct work_struct work;
124 struct user_event_mm *mm;
125 struct user_event_enabler *enabler;
129 static struct kmem_cache *fault_cache;
131 /* Global list of memory descriptors using user_events */
132 static LIST_HEAD(user_event_mms);
133 static DEFINE_SPINLOCK(user_event_mms_lock);
136 * Stores per-file events references, as users register events
137 * within a file this structure is modified and freed via RCU.
138 * The lifetime of this struct is tied to the lifetime of the file.
139 * These are not shared and only accessible by the file that created it.
141 struct user_event_refs {
144 struct user_event *events[];
147 struct user_event_file_info {
148 struct user_event_group *group;
149 struct user_event_refs *refs;
152 #define VALIDATOR_ENSURE_NULL (1 << 0)
153 #define VALIDATOR_REL (1 << 1)
155 struct user_event_validator {
156 struct list_head link;
161 typedef void (*user_event_func_t) (struct user_event *user, struct iov_iter *i,
162 void *tpdata, bool *faulted);
164 static int user_event_parse(struct user_event_group *group, char *name,
165 char *args, char *flags,
166 struct user_event **newuser);
168 static struct user_event_mm *user_event_mm_get(struct user_event_mm *mm);
169 static struct user_event_mm *user_event_mm_get_all(struct user_event *user);
170 static void user_event_mm_put(struct user_event_mm *mm);
172 static u32 user_event_key(char *name)
174 return jhash(name, strlen(name), 0);
177 static void user_event_group_destroy(struct user_event_group *group)
179 kfree(group->system_name);
183 static char *user_event_group_system_name(struct user_namespace *user_ns)
186 int len = sizeof(USER_EVENTS_SYSTEM) + 1;
188 if (user_ns != &init_user_ns) {
190 * Unexpected at this point:
191 * We only currently support init_user_ns.
192 * When we enable more, this will trigger a failure so log.
194 pr_warn("user_events: Namespace other than init_user_ns!\n");
198 system_name = kmalloc(len, GFP_KERNEL);
203 snprintf(system_name, len, "%s", USER_EVENTS_SYSTEM);
208 static inline struct user_event_group
209 *user_event_group_from_user_ns(struct user_namespace *user_ns)
211 if (user_ns == &init_user_ns)
217 static struct user_event_group *current_user_event_group(void)
219 struct user_namespace *user_ns = current_user_ns();
220 struct user_event_group *group = NULL;
223 group = user_event_group_from_user_ns(user_ns);
228 user_ns = user_ns->parent;
234 static struct user_event_group
235 *user_event_group_create(struct user_namespace *user_ns)
237 struct user_event_group *group;
239 group = kzalloc(sizeof(*group), GFP_KERNEL);
244 group->system_name = user_event_group_system_name(user_ns);
246 if (!group->system_name)
249 mutex_init(&group->reg_mutex);
250 hash_init(group->register_table);
255 user_event_group_destroy(group);
260 static void user_event_enabler_destroy(struct user_event_enabler *enabler)
262 list_del_rcu(&enabler->link);
264 /* No longer tracking the event via the enabler */
265 refcount_dec(&enabler->event->refcnt);
270 static int user_event_mm_fault_in(struct user_event_mm *mm, unsigned long uaddr,
277 * Normally this is low, ensure that it cannot be taken advantage of by
278 * bad user processes to cause excessive looping.
283 mmap_read_lock(mm->mm);
285 /* Ensure MM has tasks, cannot use after exit_mm() */
286 if (refcount_read(&mm->tasks) == 0) {
291 ret = fixup_user_fault(mm->mm, uaddr, FAULT_FLAG_WRITE | FAULT_FLAG_REMOTE,
294 mmap_read_unlock(mm->mm);
299 static int user_event_enabler_write(struct user_event_mm *mm,
300 struct user_event_enabler *enabler,
301 bool fixup_fault, int *attempt);
303 static void user_event_enabler_fault_fixup(struct work_struct *work)
305 struct user_event_enabler_fault *fault = container_of(
306 work, struct user_event_enabler_fault, work);
307 struct user_event_enabler *enabler = fault->enabler;
308 struct user_event_mm *mm = fault->mm;
309 unsigned long uaddr = enabler->addr;
310 int attempt = fault->attempt;
313 ret = user_event_mm_fault_in(mm, uaddr, attempt);
315 if (ret && ret != -ENOENT) {
316 struct user_event *user = enabler->event;
318 pr_warn("user_events: Fault for mm: 0x%pK @ 0x%llx event: %s\n",
319 mm->mm, (unsigned long long)uaddr, EVENT_NAME(user));
322 /* Prevent state changes from racing */
323 mutex_lock(&event_mutex);
325 /* User asked for enabler to be removed during fault */
326 if (test_bit(ENABLE_VAL_FREEING_BIT, ENABLE_BITOPS(enabler))) {
327 user_event_enabler_destroy(enabler);
332 * If we managed to get the page, re-issue the write. We do not
333 * want to get into a possible infinite loop, which is why we only
334 * attempt again directly if the page came in. If we couldn't get
335 * the page here, then we will try again the next time the event is
338 clear_bit(ENABLE_VAL_FAULTING_BIT, ENABLE_BITOPS(enabler));
341 mmap_read_lock(mm->mm);
342 user_event_enabler_write(mm, enabler, true, &attempt);
343 mmap_read_unlock(mm->mm);
346 mutex_unlock(&event_mutex);
348 /* In all cases we no longer need the mm or fault */
349 user_event_mm_put(mm);
350 kmem_cache_free(fault_cache, fault);
353 static bool user_event_enabler_queue_fault(struct user_event_mm *mm,
354 struct user_event_enabler *enabler,
357 struct user_event_enabler_fault *fault;
359 fault = kmem_cache_zalloc(fault_cache, GFP_NOWAIT | __GFP_NOWARN);
364 INIT_WORK(&fault->work, user_event_enabler_fault_fixup);
365 fault->mm = user_event_mm_get(mm);
366 fault->enabler = enabler;
367 fault->attempt = attempt;
369 /* Don't try to queue in again while we have a pending fault */
370 set_bit(ENABLE_VAL_FAULTING_BIT, ENABLE_BITOPS(enabler));
372 if (!schedule_work(&fault->work)) {
373 /* Allow another attempt later */
374 clear_bit(ENABLE_VAL_FAULTING_BIT, ENABLE_BITOPS(enabler));
376 user_event_mm_put(mm);
377 kmem_cache_free(fault_cache, fault);
385 static int user_event_enabler_write(struct user_event_mm *mm,
386 struct user_event_enabler *enabler,
387 bool fixup_fault, int *attempt)
389 unsigned long uaddr = enabler->addr;
395 lockdep_assert_held(&event_mutex);
396 mmap_assert_locked(mm->mm);
400 /* Ensure MM has tasks, cannot use after exit_mm() */
401 if (refcount_read(&mm->tasks) == 0)
404 if (unlikely(test_bit(ENABLE_VAL_FAULTING_BIT, ENABLE_BITOPS(enabler)) ||
405 test_bit(ENABLE_VAL_FREEING_BIT, ENABLE_BITOPS(enabler))))
408 ret = pin_user_pages_remote(mm->mm, uaddr, 1, FOLL_WRITE | FOLL_NOFAULT,
411 if (unlikely(ret <= 0)) {
415 if (!user_event_enabler_queue_fault(mm, enabler, *attempt))
416 pr_warn("user_events: Unable to queue fault handler\n");
421 kaddr = kmap_local_page(page);
422 ptr = kaddr + (uaddr & ~PAGE_MASK);
424 /* Update bit atomically, user tracers must be atomic as well */
425 if (enabler->event && enabler->event->status)
426 set_bit(enabler->values & ENABLE_VAL_BIT_MASK, ptr);
428 clear_bit(enabler->values & ENABLE_VAL_BIT_MASK, ptr);
431 unpin_user_pages_dirty_lock(&page, 1, true);
436 static bool user_event_enabler_exists(struct user_event_mm *mm,
437 unsigned long uaddr, unsigned char bit)
439 struct user_event_enabler *enabler;
440 struct user_event_enabler *next;
442 list_for_each_entry_safe(enabler, next, &mm->enablers, link) {
443 if (enabler->addr == uaddr &&
444 (enabler->values & ENABLE_VAL_BIT_MASK) == bit)
451 static void user_event_enabler_update(struct user_event *user)
453 struct user_event_enabler *enabler;
454 struct user_event_mm *mm = user_event_mm_get_all(user);
455 struct user_event_mm *next;
460 mmap_read_lock(mm->mm);
463 list_for_each_entry_rcu(enabler, &mm->enablers, link) {
464 if (enabler->event == user) {
466 user_event_enabler_write(mm, enabler, true, &attempt);
471 mmap_read_unlock(mm->mm);
472 user_event_mm_put(mm);
477 static bool user_event_enabler_dup(struct user_event_enabler *orig,
478 struct user_event_mm *mm)
480 struct user_event_enabler *enabler;
482 /* Skip pending frees */
483 if (unlikely(test_bit(ENABLE_VAL_FREEING_BIT, ENABLE_BITOPS(orig))))
486 enabler = kzalloc(sizeof(*enabler), GFP_NOWAIT | __GFP_ACCOUNT);
491 enabler->event = orig->event;
492 enabler->addr = orig->addr;
494 /* Only dup part of value (ignore future flags, etc) */
495 enabler->values = orig->values & ENABLE_VAL_DUP_MASK;
497 refcount_inc(&enabler->event->refcnt);
498 list_add_rcu(&enabler->link, &mm->enablers);
503 static struct user_event_mm *user_event_mm_get(struct user_event_mm *mm)
505 refcount_inc(&mm->refcnt);
510 static struct user_event_mm *user_event_mm_get_all(struct user_event *user)
512 struct user_event_mm *found = NULL;
513 struct user_event_enabler *enabler;
514 struct user_event_mm *mm;
517 * We do not want to block fork/exec while enablements are being
518 * updated, so we use RCU to walk the current tasks that have used
519 * user_events ABI for 1 or more events. Each enabler found in each
520 * task that matches the event being updated has a write to reflect
521 * the kernel state back into the process. Waits/faults must not occur
522 * during this. So we scan the list under RCU for all the mm that have
523 * the event within it. This is needed because mm_read_lock() can wait.
524 * Each user mm returned has a ref inc to handle remove RCU races.
528 list_for_each_entry_rcu(mm, &user_event_mms, link)
529 list_for_each_entry_rcu(enabler, &mm->enablers, link)
530 if (enabler->event == user) {
532 found = user_event_mm_get(mm);
541 static struct user_event_mm *user_event_mm_create(struct task_struct *t)
543 struct user_event_mm *user_mm;
546 user_mm = kzalloc(sizeof(*user_mm), GFP_KERNEL_ACCOUNT);
552 INIT_LIST_HEAD(&user_mm->enablers);
553 refcount_set(&user_mm->refcnt, 1);
554 refcount_set(&user_mm->tasks, 1);
556 spin_lock_irqsave(&user_event_mms_lock, flags);
557 list_add_rcu(&user_mm->link, &user_event_mms);
558 spin_unlock_irqrestore(&user_event_mms_lock, flags);
560 t->user_event_mm = user_mm;
563 * The lifetime of the memory descriptor can slightly outlast
564 * the task lifetime if a ref to the user_event_mm is taken
565 * between list_del_rcu() and call_rcu(). Therefore we need
566 * to take a reference to it to ensure it can live this long
567 * under this corner case. This can also occur in clones that
568 * outlast the parent.
575 static struct user_event_mm *current_user_event_mm(void)
577 struct user_event_mm *user_mm = current->user_event_mm;
582 user_mm = user_event_mm_create(current);
587 refcount_inc(&user_mm->refcnt);
592 static void user_event_mm_destroy(struct user_event_mm *mm)
594 struct user_event_enabler *enabler, *next;
596 list_for_each_entry_safe(enabler, next, &mm->enablers, link)
597 user_event_enabler_destroy(enabler);
603 static void user_event_mm_put(struct user_event_mm *mm)
605 if (mm && refcount_dec_and_test(&mm->refcnt))
606 user_event_mm_destroy(mm);
609 static void delayed_user_event_mm_put(struct work_struct *work)
611 struct user_event_mm *mm;
613 mm = container_of(to_rcu_work(work), struct user_event_mm, put_rwork);
614 user_event_mm_put(mm);
617 void user_event_mm_remove(struct task_struct *t)
619 struct user_event_mm *mm;
624 mm = t->user_event_mm;
625 t->user_event_mm = NULL;
627 /* Clone will increment the tasks, only remove if last clone */
628 if (!refcount_dec_and_test(&mm->tasks))
631 /* Remove the mm from the list, so it can no longer be enabled */
632 spin_lock_irqsave(&user_event_mms_lock, flags);
633 list_del_rcu(&mm->link);
634 spin_unlock_irqrestore(&user_event_mms_lock, flags);
637 * We need to wait for currently occurring writes to stop within
638 * the mm. This is required since exit_mm() snaps the current rss
639 * stats and clears them. On the final mmdrop(), check_mm() will
640 * report a bug if these increment.
642 * All writes/pins are done under mmap_read lock, take the write
643 * lock to ensure in-progress faults have completed. Faults that
644 * are pending but yet to run will check the task count and skip
645 * the fault since the mm is going away.
647 mmap_write_lock(mm->mm);
648 mmap_write_unlock(mm->mm);
651 * Put for mm must be done after RCU delay to handle new refs in
652 * between the list_del_rcu() and now. This ensures any get refs
653 * during rcu_read_lock() are accounted for during list removal.
656 * ---------------------------------------------------------------
657 * user_event_mm_remove() | rcu_read_lock();
658 * list_del_rcu() | list_for_each_entry_rcu();
659 * call_rcu() | refcount_inc();
660 * . | rcu_read_unlock();
661 * schedule_work() | .
662 * user_event_mm_put() | .
664 * mmdrop() cannot be called in the softirq context of call_rcu()
665 * so we use a work queue after call_rcu() to run within.
667 INIT_RCU_WORK(&mm->put_rwork, delayed_user_event_mm_put);
668 queue_rcu_work(system_wq, &mm->put_rwork);
671 void user_event_mm_dup(struct task_struct *t, struct user_event_mm *old_mm)
673 struct user_event_mm *mm = user_event_mm_create(t);
674 struct user_event_enabler *enabler;
681 list_for_each_entry_rcu(enabler, &old_mm->enablers, link)
682 if (!user_event_enabler_dup(enabler, mm))
690 user_event_mm_remove(t);
693 static bool current_user_event_enabler_exists(unsigned long uaddr,
696 struct user_event_mm *user_mm = current_user_event_mm();
702 exists = user_event_enabler_exists(user_mm, uaddr, bit);
704 user_event_mm_put(user_mm);
709 static struct user_event_enabler
710 *user_event_enabler_create(struct user_reg *reg, struct user_event *user,
713 struct user_event_enabler *enabler;
714 struct user_event_mm *user_mm;
715 unsigned long uaddr = (unsigned long)reg->enable_addr;
718 user_mm = current_user_event_mm();
723 enabler = kzalloc(sizeof(*enabler), GFP_KERNEL_ACCOUNT);
728 enabler->event = user;
729 enabler->addr = uaddr;
730 enabler->values = reg->enable_bit;
732 /* Prevents state changes from racing with new enablers */
733 mutex_lock(&event_mutex);
735 /* Attempt to reflect the current state within the process */
736 mmap_read_lock(user_mm->mm);
737 *write_result = user_event_enabler_write(user_mm, enabler, false,
739 mmap_read_unlock(user_mm->mm);
742 * If the write works, then we will track the enabler. A ref to the
743 * underlying user_event is held by the enabler to prevent it going
744 * away while the enabler is still in use by a process. The ref is
745 * removed when the enabler is destroyed. This means a event cannot
746 * be forcefully deleted from the system until all tasks using it
747 * exit or run exec(), which includes forks and clones.
749 if (!*write_result) {
750 refcount_inc(&enabler->event->refcnt);
751 list_add_rcu(&enabler->link, &user_mm->enablers);
754 mutex_unlock(&event_mutex);
757 /* Attempt to fault-in and retry if it worked */
758 if (!user_event_mm_fault_in(user_mm, uaddr, attempt))
765 user_event_mm_put(user_mm);
770 static __always_inline __must_check
771 bool user_event_last_ref(struct user_event *user)
773 return refcount_read(&user->refcnt) == 1;
776 static __always_inline __must_check
777 size_t copy_nofault(void *addr, size_t bytes, struct iov_iter *i)
783 ret = copy_from_iter_nocache(addr, bytes, i);
790 static struct list_head *user_event_get_fields(struct trace_event_call *call)
792 struct user_event *user = (struct user_event *)call->data;
794 return &user->fields;
798 * Parses a register command for user_events
799 * Format: event_name[:FLAG1[,FLAG2...]] [field1[;field2...]]
801 * Example event named 'test' with a 20 char 'msg' field with an unsigned int
803 * test char[20] msg;unsigned int id
805 * NOTE: Offsets are from the user data perspective, they are not from the
806 * trace_entry/buffer perspective. We automatically add the common properties
807 * sizes to the offset for the user.
809 * Upon success user_event has its ref count increased by 1.
811 static int user_event_parse_cmd(struct user_event_group *group,
812 char *raw_command, struct user_event **newuser)
814 char *name = raw_command;
815 char *args = strpbrk(name, " ");
821 flags = strpbrk(name, ":");
826 return user_event_parse(group, name, args, flags, newuser);
829 static int user_field_array_size(const char *type)
831 const char *start = strchr(type, '[');
839 if (strscpy(val, start + 1, sizeof(val)) <= 0)
842 bracket = strchr(val, ']');
849 if (kstrtouint(val, 0, &size))
852 if (size > MAX_FIELD_ARRAY_SIZE)
858 static int user_field_size(const char *type)
860 /* long is not allowed from a user, since it's ambigious in size */
861 if (strcmp(type, "s64") == 0)
863 if (strcmp(type, "u64") == 0)
865 if (strcmp(type, "s32") == 0)
867 if (strcmp(type, "u32") == 0)
869 if (strcmp(type, "int") == 0)
871 if (strcmp(type, "unsigned int") == 0)
872 return sizeof(unsigned int);
873 if (strcmp(type, "s16") == 0)
875 if (strcmp(type, "u16") == 0)
877 if (strcmp(type, "short") == 0)
878 return sizeof(short);
879 if (strcmp(type, "unsigned short") == 0)
880 return sizeof(unsigned short);
881 if (strcmp(type, "s8") == 0)
883 if (strcmp(type, "u8") == 0)
885 if (strcmp(type, "char") == 0)
887 if (strcmp(type, "unsigned char") == 0)
888 return sizeof(unsigned char);
889 if (str_has_prefix(type, "char["))
890 return user_field_array_size(type);
891 if (str_has_prefix(type, "unsigned char["))
892 return user_field_array_size(type);
893 if (str_has_prefix(type, "__data_loc "))
895 if (str_has_prefix(type, "__rel_loc "))
898 /* Uknown basic type, error */
902 static void user_event_destroy_validators(struct user_event *user)
904 struct user_event_validator *validator, *next;
905 struct list_head *head = &user->validators;
907 list_for_each_entry_safe(validator, next, head, link) {
908 list_del(&validator->link);
913 static void user_event_destroy_fields(struct user_event *user)
915 struct ftrace_event_field *field, *next;
916 struct list_head *head = &user->fields;
918 list_for_each_entry_safe(field, next, head, link) {
919 list_del(&field->link);
924 static int user_event_add_field(struct user_event *user, const char *type,
925 const char *name, int offset, int size,
926 int is_signed, int filter_type)
928 struct user_event_validator *validator;
929 struct ftrace_event_field *field;
930 int validator_flags = 0;
932 field = kmalloc(sizeof(*field), GFP_KERNEL_ACCOUNT);
937 if (str_has_prefix(type, "__data_loc "))
940 if (str_has_prefix(type, "__rel_loc ")) {
941 validator_flags |= VALIDATOR_REL;
948 if (strstr(type, "char") != NULL)
949 validator_flags |= VALIDATOR_ENSURE_NULL;
951 validator = kmalloc(sizeof(*validator), GFP_KERNEL_ACCOUNT);
958 validator->flags = validator_flags;
959 validator->offset = offset;
961 /* Want sequential access when validating */
962 list_add_tail(&validator->link, &user->validators);
967 field->offset = offset;
969 field->is_signed = is_signed;
970 field->filter_type = filter_type;
972 if (filter_type == FILTER_OTHER)
973 field->filter_type = filter_assign_type(type);
975 list_add(&field->link, &user->fields);
978 * Min size from user writes that are required, this does not include
979 * the size of trace_entry (common fields).
981 user->min_size = (offset + size) - sizeof(struct trace_entry);
987 * Parses the values of a field within the description
988 * Format: type name [size]
990 static int user_event_parse_field(char *field, struct user_event *user,
993 char *part, *type, *name;
994 u32 depth = 0, saved_offset = *offset;
995 int len, size = -EINVAL;
996 bool is_struct = false;
998 field = skip_spaces(field);
1003 /* Handle types that have a space within */
1004 len = str_has_prefix(field, "unsigned ");
1008 len = str_has_prefix(field, "struct ");
1014 len = str_has_prefix(field, "__data_loc unsigned ");
1018 len = str_has_prefix(field, "__data_loc ");
1022 len = str_has_prefix(field, "__rel_loc unsigned ");
1026 len = str_has_prefix(field, "__rel_loc ");
1033 field = strpbrk(field + len, " ");
1043 while ((part = strsep(&field, " ")) != NULL) {
1045 case FIELD_DEPTH_TYPE:
1048 case FIELD_DEPTH_NAME:
1051 case FIELD_DEPTH_SIZE:
1055 if (kstrtou32(part, 10, &size))
1063 if (depth < FIELD_DEPTH_SIZE || !name)
1066 if (depth == FIELD_DEPTH_SIZE)
1067 size = user_field_size(type);
1075 *offset = saved_offset + size;
1077 return user_event_add_field(user, type, name, saved_offset, size,
1078 type[0] != 'u', FILTER_OTHER);
1081 static int user_event_parse_fields(struct user_event *user, char *args)
1084 u32 offset = sizeof(struct trace_entry);
1090 while ((field = strsep(&args, ";")) != NULL) {
1091 ret = user_event_parse_field(field, user, &offset);
1100 static struct trace_event_fields user_event_fields_array[1];
1102 static const char *user_field_format(const char *type)
1104 if (strcmp(type, "s64") == 0)
1106 if (strcmp(type, "u64") == 0)
1108 if (strcmp(type, "s32") == 0)
1110 if (strcmp(type, "u32") == 0)
1112 if (strcmp(type, "int") == 0)
1114 if (strcmp(type, "unsigned int") == 0)
1116 if (strcmp(type, "s16") == 0)
1118 if (strcmp(type, "u16") == 0)
1120 if (strcmp(type, "short") == 0)
1122 if (strcmp(type, "unsigned short") == 0)
1124 if (strcmp(type, "s8") == 0)
1126 if (strcmp(type, "u8") == 0)
1128 if (strcmp(type, "char") == 0)
1130 if (strcmp(type, "unsigned char") == 0)
1132 if (strstr(type, "char[") != NULL)
1135 /* Unknown, likely struct, allowed treat as 64-bit */
1139 static bool user_field_is_dyn_string(const char *type, const char **str_func)
1141 if (str_has_prefix(type, "__data_loc ")) {
1142 *str_func = "__get_str";
1146 if (str_has_prefix(type, "__rel_loc ")) {
1147 *str_func = "__get_rel_str";
1153 return strstr(type, "char") != NULL;
1156 #define LEN_OR_ZERO (len ? len - pos : 0)
1157 static int user_dyn_field_set_string(int argc, const char **argv, int *iout,
1158 char *buf, int len, bool *colon)
1160 int pos = 0, i = *iout;
1164 for (; i < argc; ++i) {
1166 pos += snprintf(buf + pos, LEN_OR_ZERO, " ");
1168 pos += snprintf(buf + pos, LEN_OR_ZERO, "%s", argv[i]);
1170 if (strchr(argv[i], ';')) {
1177 /* Actual set, advance i */
1184 static int user_field_set_string(struct ftrace_event_field *field,
1185 char *buf, int len, bool colon)
1189 pos += snprintf(buf + pos, LEN_OR_ZERO, "%s", field->type);
1190 pos += snprintf(buf + pos, LEN_OR_ZERO, " ");
1191 pos += snprintf(buf + pos, LEN_OR_ZERO, "%s", field->name);
1194 pos += snprintf(buf + pos, LEN_OR_ZERO, ";");
1199 static int user_event_set_print_fmt(struct user_event *user, char *buf, int len)
1201 struct ftrace_event_field *field, *next;
1202 struct list_head *head = &user->fields;
1203 int pos = 0, depth = 0;
1204 const char *str_func;
1206 pos += snprintf(buf + pos, LEN_OR_ZERO, "\"");
1208 list_for_each_entry_safe_reverse(field, next, head, link) {
1210 pos += snprintf(buf + pos, LEN_OR_ZERO, " ");
1212 pos += snprintf(buf + pos, LEN_OR_ZERO, "%s=%s",
1213 field->name, user_field_format(field->type));
1218 pos += snprintf(buf + pos, LEN_OR_ZERO, "\"");
1220 list_for_each_entry_safe_reverse(field, next, head, link) {
1221 if (user_field_is_dyn_string(field->type, &str_func))
1222 pos += snprintf(buf + pos, LEN_OR_ZERO,
1223 ", %s(%s)", str_func, field->name);
1225 pos += snprintf(buf + pos, LEN_OR_ZERO,
1226 ", REC->%s", field->name);
1233 static int user_event_create_print_fmt(struct user_event *user)
1238 len = user_event_set_print_fmt(user, NULL, 0);
1240 print_fmt = kmalloc(len, GFP_KERNEL_ACCOUNT);
1245 user_event_set_print_fmt(user, print_fmt, len);
1247 user->call.print_fmt = print_fmt;
1252 static enum print_line_t user_event_print_trace(struct trace_iterator *iter,
1254 struct trace_event *event)
1256 return print_event_fields(iter, event);
1259 static struct trace_event_functions user_event_funcs = {
1260 .trace = user_event_print_trace,
1263 static int user_event_set_call_visible(struct user_event *user, bool visible)
1266 const struct cred *old_cred;
1269 cred = prepare_creds();
1275 * While by default tracefs is locked down, systems can be configured
1276 * to allow user_event files to be less locked down. The extreme case
1277 * being "other" has read/write access to user_events_data/status.
1279 * When not locked down, processes may not have permissions to
1280 * add/remove calls themselves to tracefs. We need to temporarily
1281 * switch to root file permission to allow for this scenario.
1283 cred->fsuid = GLOBAL_ROOT_UID;
1285 old_cred = override_creds(cred);
1288 ret = trace_add_event_call(&user->call);
1290 ret = trace_remove_event_call(&user->call);
1292 revert_creds(old_cred);
1298 static int destroy_user_event(struct user_event *user)
1302 lockdep_assert_held(&event_mutex);
1304 /* Must destroy fields before call removal */
1305 user_event_destroy_fields(user);
1307 ret = user_event_set_call_visible(user, false);
1312 dyn_event_remove(&user->devent);
1313 hash_del(&user->node);
1315 user_event_destroy_validators(user);
1316 kfree(user->call.print_fmt);
1317 kfree(EVENT_NAME(user));
1320 if (current_user_events > 0)
1321 current_user_events--;
1323 pr_alert("BUG: Bad current_user_events\n");
1328 static struct user_event *find_user_event(struct user_event_group *group,
1329 char *name, u32 *outkey)
1331 struct user_event *user;
1332 u32 key = user_event_key(name);
1336 hash_for_each_possible(group->register_table, user, node, key)
1337 if (!strcmp(EVENT_NAME(user), name)) {
1338 refcount_inc(&user->refcnt);
1345 static int user_event_validate(struct user_event *user, void *data, int len)
1347 struct list_head *head = &user->validators;
1348 struct user_event_validator *validator;
1349 void *pos, *end = data + len;
1350 u32 loc, offset, size;
1352 list_for_each_entry(validator, head, link) {
1353 pos = data + validator->offset;
1355 /* Already done min_size check, no bounds check here */
1357 offset = loc & 0xffff;
1360 if (likely(validator->flags & VALIDATOR_REL))
1361 pos += offset + sizeof(loc);
1363 pos = data + offset;
1367 if (unlikely(pos > end))
1370 if (likely(validator->flags & VALIDATOR_ENSURE_NULL))
1371 if (unlikely(*(char *)(pos - 1) != '\0'))
1379 * Writes the user supplied payload out to a trace file.
1381 static void user_event_ftrace(struct user_event *user, struct iov_iter *i,
1382 void *tpdata, bool *faulted)
1384 struct trace_event_file *file;
1385 struct trace_entry *entry;
1386 struct trace_event_buffer event_buffer;
1387 size_t size = sizeof(*entry) + i->count;
1389 file = (struct trace_event_file *)tpdata;
1392 !(file->flags & EVENT_FILE_FL_ENABLED) ||
1393 trace_trigger_soft_disabled(file))
1396 /* Allocates and fills trace_entry, + 1 of this is data payload */
1397 entry = trace_event_buffer_reserve(&event_buffer, file, size);
1399 if (unlikely(!entry))
1402 if (unlikely(!copy_nofault(entry + 1, i->count, i)))
1405 if (!list_empty(&user->validators) &&
1406 unlikely(user_event_validate(user, entry, size)))
1409 trace_event_buffer_commit(&event_buffer);
1414 __trace_event_discard_commit(event_buffer.buffer,
1415 event_buffer.event);
1418 #ifdef CONFIG_PERF_EVENTS
1420 * Writes the user supplied payload out to perf ring buffer.
1422 static void user_event_perf(struct user_event *user, struct iov_iter *i,
1423 void *tpdata, bool *faulted)
1425 struct hlist_head *perf_head;
1427 perf_head = this_cpu_ptr(user->call.perf_events);
1429 if (perf_head && !hlist_empty(perf_head)) {
1430 struct trace_entry *perf_entry;
1431 struct pt_regs *regs;
1432 size_t size = sizeof(*perf_entry) + i->count;
1435 perf_entry = perf_trace_buf_alloc(ALIGN(size, 8),
1438 if (unlikely(!perf_entry))
1441 perf_fetch_caller_regs(regs);
1443 if (unlikely(!copy_nofault(perf_entry + 1, i->count, i)))
1446 if (!list_empty(&user->validators) &&
1447 unlikely(user_event_validate(user, perf_entry, size)))
1450 perf_trace_buf_submit(perf_entry, size, context,
1451 user->call.event.type, 1, regs,
1457 perf_swevent_put_recursion_context(context);
1463 * Update the enabled bit among all user processes.
1465 static void update_enable_bit_for(struct user_event *user)
1467 struct tracepoint *tp = &user->tracepoint;
1470 if (atomic_read(&tp->key.enabled) > 0) {
1471 struct tracepoint_func *probe_func_ptr;
1472 user_event_func_t probe_func;
1474 rcu_read_lock_sched();
1476 probe_func_ptr = rcu_dereference_sched(tp->funcs);
1478 if (probe_func_ptr) {
1480 probe_func = probe_func_ptr->func;
1482 if (probe_func == user_event_ftrace)
1483 status |= EVENT_STATUS_FTRACE;
1484 #ifdef CONFIG_PERF_EVENTS
1485 else if (probe_func == user_event_perf)
1486 status |= EVENT_STATUS_PERF;
1489 status |= EVENT_STATUS_OTHER;
1490 } while ((++probe_func_ptr)->func);
1493 rcu_read_unlock_sched();
1496 user->status = status;
1498 user_event_enabler_update(user);
1502 * Register callback for our events from tracing sub-systems.
1504 static int user_event_reg(struct trace_event_call *call,
1505 enum trace_reg type,
1508 struct user_event *user = (struct user_event *)call->data;
1515 case TRACE_REG_REGISTER:
1516 ret = tracepoint_probe_register(call->tp,
1523 case TRACE_REG_UNREGISTER:
1524 tracepoint_probe_unregister(call->tp,
1529 #ifdef CONFIG_PERF_EVENTS
1530 case TRACE_REG_PERF_REGISTER:
1531 ret = tracepoint_probe_register(call->tp,
1532 call->class->perf_probe,
1538 case TRACE_REG_PERF_UNREGISTER:
1539 tracepoint_probe_unregister(call->tp,
1540 call->class->perf_probe,
1544 case TRACE_REG_PERF_OPEN:
1545 case TRACE_REG_PERF_CLOSE:
1546 case TRACE_REG_PERF_ADD:
1547 case TRACE_REG_PERF_DEL:
1554 refcount_inc(&user->refcnt);
1555 update_enable_bit_for(user);
1558 update_enable_bit_for(user);
1559 refcount_dec(&user->refcnt);
1563 static int user_event_create(const char *raw_command)
1565 struct user_event_group *group;
1566 struct user_event *user;
1570 if (!str_has_prefix(raw_command, USER_EVENTS_PREFIX))
1573 raw_command += USER_EVENTS_PREFIX_LEN;
1574 raw_command = skip_spaces(raw_command);
1576 name = kstrdup(raw_command, GFP_KERNEL_ACCOUNT);
1581 group = current_user_event_group();
1588 mutex_lock(&group->reg_mutex);
1590 ret = user_event_parse_cmd(group, name, &user);
1593 refcount_dec(&user->refcnt);
1595 mutex_unlock(&group->reg_mutex);
1603 static int user_event_show(struct seq_file *m, struct dyn_event *ev)
1605 struct user_event *user = container_of(ev, struct user_event, devent);
1606 struct ftrace_event_field *field, *next;
1607 struct list_head *head;
1610 seq_printf(m, "%s%s", USER_EVENTS_PREFIX, EVENT_NAME(user));
1612 head = trace_get_fields(&user->call);
1614 list_for_each_entry_safe_reverse(field, next, head, link) {
1620 seq_printf(m, "%s %s", field->type, field->name);
1622 if (str_has_prefix(field->type, "struct "))
1623 seq_printf(m, " %d", field->size);
1633 static bool user_event_is_busy(struct dyn_event *ev)
1635 struct user_event *user = container_of(ev, struct user_event, devent);
1637 return !user_event_last_ref(user);
1640 static int user_event_free(struct dyn_event *ev)
1642 struct user_event *user = container_of(ev, struct user_event, devent);
1644 if (!user_event_last_ref(user))
1647 return destroy_user_event(user);
1650 static bool user_field_match(struct ftrace_event_field *field, int argc,
1651 const char **argv, int *iout)
1653 char *field_name = NULL, *dyn_field_name = NULL;
1654 bool colon = false, match = false;
1660 dyn_len = user_dyn_field_set_string(argc, argv, iout, dyn_field_name,
1663 len = user_field_set_string(field, field_name, 0, colon);
1668 dyn_field_name = kmalloc(dyn_len, GFP_KERNEL);
1669 field_name = kmalloc(len, GFP_KERNEL);
1671 if (!dyn_field_name || !field_name)
1674 user_dyn_field_set_string(argc, argv, iout, dyn_field_name,
1677 user_field_set_string(field, field_name, len, colon);
1679 match = strcmp(dyn_field_name, field_name) == 0;
1681 kfree(dyn_field_name);
1687 static bool user_fields_match(struct user_event *user, int argc,
1690 struct ftrace_event_field *field, *next;
1691 struct list_head *head = &user->fields;
1694 list_for_each_entry_safe_reverse(field, next, head, link)
1695 if (!user_field_match(field, argc, argv, &i))
1704 static bool user_event_match(const char *system, const char *event,
1705 int argc, const char **argv, struct dyn_event *ev)
1707 struct user_event *user = container_of(ev, struct user_event, devent);
1710 match = strcmp(EVENT_NAME(user), event) == 0 &&
1711 (!system || strcmp(system, USER_EVENTS_SYSTEM) == 0);
1713 if (match && argc > 0)
1714 match = user_fields_match(user, argc, argv);
1719 static struct dyn_event_operations user_event_dops = {
1720 .create = user_event_create,
1721 .show = user_event_show,
1722 .is_busy = user_event_is_busy,
1723 .free = user_event_free,
1724 .match = user_event_match,
1727 static int user_event_trace_register(struct user_event *user)
1731 ret = register_trace_event(&user->call.event);
1736 ret = user_event_set_call_visible(user, true);
1739 unregister_trace_event(&user->call.event);
1745 * Parses the event name, arguments and flags then registers if successful.
1746 * The name buffer lifetime is owned by this method for success cases only.
1747 * Upon success the returned user_event has its ref count increased by 1.
1749 static int user_event_parse(struct user_event_group *group, char *name,
1750 char *args, char *flags,
1751 struct user_event **newuser)
1755 struct user_event *user;
1757 /* Prevent dyn_event from racing */
1758 mutex_lock(&event_mutex);
1759 user = find_user_event(group, name, &key);
1760 mutex_unlock(&event_mutex);
1765 * Name is allocated by caller, free it since it already exists.
1766 * Caller only worries about failure cases for freeing.
1772 user = kzalloc(sizeof(*user), GFP_KERNEL_ACCOUNT);
1777 INIT_LIST_HEAD(&user->class.fields);
1778 INIT_LIST_HEAD(&user->fields);
1779 INIT_LIST_HEAD(&user->validators);
1781 user->group = group;
1782 user->tracepoint.name = name;
1784 ret = user_event_parse_fields(user, args);
1789 ret = user_event_create_print_fmt(user);
1794 user->call.data = user;
1795 user->call.class = &user->class;
1796 user->call.name = name;
1797 user->call.flags = TRACE_EVENT_FL_TRACEPOINT;
1798 user->call.tp = &user->tracepoint;
1799 user->call.event.funcs = &user_event_funcs;
1800 user->class.system = group->system_name;
1802 user->class.fields_array = user_event_fields_array;
1803 user->class.get_fields = user_event_get_fields;
1804 user->class.reg = user_event_reg;
1805 user->class.probe = user_event_ftrace;
1806 #ifdef CONFIG_PERF_EVENTS
1807 user->class.perf_probe = user_event_perf;
1810 mutex_lock(&event_mutex);
1812 if (current_user_events >= max_user_events) {
1817 ret = user_event_trace_register(user);
1822 /* Ensure we track self ref and caller ref (2) */
1823 refcount_set(&user->refcnt, 2);
1825 dyn_event_init(&user->devent, &user_event_dops);
1826 dyn_event_add(&user->devent, &user->call);
1827 hash_add(group->register_table, &user->node, key);
1828 current_user_events++;
1830 mutex_unlock(&event_mutex);
1835 mutex_unlock(&event_mutex);
1837 user_event_destroy_fields(user);
1838 user_event_destroy_validators(user);
1839 kfree(user->call.print_fmt);
1845 * Deletes a previously created event if it is no longer being used.
1847 static int delete_user_event(struct user_event_group *group, char *name)
1850 struct user_event *user = find_user_event(group, name, &key);
1855 refcount_dec(&user->refcnt);
1857 if (!user_event_last_ref(user))
1860 return destroy_user_event(user);
1864 * Validates the user payload and writes via iterator.
1866 static ssize_t user_events_write_core(struct file *file, struct iov_iter *i)
1868 struct user_event_file_info *info = file->private_data;
1869 struct user_event_refs *refs;
1870 struct user_event *user = NULL;
1871 struct tracepoint *tp;
1872 ssize_t ret = i->count;
1875 if (unlikely(copy_from_iter(&idx, sizeof(idx), i) != sizeof(idx)))
1881 rcu_read_lock_sched();
1883 refs = rcu_dereference_sched(info->refs);
1886 * The refs->events array is protected by RCU, and new items may be
1887 * added. But the user retrieved from indexing into the events array
1888 * shall be immutable while the file is opened.
1890 if (likely(refs && idx < refs->count))
1891 user = refs->events[idx];
1893 rcu_read_unlock_sched();
1895 if (unlikely(user == NULL))
1898 if (unlikely(i->count < user->min_size))
1901 tp = &user->tracepoint;
1904 * It's possible key.enabled disables after this check, however
1905 * we don't mind if a few events are included in this condition.
1907 if (likely(atomic_read(&tp->key.enabled) > 0)) {
1908 struct tracepoint_func *probe_func_ptr;
1909 user_event_func_t probe_func;
1910 struct iov_iter copy;
1914 if (unlikely(fault_in_iov_iter_readable(i, i->count)))
1919 rcu_read_lock_sched();
1921 probe_func_ptr = rcu_dereference_sched(tp->funcs);
1923 if (probe_func_ptr) {
1926 probe_func = probe_func_ptr->func;
1927 tpdata = probe_func_ptr->data;
1928 probe_func(user, ©, tpdata, &faulted);
1929 } while ((++probe_func_ptr)->func);
1932 rcu_read_unlock_sched();
1934 if (unlikely(faulted))
1941 static int user_events_open(struct inode *node, struct file *file)
1943 struct user_event_group *group;
1944 struct user_event_file_info *info;
1946 group = current_user_event_group();
1951 info = kzalloc(sizeof(*info), GFP_KERNEL_ACCOUNT);
1956 info->group = group;
1958 file->private_data = info;
1963 static ssize_t user_events_write(struct file *file, const char __user *ubuf,
1964 size_t count, loff_t *ppos)
1969 if (unlikely(*ppos != 0))
1972 if (unlikely(import_single_range(ITER_SOURCE, (char __user *)ubuf,
1976 return user_events_write_core(file, &i);
1979 static ssize_t user_events_write_iter(struct kiocb *kp, struct iov_iter *i)
1981 return user_events_write_core(kp->ki_filp, i);
1984 static int user_events_ref_add(struct user_event_file_info *info,
1985 struct user_event *user)
1987 struct user_event_group *group = info->group;
1988 struct user_event_refs *refs, *new_refs;
1989 int i, size, count = 0;
1991 refs = rcu_dereference_protected(info->refs,
1992 lockdep_is_held(&group->reg_mutex));
1995 count = refs->count;
1997 for (i = 0; i < count; ++i)
1998 if (refs->events[i] == user)
2002 size = struct_size(refs, events, count + 1);
2004 new_refs = kzalloc(size, GFP_KERNEL_ACCOUNT);
2009 new_refs->count = count + 1;
2011 for (i = 0; i < count; ++i)
2012 new_refs->events[i] = refs->events[i];
2014 new_refs->events[i] = user;
2016 refcount_inc(&user->refcnt);
2018 rcu_assign_pointer(info->refs, new_refs);
2021 kfree_rcu(refs, rcu);
2026 static long user_reg_get(struct user_reg __user *ureg, struct user_reg *kreg)
2031 ret = get_user(size, &ureg->size);
2036 if (size > PAGE_SIZE)
2039 if (size < offsetofend(struct user_reg, write_index))
2042 ret = copy_struct_from_user(kreg, sizeof(*kreg), ureg, size);
2047 /* Ensure no flags, since we don't support any yet */
2048 if (kreg->flags != 0)
2051 /* Ensure supported size */
2052 switch (kreg->enable_size) {
2056 #if BITS_PER_LONG >= 64
2065 /* Ensure natural alignment */
2066 if (kreg->enable_addr % kreg->enable_size)
2069 /* Ensure bit range for size */
2070 if (kreg->enable_bit > (kreg->enable_size * BITS_PER_BYTE) - 1)
2073 /* Ensure accessible */
2074 if (!access_ok((const void __user *)(uintptr_t)kreg->enable_addr,
2084 * Registers a user_event on behalf of a user process.
2086 static long user_events_ioctl_reg(struct user_event_file_info *info,
2089 struct user_reg __user *ureg = (struct user_reg __user *)uarg;
2090 struct user_reg reg;
2091 struct user_event *user;
2092 struct user_event_enabler *enabler;
2097 ret = user_reg_get(ureg, ®);
2103 * Prevent users from using the same address and bit multiple times
2104 * within the same mm address space. This can cause unexpected behavior
2105 * for user processes that is far easier to debug if this is explictly
2106 * an error upon registering.
2108 if (current_user_event_enabler_exists((unsigned long)reg.enable_addr,
2112 name = strndup_user((const char __user *)(uintptr_t)reg.name_args,
2116 ret = PTR_ERR(name);
2120 ret = user_event_parse_cmd(info->group, name, &user);
2127 ret = user_events_ref_add(info, user);
2129 /* No longer need parse ref, ref_add either worked or not */
2130 refcount_dec(&user->refcnt);
2132 /* Positive number is index and valid */
2137 * user_events_ref_add succeeded:
2138 * At this point we have a user_event, it's lifetime is bound by the
2139 * reference count, not this file. If anything fails, the user_event
2140 * still has a reference until the file is released. During release
2141 * any remaining references (from user_events_ref_add) are decremented.
2143 * Attempt to create an enabler, which too has a lifetime tied in the
2144 * same way for the event. Once the task that caused the enabler to be
2145 * created exits or issues exec() then the enablers it has created
2146 * will be destroyed and the ref to the event will be decremented.
2148 enabler = user_event_enabler_create(®, user, &write_result);
2153 /* Write failed/faulted, give error back to caller */
2155 return write_result;
2157 put_user((u32)ret, &ureg->write_index);
2163 * Deletes a user_event on behalf of a user process.
2165 static long user_events_ioctl_del(struct user_event_file_info *info,
2168 void __user *ubuf = (void __user *)uarg;
2172 name = strndup_user(ubuf, MAX_EVENT_DESC);
2175 return PTR_ERR(name);
2177 /* event_mutex prevents dyn_event from racing */
2178 mutex_lock(&event_mutex);
2179 ret = delete_user_event(info->group, name);
2180 mutex_unlock(&event_mutex);
2187 static long user_unreg_get(struct user_unreg __user *ureg,
2188 struct user_unreg *kreg)
2193 ret = get_user(size, &ureg->size);
2198 if (size > PAGE_SIZE)
2201 if (size < offsetofend(struct user_unreg, disable_addr))
2204 ret = copy_struct_from_user(kreg, sizeof(*kreg), ureg, size);
2206 /* Ensure no reserved values, since we don't support any yet */
2207 if (kreg->__reserved || kreg->__reserved2)
2213 static int user_event_mm_clear_bit(struct user_event_mm *user_mm,
2214 unsigned long uaddr, unsigned char bit)
2216 struct user_event_enabler enabler;
2220 memset(&enabler, 0, sizeof(enabler));
2221 enabler.addr = uaddr;
2222 enabler.values = bit;
2224 /* Prevents state changes from racing with new enablers */
2225 mutex_lock(&event_mutex);
2227 /* Force the bit to be cleared, since no event is attached */
2228 mmap_read_lock(user_mm->mm);
2229 result = user_event_enabler_write(user_mm, &enabler, false, &attempt);
2230 mmap_read_unlock(user_mm->mm);
2232 mutex_unlock(&event_mutex);
2235 /* Attempt to fault-in and retry if it worked */
2236 if (!user_event_mm_fault_in(user_mm, uaddr, attempt))
2244 * Unregisters an enablement address/bit within a task/user mm.
2246 static long user_events_ioctl_unreg(unsigned long uarg)
2248 struct user_unreg __user *ureg = (struct user_unreg __user *)uarg;
2249 struct user_event_mm *mm = current->user_event_mm;
2250 struct user_event_enabler *enabler, *next;
2251 struct user_unreg reg;
2254 ret = user_unreg_get(ureg, ®);
2265 * Flags freeing and faulting are used to indicate if the enabler is in
2266 * use at all. When faulting is set a page-fault is occurring asyncly.
2267 * During async fault if freeing is set, the enabler will be destroyed.
2268 * If no async fault is happening, we can destroy it now since we hold
2269 * the event_mutex during these checks.
2271 mutex_lock(&event_mutex);
2273 list_for_each_entry_safe(enabler, next, &mm->enablers, link)
2274 if (enabler->addr == reg.disable_addr &&
2275 (enabler->values & ENABLE_VAL_BIT_MASK) == reg.disable_bit) {
2276 set_bit(ENABLE_VAL_FREEING_BIT, ENABLE_BITOPS(enabler));
2278 if (!test_bit(ENABLE_VAL_FAULTING_BIT, ENABLE_BITOPS(enabler)))
2279 user_event_enabler_destroy(enabler);
2281 /* Removed at least one */
2285 mutex_unlock(&event_mutex);
2287 /* Ensure bit is now cleared for user, regardless of event status */
2289 ret = user_event_mm_clear_bit(mm, reg.disable_addr,
2296 * Handles the ioctl from user mode to register or alter operations.
2298 static long user_events_ioctl(struct file *file, unsigned int cmd,
2301 struct user_event_file_info *info = file->private_data;
2302 struct user_event_group *group = info->group;
2307 mutex_lock(&group->reg_mutex);
2308 ret = user_events_ioctl_reg(info, uarg);
2309 mutex_unlock(&group->reg_mutex);
2313 mutex_lock(&group->reg_mutex);
2314 ret = user_events_ioctl_del(info, uarg);
2315 mutex_unlock(&group->reg_mutex);
2318 case DIAG_IOCSUNREG:
2319 mutex_lock(&group->reg_mutex);
2320 ret = user_events_ioctl_unreg(uarg);
2321 mutex_unlock(&group->reg_mutex);
2329 * Handles the final close of the file from user mode.
2331 static int user_events_release(struct inode *node, struct file *file)
2333 struct user_event_file_info *info = file->private_data;
2334 struct user_event_group *group;
2335 struct user_event_refs *refs;
2336 struct user_event *user;
2342 group = info->group;
2345 * Ensure refs cannot change under any situation by taking the
2346 * register mutex during the final freeing of the references.
2348 mutex_lock(&group->reg_mutex);
2356 * The lifetime of refs has reached an end, it's tied to this file.
2357 * The underlying user_events are ref counted, and cannot be freed.
2358 * After this decrement, the user_events may be freed elsewhere.
2360 for (i = 0; i < refs->count; ++i) {
2361 user = refs->events[i];
2364 refcount_dec(&user->refcnt);
2367 file->private_data = NULL;
2369 mutex_unlock(&group->reg_mutex);
2377 static const struct file_operations user_data_fops = {
2378 .open = user_events_open,
2379 .write = user_events_write,
2380 .write_iter = user_events_write_iter,
2381 .unlocked_ioctl = user_events_ioctl,
2382 .release = user_events_release,
2385 static void *user_seq_start(struct seq_file *m, loff_t *pos)
2393 static void *user_seq_next(struct seq_file *m, void *p, loff_t *pos)
2399 static void user_seq_stop(struct seq_file *m, void *p)
2403 static int user_seq_show(struct seq_file *m, void *p)
2405 struct user_event_group *group = m->private;
2406 struct user_event *user;
2408 int i, active = 0, busy = 0;
2413 mutex_lock(&group->reg_mutex);
2415 hash_for_each(group->register_table, i, user, node) {
2416 status = user->status;
2418 seq_printf(m, "%s", EVENT_NAME(user));
2424 seq_puts(m, " Used by");
2425 if (status & EVENT_STATUS_FTRACE)
2426 seq_puts(m, " ftrace");
2427 if (status & EVENT_STATUS_PERF)
2428 seq_puts(m, " perf");
2429 if (status & EVENT_STATUS_OTHER)
2430 seq_puts(m, " other");
2438 mutex_unlock(&group->reg_mutex);
2441 seq_printf(m, "Active: %d\n", active);
2442 seq_printf(m, "Busy: %d\n", busy);
2447 static const struct seq_operations user_seq_ops = {
2448 .start = user_seq_start,
2449 .next = user_seq_next,
2450 .stop = user_seq_stop,
2451 .show = user_seq_show,
2454 static int user_status_open(struct inode *node, struct file *file)
2456 struct user_event_group *group;
2459 group = current_user_event_group();
2464 ret = seq_open(file, &user_seq_ops);
2467 /* Chain group to seq_file */
2468 struct seq_file *m = file->private_data;
2476 static const struct file_operations user_status_fops = {
2477 .open = user_status_open,
2479 .llseek = seq_lseek,
2480 .release = seq_release,
2484 * Creates a set of tracefs files to allow user mode interactions.
2486 static int create_user_tracefs(void)
2488 struct dentry *edata, *emmap;
2490 edata = tracefs_create_file("user_events_data", TRACE_MODE_WRITE,
2491 NULL, NULL, &user_data_fops);
2494 pr_warn("Could not create tracefs 'user_events_data' entry\n");
2498 emmap = tracefs_create_file("user_events_status", TRACE_MODE_READ,
2499 NULL, NULL, &user_status_fops);
2502 tracefs_remove(edata);
2503 pr_warn("Could not create tracefs 'user_events_mmap' entry\n");
2512 static int set_max_user_events_sysctl(struct ctl_table *table, int write,
2513 void *buffer, size_t *lenp, loff_t *ppos)
2517 mutex_lock(&event_mutex);
2519 ret = proc_douintvec(table, write, buffer, lenp, ppos);
2521 mutex_unlock(&event_mutex);
2526 static struct ctl_table user_event_sysctls[] = {
2528 .procname = "user_events_max",
2529 .data = &max_user_events,
2530 .maxlen = sizeof(unsigned int),
2532 .proc_handler = set_max_user_events_sysctl,
2537 static int __init trace_events_user_init(void)
2541 fault_cache = KMEM_CACHE(user_event_enabler_fault, 0);
2546 init_group = user_event_group_create(&init_user_ns);
2549 kmem_cache_destroy(fault_cache);
2553 ret = create_user_tracefs();
2556 pr_warn("user_events could not register with tracefs\n");
2557 user_event_group_destroy(init_group);
2558 kmem_cache_destroy(fault_cache);
2563 if (dyn_event_register(&user_event_dops))
2564 pr_warn("user_events could not register with dyn_events\n");
2566 register_sysctl_init("kernel", user_event_sysctls);
2571 fs_initcall(trace_events_user_init);