xref: /linux/kernel/trace/trace_events_user.c (revision 0e2b2a76278153d1ac312b0691cb65dabb9aef3e)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (c) 2021, Microsoft Corporation.
4  *
5  * Authors:
6  *   Beau Belgrave <beaub@linux.microsoft.com>
7  */
8 
9 #include <linux/bitmap.h>
10 #include <linux/cdev.h>
11 #include <linux/hashtable.h>
12 #include <linux/list.h>
13 #include <linux/io.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"
27 #include "trace.h"
28 
29 #define USER_EVENTS_PREFIX_LEN (sizeof(USER_EVENTS_PREFIX)-1)
30 
31 #define FIELD_DEPTH_TYPE 0
32 #define FIELD_DEPTH_NAME 1
33 #define FIELD_DEPTH_SIZE 2
34 
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
39 
40 /*
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.
45  *
46  * These do not reflect the mapped bytes between the user and kernel space.
47  */
48 #define EVENT_STATUS_FTRACE BIT(0)
49 #define EVENT_STATUS_PERF BIT(1)
50 #define EVENT_STATUS_OTHER BIT(7)
51 
52 /*
53  * User register flags are not allowed yet, keep them here until we are
54  * ready to expose them out to the user ABI.
55  */
56 enum user_reg_flag {
57 	/* Event will not delete upon last reference closing */
58 	USER_EVENT_REG_PERSIST		= 1U << 0,
59 
60 	/* This value or above is currently non-ABI */
61 	USER_EVENT_REG_MAX		= 1U << 1,
62 };
63 
64 /*
65  * Stores the system name, tables, and locks for a group of events. This
66  * allows isolation for events by various means.
67  */
68 struct user_event_group {
69 	char		*system_name;
70 	struct		hlist_node node;
71 	struct		mutex reg_mutex;
72 	DECLARE_HASHTABLE(register_table, 8);
73 };
74 
75 /* Group for init_user_ns mapping, top-most group */
76 static struct user_event_group *init_group;
77 
78 /* Max allowed events for the whole system */
79 static unsigned int max_user_events = 32768;
80 
81 /* Current number of events on the whole system */
82 static unsigned int current_user_events;
83 
84 /*
85  * Stores per-event properties, as users register events
86  * within a file a user_event might be created if it does not
87  * already exist. These are globally used and their lifetime
88  * is tied to the refcnt member. These cannot go away until the
89  * refcnt reaches one.
90  */
91 struct user_event {
92 	struct user_event_group		*group;
93 	struct tracepoint		tracepoint;
94 	struct trace_event_call		call;
95 	struct trace_event_class	class;
96 	struct dyn_event		devent;
97 	struct hlist_node		node;
98 	struct list_head		fields;
99 	struct list_head		validators;
100 	struct work_struct		put_work;
101 	refcount_t			refcnt;
102 	int				min_size;
103 	int				reg_flags;
104 	char				status;
105 };
106 
107 /*
108  * Stores per-mm/event properties that enable an address to be
109  * updated properly for each task. As tasks are forked, we use
110  * these to track enablement sites that are tied to an event.
111  */
112 struct user_event_enabler {
113 	struct list_head	mm_enablers_link;
114 	struct user_event	*event;
115 	unsigned long		addr;
116 
117 	/* Track enable bit, flags, etc. Aligned for bitops. */
118 	unsigned long		values;
119 };
120 
121 /* Bits 0-5 are for the bit to update upon enable/disable (0-63 allowed) */
122 #define ENABLE_VAL_BIT_MASK 0x3F
123 
124 /* Bit 6 is for faulting status of enablement */
125 #define ENABLE_VAL_FAULTING_BIT 6
126 
127 /* Bit 7 is for freeing status of enablement */
128 #define ENABLE_VAL_FREEING_BIT 7
129 
130 /* Only duplicate the bit value */
131 #define ENABLE_VAL_DUP_MASK ENABLE_VAL_BIT_MASK
132 
133 #define ENABLE_BITOPS(e) (&(e)->values)
134 
135 #define ENABLE_BIT(e) ((int)((e)->values & ENABLE_VAL_BIT_MASK))
136 
137 /* Used for asynchronous faulting in of pages */
138 struct user_event_enabler_fault {
139 	struct work_struct		work;
140 	struct user_event_mm		*mm;
141 	struct user_event_enabler	*enabler;
142 	int				attempt;
143 };
144 
145 static struct kmem_cache *fault_cache;
146 
147 /* Global list of memory descriptors using user_events */
148 static LIST_HEAD(user_event_mms);
149 static DEFINE_SPINLOCK(user_event_mms_lock);
150 
151 /*
152  * Stores per-file events references, as users register events
153  * within a file this structure is modified and freed via RCU.
154  * The lifetime of this struct is tied to the lifetime of the file.
155  * These are not shared and only accessible by the file that created it.
156  */
157 struct user_event_refs {
158 	struct rcu_head		rcu;
159 	int			count;
160 	struct user_event	*events[];
161 };
162 
163 struct user_event_file_info {
164 	struct user_event_group	*group;
165 	struct user_event_refs	*refs;
166 };
167 
168 #define VALIDATOR_ENSURE_NULL (1 << 0)
169 #define VALIDATOR_REL (1 << 1)
170 
171 struct user_event_validator {
172 	struct list_head	user_event_link;
173 	int			offset;
174 	int			flags;
175 };
176 
177 typedef void (*user_event_func_t) (struct user_event *user, struct iov_iter *i,
178 				   void *tpdata, bool *faulted);
179 
180 static int user_event_parse(struct user_event_group *group, char *name,
181 			    char *args, char *flags,
182 			    struct user_event **newuser, int reg_flags);
183 
184 static struct user_event_mm *user_event_mm_get(struct user_event_mm *mm);
185 static struct user_event_mm *user_event_mm_get_all(struct user_event *user);
186 static void user_event_mm_put(struct user_event_mm *mm);
187 static int destroy_user_event(struct user_event *user);
188 
189 static u32 user_event_key(char *name)
190 {
191 	return jhash(name, strlen(name), 0);
192 }
193 
194 static struct user_event *user_event_get(struct user_event *user)
195 {
196 	refcount_inc(&user->refcnt);
197 
198 	return user;
199 }
200 
201 static void delayed_destroy_user_event(struct work_struct *work)
202 {
203 	struct user_event *user = container_of(
204 		work, struct user_event, put_work);
205 
206 	mutex_lock(&event_mutex);
207 
208 	if (!refcount_dec_and_test(&user->refcnt))
209 		goto out;
210 
211 	if (destroy_user_event(user)) {
212 		/*
213 		 * The only reason this would fail here is if we cannot
214 		 * update the visibility of the event. In this case the
215 		 * event stays in the hashtable, waiting for someone to
216 		 * attempt to delete it later.
217 		 */
218 		pr_warn("user_events: Unable to delete event\n");
219 		refcount_set(&user->refcnt, 1);
220 	}
221 out:
222 	mutex_unlock(&event_mutex);
223 }
224 
225 static void user_event_put(struct user_event *user, bool locked)
226 {
227 	bool delete;
228 
229 	if (unlikely(!user))
230 		return;
231 
232 	/*
233 	 * When the event is not enabled for auto-delete there will always
234 	 * be at least 1 reference to the event. During the event creation
235 	 * we initially set the refcnt to 2 to achieve this. In those cases
236 	 * the caller must acquire event_mutex and after decrement check if
237 	 * the refcnt is 1, meaning this is the last reference. When auto
238 	 * delete is enabled, there will only be 1 ref, IE: refcnt will be
239 	 * only set to 1 during creation to allow the below checks to go
240 	 * through upon the last put. The last put must always be done with
241 	 * the event mutex held.
242 	 */
243 	if (!locked) {
244 		lockdep_assert_not_held(&event_mutex);
245 		delete = refcount_dec_and_mutex_lock(&user->refcnt, &event_mutex);
246 	} else {
247 		lockdep_assert_held(&event_mutex);
248 		delete = refcount_dec_and_test(&user->refcnt);
249 	}
250 
251 	if (!delete)
252 		return;
253 
254 	/*
255 	 * We now have the event_mutex in all cases, which ensures that
256 	 * no new references will be taken until event_mutex is released.
257 	 * New references come through find_user_event(), which requires
258 	 * the event_mutex to be held.
259 	 */
260 
261 	if (user->reg_flags & USER_EVENT_REG_PERSIST) {
262 		/* We should not get here when persist flag is set */
263 		pr_alert("BUG: Auto-delete engaged on persistent event\n");
264 		goto out;
265 	}
266 
267 	/*
268 	 * Unfortunately we have to attempt the actual destroy in a work
269 	 * queue. This is because not all cases handle a trace_event_call
270 	 * being removed within the class->reg() operation for unregister.
271 	 */
272 	INIT_WORK(&user->put_work, delayed_destroy_user_event);
273 
274 	/*
275 	 * Since the event is still in the hashtable, we have to re-inc
276 	 * the ref count to 1. This count will be decremented and checked
277 	 * in the work queue to ensure it's still the last ref. This is
278 	 * needed because a user-process could register the same event in
279 	 * between the time of event_mutex release and the work queue
280 	 * running the delayed destroy. If we removed the item now from
281 	 * the hashtable, this would result in a timing window where a
282 	 * user process would fail a register because the trace_event_call
283 	 * register would fail in the tracing layers.
284 	 */
285 	refcount_set(&user->refcnt, 1);
286 
287 	if (WARN_ON_ONCE(!schedule_work(&user->put_work))) {
288 		/*
289 		 * If we fail we must wait for an admin to attempt delete or
290 		 * another register/close of the event, whichever is first.
291 		 */
292 		pr_warn("user_events: Unable to queue delayed destroy\n");
293 	}
294 out:
295 	/* Ensure if we didn't have event_mutex before we unlock it */
296 	if (!locked)
297 		mutex_unlock(&event_mutex);
298 }
299 
300 static void user_event_group_destroy(struct user_event_group *group)
301 {
302 	kfree(group->system_name);
303 	kfree(group);
304 }
305 
306 static char *user_event_group_system_name(void)
307 {
308 	char *system_name;
309 	int len = sizeof(USER_EVENTS_SYSTEM) + 1;
310 
311 	system_name = kmalloc(len, GFP_KERNEL);
312 
313 	if (!system_name)
314 		return NULL;
315 
316 	snprintf(system_name, len, "%s", USER_EVENTS_SYSTEM);
317 
318 	return system_name;
319 }
320 
321 static struct user_event_group *current_user_event_group(void)
322 {
323 	return init_group;
324 }
325 
326 static struct user_event_group *user_event_group_create(void)
327 {
328 	struct user_event_group *group;
329 
330 	group = kzalloc(sizeof(*group), GFP_KERNEL);
331 
332 	if (!group)
333 		return NULL;
334 
335 	group->system_name = user_event_group_system_name();
336 
337 	if (!group->system_name)
338 		goto error;
339 
340 	mutex_init(&group->reg_mutex);
341 	hash_init(group->register_table);
342 
343 	return group;
344 error:
345 	if (group)
346 		user_event_group_destroy(group);
347 
348 	return NULL;
349 };
350 
351 static void user_event_enabler_destroy(struct user_event_enabler *enabler,
352 				       bool locked)
353 {
354 	list_del_rcu(&enabler->mm_enablers_link);
355 
356 	/* No longer tracking the event via the enabler */
357 	user_event_put(enabler->event, locked);
358 
359 	kfree(enabler);
360 }
361 
362 static int user_event_mm_fault_in(struct user_event_mm *mm, unsigned long uaddr,
363 				  int attempt)
364 {
365 	bool unlocked;
366 	int ret;
367 
368 	/*
369 	 * Normally this is low, ensure that it cannot be taken advantage of by
370 	 * bad user processes to cause excessive looping.
371 	 */
372 	if (attempt > 10)
373 		return -EFAULT;
374 
375 	mmap_read_lock(mm->mm);
376 
377 	/* Ensure MM has tasks, cannot use after exit_mm() */
378 	if (refcount_read(&mm->tasks) == 0) {
379 		ret = -ENOENT;
380 		goto out;
381 	}
382 
383 	ret = fixup_user_fault(mm->mm, uaddr, FAULT_FLAG_WRITE | FAULT_FLAG_REMOTE,
384 			       &unlocked);
385 out:
386 	mmap_read_unlock(mm->mm);
387 
388 	return ret;
389 }
390 
391 static int user_event_enabler_write(struct user_event_mm *mm,
392 				    struct user_event_enabler *enabler,
393 				    bool fixup_fault, int *attempt);
394 
395 static void user_event_enabler_fault_fixup(struct work_struct *work)
396 {
397 	struct user_event_enabler_fault *fault = container_of(
398 		work, struct user_event_enabler_fault, work);
399 	struct user_event_enabler *enabler = fault->enabler;
400 	struct user_event_mm *mm = fault->mm;
401 	unsigned long uaddr = enabler->addr;
402 	int attempt = fault->attempt;
403 	int ret;
404 
405 	ret = user_event_mm_fault_in(mm, uaddr, attempt);
406 
407 	if (ret && ret != -ENOENT) {
408 		struct user_event *user = enabler->event;
409 
410 		pr_warn("user_events: Fault for mm: 0x%pK @ 0x%llx event: %s\n",
411 			mm->mm, (unsigned long long)uaddr, EVENT_NAME(user));
412 	}
413 
414 	/* Prevent state changes from racing */
415 	mutex_lock(&event_mutex);
416 
417 	/* User asked for enabler to be removed during fault */
418 	if (test_bit(ENABLE_VAL_FREEING_BIT, ENABLE_BITOPS(enabler))) {
419 		user_event_enabler_destroy(enabler, true);
420 		goto out;
421 	}
422 
423 	/*
424 	 * If we managed to get the page, re-issue the write. We do not
425 	 * want to get into a possible infinite loop, which is why we only
426 	 * attempt again directly if the page came in. If we couldn't get
427 	 * the page here, then we will try again the next time the event is
428 	 * enabled/disabled.
429 	 */
430 	clear_bit(ENABLE_VAL_FAULTING_BIT, ENABLE_BITOPS(enabler));
431 
432 	if (!ret) {
433 		mmap_read_lock(mm->mm);
434 		user_event_enabler_write(mm, enabler, true, &attempt);
435 		mmap_read_unlock(mm->mm);
436 	}
437 out:
438 	mutex_unlock(&event_mutex);
439 
440 	/* In all cases we no longer need the mm or fault */
441 	user_event_mm_put(mm);
442 	kmem_cache_free(fault_cache, fault);
443 }
444 
445 static bool user_event_enabler_queue_fault(struct user_event_mm *mm,
446 					   struct user_event_enabler *enabler,
447 					   int attempt)
448 {
449 	struct user_event_enabler_fault *fault;
450 
451 	fault = kmem_cache_zalloc(fault_cache, GFP_NOWAIT | __GFP_NOWARN);
452 
453 	if (!fault)
454 		return false;
455 
456 	INIT_WORK(&fault->work, user_event_enabler_fault_fixup);
457 	fault->mm = user_event_mm_get(mm);
458 	fault->enabler = enabler;
459 	fault->attempt = attempt;
460 
461 	/* Don't try to queue in again while we have a pending fault */
462 	set_bit(ENABLE_VAL_FAULTING_BIT, ENABLE_BITOPS(enabler));
463 
464 	if (!schedule_work(&fault->work)) {
465 		/* Allow another attempt later */
466 		clear_bit(ENABLE_VAL_FAULTING_BIT, ENABLE_BITOPS(enabler));
467 
468 		user_event_mm_put(mm);
469 		kmem_cache_free(fault_cache, fault);
470 
471 		return false;
472 	}
473 
474 	return true;
475 }
476 
477 static int user_event_enabler_write(struct user_event_mm *mm,
478 				    struct user_event_enabler *enabler,
479 				    bool fixup_fault, int *attempt)
480 {
481 	unsigned long uaddr = enabler->addr;
482 	unsigned long *ptr;
483 	struct page *page;
484 	void *kaddr;
485 	int ret;
486 
487 	lockdep_assert_held(&event_mutex);
488 	mmap_assert_locked(mm->mm);
489 
490 	*attempt += 1;
491 
492 	/* Ensure MM has tasks, cannot use after exit_mm() */
493 	if (refcount_read(&mm->tasks) == 0)
494 		return -ENOENT;
495 
496 	if (unlikely(test_bit(ENABLE_VAL_FAULTING_BIT, ENABLE_BITOPS(enabler)) ||
497 		     test_bit(ENABLE_VAL_FREEING_BIT, ENABLE_BITOPS(enabler))))
498 		return -EBUSY;
499 
500 	ret = pin_user_pages_remote(mm->mm, uaddr, 1, FOLL_WRITE | FOLL_NOFAULT,
501 				    &page, NULL);
502 
503 	if (unlikely(ret <= 0)) {
504 		if (!fixup_fault)
505 			return -EFAULT;
506 
507 		if (!user_event_enabler_queue_fault(mm, enabler, *attempt))
508 			pr_warn("user_events: Unable to queue fault handler\n");
509 
510 		return -EFAULT;
511 	}
512 
513 	kaddr = kmap_local_page(page);
514 	ptr = kaddr + (uaddr & ~PAGE_MASK);
515 
516 	/* Update bit atomically, user tracers must be atomic as well */
517 	if (enabler->event && enabler->event->status)
518 		set_bit(ENABLE_BIT(enabler), ptr);
519 	else
520 		clear_bit(ENABLE_BIT(enabler), ptr);
521 
522 	kunmap_local(kaddr);
523 	unpin_user_pages_dirty_lock(&page, 1, true);
524 
525 	return 0;
526 }
527 
528 static bool user_event_enabler_exists(struct user_event_mm *mm,
529 				      unsigned long uaddr, unsigned char bit)
530 {
531 	struct user_event_enabler *enabler;
532 
533 	list_for_each_entry(enabler, &mm->enablers, mm_enablers_link) {
534 		if (enabler->addr == uaddr && ENABLE_BIT(enabler) == bit)
535 			return true;
536 	}
537 
538 	return false;
539 }
540 
541 static void user_event_enabler_update(struct user_event *user)
542 {
543 	struct user_event_enabler *enabler;
544 	struct user_event_mm *next;
545 	struct user_event_mm *mm;
546 	int attempt;
547 
548 	lockdep_assert_held(&event_mutex);
549 
550 	/*
551 	 * We need to build a one-shot list of all the mms that have an
552 	 * enabler for the user_event passed in. This list is only valid
553 	 * while holding the event_mutex. The only reason for this is due
554 	 * to the global mm list being RCU protected and we use methods
555 	 * which can wait (mmap_read_lock and pin_user_pages_remote).
556 	 *
557 	 * NOTE: user_event_mm_get_all() increments the ref count of each
558 	 * mm that is added to the list to prevent removal timing windows.
559 	 * We must always put each mm after they are used, which may wait.
560 	 */
561 	mm = user_event_mm_get_all(user);
562 
563 	while (mm) {
564 		next = mm->next;
565 		mmap_read_lock(mm->mm);
566 
567 		list_for_each_entry(enabler, &mm->enablers, mm_enablers_link) {
568 			if (enabler->event == user) {
569 				attempt = 0;
570 				user_event_enabler_write(mm, enabler, true, &attempt);
571 			}
572 		}
573 
574 		mmap_read_unlock(mm->mm);
575 		user_event_mm_put(mm);
576 		mm = next;
577 	}
578 }
579 
580 static bool user_event_enabler_dup(struct user_event_enabler *orig,
581 				   struct user_event_mm *mm)
582 {
583 	struct user_event_enabler *enabler;
584 
585 	/* Skip pending frees */
586 	if (unlikely(test_bit(ENABLE_VAL_FREEING_BIT, ENABLE_BITOPS(orig))))
587 		return true;
588 
589 	enabler = kzalloc(sizeof(*enabler), GFP_NOWAIT | __GFP_ACCOUNT);
590 
591 	if (!enabler)
592 		return false;
593 
594 	enabler->event = user_event_get(orig->event);
595 	enabler->addr = orig->addr;
596 
597 	/* Only dup part of value (ignore future flags, etc) */
598 	enabler->values = orig->values & ENABLE_VAL_DUP_MASK;
599 
600 	/* Enablers not exposed yet, RCU not required */
601 	list_add(&enabler->mm_enablers_link, &mm->enablers);
602 
603 	return true;
604 }
605 
606 static struct user_event_mm *user_event_mm_get(struct user_event_mm *mm)
607 {
608 	refcount_inc(&mm->refcnt);
609 
610 	return mm;
611 }
612 
613 static struct user_event_mm *user_event_mm_get_all(struct user_event *user)
614 {
615 	struct user_event_mm *found = NULL;
616 	struct user_event_enabler *enabler;
617 	struct user_event_mm *mm;
618 
619 	/*
620 	 * We use the mm->next field to build a one-shot list from the global
621 	 * RCU protected list. To build this list the event_mutex must be held.
622 	 * This lets us build a list without requiring allocs that could fail
623 	 * when user based events are most wanted for diagnostics.
624 	 */
625 	lockdep_assert_held(&event_mutex);
626 
627 	/*
628 	 * We do not want to block fork/exec while enablements are being
629 	 * updated, so we use RCU to walk the current tasks that have used
630 	 * user_events ABI for 1 or more events. Each enabler found in each
631 	 * task that matches the event being updated has a write to reflect
632 	 * the kernel state back into the process. Waits/faults must not occur
633 	 * during this. So we scan the list under RCU for all the mm that have
634 	 * the event within it. This is needed because mm_read_lock() can wait.
635 	 * Each user mm returned has a ref inc to handle remove RCU races.
636 	 */
637 	rcu_read_lock();
638 
639 	list_for_each_entry_rcu(mm, &user_event_mms, mms_link) {
640 		list_for_each_entry_rcu(enabler, &mm->enablers, mm_enablers_link) {
641 			if (enabler->event == user) {
642 				mm->next = found;
643 				found = user_event_mm_get(mm);
644 				break;
645 			}
646 		}
647 	}
648 
649 	rcu_read_unlock();
650 
651 	return found;
652 }
653 
654 static struct user_event_mm *user_event_mm_alloc(struct task_struct *t)
655 {
656 	struct user_event_mm *user_mm;
657 
658 	user_mm = kzalloc(sizeof(*user_mm), GFP_KERNEL_ACCOUNT);
659 
660 	if (!user_mm)
661 		return NULL;
662 
663 	user_mm->mm = t->mm;
664 	INIT_LIST_HEAD(&user_mm->enablers);
665 	refcount_set(&user_mm->refcnt, 1);
666 	refcount_set(&user_mm->tasks, 1);
667 
668 	/*
669 	 * The lifetime of the memory descriptor can slightly outlast
670 	 * the task lifetime if a ref to the user_event_mm is taken
671 	 * between list_del_rcu() and call_rcu(). Therefore we need
672 	 * to take a reference to it to ensure it can live this long
673 	 * under this corner case. This can also occur in clones that
674 	 * outlast the parent.
675 	 */
676 	mmgrab(user_mm->mm);
677 
678 	return user_mm;
679 }
680 
681 static void user_event_mm_attach(struct user_event_mm *user_mm, struct task_struct *t)
682 {
683 	unsigned long flags;
684 
685 	spin_lock_irqsave(&user_event_mms_lock, flags);
686 	list_add_rcu(&user_mm->mms_link, &user_event_mms);
687 	spin_unlock_irqrestore(&user_event_mms_lock, flags);
688 
689 	t->user_event_mm = user_mm;
690 }
691 
692 static struct user_event_mm *current_user_event_mm(void)
693 {
694 	struct user_event_mm *user_mm = current->user_event_mm;
695 
696 	if (user_mm)
697 		goto inc;
698 
699 	user_mm = user_event_mm_alloc(current);
700 
701 	if (!user_mm)
702 		goto error;
703 
704 	user_event_mm_attach(user_mm, current);
705 inc:
706 	refcount_inc(&user_mm->refcnt);
707 error:
708 	return user_mm;
709 }
710 
711 static void user_event_mm_destroy(struct user_event_mm *mm)
712 {
713 	struct user_event_enabler *enabler, *next;
714 
715 	list_for_each_entry_safe(enabler, next, &mm->enablers, mm_enablers_link)
716 		user_event_enabler_destroy(enabler, false);
717 
718 	mmdrop(mm->mm);
719 	kfree(mm);
720 }
721 
722 static void user_event_mm_put(struct user_event_mm *mm)
723 {
724 	if (mm && refcount_dec_and_test(&mm->refcnt))
725 		user_event_mm_destroy(mm);
726 }
727 
728 static void delayed_user_event_mm_put(struct work_struct *work)
729 {
730 	struct user_event_mm *mm;
731 
732 	mm = container_of(to_rcu_work(work), struct user_event_mm, put_rwork);
733 	user_event_mm_put(mm);
734 }
735 
736 void user_event_mm_remove(struct task_struct *t)
737 {
738 	struct user_event_mm *mm;
739 	unsigned long flags;
740 
741 	might_sleep();
742 
743 	mm = t->user_event_mm;
744 	t->user_event_mm = NULL;
745 
746 	/* Clone will increment the tasks, only remove if last clone */
747 	if (!refcount_dec_and_test(&mm->tasks))
748 		return;
749 
750 	/* Remove the mm from the list, so it can no longer be enabled */
751 	spin_lock_irqsave(&user_event_mms_lock, flags);
752 	list_del_rcu(&mm->mms_link);
753 	spin_unlock_irqrestore(&user_event_mms_lock, flags);
754 
755 	/*
756 	 * We need to wait for currently occurring writes to stop within
757 	 * the mm. This is required since exit_mm() snaps the current rss
758 	 * stats and clears them. On the final mmdrop(), check_mm() will
759 	 * report a bug if these increment.
760 	 *
761 	 * All writes/pins are done under mmap_read lock, take the write
762 	 * lock to ensure in-progress faults have completed. Faults that
763 	 * are pending but yet to run will check the task count and skip
764 	 * the fault since the mm is going away.
765 	 */
766 	mmap_write_lock(mm->mm);
767 	mmap_write_unlock(mm->mm);
768 
769 	/*
770 	 * Put for mm must be done after RCU delay to handle new refs in
771 	 * between the list_del_rcu() and now. This ensures any get refs
772 	 * during rcu_read_lock() are accounted for during list removal.
773 	 *
774 	 * CPU A			|	CPU B
775 	 * ---------------------------------------------------------------
776 	 * user_event_mm_remove()	|	rcu_read_lock();
777 	 * list_del_rcu()		|	list_for_each_entry_rcu();
778 	 * call_rcu()			|	refcount_inc();
779 	 * .				|	rcu_read_unlock();
780 	 * schedule_work()		|	.
781 	 * user_event_mm_put()		|	.
782 	 *
783 	 * mmdrop() cannot be called in the softirq context of call_rcu()
784 	 * so we use a work queue after call_rcu() to run within.
785 	 */
786 	INIT_RCU_WORK(&mm->put_rwork, delayed_user_event_mm_put);
787 	queue_rcu_work(system_wq, &mm->put_rwork);
788 }
789 
790 void user_event_mm_dup(struct task_struct *t, struct user_event_mm *old_mm)
791 {
792 	struct user_event_mm *mm = user_event_mm_alloc(t);
793 	struct user_event_enabler *enabler;
794 
795 	if (!mm)
796 		return;
797 
798 	rcu_read_lock();
799 
800 	list_for_each_entry_rcu(enabler, &old_mm->enablers, mm_enablers_link) {
801 		if (!user_event_enabler_dup(enabler, mm))
802 			goto error;
803 	}
804 
805 	rcu_read_unlock();
806 
807 	user_event_mm_attach(mm, t);
808 	return;
809 error:
810 	rcu_read_unlock();
811 	user_event_mm_destroy(mm);
812 }
813 
814 static bool current_user_event_enabler_exists(unsigned long uaddr,
815 					      unsigned char bit)
816 {
817 	struct user_event_mm *user_mm = current_user_event_mm();
818 	bool exists;
819 
820 	if (!user_mm)
821 		return false;
822 
823 	exists = user_event_enabler_exists(user_mm, uaddr, bit);
824 
825 	user_event_mm_put(user_mm);
826 
827 	return exists;
828 }
829 
830 static struct user_event_enabler
831 *user_event_enabler_create(struct user_reg *reg, struct user_event *user,
832 			   int *write_result)
833 {
834 	struct user_event_enabler *enabler;
835 	struct user_event_mm *user_mm;
836 	unsigned long uaddr = (unsigned long)reg->enable_addr;
837 	int attempt = 0;
838 
839 	user_mm = current_user_event_mm();
840 
841 	if (!user_mm)
842 		return NULL;
843 
844 	enabler = kzalloc(sizeof(*enabler), GFP_KERNEL_ACCOUNT);
845 
846 	if (!enabler)
847 		goto out;
848 
849 	enabler->event = user;
850 	enabler->addr = uaddr;
851 	enabler->values = reg->enable_bit;
852 retry:
853 	/* Prevents state changes from racing with new enablers */
854 	mutex_lock(&event_mutex);
855 
856 	/* Attempt to reflect the current state within the process */
857 	mmap_read_lock(user_mm->mm);
858 	*write_result = user_event_enabler_write(user_mm, enabler, false,
859 						 &attempt);
860 	mmap_read_unlock(user_mm->mm);
861 
862 	/*
863 	 * If the write works, then we will track the enabler. A ref to the
864 	 * underlying user_event is held by the enabler to prevent it going
865 	 * away while the enabler is still in use by a process. The ref is
866 	 * removed when the enabler is destroyed. This means a event cannot
867 	 * be forcefully deleted from the system until all tasks using it
868 	 * exit or run exec(), which includes forks and clones.
869 	 */
870 	if (!*write_result) {
871 		user_event_get(user);
872 		list_add_rcu(&enabler->mm_enablers_link, &user_mm->enablers);
873 	}
874 
875 	mutex_unlock(&event_mutex);
876 
877 	if (*write_result) {
878 		/* Attempt to fault-in and retry if it worked */
879 		if (!user_event_mm_fault_in(user_mm, uaddr, attempt))
880 			goto retry;
881 
882 		kfree(enabler);
883 		enabler = NULL;
884 	}
885 out:
886 	user_event_mm_put(user_mm);
887 
888 	return enabler;
889 }
890 
891 static __always_inline __must_check
892 bool user_event_last_ref(struct user_event *user)
893 {
894 	int last = 0;
895 
896 	if (user->reg_flags & USER_EVENT_REG_PERSIST)
897 		last = 1;
898 
899 	return refcount_read(&user->refcnt) == last;
900 }
901 
902 static __always_inline __must_check
903 size_t copy_nofault(void *addr, size_t bytes, struct iov_iter *i)
904 {
905 	size_t ret;
906 
907 	pagefault_disable();
908 
909 	ret = copy_from_iter_nocache(addr, bytes, i);
910 
911 	pagefault_enable();
912 
913 	return ret;
914 }
915 
916 static struct list_head *user_event_get_fields(struct trace_event_call *call)
917 {
918 	struct user_event *user = (struct user_event *)call->data;
919 
920 	return &user->fields;
921 }
922 
923 /*
924  * Parses a register command for user_events
925  * Format: event_name[:FLAG1[,FLAG2...]] [field1[;field2...]]
926  *
927  * Example event named 'test' with a 20 char 'msg' field with an unsigned int
928  * 'id' field after:
929  * test char[20] msg;unsigned int id
930  *
931  * NOTE: Offsets are from the user data perspective, they are not from the
932  * trace_entry/buffer perspective. We automatically add the common properties
933  * sizes to the offset for the user.
934  *
935  * Upon success user_event has its ref count increased by 1.
936  */
937 static int user_event_parse_cmd(struct user_event_group *group,
938 				char *raw_command, struct user_event **newuser,
939 				int reg_flags)
940 {
941 	char *name = raw_command;
942 	char *args = strpbrk(name, " ");
943 	char *flags;
944 
945 	if (args)
946 		*args++ = '\0';
947 
948 	flags = strpbrk(name, ":");
949 
950 	if (flags)
951 		*flags++ = '\0';
952 
953 	return user_event_parse(group, name, args, flags, newuser, reg_flags);
954 }
955 
956 static int user_field_array_size(const char *type)
957 {
958 	const char *start = strchr(type, '[');
959 	char val[8];
960 	char *bracket;
961 	int size = 0;
962 
963 	if (start == NULL)
964 		return -EINVAL;
965 
966 	if (strscpy(val, start + 1, sizeof(val)) <= 0)
967 		return -EINVAL;
968 
969 	bracket = strchr(val, ']');
970 
971 	if (!bracket)
972 		return -EINVAL;
973 
974 	*bracket = '\0';
975 
976 	if (kstrtouint(val, 0, &size))
977 		return -EINVAL;
978 
979 	if (size > MAX_FIELD_ARRAY_SIZE)
980 		return -EINVAL;
981 
982 	return size;
983 }
984 
985 static int user_field_size(const char *type)
986 {
987 	/* long is not allowed from a user, since it's ambigious in size */
988 	if (strcmp(type, "s64") == 0)
989 		return sizeof(s64);
990 	if (strcmp(type, "u64") == 0)
991 		return sizeof(u64);
992 	if (strcmp(type, "s32") == 0)
993 		return sizeof(s32);
994 	if (strcmp(type, "u32") == 0)
995 		return sizeof(u32);
996 	if (strcmp(type, "int") == 0)
997 		return sizeof(int);
998 	if (strcmp(type, "unsigned int") == 0)
999 		return sizeof(unsigned int);
1000 	if (strcmp(type, "s16") == 0)
1001 		return sizeof(s16);
1002 	if (strcmp(type, "u16") == 0)
1003 		return sizeof(u16);
1004 	if (strcmp(type, "short") == 0)
1005 		return sizeof(short);
1006 	if (strcmp(type, "unsigned short") == 0)
1007 		return sizeof(unsigned short);
1008 	if (strcmp(type, "s8") == 0)
1009 		return sizeof(s8);
1010 	if (strcmp(type, "u8") == 0)
1011 		return sizeof(u8);
1012 	if (strcmp(type, "char") == 0)
1013 		return sizeof(char);
1014 	if (strcmp(type, "unsigned char") == 0)
1015 		return sizeof(unsigned char);
1016 	if (str_has_prefix(type, "char["))
1017 		return user_field_array_size(type);
1018 	if (str_has_prefix(type, "unsigned char["))
1019 		return user_field_array_size(type);
1020 	if (str_has_prefix(type, "__data_loc "))
1021 		return sizeof(u32);
1022 	if (str_has_prefix(type, "__rel_loc "))
1023 		return sizeof(u32);
1024 
1025 	/* Uknown basic type, error */
1026 	return -EINVAL;
1027 }
1028 
1029 static void user_event_destroy_validators(struct user_event *user)
1030 {
1031 	struct user_event_validator *validator, *next;
1032 	struct list_head *head = &user->validators;
1033 
1034 	list_for_each_entry_safe(validator, next, head, user_event_link) {
1035 		list_del(&validator->user_event_link);
1036 		kfree(validator);
1037 	}
1038 }
1039 
1040 static void user_event_destroy_fields(struct user_event *user)
1041 {
1042 	struct ftrace_event_field *field, *next;
1043 	struct list_head *head = &user->fields;
1044 
1045 	list_for_each_entry_safe(field, next, head, link) {
1046 		list_del(&field->link);
1047 		kfree(field);
1048 	}
1049 }
1050 
1051 static int user_event_add_field(struct user_event *user, const char *type,
1052 				const char *name, int offset, int size,
1053 				int is_signed, int filter_type)
1054 {
1055 	struct user_event_validator *validator;
1056 	struct ftrace_event_field *field;
1057 	int validator_flags = 0;
1058 
1059 	field = kmalloc(sizeof(*field), GFP_KERNEL_ACCOUNT);
1060 
1061 	if (!field)
1062 		return -ENOMEM;
1063 
1064 	if (str_has_prefix(type, "__data_loc "))
1065 		goto add_validator;
1066 
1067 	if (str_has_prefix(type, "__rel_loc ")) {
1068 		validator_flags |= VALIDATOR_REL;
1069 		goto add_validator;
1070 	}
1071 
1072 	goto add_field;
1073 
1074 add_validator:
1075 	if (strstr(type, "char") != NULL)
1076 		validator_flags |= VALIDATOR_ENSURE_NULL;
1077 
1078 	validator = kmalloc(sizeof(*validator), GFP_KERNEL_ACCOUNT);
1079 
1080 	if (!validator) {
1081 		kfree(field);
1082 		return -ENOMEM;
1083 	}
1084 
1085 	validator->flags = validator_flags;
1086 	validator->offset = offset;
1087 
1088 	/* Want sequential access when validating */
1089 	list_add_tail(&validator->user_event_link, &user->validators);
1090 
1091 add_field:
1092 	field->type = type;
1093 	field->name = name;
1094 	field->offset = offset;
1095 	field->size = size;
1096 	field->is_signed = is_signed;
1097 	field->filter_type = filter_type;
1098 
1099 	if (filter_type == FILTER_OTHER)
1100 		field->filter_type = filter_assign_type(type);
1101 
1102 	list_add(&field->link, &user->fields);
1103 
1104 	/*
1105 	 * Min size from user writes that are required, this does not include
1106 	 * the size of trace_entry (common fields).
1107 	 */
1108 	user->min_size = (offset + size) - sizeof(struct trace_entry);
1109 
1110 	return 0;
1111 }
1112 
1113 /*
1114  * Parses the values of a field within the description
1115  * Format: type name [size]
1116  */
1117 static int user_event_parse_field(char *field, struct user_event *user,
1118 				  u32 *offset)
1119 {
1120 	char *part, *type, *name;
1121 	u32 depth = 0, saved_offset = *offset;
1122 	int len, size = -EINVAL;
1123 	bool is_struct = false;
1124 
1125 	field = skip_spaces(field);
1126 
1127 	if (*field == '\0')
1128 		return 0;
1129 
1130 	/* Handle types that have a space within */
1131 	len = str_has_prefix(field, "unsigned ");
1132 	if (len)
1133 		goto skip_next;
1134 
1135 	len = str_has_prefix(field, "struct ");
1136 	if (len) {
1137 		is_struct = true;
1138 		goto skip_next;
1139 	}
1140 
1141 	len = str_has_prefix(field, "__data_loc unsigned ");
1142 	if (len)
1143 		goto skip_next;
1144 
1145 	len = str_has_prefix(field, "__data_loc ");
1146 	if (len)
1147 		goto skip_next;
1148 
1149 	len = str_has_prefix(field, "__rel_loc unsigned ");
1150 	if (len)
1151 		goto skip_next;
1152 
1153 	len = str_has_prefix(field, "__rel_loc ");
1154 	if (len)
1155 		goto skip_next;
1156 
1157 	goto parse;
1158 skip_next:
1159 	type = field;
1160 	field = strpbrk(field + len, " ");
1161 
1162 	if (field == NULL)
1163 		return -EINVAL;
1164 
1165 	*field++ = '\0';
1166 	depth++;
1167 parse:
1168 	name = NULL;
1169 
1170 	while ((part = strsep(&field, " ")) != NULL) {
1171 		switch (depth++) {
1172 		case FIELD_DEPTH_TYPE:
1173 			type = part;
1174 			break;
1175 		case FIELD_DEPTH_NAME:
1176 			name = part;
1177 			break;
1178 		case FIELD_DEPTH_SIZE:
1179 			if (!is_struct)
1180 				return -EINVAL;
1181 
1182 			if (kstrtou32(part, 10, &size))
1183 				return -EINVAL;
1184 			break;
1185 		default:
1186 			return -EINVAL;
1187 		}
1188 	}
1189 
1190 	if (depth < FIELD_DEPTH_SIZE || !name)
1191 		return -EINVAL;
1192 
1193 	if (depth == FIELD_DEPTH_SIZE)
1194 		size = user_field_size(type);
1195 
1196 	if (size == 0)
1197 		return -EINVAL;
1198 
1199 	if (size < 0)
1200 		return size;
1201 
1202 	*offset = saved_offset + size;
1203 
1204 	return user_event_add_field(user, type, name, saved_offset, size,
1205 				    type[0] != 'u', FILTER_OTHER);
1206 }
1207 
1208 static int user_event_parse_fields(struct user_event *user, char *args)
1209 {
1210 	char *field;
1211 	u32 offset = sizeof(struct trace_entry);
1212 	int ret = -EINVAL;
1213 
1214 	if (args == NULL)
1215 		return 0;
1216 
1217 	while ((field = strsep(&args, ";")) != NULL) {
1218 		ret = user_event_parse_field(field, user, &offset);
1219 
1220 		if (ret)
1221 			break;
1222 	}
1223 
1224 	return ret;
1225 }
1226 
1227 static struct trace_event_fields user_event_fields_array[1];
1228 
1229 static const char *user_field_format(const char *type)
1230 {
1231 	if (strcmp(type, "s64") == 0)
1232 		return "%lld";
1233 	if (strcmp(type, "u64") == 0)
1234 		return "%llu";
1235 	if (strcmp(type, "s32") == 0)
1236 		return "%d";
1237 	if (strcmp(type, "u32") == 0)
1238 		return "%u";
1239 	if (strcmp(type, "int") == 0)
1240 		return "%d";
1241 	if (strcmp(type, "unsigned int") == 0)
1242 		return "%u";
1243 	if (strcmp(type, "s16") == 0)
1244 		return "%d";
1245 	if (strcmp(type, "u16") == 0)
1246 		return "%u";
1247 	if (strcmp(type, "short") == 0)
1248 		return "%d";
1249 	if (strcmp(type, "unsigned short") == 0)
1250 		return "%u";
1251 	if (strcmp(type, "s8") == 0)
1252 		return "%d";
1253 	if (strcmp(type, "u8") == 0)
1254 		return "%u";
1255 	if (strcmp(type, "char") == 0)
1256 		return "%d";
1257 	if (strcmp(type, "unsigned char") == 0)
1258 		return "%u";
1259 	if (strstr(type, "char[") != NULL)
1260 		return "%s";
1261 
1262 	/* Unknown, likely struct, allowed treat as 64-bit */
1263 	return "%llu";
1264 }
1265 
1266 static bool user_field_is_dyn_string(const char *type, const char **str_func)
1267 {
1268 	if (str_has_prefix(type, "__data_loc ")) {
1269 		*str_func = "__get_str";
1270 		goto check;
1271 	}
1272 
1273 	if (str_has_prefix(type, "__rel_loc ")) {
1274 		*str_func = "__get_rel_str";
1275 		goto check;
1276 	}
1277 
1278 	return false;
1279 check:
1280 	return strstr(type, "char") != NULL;
1281 }
1282 
1283 #define LEN_OR_ZERO (len ? len - pos : 0)
1284 static int user_dyn_field_set_string(int argc, const char **argv, int *iout,
1285 				     char *buf, int len, bool *colon)
1286 {
1287 	int pos = 0, i = *iout;
1288 
1289 	*colon = false;
1290 
1291 	for (; i < argc; ++i) {
1292 		if (i != *iout)
1293 			pos += snprintf(buf + pos, LEN_OR_ZERO, " ");
1294 
1295 		pos += snprintf(buf + pos, LEN_OR_ZERO, "%s", argv[i]);
1296 
1297 		if (strchr(argv[i], ';')) {
1298 			++i;
1299 			*colon = true;
1300 			break;
1301 		}
1302 	}
1303 
1304 	/* Actual set, advance i */
1305 	if (len != 0)
1306 		*iout = i;
1307 
1308 	return pos + 1;
1309 }
1310 
1311 static int user_field_set_string(struct ftrace_event_field *field,
1312 				 char *buf, int len, bool colon)
1313 {
1314 	int pos = 0;
1315 
1316 	pos += snprintf(buf + pos, LEN_OR_ZERO, "%s", field->type);
1317 	pos += snprintf(buf + pos, LEN_OR_ZERO, " ");
1318 	pos += snprintf(buf + pos, LEN_OR_ZERO, "%s", field->name);
1319 
1320 	if (colon)
1321 		pos += snprintf(buf + pos, LEN_OR_ZERO, ";");
1322 
1323 	return pos + 1;
1324 }
1325 
1326 static int user_event_set_print_fmt(struct user_event *user, char *buf, int len)
1327 {
1328 	struct ftrace_event_field *field, *next;
1329 	struct list_head *head = &user->fields;
1330 	int pos = 0, depth = 0;
1331 	const char *str_func;
1332 
1333 	pos += snprintf(buf + pos, LEN_OR_ZERO, "\"");
1334 
1335 	list_for_each_entry_safe_reverse(field, next, head, link) {
1336 		if (depth != 0)
1337 			pos += snprintf(buf + pos, LEN_OR_ZERO, " ");
1338 
1339 		pos += snprintf(buf + pos, LEN_OR_ZERO, "%s=%s",
1340 				field->name, user_field_format(field->type));
1341 
1342 		depth++;
1343 	}
1344 
1345 	pos += snprintf(buf + pos, LEN_OR_ZERO, "\"");
1346 
1347 	list_for_each_entry_safe_reverse(field, next, head, link) {
1348 		if (user_field_is_dyn_string(field->type, &str_func))
1349 			pos += snprintf(buf + pos, LEN_OR_ZERO,
1350 					", %s(%s)", str_func, field->name);
1351 		else
1352 			pos += snprintf(buf + pos, LEN_OR_ZERO,
1353 					", REC->%s", field->name);
1354 	}
1355 
1356 	return pos + 1;
1357 }
1358 #undef LEN_OR_ZERO
1359 
1360 static int user_event_create_print_fmt(struct user_event *user)
1361 {
1362 	char *print_fmt;
1363 	int len;
1364 
1365 	len = user_event_set_print_fmt(user, NULL, 0);
1366 
1367 	print_fmt = kmalloc(len, GFP_KERNEL_ACCOUNT);
1368 
1369 	if (!print_fmt)
1370 		return -ENOMEM;
1371 
1372 	user_event_set_print_fmt(user, print_fmt, len);
1373 
1374 	user->call.print_fmt = print_fmt;
1375 
1376 	return 0;
1377 }
1378 
1379 static enum print_line_t user_event_print_trace(struct trace_iterator *iter,
1380 						int flags,
1381 						struct trace_event *event)
1382 {
1383 	return print_event_fields(iter, event);
1384 }
1385 
1386 static struct trace_event_functions user_event_funcs = {
1387 	.trace = user_event_print_trace,
1388 };
1389 
1390 static int user_event_set_call_visible(struct user_event *user, bool visible)
1391 {
1392 	int ret;
1393 	const struct cred *old_cred;
1394 	struct cred *cred;
1395 
1396 	cred = prepare_creds();
1397 
1398 	if (!cred)
1399 		return -ENOMEM;
1400 
1401 	/*
1402 	 * While by default tracefs is locked down, systems can be configured
1403 	 * to allow user_event files to be less locked down. The extreme case
1404 	 * being "other" has read/write access to user_events_data/status.
1405 	 *
1406 	 * When not locked down, processes may not have permissions to
1407 	 * add/remove calls themselves to tracefs. We need to temporarily
1408 	 * switch to root file permission to allow for this scenario.
1409 	 */
1410 	cred->fsuid = GLOBAL_ROOT_UID;
1411 
1412 	old_cred = override_creds(cred);
1413 
1414 	if (visible)
1415 		ret = trace_add_event_call(&user->call);
1416 	else
1417 		ret = trace_remove_event_call(&user->call);
1418 
1419 	revert_creds(old_cred);
1420 	put_cred(cred);
1421 
1422 	return ret;
1423 }
1424 
1425 static int destroy_user_event(struct user_event *user)
1426 {
1427 	int ret = 0;
1428 
1429 	lockdep_assert_held(&event_mutex);
1430 
1431 	/* Must destroy fields before call removal */
1432 	user_event_destroy_fields(user);
1433 
1434 	ret = user_event_set_call_visible(user, false);
1435 
1436 	if (ret)
1437 		return ret;
1438 
1439 	dyn_event_remove(&user->devent);
1440 	hash_del(&user->node);
1441 
1442 	user_event_destroy_validators(user);
1443 	kfree(user->call.print_fmt);
1444 	kfree(EVENT_NAME(user));
1445 	kfree(user);
1446 
1447 	if (current_user_events > 0)
1448 		current_user_events--;
1449 	else
1450 		pr_alert("BUG: Bad current_user_events\n");
1451 
1452 	return ret;
1453 }
1454 
1455 static struct user_event *find_user_event(struct user_event_group *group,
1456 					  char *name, u32 *outkey)
1457 {
1458 	struct user_event *user;
1459 	u32 key = user_event_key(name);
1460 
1461 	*outkey = key;
1462 
1463 	hash_for_each_possible(group->register_table, user, node, key)
1464 		if (!strcmp(EVENT_NAME(user), name))
1465 			return user_event_get(user);
1466 
1467 	return NULL;
1468 }
1469 
1470 static int user_event_validate(struct user_event *user, void *data, int len)
1471 {
1472 	struct list_head *head = &user->validators;
1473 	struct user_event_validator *validator;
1474 	void *pos, *end = data + len;
1475 	u32 loc, offset, size;
1476 
1477 	list_for_each_entry(validator, head, user_event_link) {
1478 		pos = data + validator->offset;
1479 
1480 		/* Already done min_size check, no bounds check here */
1481 		loc = *(u32 *)pos;
1482 		offset = loc & 0xffff;
1483 		size = loc >> 16;
1484 
1485 		if (likely(validator->flags & VALIDATOR_REL))
1486 			pos += offset + sizeof(loc);
1487 		else
1488 			pos = data + offset;
1489 
1490 		pos += size;
1491 
1492 		if (unlikely(pos > end))
1493 			return -EFAULT;
1494 
1495 		if (likely(validator->flags & VALIDATOR_ENSURE_NULL))
1496 			if (unlikely(*(char *)(pos - 1) != '\0'))
1497 				return -EFAULT;
1498 	}
1499 
1500 	return 0;
1501 }
1502 
1503 /*
1504  * Writes the user supplied payload out to a trace file.
1505  */
1506 static void user_event_ftrace(struct user_event *user, struct iov_iter *i,
1507 			      void *tpdata, bool *faulted)
1508 {
1509 	struct trace_event_file *file;
1510 	struct trace_entry *entry;
1511 	struct trace_event_buffer event_buffer;
1512 	size_t size = sizeof(*entry) + i->count;
1513 
1514 	file = (struct trace_event_file *)tpdata;
1515 
1516 	if (!file ||
1517 	    !(file->flags & EVENT_FILE_FL_ENABLED) ||
1518 	    trace_trigger_soft_disabled(file))
1519 		return;
1520 
1521 	/* Allocates and fills trace_entry, + 1 of this is data payload */
1522 	entry = trace_event_buffer_reserve(&event_buffer, file, size);
1523 
1524 	if (unlikely(!entry))
1525 		return;
1526 
1527 	if (unlikely(i->count != 0 && !copy_nofault(entry + 1, i->count, i)))
1528 		goto discard;
1529 
1530 	if (!list_empty(&user->validators) &&
1531 	    unlikely(user_event_validate(user, entry, size)))
1532 		goto discard;
1533 
1534 	trace_event_buffer_commit(&event_buffer);
1535 
1536 	return;
1537 discard:
1538 	*faulted = true;
1539 	__trace_event_discard_commit(event_buffer.buffer,
1540 				     event_buffer.event);
1541 }
1542 
1543 #ifdef CONFIG_PERF_EVENTS
1544 /*
1545  * Writes the user supplied payload out to perf ring buffer.
1546  */
1547 static void user_event_perf(struct user_event *user, struct iov_iter *i,
1548 			    void *tpdata, bool *faulted)
1549 {
1550 	struct hlist_head *perf_head;
1551 
1552 	perf_head = this_cpu_ptr(user->call.perf_events);
1553 
1554 	if (perf_head && !hlist_empty(perf_head)) {
1555 		struct trace_entry *perf_entry;
1556 		struct pt_regs *regs;
1557 		size_t size = sizeof(*perf_entry) + i->count;
1558 		int context;
1559 
1560 		perf_entry = perf_trace_buf_alloc(ALIGN(size, 8),
1561 						  &regs, &context);
1562 
1563 		if (unlikely(!perf_entry))
1564 			return;
1565 
1566 		perf_fetch_caller_regs(regs);
1567 
1568 		if (unlikely(i->count != 0 && !copy_nofault(perf_entry + 1, i->count, i)))
1569 			goto discard;
1570 
1571 		if (!list_empty(&user->validators) &&
1572 		    unlikely(user_event_validate(user, perf_entry, size)))
1573 			goto discard;
1574 
1575 		perf_trace_buf_submit(perf_entry, size, context,
1576 				      user->call.event.type, 1, regs,
1577 				      perf_head, NULL);
1578 
1579 		return;
1580 discard:
1581 		*faulted = true;
1582 		perf_swevent_put_recursion_context(context);
1583 	}
1584 }
1585 #endif
1586 
1587 /*
1588  * Update the enabled bit among all user processes.
1589  */
1590 static void update_enable_bit_for(struct user_event *user)
1591 {
1592 	struct tracepoint *tp = &user->tracepoint;
1593 	char status = 0;
1594 
1595 	if (atomic_read(&tp->key.enabled) > 0) {
1596 		struct tracepoint_func *probe_func_ptr;
1597 		user_event_func_t probe_func;
1598 
1599 		rcu_read_lock_sched();
1600 
1601 		probe_func_ptr = rcu_dereference_sched(tp->funcs);
1602 
1603 		if (probe_func_ptr) {
1604 			do {
1605 				probe_func = probe_func_ptr->func;
1606 
1607 				if (probe_func == user_event_ftrace)
1608 					status |= EVENT_STATUS_FTRACE;
1609 #ifdef CONFIG_PERF_EVENTS
1610 				else if (probe_func == user_event_perf)
1611 					status |= EVENT_STATUS_PERF;
1612 #endif
1613 				else
1614 					status |= EVENT_STATUS_OTHER;
1615 			} while ((++probe_func_ptr)->func);
1616 		}
1617 
1618 		rcu_read_unlock_sched();
1619 	}
1620 
1621 	user->status = status;
1622 
1623 	user_event_enabler_update(user);
1624 }
1625 
1626 /*
1627  * Register callback for our events from tracing sub-systems.
1628  */
1629 static int user_event_reg(struct trace_event_call *call,
1630 			  enum trace_reg type,
1631 			  void *data)
1632 {
1633 	struct user_event *user = (struct user_event *)call->data;
1634 	int ret = 0;
1635 
1636 	if (!user)
1637 		return -ENOENT;
1638 
1639 	switch (type) {
1640 	case TRACE_REG_REGISTER:
1641 		ret = tracepoint_probe_register(call->tp,
1642 						call->class->probe,
1643 						data);
1644 		if (!ret)
1645 			goto inc;
1646 		break;
1647 
1648 	case TRACE_REG_UNREGISTER:
1649 		tracepoint_probe_unregister(call->tp,
1650 					    call->class->probe,
1651 					    data);
1652 		goto dec;
1653 
1654 #ifdef CONFIG_PERF_EVENTS
1655 	case TRACE_REG_PERF_REGISTER:
1656 		ret = tracepoint_probe_register(call->tp,
1657 						call->class->perf_probe,
1658 						data);
1659 		if (!ret)
1660 			goto inc;
1661 		break;
1662 
1663 	case TRACE_REG_PERF_UNREGISTER:
1664 		tracepoint_probe_unregister(call->tp,
1665 					    call->class->perf_probe,
1666 					    data);
1667 		goto dec;
1668 
1669 	case TRACE_REG_PERF_OPEN:
1670 	case TRACE_REG_PERF_CLOSE:
1671 	case TRACE_REG_PERF_ADD:
1672 	case TRACE_REG_PERF_DEL:
1673 		break;
1674 #endif
1675 	}
1676 
1677 	return ret;
1678 inc:
1679 	user_event_get(user);
1680 	update_enable_bit_for(user);
1681 	return 0;
1682 dec:
1683 	update_enable_bit_for(user);
1684 	user_event_put(user, true);
1685 	return 0;
1686 }
1687 
1688 static int user_event_create(const char *raw_command)
1689 {
1690 	struct user_event_group *group;
1691 	struct user_event *user;
1692 	char *name;
1693 	int ret;
1694 
1695 	if (!str_has_prefix(raw_command, USER_EVENTS_PREFIX))
1696 		return -ECANCELED;
1697 
1698 	raw_command += USER_EVENTS_PREFIX_LEN;
1699 	raw_command = skip_spaces(raw_command);
1700 
1701 	name = kstrdup(raw_command, GFP_KERNEL_ACCOUNT);
1702 
1703 	if (!name)
1704 		return -ENOMEM;
1705 
1706 	group = current_user_event_group();
1707 
1708 	if (!group) {
1709 		kfree(name);
1710 		return -ENOENT;
1711 	}
1712 
1713 	mutex_lock(&group->reg_mutex);
1714 
1715 	/* Dyn events persist, otherwise they would cleanup immediately */
1716 	ret = user_event_parse_cmd(group, name, &user, USER_EVENT_REG_PERSIST);
1717 
1718 	if (!ret)
1719 		user_event_put(user, false);
1720 
1721 	mutex_unlock(&group->reg_mutex);
1722 
1723 	if (ret)
1724 		kfree(name);
1725 
1726 	return ret;
1727 }
1728 
1729 static int user_event_show(struct seq_file *m, struct dyn_event *ev)
1730 {
1731 	struct user_event *user = container_of(ev, struct user_event, devent);
1732 	struct ftrace_event_field *field, *next;
1733 	struct list_head *head;
1734 	int depth = 0;
1735 
1736 	seq_printf(m, "%s%s", USER_EVENTS_PREFIX, EVENT_NAME(user));
1737 
1738 	head = trace_get_fields(&user->call);
1739 
1740 	list_for_each_entry_safe_reverse(field, next, head, link) {
1741 		if (depth == 0)
1742 			seq_puts(m, " ");
1743 		else
1744 			seq_puts(m, "; ");
1745 
1746 		seq_printf(m, "%s %s", field->type, field->name);
1747 
1748 		if (str_has_prefix(field->type, "struct "))
1749 			seq_printf(m, " %d", field->size);
1750 
1751 		depth++;
1752 	}
1753 
1754 	seq_puts(m, "\n");
1755 
1756 	return 0;
1757 }
1758 
1759 static bool user_event_is_busy(struct dyn_event *ev)
1760 {
1761 	struct user_event *user = container_of(ev, struct user_event, devent);
1762 
1763 	return !user_event_last_ref(user);
1764 }
1765 
1766 static int user_event_free(struct dyn_event *ev)
1767 {
1768 	struct user_event *user = container_of(ev, struct user_event, devent);
1769 
1770 	if (!user_event_last_ref(user))
1771 		return -EBUSY;
1772 
1773 	return destroy_user_event(user);
1774 }
1775 
1776 static bool user_field_match(struct ftrace_event_field *field, int argc,
1777 			     const char **argv, int *iout)
1778 {
1779 	char *field_name = NULL, *dyn_field_name = NULL;
1780 	bool colon = false, match = false;
1781 	int dyn_len, len;
1782 
1783 	if (*iout >= argc)
1784 		return false;
1785 
1786 	dyn_len = user_dyn_field_set_string(argc, argv, iout, dyn_field_name,
1787 					    0, &colon);
1788 
1789 	len = user_field_set_string(field, field_name, 0, colon);
1790 
1791 	if (dyn_len != len)
1792 		return false;
1793 
1794 	dyn_field_name = kmalloc(dyn_len, GFP_KERNEL);
1795 	field_name = kmalloc(len, GFP_KERNEL);
1796 
1797 	if (!dyn_field_name || !field_name)
1798 		goto out;
1799 
1800 	user_dyn_field_set_string(argc, argv, iout, dyn_field_name,
1801 				  dyn_len, &colon);
1802 
1803 	user_field_set_string(field, field_name, len, colon);
1804 
1805 	match = strcmp(dyn_field_name, field_name) == 0;
1806 out:
1807 	kfree(dyn_field_name);
1808 	kfree(field_name);
1809 
1810 	return match;
1811 }
1812 
1813 static bool user_fields_match(struct user_event *user, int argc,
1814 			      const char **argv)
1815 {
1816 	struct ftrace_event_field *field, *next;
1817 	struct list_head *head = &user->fields;
1818 	int i = 0;
1819 
1820 	list_for_each_entry_safe_reverse(field, next, head, link)
1821 		if (!user_field_match(field, argc, argv, &i))
1822 			return false;
1823 
1824 	if (i != argc)
1825 		return false;
1826 
1827 	return true;
1828 }
1829 
1830 static bool user_event_match(const char *system, const char *event,
1831 			     int argc, const char **argv, struct dyn_event *ev)
1832 {
1833 	struct user_event *user = container_of(ev, struct user_event, devent);
1834 	bool match;
1835 
1836 	match = strcmp(EVENT_NAME(user), event) == 0 &&
1837 		(!system || strcmp(system, USER_EVENTS_SYSTEM) == 0);
1838 
1839 	if (match && argc > 0)
1840 		match = user_fields_match(user, argc, argv);
1841 	else if (match && argc == 0)
1842 		match = list_empty(&user->fields);
1843 
1844 	return match;
1845 }
1846 
1847 static struct dyn_event_operations user_event_dops = {
1848 	.create = user_event_create,
1849 	.show = user_event_show,
1850 	.is_busy = user_event_is_busy,
1851 	.free = user_event_free,
1852 	.match = user_event_match,
1853 };
1854 
1855 static int user_event_trace_register(struct user_event *user)
1856 {
1857 	int ret;
1858 
1859 	ret = register_trace_event(&user->call.event);
1860 
1861 	if (!ret)
1862 		return -ENODEV;
1863 
1864 	ret = user_event_set_call_visible(user, true);
1865 
1866 	if (ret)
1867 		unregister_trace_event(&user->call.event);
1868 
1869 	return ret;
1870 }
1871 
1872 /*
1873  * Parses the event name, arguments and flags then registers if successful.
1874  * The name buffer lifetime is owned by this method for success cases only.
1875  * Upon success the returned user_event has its ref count increased by 1.
1876  */
1877 static int user_event_parse(struct user_event_group *group, char *name,
1878 			    char *args, char *flags,
1879 			    struct user_event **newuser, int reg_flags)
1880 {
1881 	int ret;
1882 	u32 key;
1883 	struct user_event *user;
1884 	int argc = 0;
1885 	char **argv;
1886 
1887 	/* User register flags are not ready yet */
1888 	if (reg_flags != 0 || flags != NULL)
1889 		return -EINVAL;
1890 
1891 	/* Prevent dyn_event from racing */
1892 	mutex_lock(&event_mutex);
1893 	user = find_user_event(group, name, &key);
1894 	mutex_unlock(&event_mutex);
1895 
1896 	if (user) {
1897 		if (args) {
1898 			argv = argv_split(GFP_KERNEL, args, &argc);
1899 			if (!argv) {
1900 				ret = -ENOMEM;
1901 				goto error;
1902 			}
1903 
1904 			ret = user_fields_match(user, argc, (const char **)argv);
1905 			argv_free(argv);
1906 
1907 		} else
1908 			ret = list_empty(&user->fields);
1909 
1910 		if (ret) {
1911 			*newuser = user;
1912 			/*
1913 			 * Name is allocated by caller, free it since it already exists.
1914 			 * Caller only worries about failure cases for freeing.
1915 			 */
1916 			kfree(name);
1917 		} else {
1918 			ret = -EADDRINUSE;
1919 			goto error;
1920 		}
1921 
1922 		return 0;
1923 error:
1924 		user_event_put(user, false);
1925 		return ret;
1926 	}
1927 
1928 	user = kzalloc(sizeof(*user), GFP_KERNEL_ACCOUNT);
1929 
1930 	if (!user)
1931 		return -ENOMEM;
1932 
1933 	INIT_LIST_HEAD(&user->class.fields);
1934 	INIT_LIST_HEAD(&user->fields);
1935 	INIT_LIST_HEAD(&user->validators);
1936 
1937 	user->group = group;
1938 	user->tracepoint.name = name;
1939 
1940 	ret = user_event_parse_fields(user, args);
1941 
1942 	if (ret)
1943 		goto put_user;
1944 
1945 	ret = user_event_create_print_fmt(user);
1946 
1947 	if (ret)
1948 		goto put_user;
1949 
1950 	user->call.data = user;
1951 	user->call.class = &user->class;
1952 	user->call.name = name;
1953 	user->call.flags = TRACE_EVENT_FL_TRACEPOINT;
1954 	user->call.tp = &user->tracepoint;
1955 	user->call.event.funcs = &user_event_funcs;
1956 	user->class.system = group->system_name;
1957 
1958 	user->class.fields_array = user_event_fields_array;
1959 	user->class.get_fields = user_event_get_fields;
1960 	user->class.reg = user_event_reg;
1961 	user->class.probe = user_event_ftrace;
1962 #ifdef CONFIG_PERF_EVENTS
1963 	user->class.perf_probe = user_event_perf;
1964 #endif
1965 
1966 	mutex_lock(&event_mutex);
1967 
1968 	if (current_user_events >= max_user_events) {
1969 		ret = -EMFILE;
1970 		goto put_user_lock;
1971 	}
1972 
1973 	ret = user_event_trace_register(user);
1974 
1975 	if (ret)
1976 		goto put_user_lock;
1977 
1978 	user->reg_flags = reg_flags;
1979 
1980 	if (user->reg_flags & USER_EVENT_REG_PERSIST) {
1981 		/* Ensure we track self ref and caller ref (2) */
1982 		refcount_set(&user->refcnt, 2);
1983 	} else {
1984 		/* Ensure we track only caller ref (1) */
1985 		refcount_set(&user->refcnt, 1);
1986 	}
1987 
1988 	dyn_event_init(&user->devent, &user_event_dops);
1989 	dyn_event_add(&user->devent, &user->call);
1990 	hash_add(group->register_table, &user->node, key);
1991 	current_user_events++;
1992 
1993 	mutex_unlock(&event_mutex);
1994 
1995 	*newuser = user;
1996 	return 0;
1997 put_user_lock:
1998 	mutex_unlock(&event_mutex);
1999 put_user:
2000 	user_event_destroy_fields(user);
2001 	user_event_destroy_validators(user);
2002 	kfree(user->call.print_fmt);
2003 	kfree(user);
2004 	return ret;
2005 }
2006 
2007 /*
2008  * Deletes a previously created event if it is no longer being used.
2009  */
2010 static int delete_user_event(struct user_event_group *group, char *name)
2011 {
2012 	u32 key;
2013 	struct user_event *user = find_user_event(group, name, &key);
2014 
2015 	if (!user)
2016 		return -ENOENT;
2017 
2018 	user_event_put(user, true);
2019 
2020 	if (!user_event_last_ref(user))
2021 		return -EBUSY;
2022 
2023 	return destroy_user_event(user);
2024 }
2025 
2026 /*
2027  * Validates the user payload and writes via iterator.
2028  */
2029 static ssize_t user_events_write_core(struct file *file, struct iov_iter *i)
2030 {
2031 	struct user_event_file_info *info = file->private_data;
2032 	struct user_event_refs *refs;
2033 	struct user_event *user = NULL;
2034 	struct tracepoint *tp;
2035 	ssize_t ret = i->count;
2036 	int idx;
2037 
2038 	if (unlikely(copy_from_iter(&idx, sizeof(idx), i) != sizeof(idx)))
2039 		return -EFAULT;
2040 
2041 	if (idx < 0)
2042 		return -EINVAL;
2043 
2044 	rcu_read_lock_sched();
2045 
2046 	refs = rcu_dereference_sched(info->refs);
2047 
2048 	/*
2049 	 * The refs->events array is protected by RCU, and new items may be
2050 	 * added. But the user retrieved from indexing into the events array
2051 	 * shall be immutable while the file is opened.
2052 	 */
2053 	if (likely(refs && idx < refs->count))
2054 		user = refs->events[idx];
2055 
2056 	rcu_read_unlock_sched();
2057 
2058 	if (unlikely(user == NULL))
2059 		return -ENOENT;
2060 
2061 	if (unlikely(i->count < user->min_size))
2062 		return -EINVAL;
2063 
2064 	tp = &user->tracepoint;
2065 
2066 	/*
2067 	 * It's possible key.enabled disables after this check, however
2068 	 * we don't mind if a few events are included in this condition.
2069 	 */
2070 	if (likely(atomic_read(&tp->key.enabled) > 0)) {
2071 		struct tracepoint_func *probe_func_ptr;
2072 		user_event_func_t probe_func;
2073 		struct iov_iter copy;
2074 		void *tpdata;
2075 		bool faulted;
2076 
2077 		if (unlikely(fault_in_iov_iter_readable(i, i->count)))
2078 			return -EFAULT;
2079 
2080 		faulted = false;
2081 
2082 		rcu_read_lock_sched();
2083 
2084 		probe_func_ptr = rcu_dereference_sched(tp->funcs);
2085 
2086 		if (probe_func_ptr) {
2087 			do {
2088 				copy = *i;
2089 				probe_func = probe_func_ptr->func;
2090 				tpdata = probe_func_ptr->data;
2091 				probe_func(user, &copy, tpdata, &faulted);
2092 			} while ((++probe_func_ptr)->func);
2093 		}
2094 
2095 		rcu_read_unlock_sched();
2096 
2097 		if (unlikely(faulted))
2098 			return -EFAULT;
2099 	} else
2100 		return -EBADF;
2101 
2102 	return ret;
2103 }
2104 
2105 static int user_events_open(struct inode *node, struct file *file)
2106 {
2107 	struct user_event_group *group;
2108 	struct user_event_file_info *info;
2109 
2110 	group = current_user_event_group();
2111 
2112 	if (!group)
2113 		return -ENOENT;
2114 
2115 	info = kzalloc(sizeof(*info), GFP_KERNEL_ACCOUNT);
2116 
2117 	if (!info)
2118 		return -ENOMEM;
2119 
2120 	info->group = group;
2121 
2122 	file->private_data = info;
2123 
2124 	return 0;
2125 }
2126 
2127 static ssize_t user_events_write(struct file *file, const char __user *ubuf,
2128 				 size_t count, loff_t *ppos)
2129 {
2130 	struct iovec iov;
2131 	struct iov_iter i;
2132 
2133 	if (unlikely(*ppos != 0))
2134 		return -EFAULT;
2135 
2136 	if (unlikely(import_single_range(ITER_SOURCE, (char __user *)ubuf,
2137 					 count, &iov, &i)))
2138 		return -EFAULT;
2139 
2140 	return user_events_write_core(file, &i);
2141 }
2142 
2143 static ssize_t user_events_write_iter(struct kiocb *kp, struct iov_iter *i)
2144 {
2145 	return user_events_write_core(kp->ki_filp, i);
2146 }
2147 
2148 static int user_events_ref_add(struct user_event_file_info *info,
2149 			       struct user_event *user)
2150 {
2151 	struct user_event_group *group = info->group;
2152 	struct user_event_refs *refs, *new_refs;
2153 	int i, size, count = 0;
2154 
2155 	refs = rcu_dereference_protected(info->refs,
2156 					 lockdep_is_held(&group->reg_mutex));
2157 
2158 	if (refs) {
2159 		count = refs->count;
2160 
2161 		for (i = 0; i < count; ++i)
2162 			if (refs->events[i] == user)
2163 				return i;
2164 	}
2165 
2166 	size = struct_size(refs, events, count + 1);
2167 
2168 	new_refs = kzalloc(size, GFP_KERNEL_ACCOUNT);
2169 
2170 	if (!new_refs)
2171 		return -ENOMEM;
2172 
2173 	new_refs->count = count + 1;
2174 
2175 	for (i = 0; i < count; ++i)
2176 		new_refs->events[i] = refs->events[i];
2177 
2178 	new_refs->events[i] = user_event_get(user);
2179 
2180 	rcu_assign_pointer(info->refs, new_refs);
2181 
2182 	if (refs)
2183 		kfree_rcu(refs, rcu);
2184 
2185 	return i;
2186 }
2187 
2188 static long user_reg_get(struct user_reg __user *ureg, struct user_reg *kreg)
2189 {
2190 	u32 size;
2191 	long ret;
2192 
2193 	ret = get_user(size, &ureg->size);
2194 
2195 	if (ret)
2196 		return ret;
2197 
2198 	if (size > PAGE_SIZE)
2199 		return -E2BIG;
2200 
2201 	if (size < offsetofend(struct user_reg, write_index))
2202 		return -EINVAL;
2203 
2204 	ret = copy_struct_from_user(kreg, sizeof(*kreg), ureg, size);
2205 
2206 	if (ret)
2207 		return ret;
2208 
2209 	/* Ensure only valid flags */
2210 	if (kreg->flags & ~(USER_EVENT_REG_MAX-1))
2211 		return -EINVAL;
2212 
2213 	/* Ensure supported size */
2214 	switch (kreg->enable_size) {
2215 	case 4:
2216 		/* 32-bit */
2217 		break;
2218 #if BITS_PER_LONG >= 64
2219 	case 8:
2220 		/* 64-bit */
2221 		break;
2222 #endif
2223 	default:
2224 		return -EINVAL;
2225 	}
2226 
2227 	/* Ensure natural alignment */
2228 	if (kreg->enable_addr % kreg->enable_size)
2229 		return -EINVAL;
2230 
2231 	/* Ensure bit range for size */
2232 	if (kreg->enable_bit > (kreg->enable_size * BITS_PER_BYTE) - 1)
2233 		return -EINVAL;
2234 
2235 	/* Ensure accessible */
2236 	if (!access_ok((const void __user *)(uintptr_t)kreg->enable_addr,
2237 		       kreg->enable_size))
2238 		return -EFAULT;
2239 
2240 	kreg->size = size;
2241 
2242 	return 0;
2243 }
2244 
2245 /*
2246  * Registers a user_event on behalf of a user process.
2247  */
2248 static long user_events_ioctl_reg(struct user_event_file_info *info,
2249 				  unsigned long uarg)
2250 {
2251 	struct user_reg __user *ureg = (struct user_reg __user *)uarg;
2252 	struct user_reg reg;
2253 	struct user_event *user;
2254 	struct user_event_enabler *enabler;
2255 	char *name;
2256 	long ret;
2257 	int write_result;
2258 
2259 	ret = user_reg_get(ureg, &reg);
2260 
2261 	if (ret)
2262 		return ret;
2263 
2264 	/*
2265 	 * Prevent users from using the same address and bit multiple times
2266 	 * within the same mm address space. This can cause unexpected behavior
2267 	 * for user processes that is far easier to debug if this is explictly
2268 	 * an error upon registering.
2269 	 */
2270 	if (current_user_event_enabler_exists((unsigned long)reg.enable_addr,
2271 					      reg.enable_bit))
2272 		return -EADDRINUSE;
2273 
2274 	name = strndup_user((const char __user *)(uintptr_t)reg.name_args,
2275 			    MAX_EVENT_DESC);
2276 
2277 	if (IS_ERR(name)) {
2278 		ret = PTR_ERR(name);
2279 		return ret;
2280 	}
2281 
2282 	ret = user_event_parse_cmd(info->group, name, &user, reg.flags);
2283 
2284 	if (ret) {
2285 		kfree(name);
2286 		return ret;
2287 	}
2288 
2289 	ret = user_events_ref_add(info, user);
2290 
2291 	/* No longer need parse ref, ref_add either worked or not */
2292 	user_event_put(user, false);
2293 
2294 	/* Positive number is index and valid */
2295 	if (ret < 0)
2296 		return ret;
2297 
2298 	/*
2299 	 * user_events_ref_add succeeded:
2300 	 * At this point we have a user_event, it's lifetime is bound by the
2301 	 * reference count, not this file. If anything fails, the user_event
2302 	 * still has a reference until the file is released. During release
2303 	 * any remaining references (from user_events_ref_add) are decremented.
2304 	 *
2305 	 * Attempt to create an enabler, which too has a lifetime tied in the
2306 	 * same way for the event. Once the task that caused the enabler to be
2307 	 * created exits or issues exec() then the enablers it has created
2308 	 * will be destroyed and the ref to the event will be decremented.
2309 	 */
2310 	enabler = user_event_enabler_create(&reg, user, &write_result);
2311 
2312 	if (!enabler)
2313 		return -ENOMEM;
2314 
2315 	/* Write failed/faulted, give error back to caller */
2316 	if (write_result)
2317 		return write_result;
2318 
2319 	put_user((u32)ret, &ureg->write_index);
2320 
2321 	return 0;
2322 }
2323 
2324 /*
2325  * Deletes a user_event on behalf of a user process.
2326  */
2327 static long user_events_ioctl_del(struct user_event_file_info *info,
2328 				  unsigned long uarg)
2329 {
2330 	void __user *ubuf = (void __user *)uarg;
2331 	char *name;
2332 	long ret;
2333 
2334 	name = strndup_user(ubuf, MAX_EVENT_DESC);
2335 
2336 	if (IS_ERR(name))
2337 		return PTR_ERR(name);
2338 
2339 	/* event_mutex prevents dyn_event from racing */
2340 	mutex_lock(&event_mutex);
2341 	ret = delete_user_event(info->group, name);
2342 	mutex_unlock(&event_mutex);
2343 
2344 	kfree(name);
2345 
2346 	return ret;
2347 }
2348 
2349 static long user_unreg_get(struct user_unreg __user *ureg,
2350 			   struct user_unreg *kreg)
2351 {
2352 	u32 size;
2353 	long ret;
2354 
2355 	ret = get_user(size, &ureg->size);
2356 
2357 	if (ret)
2358 		return ret;
2359 
2360 	if (size > PAGE_SIZE)
2361 		return -E2BIG;
2362 
2363 	if (size < offsetofend(struct user_unreg, disable_addr))
2364 		return -EINVAL;
2365 
2366 	ret = copy_struct_from_user(kreg, sizeof(*kreg), ureg, size);
2367 
2368 	/* Ensure no reserved values, since we don't support any yet */
2369 	if (kreg->__reserved || kreg->__reserved2)
2370 		return -EINVAL;
2371 
2372 	return ret;
2373 }
2374 
2375 static int user_event_mm_clear_bit(struct user_event_mm *user_mm,
2376 				   unsigned long uaddr, unsigned char bit)
2377 {
2378 	struct user_event_enabler enabler;
2379 	int result;
2380 	int attempt = 0;
2381 
2382 	memset(&enabler, 0, sizeof(enabler));
2383 	enabler.addr = uaddr;
2384 	enabler.values = bit;
2385 retry:
2386 	/* Prevents state changes from racing with new enablers */
2387 	mutex_lock(&event_mutex);
2388 
2389 	/* Force the bit to be cleared, since no event is attached */
2390 	mmap_read_lock(user_mm->mm);
2391 	result = user_event_enabler_write(user_mm, &enabler, false, &attempt);
2392 	mmap_read_unlock(user_mm->mm);
2393 
2394 	mutex_unlock(&event_mutex);
2395 
2396 	if (result) {
2397 		/* Attempt to fault-in and retry if it worked */
2398 		if (!user_event_mm_fault_in(user_mm, uaddr, attempt))
2399 			goto retry;
2400 	}
2401 
2402 	return result;
2403 }
2404 
2405 /*
2406  * Unregisters an enablement address/bit within a task/user mm.
2407  */
2408 static long user_events_ioctl_unreg(unsigned long uarg)
2409 {
2410 	struct user_unreg __user *ureg = (struct user_unreg __user *)uarg;
2411 	struct user_event_mm *mm = current->user_event_mm;
2412 	struct user_event_enabler *enabler, *next;
2413 	struct user_unreg reg;
2414 	long ret;
2415 
2416 	ret = user_unreg_get(ureg, &reg);
2417 
2418 	if (ret)
2419 		return ret;
2420 
2421 	if (!mm)
2422 		return -ENOENT;
2423 
2424 	ret = -ENOENT;
2425 
2426 	/*
2427 	 * Flags freeing and faulting are used to indicate if the enabler is in
2428 	 * use at all. When faulting is set a page-fault is occurring asyncly.
2429 	 * During async fault if freeing is set, the enabler will be destroyed.
2430 	 * If no async fault is happening, we can destroy it now since we hold
2431 	 * the event_mutex during these checks.
2432 	 */
2433 	mutex_lock(&event_mutex);
2434 
2435 	list_for_each_entry_safe(enabler, next, &mm->enablers, mm_enablers_link) {
2436 		if (enabler->addr == reg.disable_addr &&
2437 		    ENABLE_BIT(enabler) == reg.disable_bit) {
2438 			set_bit(ENABLE_VAL_FREEING_BIT, ENABLE_BITOPS(enabler));
2439 
2440 			if (!test_bit(ENABLE_VAL_FAULTING_BIT, ENABLE_BITOPS(enabler)))
2441 				user_event_enabler_destroy(enabler, true);
2442 
2443 			/* Removed at least one */
2444 			ret = 0;
2445 		}
2446 	}
2447 
2448 	mutex_unlock(&event_mutex);
2449 
2450 	/* Ensure bit is now cleared for user, regardless of event status */
2451 	if (!ret)
2452 		ret = user_event_mm_clear_bit(mm, reg.disable_addr,
2453 					      reg.disable_bit);
2454 
2455 	return ret;
2456 }
2457 
2458 /*
2459  * Handles the ioctl from user mode to register or alter operations.
2460  */
2461 static long user_events_ioctl(struct file *file, unsigned int cmd,
2462 			      unsigned long uarg)
2463 {
2464 	struct user_event_file_info *info = file->private_data;
2465 	struct user_event_group *group = info->group;
2466 	long ret = -ENOTTY;
2467 
2468 	switch (cmd) {
2469 	case DIAG_IOCSREG:
2470 		mutex_lock(&group->reg_mutex);
2471 		ret = user_events_ioctl_reg(info, uarg);
2472 		mutex_unlock(&group->reg_mutex);
2473 		break;
2474 
2475 	case DIAG_IOCSDEL:
2476 		mutex_lock(&group->reg_mutex);
2477 		ret = user_events_ioctl_del(info, uarg);
2478 		mutex_unlock(&group->reg_mutex);
2479 		break;
2480 
2481 	case DIAG_IOCSUNREG:
2482 		mutex_lock(&group->reg_mutex);
2483 		ret = user_events_ioctl_unreg(uarg);
2484 		mutex_unlock(&group->reg_mutex);
2485 		break;
2486 	}
2487 
2488 	return ret;
2489 }
2490 
2491 /*
2492  * Handles the final close of the file from user mode.
2493  */
2494 static int user_events_release(struct inode *node, struct file *file)
2495 {
2496 	struct user_event_file_info *info = file->private_data;
2497 	struct user_event_group *group;
2498 	struct user_event_refs *refs;
2499 	int i;
2500 
2501 	if (!info)
2502 		return -EINVAL;
2503 
2504 	group = info->group;
2505 
2506 	/*
2507 	 * Ensure refs cannot change under any situation by taking the
2508 	 * register mutex during the final freeing of the references.
2509 	 */
2510 	mutex_lock(&group->reg_mutex);
2511 
2512 	refs = info->refs;
2513 
2514 	if (!refs)
2515 		goto out;
2516 
2517 	/*
2518 	 * The lifetime of refs has reached an end, it's tied to this file.
2519 	 * The underlying user_events are ref counted, and cannot be freed.
2520 	 * After this decrement, the user_events may be freed elsewhere.
2521 	 */
2522 	for (i = 0; i < refs->count; ++i)
2523 		user_event_put(refs->events[i], false);
2524 
2525 out:
2526 	file->private_data = NULL;
2527 
2528 	mutex_unlock(&group->reg_mutex);
2529 
2530 	kfree(refs);
2531 	kfree(info);
2532 
2533 	return 0;
2534 }
2535 
2536 static const struct file_operations user_data_fops = {
2537 	.open		= user_events_open,
2538 	.write		= user_events_write,
2539 	.write_iter	= user_events_write_iter,
2540 	.unlocked_ioctl	= user_events_ioctl,
2541 	.release	= user_events_release,
2542 };
2543 
2544 static void *user_seq_start(struct seq_file *m, loff_t *pos)
2545 {
2546 	if (*pos)
2547 		return NULL;
2548 
2549 	return (void *)1;
2550 }
2551 
2552 static void *user_seq_next(struct seq_file *m, void *p, loff_t *pos)
2553 {
2554 	++*pos;
2555 	return NULL;
2556 }
2557 
2558 static void user_seq_stop(struct seq_file *m, void *p)
2559 {
2560 }
2561 
2562 static int user_seq_show(struct seq_file *m, void *p)
2563 {
2564 	struct user_event_group *group = m->private;
2565 	struct user_event *user;
2566 	char status;
2567 	int i, active = 0, busy = 0;
2568 
2569 	if (!group)
2570 		return -EINVAL;
2571 
2572 	mutex_lock(&group->reg_mutex);
2573 
2574 	hash_for_each(group->register_table, i, user, node) {
2575 		status = user->status;
2576 
2577 		seq_printf(m, "%s", EVENT_NAME(user));
2578 
2579 		if (status != 0)
2580 			seq_puts(m, " #");
2581 
2582 		if (status != 0) {
2583 			seq_puts(m, " Used by");
2584 			if (status & EVENT_STATUS_FTRACE)
2585 				seq_puts(m, " ftrace");
2586 			if (status & EVENT_STATUS_PERF)
2587 				seq_puts(m, " perf");
2588 			if (status & EVENT_STATUS_OTHER)
2589 				seq_puts(m, " other");
2590 			busy++;
2591 		}
2592 
2593 		seq_puts(m, "\n");
2594 		active++;
2595 	}
2596 
2597 	mutex_unlock(&group->reg_mutex);
2598 
2599 	seq_puts(m, "\n");
2600 	seq_printf(m, "Active: %d\n", active);
2601 	seq_printf(m, "Busy: %d\n", busy);
2602 
2603 	return 0;
2604 }
2605 
2606 static const struct seq_operations user_seq_ops = {
2607 	.start	= user_seq_start,
2608 	.next	= user_seq_next,
2609 	.stop	= user_seq_stop,
2610 	.show	= user_seq_show,
2611 };
2612 
2613 static int user_status_open(struct inode *node, struct file *file)
2614 {
2615 	struct user_event_group *group;
2616 	int ret;
2617 
2618 	group = current_user_event_group();
2619 
2620 	if (!group)
2621 		return -ENOENT;
2622 
2623 	ret = seq_open(file, &user_seq_ops);
2624 
2625 	if (!ret) {
2626 		/* Chain group to seq_file */
2627 		struct seq_file *m = file->private_data;
2628 
2629 		m->private = group;
2630 	}
2631 
2632 	return ret;
2633 }
2634 
2635 static const struct file_operations user_status_fops = {
2636 	.open		= user_status_open,
2637 	.read		= seq_read,
2638 	.llseek		= seq_lseek,
2639 	.release	= seq_release,
2640 };
2641 
2642 /*
2643  * Creates a set of tracefs files to allow user mode interactions.
2644  */
2645 static int create_user_tracefs(void)
2646 {
2647 	struct dentry *edata, *emmap;
2648 
2649 	edata = tracefs_create_file("user_events_data", TRACE_MODE_WRITE,
2650 				    NULL, NULL, &user_data_fops);
2651 
2652 	if (!edata) {
2653 		pr_warn("Could not create tracefs 'user_events_data' entry\n");
2654 		goto err;
2655 	}
2656 
2657 	emmap = tracefs_create_file("user_events_status", TRACE_MODE_READ,
2658 				    NULL, NULL, &user_status_fops);
2659 
2660 	if (!emmap) {
2661 		tracefs_remove(edata);
2662 		pr_warn("Could not create tracefs 'user_events_mmap' entry\n");
2663 		goto err;
2664 	}
2665 
2666 	return 0;
2667 err:
2668 	return -ENODEV;
2669 }
2670 
2671 static int set_max_user_events_sysctl(struct ctl_table *table, int write,
2672 				      void *buffer, size_t *lenp, loff_t *ppos)
2673 {
2674 	int ret;
2675 
2676 	mutex_lock(&event_mutex);
2677 
2678 	ret = proc_douintvec(table, write, buffer, lenp, ppos);
2679 
2680 	mutex_unlock(&event_mutex);
2681 
2682 	return ret;
2683 }
2684 
2685 static struct ctl_table user_event_sysctls[] = {
2686 	{
2687 		.procname	= "user_events_max",
2688 		.data		= &max_user_events,
2689 		.maxlen		= sizeof(unsigned int),
2690 		.mode		= 0644,
2691 		.proc_handler	= set_max_user_events_sysctl,
2692 	},
2693 	{}
2694 };
2695 
2696 static int __init trace_events_user_init(void)
2697 {
2698 	int ret;
2699 
2700 	fault_cache = KMEM_CACHE(user_event_enabler_fault, 0);
2701 
2702 	if (!fault_cache)
2703 		return -ENOMEM;
2704 
2705 	init_group = user_event_group_create();
2706 
2707 	if (!init_group) {
2708 		kmem_cache_destroy(fault_cache);
2709 		return -ENOMEM;
2710 	}
2711 
2712 	ret = create_user_tracefs();
2713 
2714 	if (ret) {
2715 		pr_warn("user_events could not register with tracefs\n");
2716 		user_event_group_destroy(init_group);
2717 		kmem_cache_destroy(fault_cache);
2718 		init_group = NULL;
2719 		return ret;
2720 	}
2721 
2722 	if (dyn_event_register(&user_event_dops))
2723 		pr_warn("user_events could not register with dyn_events\n");
2724 
2725 	register_sysctl_init("kernel", user_event_sysctls);
2726 
2727 	return 0;
2728 }
2729 
2730 fs_initcall(trace_events_user_init);
2731