• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Performance events core code:
4  *
5  *  Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
6  *  Copyright (C) 2008-2011 Red Hat, Inc., Ingo Molnar
7  *  Copyright (C) 2008-2011 Red Hat, Inc., Peter Zijlstra
8  *  Copyright  ©  2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
9  */
10 
11 #include <linux/fs.h>
12 #include <linux/mm.h>
13 #include <linux/cpu.h>
14 #include <linux/smp.h>
15 #include <linux/idr.h>
16 #include <linux/file.h>
17 #include <linux/poll.h>
18 #include <linux/slab.h>
19 #include <linux/hash.h>
20 #include <linux/tick.h>
21 #include <linux/sysfs.h>
22 #include <linux/dcache.h>
23 #include <linux/percpu.h>
24 #include <linux/ptrace.h>
25 #include <linux/reboot.h>
26 #include <linux/vmstat.h>
27 #include <linux/device.h>
28 #include <linux/export.h>
29 #include <linux/vmalloc.h>
30 #include <linux/hardirq.h>
31 #include <linux/hugetlb.h>
32 #include <linux/rculist.h>
33 #include <linux/uaccess.h>
34 #include <linux/syscalls.h>
35 #include <linux/anon_inodes.h>
36 #include <linux/kernel_stat.h>
37 #include <linux/cgroup.h>
38 #include <linux/perf_event.h>
39 #include <linux/trace_events.h>
40 #include <linux/hw_breakpoint.h>
41 #include <linux/mm_types.h>
42 #include <linux/module.h>
43 #include <linux/mman.h>
44 #include <linux/compat.h>
45 #include <linux/bpf.h>
46 #include <linux/filter.h>
47 #include <linux/namei.h>
48 #include <linux/parser.h>
49 #include <linux/sched/clock.h>
50 #include <linux/sched/mm.h>
51 #include <linux/proc_ns.h>
52 #include <linux/mount.h>
53 #include <linux/min_heap.h>
54 
55 #include "internal.h"
56 
57 #include <asm/irq_regs.h>
58 
59 typedef int (*remote_function_f)(void *);
60 
61 struct remote_function_call {
62 	struct task_struct	*p;
63 	remote_function_f	func;
64 	void			*info;
65 	int			ret;
66 };
67 
remote_function(void * data)68 static void remote_function(void *data)
69 {
70 	struct remote_function_call *tfc = data;
71 	struct task_struct *p = tfc->p;
72 
73 	if (p) {
74 		/* -EAGAIN */
75 		if (task_cpu(p) != smp_processor_id())
76 			return;
77 
78 		/*
79 		 * Now that we're on right CPU with IRQs disabled, we can test
80 		 * if we hit the right task without races.
81 		 */
82 
83 		tfc->ret = -ESRCH; /* No such (running) process */
84 		if (p != current)
85 			return;
86 	}
87 
88 	tfc->ret = tfc->func(tfc->info);
89 }
90 
91 /**
92  * task_function_call - call a function on the cpu on which a task runs
93  * @p:		the task to evaluate
94  * @func:	the function to be called
95  * @info:	the function call argument
96  *
97  * Calls the function @func when the task is currently running. This might
98  * be on the current CPU, which just calls the function directly.  This will
99  * retry due to any failures in smp_call_function_single(), such as if the
100  * task_cpu() goes offline concurrently.
101  *
102  * returns @func return value or -ESRCH or -ENXIO when the process isn't running
103  */
104 static int
task_function_call(struct task_struct * p,remote_function_f func,void * info)105 task_function_call(struct task_struct *p, remote_function_f func, void *info)
106 {
107 	struct remote_function_call data = {
108 		.p	= p,
109 		.func	= func,
110 		.info	= info,
111 		.ret	= -EAGAIN,
112 	};
113 	int ret;
114 
115 	for (;;) {
116 		ret = smp_call_function_single(task_cpu(p), remote_function,
117 					       &data, 1);
118 		if (!ret)
119 			ret = data.ret;
120 
121 		if (ret != -EAGAIN)
122 			break;
123 
124 		cond_resched();
125 	}
126 
127 	return ret;
128 }
129 
130 /**
131  * cpu_function_call - call a function on the cpu
132  * @func:	the function to be called
133  * @info:	the function call argument
134  *
135  * Calls the function @func on the remote cpu.
136  *
137  * returns: @func return value or -ENXIO when the cpu is offline
138  */
cpu_function_call(int cpu,remote_function_f func,void * info)139 static int cpu_function_call(int cpu, remote_function_f func, void *info)
140 {
141 	struct remote_function_call data = {
142 		.p	= NULL,
143 		.func	= func,
144 		.info	= info,
145 		.ret	= -ENXIO, /* No such CPU */
146 	};
147 
148 	smp_call_function_single(cpu, remote_function, &data, 1);
149 
150 	return data.ret;
151 }
152 
153 static inline struct perf_cpu_context *
__get_cpu_context(struct perf_event_context * ctx)154 __get_cpu_context(struct perf_event_context *ctx)
155 {
156 	return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
157 }
158 
perf_ctx_lock(struct perf_cpu_context * cpuctx,struct perf_event_context * ctx)159 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
160 			  struct perf_event_context *ctx)
161 {
162 	raw_spin_lock(&cpuctx->ctx.lock);
163 	if (ctx)
164 		raw_spin_lock(&ctx->lock);
165 }
166 
perf_ctx_unlock(struct perf_cpu_context * cpuctx,struct perf_event_context * ctx)167 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
168 			    struct perf_event_context *ctx)
169 {
170 	if (ctx)
171 		raw_spin_unlock(&ctx->lock);
172 	raw_spin_unlock(&cpuctx->ctx.lock);
173 }
174 
175 #define TASK_TOMBSTONE ((void *)-1L)
176 
is_kernel_event(struct perf_event * event)177 static bool is_kernel_event(struct perf_event *event)
178 {
179 	return READ_ONCE(event->owner) == TASK_TOMBSTONE;
180 }
181 
182 /*
183  * On task ctx scheduling...
184  *
185  * When !ctx->nr_events a task context will not be scheduled. This means
186  * we can disable the scheduler hooks (for performance) without leaving
187  * pending task ctx state.
188  *
189  * This however results in two special cases:
190  *
191  *  - removing the last event from a task ctx; this is relatively straight
192  *    forward and is done in __perf_remove_from_context.
193  *
194  *  - adding the first event to a task ctx; this is tricky because we cannot
195  *    rely on ctx->is_active and therefore cannot use event_function_call().
196  *    See perf_install_in_context().
197  *
198  * If ctx->nr_events, then ctx->is_active and cpuctx->task_ctx are set.
199  */
200 
201 typedef void (*event_f)(struct perf_event *, struct perf_cpu_context *,
202 			struct perf_event_context *, void *);
203 
204 struct event_function_struct {
205 	struct perf_event *event;
206 	event_f func;
207 	void *data;
208 };
209 
event_function(void * info)210 static int event_function(void *info)
211 {
212 	struct event_function_struct *efs = info;
213 	struct perf_event *event = efs->event;
214 	struct perf_event_context *ctx = event->ctx;
215 	struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
216 	struct perf_event_context *task_ctx = cpuctx->task_ctx;
217 	int ret = 0;
218 
219 	lockdep_assert_irqs_disabled();
220 
221 	perf_ctx_lock(cpuctx, task_ctx);
222 	/*
223 	 * Since we do the IPI call without holding ctx->lock things can have
224 	 * changed, double check we hit the task we set out to hit.
225 	 */
226 	if (ctx->task) {
227 		if (ctx->task != current) {
228 			ret = -ESRCH;
229 			goto unlock;
230 		}
231 
232 		/*
233 		 * We only use event_function_call() on established contexts,
234 		 * and event_function() is only ever called when active (or
235 		 * rather, we'll have bailed in task_function_call() or the
236 		 * above ctx->task != current test), therefore we must have
237 		 * ctx->is_active here.
238 		 */
239 		WARN_ON_ONCE(!ctx->is_active);
240 		/*
241 		 * And since we have ctx->is_active, cpuctx->task_ctx must
242 		 * match.
243 		 */
244 		WARN_ON_ONCE(task_ctx != ctx);
245 	} else {
246 		WARN_ON_ONCE(&cpuctx->ctx != ctx);
247 	}
248 
249 	efs->func(event, cpuctx, ctx, efs->data);
250 unlock:
251 	perf_ctx_unlock(cpuctx, task_ctx);
252 
253 	return ret;
254 }
255 
event_function_call(struct perf_event * event,event_f func,void * data)256 static void event_function_call(struct perf_event *event, event_f func, void *data)
257 {
258 	struct perf_event_context *ctx = event->ctx;
259 	struct task_struct *task = READ_ONCE(ctx->task); /* verified in event_function */
260 	struct event_function_struct efs = {
261 		.event = event,
262 		.func = func,
263 		.data = data,
264 	};
265 
266 	if (!event->parent) {
267 		/*
268 		 * If this is a !child event, we must hold ctx::mutex to
269 		 * stabilize the event->ctx relation. See
270 		 * perf_event_ctx_lock().
271 		 */
272 		lockdep_assert_held(&ctx->mutex);
273 	}
274 
275 	if (!task) {
276 		cpu_function_call(event->cpu, event_function, &efs);
277 		return;
278 	}
279 
280 	if (task == TASK_TOMBSTONE)
281 		return;
282 
283 again:
284 	if (!task_function_call(task, event_function, &efs))
285 		return;
286 
287 	raw_spin_lock_irq(&ctx->lock);
288 	/*
289 	 * Reload the task pointer, it might have been changed by
290 	 * a concurrent perf_event_context_sched_out().
291 	 */
292 	task = ctx->task;
293 	if (task == TASK_TOMBSTONE) {
294 		raw_spin_unlock_irq(&ctx->lock);
295 		return;
296 	}
297 	if (ctx->is_active) {
298 		raw_spin_unlock_irq(&ctx->lock);
299 		goto again;
300 	}
301 	func(event, NULL, ctx, data);
302 	raw_spin_unlock_irq(&ctx->lock);
303 }
304 
305 /*
306  * Similar to event_function_call() + event_function(), but hard assumes IRQs
307  * are already disabled and we're on the right CPU.
308  */
event_function_local(struct perf_event * event,event_f func,void * data)309 static void event_function_local(struct perf_event *event, event_f func, void *data)
310 {
311 	struct perf_event_context *ctx = event->ctx;
312 	struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
313 	struct task_struct *task = READ_ONCE(ctx->task);
314 	struct perf_event_context *task_ctx = NULL;
315 
316 	lockdep_assert_irqs_disabled();
317 
318 	if (task) {
319 		if (task == TASK_TOMBSTONE)
320 			return;
321 
322 		task_ctx = ctx;
323 	}
324 
325 	perf_ctx_lock(cpuctx, task_ctx);
326 
327 	task = ctx->task;
328 	if (task == TASK_TOMBSTONE)
329 		goto unlock;
330 
331 	if (task) {
332 		/*
333 		 * We must be either inactive or active and the right task,
334 		 * otherwise we're screwed, since we cannot IPI to somewhere
335 		 * else.
336 		 */
337 		if (ctx->is_active) {
338 			if (WARN_ON_ONCE(task != current))
339 				goto unlock;
340 
341 			if (WARN_ON_ONCE(cpuctx->task_ctx != ctx))
342 				goto unlock;
343 		}
344 	} else {
345 		WARN_ON_ONCE(&cpuctx->ctx != ctx);
346 	}
347 
348 	func(event, cpuctx, ctx, data);
349 unlock:
350 	perf_ctx_unlock(cpuctx, task_ctx);
351 }
352 
353 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
354 		       PERF_FLAG_FD_OUTPUT  |\
355 		       PERF_FLAG_PID_CGROUP |\
356 		       PERF_FLAG_FD_CLOEXEC)
357 
358 /*
359  * branch priv levels that need permission checks
360  */
361 #define PERF_SAMPLE_BRANCH_PERM_PLM \
362 	(PERF_SAMPLE_BRANCH_KERNEL |\
363 	 PERF_SAMPLE_BRANCH_HV)
364 
365 enum event_type_t {
366 	EVENT_FLEXIBLE = 0x1,
367 	EVENT_PINNED = 0x2,
368 	EVENT_TIME = 0x4,
369 	/* see ctx_resched() for details */
370 	EVENT_CPU = 0x8,
371 	EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
372 };
373 
374 /*
375  * perf_sched_events : >0 events exist
376  * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
377  */
378 
379 static void perf_sched_delayed(struct work_struct *work);
380 DEFINE_STATIC_KEY_FALSE(perf_sched_events);
381 static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed);
382 static DEFINE_MUTEX(perf_sched_mutex);
383 static atomic_t perf_sched_count;
384 
385 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
386 static DEFINE_PER_CPU(int, perf_sched_cb_usages);
387 static DEFINE_PER_CPU(struct pmu_event_list, pmu_sb_events);
388 
389 static atomic_t nr_mmap_events __read_mostly;
390 static atomic_t nr_comm_events __read_mostly;
391 static atomic_t nr_namespaces_events __read_mostly;
392 static atomic_t nr_task_events __read_mostly;
393 static atomic_t nr_freq_events __read_mostly;
394 static atomic_t nr_switch_events __read_mostly;
395 static atomic_t nr_ksymbol_events __read_mostly;
396 static atomic_t nr_bpf_events __read_mostly;
397 static atomic_t nr_cgroup_events __read_mostly;
398 static atomic_t nr_text_poke_events __read_mostly;
399 
400 static LIST_HEAD(pmus);
401 static DEFINE_MUTEX(pmus_lock);
402 static struct srcu_struct pmus_srcu;
403 static cpumask_var_t perf_online_mask;
404 
405 /*
406  * perf event paranoia level:
407  *  -1 - not paranoid at all
408  *   0 - disallow raw tracepoint access for unpriv
409  *   1 - disallow cpu events for unpriv
410  *   2 - disallow kernel profiling for unpriv
411  */
412 int sysctl_perf_event_paranoid __read_mostly = 2;
413 
414 /* Minimum for 512 kiB + 1 user control page */
415 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
416 
417 /*
418  * max perf event sample rate
419  */
420 #define DEFAULT_MAX_SAMPLE_RATE		100000
421 #define DEFAULT_SAMPLE_PERIOD_NS	(NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
422 #define DEFAULT_CPU_TIME_MAX_PERCENT	25
423 
424 int sysctl_perf_event_sample_rate __read_mostly	= DEFAULT_MAX_SAMPLE_RATE;
425 
426 static int max_samples_per_tick __read_mostly	= DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
427 static int perf_sample_period_ns __read_mostly	= DEFAULT_SAMPLE_PERIOD_NS;
428 
429 static int perf_sample_allowed_ns __read_mostly =
430 	DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
431 
update_perf_cpu_limits(void)432 static void update_perf_cpu_limits(void)
433 {
434 	u64 tmp = perf_sample_period_ns;
435 
436 	tmp *= sysctl_perf_cpu_time_max_percent;
437 	tmp = div_u64(tmp, 100);
438 	if (!tmp)
439 		tmp = 1;
440 
441 	WRITE_ONCE(perf_sample_allowed_ns, tmp);
442 }
443 
444 static bool perf_rotate_context(struct perf_cpu_context *cpuctx);
445 
perf_proc_update_handler(struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)446 int perf_proc_update_handler(struct ctl_table *table, int write,
447 		void *buffer, size_t *lenp, loff_t *ppos)
448 {
449 	int ret;
450 	int perf_cpu = sysctl_perf_cpu_time_max_percent;
451 	/*
452 	 * If throttling is disabled don't allow the write:
453 	 */
454 	if (write && (perf_cpu == 100 || perf_cpu == 0))
455 		return -EINVAL;
456 
457 	ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
458 	if (ret || !write)
459 		return ret;
460 
461 	max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
462 	perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
463 	update_perf_cpu_limits();
464 
465 	return 0;
466 }
467 
468 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
469 
perf_cpu_time_max_percent_handler(struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)470 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
471 		void *buffer, size_t *lenp, loff_t *ppos)
472 {
473 	int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
474 
475 	if (ret || !write)
476 		return ret;
477 
478 	if (sysctl_perf_cpu_time_max_percent == 100 ||
479 	    sysctl_perf_cpu_time_max_percent == 0) {
480 		printk(KERN_WARNING
481 		       "perf: Dynamic interrupt throttling disabled, can hang your system!\n");
482 		WRITE_ONCE(perf_sample_allowed_ns, 0);
483 	} else {
484 		update_perf_cpu_limits();
485 	}
486 
487 	return 0;
488 }
489 
490 /*
491  * perf samples are done in some very critical code paths (NMIs).
492  * If they take too much CPU time, the system can lock up and not
493  * get any real work done.  This will drop the sample rate when
494  * we detect that events are taking too long.
495  */
496 #define NR_ACCUMULATED_SAMPLES 128
497 static DEFINE_PER_CPU(u64, running_sample_length);
498 
499 static u64 __report_avg;
500 static u64 __report_allowed;
501 
perf_duration_warn(struct irq_work * w)502 static void perf_duration_warn(struct irq_work *w)
503 {
504 	printk_ratelimited(KERN_INFO
505 		"perf: interrupt took too long (%lld > %lld), lowering "
506 		"kernel.perf_event_max_sample_rate to %d\n",
507 		__report_avg, __report_allowed,
508 		sysctl_perf_event_sample_rate);
509 }
510 
511 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
512 
perf_sample_event_took(u64 sample_len_ns)513 void perf_sample_event_took(u64 sample_len_ns)
514 {
515 	u64 max_len = READ_ONCE(perf_sample_allowed_ns);
516 	u64 running_len;
517 	u64 avg_len;
518 	u32 max;
519 
520 	if (max_len == 0)
521 		return;
522 
523 	/* Decay the counter by 1 average sample. */
524 	running_len = __this_cpu_read(running_sample_length);
525 	running_len -= running_len/NR_ACCUMULATED_SAMPLES;
526 	running_len += sample_len_ns;
527 	__this_cpu_write(running_sample_length, running_len);
528 
529 	/*
530 	 * Note: this will be biased artifically low until we have
531 	 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
532 	 * from having to maintain a count.
533 	 */
534 	avg_len = running_len/NR_ACCUMULATED_SAMPLES;
535 	if (avg_len <= max_len)
536 		return;
537 
538 	__report_avg = avg_len;
539 	__report_allowed = max_len;
540 
541 	/*
542 	 * Compute a throttle threshold 25% below the current duration.
543 	 */
544 	avg_len += avg_len / 4;
545 	max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent;
546 	if (avg_len < max)
547 		max /= (u32)avg_len;
548 	else
549 		max = 1;
550 
551 	WRITE_ONCE(perf_sample_allowed_ns, avg_len);
552 	WRITE_ONCE(max_samples_per_tick, max);
553 
554 	sysctl_perf_event_sample_rate = max * HZ;
555 	perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
556 
557 	if (!irq_work_queue(&perf_duration_work)) {
558 		early_printk("perf: interrupt took too long (%lld > %lld), lowering "
559 			     "kernel.perf_event_max_sample_rate to %d\n",
560 			     __report_avg, __report_allowed,
561 			     sysctl_perf_event_sample_rate);
562 	}
563 }
564 
565 static atomic64_t perf_event_id;
566 
567 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
568 			      enum event_type_t event_type);
569 
570 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
571 			     enum event_type_t event_type,
572 			     struct task_struct *task);
573 
574 static void update_context_time(struct perf_event_context *ctx);
575 static u64 perf_event_time(struct perf_event *event);
576 
perf_event_print_debug(void)577 void __weak perf_event_print_debug(void)	{ }
578 
perf_pmu_name(void)579 extern __weak const char *perf_pmu_name(void)
580 {
581 	return "pmu";
582 }
583 
perf_clock(void)584 static inline u64 perf_clock(void)
585 {
586 	return local_clock();
587 }
588 
perf_event_clock(struct perf_event * event)589 static inline u64 perf_event_clock(struct perf_event *event)
590 {
591 	return event->clock();
592 }
593 
594 /*
595  * State based event timekeeping...
596  *
597  * The basic idea is to use event->state to determine which (if any) time
598  * fields to increment with the current delta. This means we only need to
599  * update timestamps when we change state or when they are explicitly requested
600  * (read).
601  *
602  * Event groups make things a little more complicated, but not terribly so. The
603  * rules for a group are that if the group leader is OFF the entire group is
604  * OFF, irrespecive of what the group member states are. This results in
605  * __perf_effective_state().
606  *
607  * A futher ramification is that when a group leader flips between OFF and
608  * !OFF, we need to update all group member times.
609  *
610  *
611  * NOTE: perf_event_time() is based on the (cgroup) context time, and thus we
612  * need to make sure the relevant context time is updated before we try and
613  * update our timestamps.
614  */
615 
616 static __always_inline enum perf_event_state
__perf_effective_state(struct perf_event * event)617 __perf_effective_state(struct perf_event *event)
618 {
619 	struct perf_event *leader = event->group_leader;
620 
621 	if (leader->state <= PERF_EVENT_STATE_OFF)
622 		return leader->state;
623 
624 	return event->state;
625 }
626 
627 static __always_inline void
__perf_update_times(struct perf_event * event,u64 now,u64 * enabled,u64 * running)628 __perf_update_times(struct perf_event *event, u64 now, u64 *enabled, u64 *running)
629 {
630 	enum perf_event_state state = __perf_effective_state(event);
631 	u64 delta = now - event->tstamp;
632 
633 	*enabled = event->total_time_enabled;
634 	if (state >= PERF_EVENT_STATE_INACTIVE)
635 		*enabled += delta;
636 
637 	*running = event->total_time_running;
638 	if (state >= PERF_EVENT_STATE_ACTIVE)
639 		*running += delta;
640 }
641 
perf_event_update_time(struct perf_event * event)642 static void perf_event_update_time(struct perf_event *event)
643 {
644 	u64 now = perf_event_time(event);
645 
646 	__perf_update_times(event, now, &event->total_time_enabled,
647 					&event->total_time_running);
648 	event->tstamp = now;
649 }
650 
perf_event_update_sibling_time(struct perf_event * leader)651 static void perf_event_update_sibling_time(struct perf_event *leader)
652 {
653 	struct perf_event *sibling;
654 
655 	for_each_sibling_event(sibling, leader)
656 		perf_event_update_time(sibling);
657 }
658 
659 static void
perf_event_set_state(struct perf_event * event,enum perf_event_state state)660 perf_event_set_state(struct perf_event *event, enum perf_event_state state)
661 {
662 	if (event->state == state)
663 		return;
664 
665 	perf_event_update_time(event);
666 	/*
667 	 * If a group leader gets enabled/disabled all its siblings
668 	 * are affected too.
669 	 */
670 	if ((event->state < 0) ^ (state < 0))
671 		perf_event_update_sibling_time(event);
672 
673 	WRITE_ONCE(event->state, state);
674 }
675 
676 /*
677  * UP store-release, load-acquire
678  */
679 
680 #define __store_release(ptr, val)					\
681 do {									\
682 	barrier();							\
683 	WRITE_ONCE(*(ptr), (val));					\
684 } while (0)
685 
686 #define __load_acquire(ptr)						\
687 ({									\
688 	__unqual_scalar_typeof(*(ptr)) ___p = READ_ONCE(*(ptr));	\
689 	barrier();							\
690 	___p;								\
691 })
692 
693 #ifdef CONFIG_CGROUP_PERF
694 
695 static inline bool
perf_cgroup_match(struct perf_event * event)696 perf_cgroup_match(struct perf_event *event)
697 {
698 	struct perf_event_context *ctx = event->ctx;
699 	struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
700 
701 	/* @event doesn't care about cgroup */
702 	if (!event->cgrp)
703 		return true;
704 
705 	/* wants specific cgroup scope but @cpuctx isn't associated with any */
706 	if (!cpuctx->cgrp)
707 		return false;
708 
709 	/*
710 	 * Cgroup scoping is recursive.  An event enabled for a cgroup is
711 	 * also enabled for all its descendant cgroups.  If @cpuctx's
712 	 * cgroup is a descendant of @event's (the test covers identity
713 	 * case), it's a match.
714 	 */
715 	return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
716 				    event->cgrp->css.cgroup);
717 }
718 
perf_detach_cgroup(struct perf_event * event)719 static inline void perf_detach_cgroup(struct perf_event *event)
720 {
721 	css_put(&event->cgrp->css);
722 	event->cgrp = NULL;
723 }
724 
is_cgroup_event(struct perf_event * event)725 static inline int is_cgroup_event(struct perf_event *event)
726 {
727 	return event->cgrp != NULL;
728 }
729 
perf_cgroup_event_time(struct perf_event * event)730 static inline u64 perf_cgroup_event_time(struct perf_event *event)
731 {
732 	struct perf_cgroup_info *t;
733 
734 	t = per_cpu_ptr(event->cgrp->info, event->cpu);
735 	return t->time;
736 }
737 
perf_cgroup_event_time_now(struct perf_event * event,u64 now)738 static inline u64 perf_cgroup_event_time_now(struct perf_event *event, u64 now)
739 {
740 	struct perf_cgroup_info *t;
741 
742 	t = per_cpu_ptr(event->cgrp->info, event->cpu);
743 	if (!__load_acquire(&t->active))
744 		return t->time;
745 	now += READ_ONCE(t->timeoffset);
746 	return now;
747 }
748 
__update_cgrp_time(struct perf_cgroup_info * info,u64 now,bool adv)749 static inline void __update_cgrp_time(struct perf_cgroup_info *info, u64 now, bool adv)
750 {
751 	if (adv)
752 		info->time += now - info->timestamp;
753 	info->timestamp = now;
754 	/*
755 	 * see update_context_time()
756 	 */
757 	WRITE_ONCE(info->timeoffset, info->time - info->timestamp);
758 }
759 
update_cgrp_time_from_cpuctx(struct perf_cpu_context * cpuctx,bool final)760 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx, bool final)
761 {
762 	struct perf_cgroup *cgrp = cpuctx->cgrp;
763 	struct cgroup_subsys_state *css;
764 	struct perf_cgroup_info *info;
765 
766 	if (cgrp) {
767 		u64 now = perf_clock();
768 
769 		for (css = &cgrp->css; css; css = css->parent) {
770 			cgrp = container_of(css, struct perf_cgroup, css);
771 			info = this_cpu_ptr(cgrp->info);
772 
773 			__update_cgrp_time(info, now, true);
774 			if (final)
775 				__store_release(&info->active, 0);
776 		}
777 	}
778 }
779 
update_cgrp_time_from_event(struct perf_event * event)780 static inline void update_cgrp_time_from_event(struct perf_event *event)
781 {
782 	struct perf_cgroup_info *info;
783 	struct perf_cgroup *cgrp;
784 
785 	/*
786 	 * ensure we access cgroup data only when needed and
787 	 * when we know the cgroup is pinned (css_get)
788 	 */
789 	if (!is_cgroup_event(event))
790 		return;
791 
792 	cgrp = perf_cgroup_from_task(current, event->ctx);
793 	/*
794 	 * Do not update time when cgroup is not active
795 	 */
796 	if (cgroup_is_descendant(cgrp->css.cgroup, event->cgrp->css.cgroup)) {
797 		info = this_cpu_ptr(event->cgrp->info);
798 		__update_cgrp_time(info, perf_clock(), true);
799 	}
800 }
801 
802 static inline void
perf_cgroup_set_timestamp(struct task_struct * task,struct perf_event_context * ctx)803 perf_cgroup_set_timestamp(struct task_struct *task,
804 			  struct perf_event_context *ctx)
805 {
806 	struct perf_cgroup *cgrp;
807 	struct perf_cgroup_info *info;
808 	struct cgroup_subsys_state *css;
809 
810 	/*
811 	 * ctx->lock held by caller
812 	 * ensure we do not access cgroup data
813 	 * unless we have the cgroup pinned (css_get)
814 	 */
815 	if (!task || !ctx->nr_cgroups)
816 		return;
817 
818 	cgrp = perf_cgroup_from_task(task, ctx);
819 
820 	for (css = &cgrp->css; css; css = css->parent) {
821 		cgrp = container_of(css, struct perf_cgroup, css);
822 		info = this_cpu_ptr(cgrp->info);
823 		__update_cgrp_time(info, ctx->timestamp, false);
824 		__store_release(&info->active, 1);
825 	}
826 }
827 
828 static DEFINE_PER_CPU(struct list_head, cgrp_cpuctx_list);
829 
830 #define PERF_CGROUP_SWOUT	0x1 /* cgroup switch out every event */
831 #define PERF_CGROUP_SWIN	0x2 /* cgroup switch in events based on task */
832 
833 /*
834  * reschedule events based on the cgroup constraint of task.
835  *
836  * mode SWOUT : schedule out everything
837  * mode SWIN : schedule in based on cgroup for next
838  */
perf_cgroup_switch(struct task_struct * task,int mode)839 static void perf_cgroup_switch(struct task_struct *task, int mode)
840 {
841 	struct perf_cpu_context *cpuctx, *tmp;
842 	struct list_head *list;
843 	unsigned long flags;
844 
845 	/*
846 	 * Disable interrupts and preemption to avoid this CPU's
847 	 * cgrp_cpuctx_entry to change under us.
848 	 */
849 	local_irq_save(flags);
850 
851 	list = this_cpu_ptr(&cgrp_cpuctx_list);
852 	list_for_each_entry_safe(cpuctx, tmp, list, cgrp_cpuctx_entry) {
853 		WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0);
854 
855 		perf_ctx_lock(cpuctx, cpuctx->task_ctx);
856 		perf_pmu_disable(cpuctx->ctx.pmu);
857 
858 		if (mode & PERF_CGROUP_SWOUT) {
859 			cpu_ctx_sched_out(cpuctx, EVENT_ALL);
860 			/*
861 			 * must not be done before ctxswout due
862 			 * to event_filter_match() in event_sched_out()
863 			 */
864 			cpuctx->cgrp = NULL;
865 		}
866 
867 		if (mode & PERF_CGROUP_SWIN) {
868 			WARN_ON_ONCE(cpuctx->cgrp);
869 			/*
870 			 * set cgrp before ctxsw in to allow
871 			 * event_filter_match() to not have to pass
872 			 * task around
873 			 * we pass the cpuctx->ctx to perf_cgroup_from_task()
874 			 * because cgorup events are only per-cpu
875 			 */
876 			cpuctx->cgrp = perf_cgroup_from_task(task,
877 							     &cpuctx->ctx);
878 			cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
879 		}
880 		perf_pmu_enable(cpuctx->ctx.pmu);
881 		perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
882 	}
883 
884 	local_irq_restore(flags);
885 }
886 
perf_cgroup_sched_out(struct task_struct * task,struct task_struct * next)887 static inline void perf_cgroup_sched_out(struct task_struct *task,
888 					 struct task_struct *next)
889 {
890 	struct perf_cgroup *cgrp1;
891 	struct perf_cgroup *cgrp2 = NULL;
892 
893 	rcu_read_lock();
894 	/*
895 	 * we come here when we know perf_cgroup_events > 0
896 	 * we do not need to pass the ctx here because we know
897 	 * we are holding the rcu lock
898 	 */
899 	cgrp1 = perf_cgroup_from_task(task, NULL);
900 	cgrp2 = perf_cgroup_from_task(next, NULL);
901 
902 	/*
903 	 * only schedule out current cgroup events if we know
904 	 * that we are switching to a different cgroup. Otherwise,
905 	 * do no touch the cgroup events.
906 	 */
907 	if (cgrp1 != cgrp2)
908 		perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
909 
910 	rcu_read_unlock();
911 }
912 
perf_cgroup_sched_in(struct task_struct * prev,struct task_struct * task)913 static inline void perf_cgroup_sched_in(struct task_struct *prev,
914 					struct task_struct *task)
915 {
916 	struct perf_cgroup *cgrp1;
917 	struct perf_cgroup *cgrp2 = NULL;
918 
919 	rcu_read_lock();
920 	/*
921 	 * we come here when we know perf_cgroup_events > 0
922 	 * we do not need to pass the ctx here because we know
923 	 * we are holding the rcu lock
924 	 */
925 	cgrp1 = perf_cgroup_from_task(task, NULL);
926 	cgrp2 = perf_cgroup_from_task(prev, NULL);
927 
928 	/*
929 	 * only need to schedule in cgroup events if we are changing
930 	 * cgroup during ctxsw. Cgroup events were not scheduled
931 	 * out of ctxsw out if that was not the case.
932 	 */
933 	if (cgrp1 != cgrp2)
934 		perf_cgroup_switch(task, PERF_CGROUP_SWIN);
935 
936 	rcu_read_unlock();
937 }
938 
perf_cgroup_ensure_storage(struct perf_event * event,struct cgroup_subsys_state * css)939 static int perf_cgroup_ensure_storage(struct perf_event *event,
940 				struct cgroup_subsys_state *css)
941 {
942 	struct perf_cpu_context *cpuctx;
943 	struct perf_event **storage;
944 	int cpu, heap_size, ret = 0;
945 
946 	/*
947 	 * Allow storage to have sufficent space for an iterator for each
948 	 * possibly nested cgroup plus an iterator for events with no cgroup.
949 	 */
950 	for (heap_size = 1; css; css = css->parent)
951 		heap_size++;
952 
953 	for_each_possible_cpu(cpu) {
954 		cpuctx = per_cpu_ptr(event->pmu->pmu_cpu_context, cpu);
955 		if (heap_size <= cpuctx->heap_size)
956 			continue;
957 
958 		storage = kmalloc_node(heap_size * sizeof(struct perf_event *),
959 				       GFP_KERNEL, cpu_to_node(cpu));
960 		if (!storage) {
961 			ret = -ENOMEM;
962 			break;
963 		}
964 
965 		raw_spin_lock_irq(&cpuctx->ctx.lock);
966 		if (cpuctx->heap_size < heap_size) {
967 			swap(cpuctx->heap, storage);
968 			if (storage == cpuctx->heap_default)
969 				storage = NULL;
970 			cpuctx->heap_size = heap_size;
971 		}
972 		raw_spin_unlock_irq(&cpuctx->ctx.lock);
973 
974 		kfree(storage);
975 	}
976 
977 	return ret;
978 }
979 
perf_cgroup_connect(int fd,struct perf_event * event,struct perf_event_attr * attr,struct perf_event * group_leader)980 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
981 				      struct perf_event_attr *attr,
982 				      struct perf_event *group_leader)
983 {
984 	struct perf_cgroup *cgrp;
985 	struct cgroup_subsys_state *css;
986 	struct fd f = fdget(fd);
987 	int ret = 0;
988 
989 	if (!f.file)
990 		return -EBADF;
991 
992 	css = css_tryget_online_from_dir(f.file->f_path.dentry,
993 					 &perf_event_cgrp_subsys);
994 	if (IS_ERR(css)) {
995 		ret = PTR_ERR(css);
996 		goto out;
997 	}
998 
999 	ret = perf_cgroup_ensure_storage(event, css);
1000 	if (ret)
1001 		goto out;
1002 
1003 	cgrp = container_of(css, struct perf_cgroup, css);
1004 	event->cgrp = cgrp;
1005 
1006 	/*
1007 	 * all events in a group must monitor
1008 	 * the same cgroup because a task belongs
1009 	 * to only one perf cgroup at a time
1010 	 */
1011 	if (group_leader && group_leader->cgrp != cgrp) {
1012 		perf_detach_cgroup(event);
1013 		ret = -EINVAL;
1014 	}
1015 out:
1016 	fdput(f);
1017 	return ret;
1018 }
1019 
1020 static inline void
perf_cgroup_event_enable(struct perf_event * event,struct perf_event_context * ctx)1021 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
1022 {
1023 	struct perf_cpu_context *cpuctx;
1024 
1025 	if (!is_cgroup_event(event))
1026 		return;
1027 
1028 	/*
1029 	 * Because cgroup events are always per-cpu events,
1030 	 * @ctx == &cpuctx->ctx.
1031 	 */
1032 	cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
1033 
1034 	/*
1035 	 * Since setting cpuctx->cgrp is conditional on the current @cgrp
1036 	 * matching the event's cgroup, we must do this for every new event,
1037 	 * because if the first would mismatch, the second would not try again
1038 	 * and we would leave cpuctx->cgrp unset.
1039 	 */
1040 	if (ctx->is_active && !cpuctx->cgrp) {
1041 		struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
1042 
1043 		if (cgroup_is_descendant(cgrp->css.cgroup, event->cgrp->css.cgroup))
1044 			cpuctx->cgrp = cgrp;
1045 	}
1046 
1047 	if (ctx->nr_cgroups++)
1048 		return;
1049 
1050 	list_add(&cpuctx->cgrp_cpuctx_entry,
1051 			per_cpu_ptr(&cgrp_cpuctx_list, event->cpu));
1052 }
1053 
1054 static inline void
perf_cgroup_event_disable(struct perf_event * event,struct perf_event_context * ctx)1055 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1056 {
1057 	struct perf_cpu_context *cpuctx;
1058 
1059 	if (!is_cgroup_event(event))
1060 		return;
1061 
1062 	/*
1063 	 * Because cgroup events are always per-cpu events,
1064 	 * @ctx == &cpuctx->ctx.
1065 	 */
1066 	cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
1067 
1068 	if (--ctx->nr_cgroups)
1069 		return;
1070 
1071 	if (ctx->is_active && cpuctx->cgrp)
1072 		cpuctx->cgrp = NULL;
1073 
1074 	list_del(&cpuctx->cgrp_cpuctx_entry);
1075 }
1076 
1077 #else /* !CONFIG_CGROUP_PERF */
1078 
1079 static inline bool
perf_cgroup_match(struct perf_event * event)1080 perf_cgroup_match(struct perf_event *event)
1081 {
1082 	return true;
1083 }
1084 
perf_detach_cgroup(struct perf_event * event)1085 static inline void perf_detach_cgroup(struct perf_event *event)
1086 {}
1087 
is_cgroup_event(struct perf_event * event)1088 static inline int is_cgroup_event(struct perf_event *event)
1089 {
1090 	return 0;
1091 }
1092 
update_cgrp_time_from_event(struct perf_event * event)1093 static inline void update_cgrp_time_from_event(struct perf_event *event)
1094 {
1095 }
1096 
update_cgrp_time_from_cpuctx(struct perf_cpu_context * cpuctx,bool final)1097 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx,
1098 						bool final)
1099 {
1100 }
1101 
perf_cgroup_sched_out(struct task_struct * task,struct task_struct * next)1102 static inline void perf_cgroup_sched_out(struct task_struct *task,
1103 					 struct task_struct *next)
1104 {
1105 }
1106 
perf_cgroup_sched_in(struct task_struct * prev,struct task_struct * task)1107 static inline void perf_cgroup_sched_in(struct task_struct *prev,
1108 					struct task_struct *task)
1109 {
1110 }
1111 
perf_cgroup_connect(pid_t pid,struct perf_event * event,struct perf_event_attr * attr,struct perf_event * group_leader)1112 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
1113 				      struct perf_event_attr *attr,
1114 				      struct perf_event *group_leader)
1115 {
1116 	return -EINVAL;
1117 }
1118 
1119 static inline void
perf_cgroup_set_timestamp(struct task_struct * task,struct perf_event_context * ctx)1120 perf_cgroup_set_timestamp(struct task_struct *task,
1121 			  struct perf_event_context *ctx)
1122 {
1123 }
1124 
1125 static inline void
perf_cgroup_switch(struct task_struct * task,struct task_struct * next)1126 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
1127 {
1128 }
1129 
perf_cgroup_event_time(struct perf_event * event)1130 static inline u64 perf_cgroup_event_time(struct perf_event *event)
1131 {
1132 	return 0;
1133 }
1134 
perf_cgroup_event_time_now(struct perf_event * event,u64 now)1135 static inline u64 perf_cgroup_event_time_now(struct perf_event *event, u64 now)
1136 {
1137 	return 0;
1138 }
1139 
1140 static inline void
perf_cgroup_event_enable(struct perf_event * event,struct perf_event_context * ctx)1141 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
1142 {
1143 }
1144 
1145 static inline void
perf_cgroup_event_disable(struct perf_event * event,struct perf_event_context * ctx)1146 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1147 {
1148 }
1149 #endif
1150 
1151 /*
1152  * set default to be dependent on timer tick just
1153  * like original code
1154  */
1155 #define PERF_CPU_HRTIMER (1000 / HZ)
1156 /*
1157  * function must be called with interrupts disabled
1158  */
perf_mux_hrtimer_handler(struct hrtimer * hr)1159 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
1160 {
1161 	struct perf_cpu_context *cpuctx;
1162 	bool rotations;
1163 
1164 	lockdep_assert_irqs_disabled();
1165 
1166 	cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
1167 	rotations = perf_rotate_context(cpuctx);
1168 
1169 	raw_spin_lock(&cpuctx->hrtimer_lock);
1170 	if (rotations)
1171 		hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
1172 	else
1173 		cpuctx->hrtimer_active = 0;
1174 	raw_spin_unlock(&cpuctx->hrtimer_lock);
1175 
1176 	return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
1177 }
1178 
__perf_mux_hrtimer_init(struct perf_cpu_context * cpuctx,int cpu)1179 static void __perf_mux_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
1180 {
1181 	struct hrtimer *timer = &cpuctx->hrtimer;
1182 	struct pmu *pmu = cpuctx->ctx.pmu;
1183 	u64 interval;
1184 
1185 	/* no multiplexing needed for SW PMU */
1186 	if (pmu->task_ctx_nr == perf_sw_context)
1187 		return;
1188 
1189 	/*
1190 	 * check default is sane, if not set then force to
1191 	 * default interval (1/tick)
1192 	 */
1193 	interval = pmu->hrtimer_interval_ms;
1194 	if (interval < 1)
1195 		interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
1196 
1197 	cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
1198 
1199 	raw_spin_lock_init(&cpuctx->hrtimer_lock);
1200 	hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED_HARD);
1201 	timer->function = perf_mux_hrtimer_handler;
1202 }
1203 
perf_mux_hrtimer_restart(struct perf_cpu_context * cpuctx)1204 static int perf_mux_hrtimer_restart(struct perf_cpu_context *cpuctx)
1205 {
1206 	struct hrtimer *timer = &cpuctx->hrtimer;
1207 	struct pmu *pmu = cpuctx->ctx.pmu;
1208 	unsigned long flags;
1209 
1210 	/* not for SW PMU */
1211 	if (pmu->task_ctx_nr == perf_sw_context)
1212 		return 0;
1213 
1214 	raw_spin_lock_irqsave(&cpuctx->hrtimer_lock, flags);
1215 	if (!cpuctx->hrtimer_active) {
1216 		cpuctx->hrtimer_active = 1;
1217 		hrtimer_forward_now(timer, cpuctx->hrtimer_interval);
1218 		hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED_HARD);
1219 	}
1220 	raw_spin_unlock_irqrestore(&cpuctx->hrtimer_lock, flags);
1221 
1222 	return 0;
1223 }
1224 
perf_mux_hrtimer_restart_ipi(void * arg)1225 static int perf_mux_hrtimer_restart_ipi(void *arg)
1226 {
1227 	return perf_mux_hrtimer_restart(arg);
1228 }
1229 
perf_pmu_disable(struct pmu * pmu)1230 void perf_pmu_disable(struct pmu *pmu)
1231 {
1232 	int *count = this_cpu_ptr(pmu->pmu_disable_count);
1233 	if (!(*count)++)
1234 		pmu->pmu_disable(pmu);
1235 }
1236 
perf_pmu_enable(struct pmu * pmu)1237 void perf_pmu_enable(struct pmu *pmu)
1238 {
1239 	int *count = this_cpu_ptr(pmu->pmu_disable_count);
1240 	if (!--(*count))
1241 		pmu->pmu_enable(pmu);
1242 }
1243 
1244 static DEFINE_PER_CPU(struct list_head, active_ctx_list);
1245 
1246 /*
1247  * perf_event_ctx_activate(), perf_event_ctx_deactivate(), and
1248  * perf_event_task_tick() are fully serialized because they're strictly cpu
1249  * affine and perf_event_ctx{activate,deactivate} are called with IRQs
1250  * disabled, while perf_event_task_tick is called from IRQ context.
1251  */
perf_event_ctx_activate(struct perf_event_context * ctx)1252 static void perf_event_ctx_activate(struct perf_event_context *ctx)
1253 {
1254 	struct list_head *head = this_cpu_ptr(&active_ctx_list);
1255 
1256 	lockdep_assert_irqs_disabled();
1257 
1258 	WARN_ON(!list_empty(&ctx->active_ctx_list));
1259 
1260 	list_add(&ctx->active_ctx_list, head);
1261 }
1262 
perf_event_ctx_deactivate(struct perf_event_context * ctx)1263 static void perf_event_ctx_deactivate(struct perf_event_context *ctx)
1264 {
1265 	lockdep_assert_irqs_disabled();
1266 
1267 	WARN_ON(list_empty(&ctx->active_ctx_list));
1268 
1269 	list_del_init(&ctx->active_ctx_list);
1270 }
1271 
get_ctx(struct perf_event_context * ctx)1272 static void get_ctx(struct perf_event_context *ctx)
1273 {
1274 	refcount_inc(&ctx->refcount);
1275 }
1276 
alloc_task_ctx_data(struct pmu * pmu)1277 static void *alloc_task_ctx_data(struct pmu *pmu)
1278 {
1279 	if (pmu->task_ctx_cache)
1280 		return kmem_cache_zalloc(pmu->task_ctx_cache, GFP_KERNEL);
1281 
1282 	return NULL;
1283 }
1284 
free_task_ctx_data(struct pmu * pmu,void * task_ctx_data)1285 static void free_task_ctx_data(struct pmu *pmu, void *task_ctx_data)
1286 {
1287 	if (pmu->task_ctx_cache && task_ctx_data)
1288 		kmem_cache_free(pmu->task_ctx_cache, task_ctx_data);
1289 }
1290 
free_ctx(struct rcu_head * head)1291 static void free_ctx(struct rcu_head *head)
1292 {
1293 	struct perf_event_context *ctx;
1294 
1295 	ctx = container_of(head, struct perf_event_context, rcu_head);
1296 	free_task_ctx_data(ctx->pmu, ctx->task_ctx_data);
1297 	kfree(ctx);
1298 }
1299 
put_ctx(struct perf_event_context * ctx)1300 static void put_ctx(struct perf_event_context *ctx)
1301 {
1302 	if (refcount_dec_and_test(&ctx->refcount)) {
1303 		if (ctx->parent_ctx)
1304 			put_ctx(ctx->parent_ctx);
1305 		if (ctx->task && ctx->task != TASK_TOMBSTONE)
1306 			put_task_struct(ctx->task);
1307 		call_rcu(&ctx->rcu_head, free_ctx);
1308 	}
1309 }
1310 
1311 /*
1312  * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
1313  * perf_pmu_migrate_context() we need some magic.
1314  *
1315  * Those places that change perf_event::ctx will hold both
1316  * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
1317  *
1318  * Lock ordering is by mutex address. There are two other sites where
1319  * perf_event_context::mutex nests and those are:
1320  *
1321  *  - perf_event_exit_task_context()	[ child , 0 ]
1322  *      perf_event_exit_event()
1323  *        put_event()			[ parent, 1 ]
1324  *
1325  *  - perf_event_init_context()		[ parent, 0 ]
1326  *      inherit_task_group()
1327  *        inherit_group()
1328  *          inherit_event()
1329  *            perf_event_alloc()
1330  *              perf_init_event()
1331  *                perf_try_init_event()	[ child , 1 ]
1332  *
1333  * While it appears there is an obvious deadlock here -- the parent and child
1334  * nesting levels are inverted between the two. This is in fact safe because
1335  * life-time rules separate them. That is an exiting task cannot fork, and a
1336  * spawning task cannot (yet) exit.
1337  *
1338  * But remember that these are parent<->child context relations, and
1339  * migration does not affect children, therefore these two orderings should not
1340  * interact.
1341  *
1342  * The change in perf_event::ctx does not affect children (as claimed above)
1343  * because the sys_perf_event_open() case will install a new event and break
1344  * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
1345  * concerned with cpuctx and that doesn't have children.
1346  *
1347  * The places that change perf_event::ctx will issue:
1348  *
1349  *   perf_remove_from_context();
1350  *   synchronize_rcu();
1351  *   perf_install_in_context();
1352  *
1353  * to affect the change. The remove_from_context() + synchronize_rcu() should
1354  * quiesce the event, after which we can install it in the new location. This
1355  * means that only external vectors (perf_fops, prctl) can perturb the event
1356  * while in transit. Therefore all such accessors should also acquire
1357  * perf_event_context::mutex to serialize against this.
1358  *
1359  * However; because event->ctx can change while we're waiting to acquire
1360  * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
1361  * function.
1362  *
1363  * Lock order:
1364  *    exec_update_lock
1365  *	task_struct::perf_event_mutex
1366  *	  perf_event_context::mutex
1367  *	    perf_event::child_mutex;
1368  *	      perf_event_context::lock
1369  *	    perf_event::mmap_mutex
1370  *	    mmap_lock
1371  *	      perf_addr_filters_head::lock
1372  *
1373  *    cpu_hotplug_lock
1374  *      pmus_lock
1375  *	  cpuctx->mutex / perf_event_context::mutex
1376  */
1377 static struct perf_event_context *
perf_event_ctx_lock_nested(struct perf_event * event,int nesting)1378 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
1379 {
1380 	struct perf_event_context *ctx;
1381 
1382 again:
1383 	rcu_read_lock();
1384 	ctx = READ_ONCE(event->ctx);
1385 	if (!refcount_inc_not_zero(&ctx->refcount)) {
1386 		rcu_read_unlock();
1387 		goto again;
1388 	}
1389 	rcu_read_unlock();
1390 
1391 	mutex_lock_nested(&ctx->mutex, nesting);
1392 	if (event->ctx != ctx) {
1393 		mutex_unlock(&ctx->mutex);
1394 		put_ctx(ctx);
1395 		goto again;
1396 	}
1397 
1398 	return ctx;
1399 }
1400 
1401 static inline struct perf_event_context *
perf_event_ctx_lock(struct perf_event * event)1402 perf_event_ctx_lock(struct perf_event *event)
1403 {
1404 	return perf_event_ctx_lock_nested(event, 0);
1405 }
1406 
perf_event_ctx_unlock(struct perf_event * event,struct perf_event_context * ctx)1407 static void perf_event_ctx_unlock(struct perf_event *event,
1408 				  struct perf_event_context *ctx)
1409 {
1410 	mutex_unlock(&ctx->mutex);
1411 	put_ctx(ctx);
1412 }
1413 
1414 /*
1415  * This must be done under the ctx->lock, such as to serialize against
1416  * context_equiv(), therefore we cannot call put_ctx() since that might end up
1417  * calling scheduler related locks and ctx->lock nests inside those.
1418  */
1419 static __must_check struct perf_event_context *
unclone_ctx(struct perf_event_context * ctx)1420 unclone_ctx(struct perf_event_context *ctx)
1421 {
1422 	struct perf_event_context *parent_ctx = ctx->parent_ctx;
1423 
1424 	lockdep_assert_held(&ctx->lock);
1425 
1426 	if (parent_ctx)
1427 		ctx->parent_ctx = NULL;
1428 	ctx->generation++;
1429 
1430 	return parent_ctx;
1431 }
1432 
perf_event_pid_type(struct perf_event * event,struct task_struct * p,enum pid_type type)1433 static u32 perf_event_pid_type(struct perf_event *event, struct task_struct *p,
1434 				enum pid_type type)
1435 {
1436 	u32 nr;
1437 	/*
1438 	 * only top level events have the pid namespace they were created in
1439 	 */
1440 	if (event->parent)
1441 		event = event->parent;
1442 
1443 	nr = __task_pid_nr_ns(p, type, event->ns);
1444 	/* avoid -1 if it is idle thread or runs in another ns */
1445 	if (!nr && !pid_alive(p))
1446 		nr = -1;
1447 	return nr;
1448 }
1449 
perf_event_pid(struct perf_event * event,struct task_struct * p)1450 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1451 {
1452 	return perf_event_pid_type(event, p, PIDTYPE_TGID);
1453 }
1454 
perf_event_tid(struct perf_event * event,struct task_struct * p)1455 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1456 {
1457 	return perf_event_pid_type(event, p, PIDTYPE_PID);
1458 }
1459 
1460 /*
1461  * If we inherit events we want to return the parent event id
1462  * to userspace.
1463  */
primary_event_id(struct perf_event * event)1464 static u64 primary_event_id(struct perf_event *event)
1465 {
1466 	u64 id = event->id;
1467 
1468 	if (event->parent)
1469 		id = event->parent->id;
1470 
1471 	return id;
1472 }
1473 
1474 /*
1475  * Get the perf_event_context for a task and lock it.
1476  *
1477  * This has to cope with the fact that until it is locked,
1478  * the context could get moved to another task.
1479  */
1480 static struct perf_event_context *
perf_lock_task_context(struct task_struct * task,int ctxn,unsigned long * flags)1481 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
1482 {
1483 	struct perf_event_context *ctx;
1484 
1485 retry:
1486 	/*
1487 	 * One of the few rules of preemptible RCU is that one cannot do
1488 	 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1489 	 * part of the read side critical section was irqs-enabled -- see
1490 	 * rcu_read_unlock_special().
1491 	 *
1492 	 * Since ctx->lock nests under rq->lock we must ensure the entire read
1493 	 * side critical section has interrupts disabled.
1494 	 */
1495 	local_irq_save(*flags);
1496 	rcu_read_lock();
1497 	ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
1498 	if (ctx) {
1499 		/*
1500 		 * If this context is a clone of another, it might
1501 		 * get swapped for another underneath us by
1502 		 * perf_event_task_sched_out, though the
1503 		 * rcu_read_lock() protects us from any context
1504 		 * getting freed.  Lock the context and check if it
1505 		 * got swapped before we could get the lock, and retry
1506 		 * if so.  If we locked the right context, then it
1507 		 * can't get swapped on us any more.
1508 		 */
1509 		raw_spin_lock(&ctx->lock);
1510 		if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
1511 			raw_spin_unlock(&ctx->lock);
1512 			rcu_read_unlock();
1513 			local_irq_restore(*flags);
1514 			goto retry;
1515 		}
1516 
1517 		if (ctx->task == TASK_TOMBSTONE ||
1518 		    !refcount_inc_not_zero(&ctx->refcount)) {
1519 			raw_spin_unlock(&ctx->lock);
1520 			ctx = NULL;
1521 		} else {
1522 			WARN_ON_ONCE(ctx->task != task);
1523 		}
1524 	}
1525 	rcu_read_unlock();
1526 	if (!ctx)
1527 		local_irq_restore(*flags);
1528 	return ctx;
1529 }
1530 
1531 /*
1532  * Get the context for a task and increment its pin_count so it
1533  * can't get swapped to another task.  This also increments its
1534  * reference count so that the context can't get freed.
1535  */
1536 static struct perf_event_context *
perf_pin_task_context(struct task_struct * task,int ctxn)1537 perf_pin_task_context(struct task_struct *task, int ctxn)
1538 {
1539 	struct perf_event_context *ctx;
1540 	unsigned long flags;
1541 
1542 	ctx = perf_lock_task_context(task, ctxn, &flags);
1543 	if (ctx) {
1544 		++ctx->pin_count;
1545 		raw_spin_unlock_irqrestore(&ctx->lock, flags);
1546 	}
1547 	return ctx;
1548 }
1549 
perf_unpin_context(struct perf_event_context * ctx)1550 static void perf_unpin_context(struct perf_event_context *ctx)
1551 {
1552 	unsigned long flags;
1553 
1554 	raw_spin_lock_irqsave(&ctx->lock, flags);
1555 	--ctx->pin_count;
1556 	raw_spin_unlock_irqrestore(&ctx->lock, flags);
1557 }
1558 
1559 /*
1560  * Update the record of the current time in a context.
1561  */
__update_context_time(struct perf_event_context * ctx,bool adv)1562 static void __update_context_time(struct perf_event_context *ctx, bool adv)
1563 {
1564 	u64 now = perf_clock();
1565 
1566 	if (adv)
1567 		ctx->time += now - ctx->timestamp;
1568 	ctx->timestamp = now;
1569 
1570 	/*
1571 	 * The above: time' = time + (now - timestamp), can be re-arranged
1572 	 * into: time` = now + (time - timestamp), which gives a single value
1573 	 * offset to compute future time without locks on.
1574 	 *
1575 	 * See perf_event_time_now(), which can be used from NMI context where
1576 	 * it's (obviously) not possible to acquire ctx->lock in order to read
1577 	 * both the above values in a consistent manner.
1578 	 */
1579 	WRITE_ONCE(ctx->timeoffset, ctx->time - ctx->timestamp);
1580 }
1581 
update_context_time(struct perf_event_context * ctx)1582 static void update_context_time(struct perf_event_context *ctx)
1583 {
1584 	__update_context_time(ctx, true);
1585 }
1586 
perf_event_time(struct perf_event * event)1587 static u64 perf_event_time(struct perf_event *event)
1588 {
1589 	struct perf_event_context *ctx = event->ctx;
1590 
1591 	if (unlikely(!ctx))
1592 		return 0;
1593 
1594 	if (is_cgroup_event(event))
1595 		return perf_cgroup_event_time(event);
1596 
1597 	return ctx->time;
1598 }
1599 
perf_event_time_now(struct perf_event * event,u64 now)1600 static u64 perf_event_time_now(struct perf_event *event, u64 now)
1601 {
1602 	struct perf_event_context *ctx = event->ctx;
1603 
1604 	if (unlikely(!ctx))
1605 		return 0;
1606 
1607 	if (is_cgroup_event(event))
1608 		return perf_cgroup_event_time_now(event, now);
1609 
1610 	if (!(__load_acquire(&ctx->is_active) & EVENT_TIME))
1611 		return ctx->time;
1612 
1613 	now += READ_ONCE(ctx->timeoffset);
1614 	return now;
1615 }
1616 
get_event_type(struct perf_event * event)1617 static enum event_type_t get_event_type(struct perf_event *event)
1618 {
1619 	struct perf_event_context *ctx = event->ctx;
1620 	enum event_type_t event_type;
1621 
1622 	lockdep_assert_held(&ctx->lock);
1623 
1624 	/*
1625 	 * It's 'group type', really, because if our group leader is
1626 	 * pinned, so are we.
1627 	 */
1628 	if (event->group_leader != event)
1629 		event = event->group_leader;
1630 
1631 	event_type = event->attr.pinned ? EVENT_PINNED : EVENT_FLEXIBLE;
1632 	if (!ctx->task)
1633 		event_type |= EVENT_CPU;
1634 
1635 	return event_type;
1636 }
1637 
1638 /*
1639  * Helper function to initialize event group nodes.
1640  */
init_event_group(struct perf_event * event)1641 static void init_event_group(struct perf_event *event)
1642 {
1643 	RB_CLEAR_NODE(&event->group_node);
1644 	event->group_index = 0;
1645 }
1646 
1647 /*
1648  * Extract pinned or flexible groups from the context
1649  * based on event attrs bits.
1650  */
1651 static struct perf_event_groups *
get_event_groups(struct perf_event * event,struct perf_event_context * ctx)1652 get_event_groups(struct perf_event *event, struct perf_event_context *ctx)
1653 {
1654 	if (event->attr.pinned)
1655 		return &ctx->pinned_groups;
1656 	else
1657 		return &ctx->flexible_groups;
1658 }
1659 
1660 /*
1661  * Helper function to initializes perf_event_group trees.
1662  */
perf_event_groups_init(struct perf_event_groups * groups)1663 static void perf_event_groups_init(struct perf_event_groups *groups)
1664 {
1665 	groups->tree = RB_ROOT;
1666 	groups->index = 0;
1667 }
1668 
1669 /*
1670  * Compare function for event groups;
1671  *
1672  * Implements complex key that first sorts by CPU and then by virtual index
1673  * which provides ordering when rotating groups for the same CPU.
1674  */
1675 static bool
perf_event_groups_less(struct perf_event * left,struct perf_event * right)1676 perf_event_groups_less(struct perf_event *left, struct perf_event *right)
1677 {
1678 	if (left->cpu < right->cpu)
1679 		return true;
1680 	if (left->cpu > right->cpu)
1681 		return false;
1682 
1683 #ifdef CONFIG_CGROUP_PERF
1684 	if (left->cgrp != right->cgrp) {
1685 		if (!left->cgrp || !left->cgrp->css.cgroup) {
1686 			/*
1687 			 * Left has no cgroup but right does, no cgroups come
1688 			 * first.
1689 			 */
1690 			return true;
1691 		}
1692 		if (!right->cgrp || !right->cgrp->css.cgroup) {
1693 			/*
1694 			 * Right has no cgroup but left does, no cgroups come
1695 			 * first.
1696 			 */
1697 			return false;
1698 		}
1699 		/* Two dissimilar cgroups, order by id. */
1700 		if (left->cgrp->css.cgroup->kn->id < right->cgrp->css.cgroup->kn->id)
1701 			return true;
1702 
1703 		return false;
1704 	}
1705 #endif
1706 
1707 	if (left->group_index < right->group_index)
1708 		return true;
1709 	if (left->group_index > right->group_index)
1710 		return false;
1711 
1712 	return false;
1713 }
1714 
1715 /*
1716  * Insert @event into @groups' tree; using {@event->cpu, ++@groups->index} for
1717  * key (see perf_event_groups_less). This places it last inside the CPU
1718  * subtree.
1719  */
1720 static void
perf_event_groups_insert(struct perf_event_groups * groups,struct perf_event * event)1721 perf_event_groups_insert(struct perf_event_groups *groups,
1722 			 struct perf_event *event)
1723 {
1724 	struct perf_event *node_event;
1725 	struct rb_node *parent;
1726 	struct rb_node **node;
1727 
1728 	event->group_index = ++groups->index;
1729 
1730 	node = &groups->tree.rb_node;
1731 	parent = *node;
1732 
1733 	while (*node) {
1734 		parent = *node;
1735 		node_event = container_of(*node, struct perf_event, group_node);
1736 
1737 		if (perf_event_groups_less(event, node_event))
1738 			node = &parent->rb_left;
1739 		else
1740 			node = &parent->rb_right;
1741 	}
1742 
1743 	rb_link_node(&event->group_node, parent, node);
1744 	rb_insert_color(&event->group_node, &groups->tree);
1745 }
1746 
1747 /*
1748  * Helper function to insert event into the pinned or flexible groups.
1749  */
1750 static void
add_event_to_groups(struct perf_event * event,struct perf_event_context * ctx)1751 add_event_to_groups(struct perf_event *event, struct perf_event_context *ctx)
1752 {
1753 	struct perf_event_groups *groups;
1754 
1755 	groups = get_event_groups(event, ctx);
1756 	perf_event_groups_insert(groups, event);
1757 }
1758 
1759 /*
1760  * Delete a group from a tree.
1761  */
1762 static void
perf_event_groups_delete(struct perf_event_groups * groups,struct perf_event * event)1763 perf_event_groups_delete(struct perf_event_groups *groups,
1764 			 struct perf_event *event)
1765 {
1766 	WARN_ON_ONCE(RB_EMPTY_NODE(&event->group_node) ||
1767 		     RB_EMPTY_ROOT(&groups->tree));
1768 
1769 	rb_erase(&event->group_node, &groups->tree);
1770 	init_event_group(event);
1771 }
1772 
1773 /*
1774  * Helper function to delete event from its groups.
1775  */
1776 static void
del_event_from_groups(struct perf_event * event,struct perf_event_context * ctx)1777 del_event_from_groups(struct perf_event *event, struct perf_event_context *ctx)
1778 {
1779 	struct perf_event_groups *groups;
1780 
1781 	groups = get_event_groups(event, ctx);
1782 	perf_event_groups_delete(groups, event);
1783 }
1784 
1785 /*
1786  * Get the leftmost event in the cpu/cgroup subtree.
1787  */
1788 static struct perf_event *
perf_event_groups_first(struct perf_event_groups * groups,int cpu,struct cgroup * cgrp)1789 perf_event_groups_first(struct perf_event_groups *groups, int cpu,
1790 			struct cgroup *cgrp)
1791 {
1792 	struct perf_event *node_event = NULL, *match = NULL;
1793 	struct rb_node *node = groups->tree.rb_node;
1794 #ifdef CONFIG_CGROUP_PERF
1795 	u64 node_cgrp_id, cgrp_id = 0;
1796 
1797 	if (cgrp)
1798 		cgrp_id = cgrp->kn->id;
1799 #endif
1800 
1801 	while (node) {
1802 		node_event = container_of(node, struct perf_event, group_node);
1803 
1804 		if (cpu < node_event->cpu) {
1805 			node = node->rb_left;
1806 			continue;
1807 		}
1808 		if (cpu > node_event->cpu) {
1809 			node = node->rb_right;
1810 			continue;
1811 		}
1812 #ifdef CONFIG_CGROUP_PERF
1813 		node_cgrp_id = 0;
1814 		if (node_event->cgrp && node_event->cgrp->css.cgroup)
1815 			node_cgrp_id = node_event->cgrp->css.cgroup->kn->id;
1816 
1817 		if (cgrp_id < node_cgrp_id) {
1818 			node = node->rb_left;
1819 			continue;
1820 		}
1821 		if (cgrp_id > node_cgrp_id) {
1822 			node = node->rb_right;
1823 			continue;
1824 		}
1825 #endif
1826 		match = node_event;
1827 		node = node->rb_left;
1828 	}
1829 
1830 	return match;
1831 }
1832 
1833 /*
1834  * Like rb_entry_next_safe() for the @cpu subtree.
1835  */
1836 static struct perf_event *
perf_event_groups_next(struct perf_event * event)1837 perf_event_groups_next(struct perf_event *event)
1838 {
1839 	struct perf_event *next;
1840 #ifdef CONFIG_CGROUP_PERF
1841 	u64 curr_cgrp_id = 0;
1842 	u64 next_cgrp_id = 0;
1843 #endif
1844 
1845 	next = rb_entry_safe(rb_next(&event->group_node), typeof(*event), group_node);
1846 	if (next == NULL || next->cpu != event->cpu)
1847 		return NULL;
1848 
1849 #ifdef CONFIG_CGROUP_PERF
1850 	if (event->cgrp && event->cgrp->css.cgroup)
1851 		curr_cgrp_id = event->cgrp->css.cgroup->kn->id;
1852 
1853 	if (next->cgrp && next->cgrp->css.cgroup)
1854 		next_cgrp_id = next->cgrp->css.cgroup->kn->id;
1855 
1856 	if (curr_cgrp_id != next_cgrp_id)
1857 		return NULL;
1858 #endif
1859 	return next;
1860 }
1861 
1862 /*
1863  * Iterate through the whole groups tree.
1864  */
1865 #define perf_event_groups_for_each(event, groups)			\
1866 	for (event = rb_entry_safe(rb_first(&((groups)->tree)),		\
1867 				typeof(*event), group_node); event;	\
1868 		event = rb_entry_safe(rb_next(&event->group_node),	\
1869 				typeof(*event), group_node))
1870 
1871 /*
1872  * Add an event from the lists for its context.
1873  * Must be called with ctx->mutex and ctx->lock held.
1874  */
1875 static void
list_add_event(struct perf_event * event,struct perf_event_context * ctx)1876 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1877 {
1878 	lockdep_assert_held(&ctx->lock);
1879 
1880 	WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1881 	event->attach_state |= PERF_ATTACH_CONTEXT;
1882 
1883 	event->tstamp = perf_event_time(event);
1884 
1885 	/*
1886 	 * If we're a stand alone event or group leader, we go to the context
1887 	 * list, group events are kept attached to the group so that
1888 	 * perf_group_detach can, at all times, locate all siblings.
1889 	 */
1890 	if (event->group_leader == event) {
1891 		event->group_caps = event->event_caps;
1892 		add_event_to_groups(event, ctx);
1893 	}
1894 
1895 	list_add_rcu(&event->event_entry, &ctx->event_list);
1896 	ctx->nr_events++;
1897 	if (event->attr.inherit_stat)
1898 		ctx->nr_stat++;
1899 
1900 	if (event->state > PERF_EVENT_STATE_OFF)
1901 		perf_cgroup_event_enable(event, ctx);
1902 
1903 	ctx->generation++;
1904 }
1905 
1906 /*
1907  * Initialize event state based on the perf_event_attr::disabled.
1908  */
perf_event__state_init(struct perf_event * event)1909 static inline void perf_event__state_init(struct perf_event *event)
1910 {
1911 	event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1912 					      PERF_EVENT_STATE_INACTIVE;
1913 }
1914 
__perf_event_read_size(u64 read_format,int nr_siblings)1915 static int __perf_event_read_size(u64 read_format, int nr_siblings)
1916 {
1917 	int entry = sizeof(u64); /* value */
1918 	int size = 0;
1919 	int nr = 1;
1920 
1921 	if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1922 		size += sizeof(u64);
1923 
1924 	if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1925 		size += sizeof(u64);
1926 
1927 	if (read_format & PERF_FORMAT_ID)
1928 		entry += sizeof(u64);
1929 
1930 	if (read_format & PERF_FORMAT_LOST)
1931 		entry += sizeof(u64);
1932 
1933 	if (read_format & PERF_FORMAT_GROUP) {
1934 		nr += nr_siblings;
1935 		size += sizeof(u64);
1936 	}
1937 
1938 	/*
1939 	 * Since perf_event_validate_size() limits this to 16k and inhibits
1940 	 * adding more siblings, this will never overflow.
1941 	 */
1942 	return size + nr * entry;
1943 }
1944 
__perf_event_header_size(struct perf_event * event,u64 sample_type)1945 static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
1946 {
1947 	struct perf_sample_data *data;
1948 	u16 size = 0;
1949 
1950 	if (sample_type & PERF_SAMPLE_IP)
1951 		size += sizeof(data->ip);
1952 
1953 	if (sample_type & PERF_SAMPLE_ADDR)
1954 		size += sizeof(data->addr);
1955 
1956 	if (sample_type & PERF_SAMPLE_PERIOD)
1957 		size += sizeof(data->period);
1958 
1959 	if (sample_type & PERF_SAMPLE_WEIGHT)
1960 		size += sizeof(data->weight);
1961 
1962 	if (sample_type & PERF_SAMPLE_READ)
1963 		size += event->read_size;
1964 
1965 	if (sample_type & PERF_SAMPLE_DATA_SRC)
1966 		size += sizeof(data->data_src.val);
1967 
1968 	if (sample_type & PERF_SAMPLE_TRANSACTION)
1969 		size += sizeof(data->txn);
1970 
1971 	if (sample_type & PERF_SAMPLE_PHYS_ADDR)
1972 		size += sizeof(data->phys_addr);
1973 
1974 	if (sample_type & PERF_SAMPLE_CGROUP)
1975 		size += sizeof(data->cgroup);
1976 
1977 	event->header_size = size;
1978 }
1979 
1980 /*
1981  * Called at perf_event creation and when events are attached/detached from a
1982  * group.
1983  */
perf_event__header_size(struct perf_event * event)1984 static void perf_event__header_size(struct perf_event *event)
1985 {
1986 	event->read_size =
1987 		__perf_event_read_size(event->attr.read_format,
1988 				       event->group_leader->nr_siblings);
1989 	__perf_event_header_size(event, event->attr.sample_type);
1990 }
1991 
perf_event__id_header_size(struct perf_event * event)1992 static void perf_event__id_header_size(struct perf_event *event)
1993 {
1994 	struct perf_sample_data *data;
1995 	u64 sample_type = event->attr.sample_type;
1996 	u16 size = 0;
1997 
1998 	if (sample_type & PERF_SAMPLE_TID)
1999 		size += sizeof(data->tid_entry);
2000 
2001 	if (sample_type & PERF_SAMPLE_TIME)
2002 		size += sizeof(data->time);
2003 
2004 	if (sample_type & PERF_SAMPLE_IDENTIFIER)
2005 		size += sizeof(data->id);
2006 
2007 	if (sample_type & PERF_SAMPLE_ID)
2008 		size += sizeof(data->id);
2009 
2010 	if (sample_type & PERF_SAMPLE_STREAM_ID)
2011 		size += sizeof(data->stream_id);
2012 
2013 	if (sample_type & PERF_SAMPLE_CPU)
2014 		size += sizeof(data->cpu_entry);
2015 
2016 	event->id_header_size = size;
2017 }
2018 
2019 /*
2020  * Check that adding an event to the group does not result in anybody
2021  * overflowing the 64k event limit imposed by the output buffer.
2022  *
2023  * Specifically, check that the read_size for the event does not exceed 16k,
2024  * read_size being the one term that grows with groups size. Since read_size
2025  * depends on per-event read_format, also (re)check the existing events.
2026  *
2027  * This leaves 48k for the constant size fields and things like callchains,
2028  * branch stacks and register sets.
2029  */
perf_event_validate_size(struct perf_event * event)2030 static bool perf_event_validate_size(struct perf_event *event)
2031 {
2032 	struct perf_event *sibling, *group_leader = event->group_leader;
2033 
2034 	if (__perf_event_read_size(event->attr.read_format,
2035 				   group_leader->nr_siblings + 1) > 16*1024)
2036 		return false;
2037 
2038 	if (__perf_event_read_size(group_leader->attr.read_format,
2039 				   group_leader->nr_siblings + 1) > 16*1024)
2040 		return false;
2041 
2042 	/*
2043 	 * When creating a new group leader, group_leader->ctx is initialized
2044 	 * after the size has been validated, but we cannot safely use
2045 	 * for_each_sibling_event() until group_leader->ctx is set. A new group
2046 	 * leader cannot have any siblings yet, so we can safely skip checking
2047 	 * the non-existent siblings.
2048 	 */
2049 	if (event == group_leader)
2050 		return true;
2051 
2052 	for_each_sibling_event(sibling, group_leader) {
2053 		if (__perf_event_read_size(sibling->attr.read_format,
2054 					   group_leader->nr_siblings + 1) > 16*1024)
2055 			return false;
2056 	}
2057 
2058 	return true;
2059 }
2060 
perf_group_attach(struct perf_event * event)2061 static void perf_group_attach(struct perf_event *event)
2062 {
2063 	struct perf_event *group_leader = event->group_leader, *pos;
2064 
2065 	lockdep_assert_held(&event->ctx->lock);
2066 
2067 	/*
2068 	 * We can have double attach due to group movement in perf_event_open.
2069 	 */
2070 	if (event->attach_state & PERF_ATTACH_GROUP)
2071 		return;
2072 
2073 	event->attach_state |= PERF_ATTACH_GROUP;
2074 
2075 	if (group_leader == event)
2076 		return;
2077 
2078 	WARN_ON_ONCE(group_leader->ctx != event->ctx);
2079 
2080 	group_leader->group_caps &= event->event_caps;
2081 
2082 	list_add_tail(&event->sibling_list, &group_leader->sibling_list);
2083 	group_leader->nr_siblings++;
2084 	group_leader->group_generation++;
2085 
2086 	perf_event__header_size(group_leader);
2087 
2088 	for_each_sibling_event(pos, group_leader)
2089 		perf_event__header_size(pos);
2090 }
2091 
2092 /*
2093  * Remove an event from the lists for its context.
2094  * Must be called with ctx->mutex and ctx->lock held.
2095  */
2096 static void
list_del_event(struct perf_event * event,struct perf_event_context * ctx)2097 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
2098 {
2099 	WARN_ON_ONCE(event->ctx != ctx);
2100 	lockdep_assert_held(&ctx->lock);
2101 
2102 	/*
2103 	 * We can have double detach due to exit/hot-unplug + close.
2104 	 */
2105 	if (!(event->attach_state & PERF_ATTACH_CONTEXT))
2106 		return;
2107 
2108 	event->attach_state &= ~PERF_ATTACH_CONTEXT;
2109 
2110 	ctx->nr_events--;
2111 	if (event->attr.inherit_stat)
2112 		ctx->nr_stat--;
2113 
2114 	list_del_rcu(&event->event_entry);
2115 
2116 	if (event->group_leader == event)
2117 		del_event_from_groups(event, ctx);
2118 
2119 	/*
2120 	 * If event was in error state, then keep it
2121 	 * that way, otherwise bogus counts will be
2122 	 * returned on read(). The only way to get out
2123 	 * of error state is by explicit re-enabling
2124 	 * of the event
2125 	 */
2126 	if (event->state > PERF_EVENT_STATE_OFF) {
2127 		perf_cgroup_event_disable(event, ctx);
2128 		perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2129 	}
2130 
2131 	ctx->generation++;
2132 }
2133 
2134 static int
perf_aux_output_match(struct perf_event * event,struct perf_event * aux_event)2135 perf_aux_output_match(struct perf_event *event, struct perf_event *aux_event)
2136 {
2137 	if (!has_aux(aux_event))
2138 		return 0;
2139 
2140 	if (!event->pmu->aux_output_match)
2141 		return 0;
2142 
2143 	return event->pmu->aux_output_match(aux_event);
2144 }
2145 
2146 static void put_event(struct perf_event *event);
2147 static void event_sched_out(struct perf_event *event,
2148 			    struct perf_cpu_context *cpuctx,
2149 			    struct perf_event_context *ctx);
2150 
perf_put_aux_event(struct perf_event * event)2151 static void perf_put_aux_event(struct perf_event *event)
2152 {
2153 	struct perf_event_context *ctx = event->ctx;
2154 	struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2155 	struct perf_event *iter;
2156 
2157 	/*
2158 	 * If event uses aux_event tear down the link
2159 	 */
2160 	if (event->aux_event) {
2161 		iter = event->aux_event;
2162 		event->aux_event = NULL;
2163 		put_event(iter);
2164 		return;
2165 	}
2166 
2167 	/*
2168 	 * If the event is an aux_event, tear down all links to
2169 	 * it from other events.
2170 	 */
2171 	for_each_sibling_event(iter, event->group_leader) {
2172 		if (iter->aux_event != event)
2173 			continue;
2174 
2175 		iter->aux_event = NULL;
2176 		put_event(event);
2177 
2178 		/*
2179 		 * If it's ACTIVE, schedule it out and put it into ERROR
2180 		 * state so that we don't try to schedule it again. Note
2181 		 * that perf_event_enable() will clear the ERROR status.
2182 		 */
2183 		event_sched_out(iter, cpuctx, ctx);
2184 		perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
2185 	}
2186 }
2187 
perf_need_aux_event(struct perf_event * event)2188 static bool perf_need_aux_event(struct perf_event *event)
2189 {
2190 	return !!event->attr.aux_output || !!event->attr.aux_sample_size;
2191 }
2192 
perf_get_aux_event(struct perf_event * event,struct perf_event * group_leader)2193 static int perf_get_aux_event(struct perf_event *event,
2194 			      struct perf_event *group_leader)
2195 {
2196 	/*
2197 	 * Our group leader must be an aux event if we want to be
2198 	 * an aux_output. This way, the aux event will precede its
2199 	 * aux_output events in the group, and therefore will always
2200 	 * schedule first.
2201 	 */
2202 	if (!group_leader)
2203 		return 0;
2204 
2205 	/*
2206 	 * aux_output and aux_sample_size are mutually exclusive.
2207 	 */
2208 	if (event->attr.aux_output && event->attr.aux_sample_size)
2209 		return 0;
2210 
2211 	if (event->attr.aux_output &&
2212 	    !perf_aux_output_match(event, group_leader))
2213 		return 0;
2214 
2215 	if (event->attr.aux_sample_size && !group_leader->pmu->snapshot_aux)
2216 		return 0;
2217 
2218 	if (!atomic_long_inc_not_zero(&group_leader->refcount))
2219 		return 0;
2220 
2221 	/*
2222 	 * Link aux_outputs to their aux event; this is undone in
2223 	 * perf_group_detach() by perf_put_aux_event(). When the
2224 	 * group in torn down, the aux_output events loose their
2225 	 * link to the aux_event and can't schedule any more.
2226 	 */
2227 	event->aux_event = group_leader;
2228 
2229 	return 1;
2230 }
2231 
get_event_list(struct perf_event * event)2232 static inline struct list_head *get_event_list(struct perf_event *event)
2233 {
2234 	struct perf_event_context *ctx = event->ctx;
2235 	return event->attr.pinned ? &ctx->pinned_active : &ctx->flexible_active;
2236 }
2237 
2238 /*
2239  * Events that have PERF_EV_CAP_SIBLING require being part of a group and
2240  * cannot exist on their own, schedule them out and move them into the ERROR
2241  * state. Also see _perf_event_enable(), it will not be able to recover
2242  * this ERROR state.
2243  */
perf_remove_sibling_event(struct perf_event * event)2244 static inline void perf_remove_sibling_event(struct perf_event *event)
2245 {
2246 	struct perf_event_context *ctx = event->ctx;
2247 	struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2248 
2249 	event_sched_out(event, cpuctx, ctx);
2250 	perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
2251 }
2252 
perf_group_detach(struct perf_event * event)2253 static void perf_group_detach(struct perf_event *event)
2254 {
2255 	struct perf_event *leader = event->group_leader;
2256 	struct perf_event *sibling, *tmp;
2257 	struct perf_event_context *ctx = event->ctx;
2258 
2259 	lockdep_assert_held(&ctx->lock);
2260 
2261 	/*
2262 	 * We can have double detach due to exit/hot-unplug + close.
2263 	 */
2264 	if (!(event->attach_state & PERF_ATTACH_GROUP))
2265 		return;
2266 
2267 	event->attach_state &= ~PERF_ATTACH_GROUP;
2268 
2269 	perf_put_aux_event(event);
2270 
2271 	/*
2272 	 * If this is a sibling, remove it from its group.
2273 	 */
2274 	if (leader != event) {
2275 		list_del_init(&event->sibling_list);
2276 		event->group_leader->nr_siblings--;
2277 		event->group_leader->group_generation++;
2278 		goto out;
2279 	}
2280 
2281 	/*
2282 	 * If this was a group event with sibling events then
2283 	 * upgrade the siblings to singleton events by adding them
2284 	 * to whatever list we are on.
2285 	 */
2286 	list_for_each_entry_safe(sibling, tmp, &event->sibling_list, sibling_list) {
2287 
2288 		if (sibling->event_caps & PERF_EV_CAP_SIBLING)
2289 			perf_remove_sibling_event(sibling);
2290 
2291 		sibling->group_leader = sibling;
2292 		list_del_init(&sibling->sibling_list);
2293 
2294 		/* Inherit group flags from the previous leader */
2295 		sibling->group_caps = event->group_caps;
2296 
2297 		if (!RB_EMPTY_NODE(&event->group_node)) {
2298 			add_event_to_groups(sibling, event->ctx);
2299 
2300 			if (sibling->state == PERF_EVENT_STATE_ACTIVE)
2301 				list_add_tail(&sibling->active_list, get_event_list(sibling));
2302 		}
2303 
2304 		WARN_ON_ONCE(sibling->ctx != event->ctx);
2305 	}
2306 
2307 out:
2308 	for_each_sibling_event(tmp, leader)
2309 		perf_event__header_size(tmp);
2310 
2311 	perf_event__header_size(leader);
2312 }
2313 
is_orphaned_event(struct perf_event * event)2314 static bool is_orphaned_event(struct perf_event *event)
2315 {
2316 	return event->state == PERF_EVENT_STATE_DEAD;
2317 }
2318 
__pmu_filter_match(struct perf_event * event)2319 static inline int __pmu_filter_match(struct perf_event *event)
2320 {
2321 	struct pmu *pmu = event->pmu;
2322 	return pmu->filter_match ? pmu->filter_match(event) : 1;
2323 }
2324 
2325 /*
2326  * Check whether we should attempt to schedule an event group based on
2327  * PMU-specific filtering. An event group can consist of HW and SW events,
2328  * potentially with a SW leader, so we must check all the filters, to
2329  * determine whether a group is schedulable:
2330  */
pmu_filter_match(struct perf_event * event)2331 static inline int pmu_filter_match(struct perf_event *event)
2332 {
2333 	struct perf_event *sibling;
2334 
2335 	if (!__pmu_filter_match(event))
2336 		return 0;
2337 
2338 	for_each_sibling_event(sibling, event) {
2339 		if (!__pmu_filter_match(sibling))
2340 			return 0;
2341 	}
2342 
2343 	return 1;
2344 }
2345 
2346 static inline int
event_filter_match(struct perf_event * event)2347 event_filter_match(struct perf_event *event)
2348 {
2349 	return (event->cpu == -1 || event->cpu == smp_processor_id()) &&
2350 	       perf_cgroup_match(event) && pmu_filter_match(event);
2351 }
2352 
2353 static void
event_sched_out(struct perf_event * event,struct perf_cpu_context * cpuctx,struct perf_event_context * ctx)2354 event_sched_out(struct perf_event *event,
2355 		  struct perf_cpu_context *cpuctx,
2356 		  struct perf_event_context *ctx)
2357 {
2358 	enum perf_event_state state = PERF_EVENT_STATE_INACTIVE;
2359 
2360 	WARN_ON_ONCE(event->ctx != ctx);
2361 	lockdep_assert_held(&ctx->lock);
2362 
2363 	if (event->state != PERF_EVENT_STATE_ACTIVE)
2364 		return;
2365 
2366 	/*
2367 	 * Asymmetry; we only schedule events _IN_ through ctx_sched_in(), but
2368 	 * we can schedule events _OUT_ individually through things like
2369 	 * __perf_remove_from_context().
2370 	 */
2371 	list_del_init(&event->active_list);
2372 
2373 	perf_pmu_disable(event->pmu);
2374 
2375 	event->pmu->del(event, 0);
2376 	event->oncpu = -1;
2377 
2378 	if (READ_ONCE(event->pending_disable) >= 0) {
2379 		WRITE_ONCE(event->pending_disable, -1);
2380 		perf_cgroup_event_disable(event, ctx);
2381 		state = PERF_EVENT_STATE_OFF;
2382 	}
2383 	perf_event_set_state(event, state);
2384 
2385 	if (!is_software_event(event))
2386 		cpuctx->active_oncpu--;
2387 	if (!--ctx->nr_active)
2388 		perf_event_ctx_deactivate(ctx);
2389 	if (event->attr.freq && event->attr.sample_freq)
2390 		ctx->nr_freq--;
2391 	if (event->attr.exclusive || !cpuctx->active_oncpu)
2392 		cpuctx->exclusive = 0;
2393 
2394 	perf_pmu_enable(event->pmu);
2395 }
2396 
2397 static void
group_sched_out(struct perf_event * group_event,struct perf_cpu_context * cpuctx,struct perf_event_context * ctx)2398 group_sched_out(struct perf_event *group_event,
2399 		struct perf_cpu_context *cpuctx,
2400 		struct perf_event_context *ctx)
2401 {
2402 	struct perf_event *event;
2403 
2404 	if (group_event->state != PERF_EVENT_STATE_ACTIVE)
2405 		return;
2406 
2407 	perf_pmu_disable(ctx->pmu);
2408 
2409 	event_sched_out(group_event, cpuctx, ctx);
2410 
2411 	/*
2412 	 * Schedule out siblings (if any):
2413 	 */
2414 	for_each_sibling_event(event, group_event)
2415 		event_sched_out(event, cpuctx, ctx);
2416 
2417 	perf_pmu_enable(ctx->pmu);
2418 }
2419 
2420 #define DETACH_GROUP	0x01UL
2421 
2422 /*
2423  * Cross CPU call to remove a performance event
2424  *
2425  * We disable the event on the hardware level first. After that we
2426  * remove it from the context list.
2427  */
2428 static void
__perf_remove_from_context(struct perf_event * event,struct perf_cpu_context * cpuctx,struct perf_event_context * ctx,void * info)2429 __perf_remove_from_context(struct perf_event *event,
2430 			   struct perf_cpu_context *cpuctx,
2431 			   struct perf_event_context *ctx,
2432 			   void *info)
2433 {
2434 	unsigned long flags = (unsigned long)info;
2435 
2436 	if (ctx->is_active & EVENT_TIME) {
2437 		update_context_time(ctx);
2438 		update_cgrp_time_from_cpuctx(cpuctx, false);
2439 	}
2440 
2441 	event_sched_out(event, cpuctx, ctx);
2442 	if (flags & DETACH_GROUP)
2443 		perf_group_detach(event);
2444 	list_del_event(event, ctx);
2445 
2446 	if (!ctx->nr_events && ctx->is_active) {
2447 		if (ctx == &cpuctx->ctx)
2448 			update_cgrp_time_from_cpuctx(cpuctx, true);
2449 
2450 		ctx->is_active = 0;
2451 		ctx->rotate_necessary = 0;
2452 		if (ctx->task) {
2453 			WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2454 			cpuctx->task_ctx = NULL;
2455 		}
2456 	}
2457 }
2458 
2459 /*
2460  * Remove the event from a task's (or a CPU's) list of events.
2461  *
2462  * If event->ctx is a cloned context, callers must make sure that
2463  * every task struct that event->ctx->task could possibly point to
2464  * remains valid.  This is OK when called from perf_release since
2465  * that only calls us on the top-level context, which can't be a clone.
2466  * When called from perf_event_exit_task, it's OK because the
2467  * context has been detached from its task.
2468  */
perf_remove_from_context(struct perf_event * event,unsigned long flags)2469 static void perf_remove_from_context(struct perf_event *event, unsigned long flags)
2470 {
2471 	struct perf_event_context *ctx = event->ctx;
2472 
2473 	lockdep_assert_held(&ctx->mutex);
2474 
2475 	event_function_call(event, __perf_remove_from_context, (void *)flags);
2476 
2477 	/*
2478 	 * The above event_function_call() can NO-OP when it hits
2479 	 * TASK_TOMBSTONE. In that case we must already have been detached
2480 	 * from the context (by perf_event_exit_event()) but the grouping
2481 	 * might still be in-tact.
2482 	 */
2483 	WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
2484 	if ((flags & DETACH_GROUP) &&
2485 	    (event->attach_state & PERF_ATTACH_GROUP)) {
2486 		/*
2487 		 * Since in that case we cannot possibly be scheduled, simply
2488 		 * detach now.
2489 		 */
2490 		raw_spin_lock_irq(&ctx->lock);
2491 		perf_group_detach(event);
2492 		raw_spin_unlock_irq(&ctx->lock);
2493 	}
2494 }
2495 
2496 /*
2497  * Cross CPU call to disable a performance event
2498  */
__perf_event_disable(struct perf_event * event,struct perf_cpu_context * cpuctx,struct perf_event_context * ctx,void * info)2499 static void __perf_event_disable(struct perf_event *event,
2500 				 struct perf_cpu_context *cpuctx,
2501 				 struct perf_event_context *ctx,
2502 				 void *info)
2503 {
2504 	if (event->state < PERF_EVENT_STATE_INACTIVE)
2505 		return;
2506 
2507 	if (ctx->is_active & EVENT_TIME) {
2508 		update_context_time(ctx);
2509 		update_cgrp_time_from_event(event);
2510 	}
2511 
2512 	if (event == event->group_leader)
2513 		group_sched_out(event, cpuctx, ctx);
2514 	else
2515 		event_sched_out(event, cpuctx, ctx);
2516 
2517 	perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2518 	perf_cgroup_event_disable(event, ctx);
2519 }
2520 
2521 /*
2522  * Disable an event.
2523  *
2524  * If event->ctx is a cloned context, callers must make sure that
2525  * every task struct that event->ctx->task could possibly point to
2526  * remains valid.  This condition is satisfied when called through
2527  * perf_event_for_each_child or perf_event_for_each because they
2528  * hold the top-level event's child_mutex, so any descendant that
2529  * goes to exit will block in perf_event_exit_event().
2530  *
2531  * When called from perf_pending_event it's OK because event->ctx
2532  * is the current context on this CPU and preemption is disabled,
2533  * hence we can't get into perf_event_task_sched_out for this context.
2534  */
_perf_event_disable(struct perf_event * event)2535 static void _perf_event_disable(struct perf_event *event)
2536 {
2537 	struct perf_event_context *ctx = event->ctx;
2538 
2539 	raw_spin_lock_irq(&ctx->lock);
2540 	if (event->state <= PERF_EVENT_STATE_OFF) {
2541 		raw_spin_unlock_irq(&ctx->lock);
2542 		return;
2543 	}
2544 	raw_spin_unlock_irq(&ctx->lock);
2545 
2546 	event_function_call(event, __perf_event_disable, NULL);
2547 }
2548 
perf_event_disable_local(struct perf_event * event)2549 void perf_event_disable_local(struct perf_event *event)
2550 {
2551 	event_function_local(event, __perf_event_disable, NULL);
2552 }
2553 
2554 /*
2555  * Strictly speaking kernel users cannot create groups and therefore this
2556  * interface does not need the perf_event_ctx_lock() magic.
2557  */
perf_event_disable(struct perf_event * event)2558 void perf_event_disable(struct perf_event *event)
2559 {
2560 	struct perf_event_context *ctx;
2561 
2562 	ctx = perf_event_ctx_lock(event);
2563 	_perf_event_disable(event);
2564 	perf_event_ctx_unlock(event, ctx);
2565 }
2566 EXPORT_SYMBOL_GPL(perf_event_disable);
2567 
perf_event_disable_inatomic(struct perf_event * event)2568 void perf_event_disable_inatomic(struct perf_event *event)
2569 {
2570 	WRITE_ONCE(event->pending_disable, smp_processor_id());
2571 	/* can fail, see perf_pending_event_disable() */
2572 	irq_work_queue(&event->pending);
2573 }
2574 
2575 #define MAX_INTERRUPTS (~0ULL)
2576 
2577 static void perf_log_throttle(struct perf_event *event, int enable);
2578 static void perf_log_itrace_start(struct perf_event *event);
2579 
2580 static int
event_sched_in(struct perf_event * event,struct perf_cpu_context * cpuctx,struct perf_event_context * ctx)2581 event_sched_in(struct perf_event *event,
2582 		 struct perf_cpu_context *cpuctx,
2583 		 struct perf_event_context *ctx)
2584 {
2585 	int ret = 0;
2586 
2587 	WARN_ON_ONCE(event->ctx != ctx);
2588 
2589 	lockdep_assert_held(&ctx->lock);
2590 
2591 	if (event->state <= PERF_EVENT_STATE_OFF)
2592 		return 0;
2593 
2594 	WRITE_ONCE(event->oncpu, smp_processor_id());
2595 	/*
2596 	 * Order event::oncpu write to happen before the ACTIVE state is
2597 	 * visible. This allows perf_event_{stop,read}() to observe the correct
2598 	 * ->oncpu if it sees ACTIVE.
2599 	 */
2600 	smp_wmb();
2601 	perf_event_set_state(event, PERF_EVENT_STATE_ACTIVE);
2602 
2603 	/*
2604 	 * Unthrottle events, since we scheduled we might have missed several
2605 	 * ticks already, also for a heavily scheduling task there is little
2606 	 * guarantee it'll get a tick in a timely manner.
2607 	 */
2608 	if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
2609 		perf_log_throttle(event, 1);
2610 		event->hw.interrupts = 0;
2611 	}
2612 
2613 	perf_pmu_disable(event->pmu);
2614 
2615 	perf_log_itrace_start(event);
2616 
2617 	if (event->pmu->add(event, PERF_EF_START)) {
2618 		perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2619 		event->oncpu = -1;
2620 		ret = -EAGAIN;
2621 		goto out;
2622 	}
2623 
2624 	if (!is_software_event(event))
2625 		cpuctx->active_oncpu++;
2626 	if (!ctx->nr_active++)
2627 		perf_event_ctx_activate(ctx);
2628 	if (event->attr.freq && event->attr.sample_freq)
2629 		ctx->nr_freq++;
2630 
2631 	if (event->attr.exclusive)
2632 		cpuctx->exclusive = 1;
2633 
2634 out:
2635 	perf_pmu_enable(event->pmu);
2636 
2637 	return ret;
2638 }
2639 
2640 static int
group_sched_in(struct perf_event * group_event,struct perf_cpu_context * cpuctx,struct perf_event_context * ctx)2641 group_sched_in(struct perf_event *group_event,
2642 	       struct perf_cpu_context *cpuctx,
2643 	       struct perf_event_context *ctx)
2644 {
2645 	struct perf_event *event, *partial_group = NULL;
2646 	struct pmu *pmu = ctx->pmu;
2647 
2648 	if (group_event->state == PERF_EVENT_STATE_OFF)
2649 		return 0;
2650 
2651 	pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
2652 
2653 	if (event_sched_in(group_event, cpuctx, ctx))
2654 		goto error;
2655 
2656 	/*
2657 	 * Schedule in siblings as one group (if any):
2658 	 */
2659 	for_each_sibling_event(event, group_event) {
2660 		if (event_sched_in(event, cpuctx, ctx)) {
2661 			partial_group = event;
2662 			goto group_error;
2663 		}
2664 	}
2665 
2666 	if (!pmu->commit_txn(pmu))
2667 		return 0;
2668 
2669 group_error:
2670 	/*
2671 	 * Groups can be scheduled in as one unit only, so undo any
2672 	 * partial group before returning:
2673 	 * The events up to the failed event are scheduled out normally.
2674 	 */
2675 	for_each_sibling_event(event, group_event) {
2676 		if (event == partial_group)
2677 			break;
2678 
2679 		event_sched_out(event, cpuctx, ctx);
2680 	}
2681 	event_sched_out(group_event, cpuctx, ctx);
2682 
2683 error:
2684 	pmu->cancel_txn(pmu);
2685 	return -EAGAIN;
2686 }
2687 
2688 /*
2689  * Work out whether we can put this event group on the CPU now.
2690  */
group_can_go_on(struct perf_event * event,struct perf_cpu_context * cpuctx,int can_add_hw)2691 static int group_can_go_on(struct perf_event *event,
2692 			   struct perf_cpu_context *cpuctx,
2693 			   int can_add_hw)
2694 {
2695 	/*
2696 	 * Groups consisting entirely of software events can always go on.
2697 	 */
2698 	if (event->group_caps & PERF_EV_CAP_SOFTWARE)
2699 		return 1;
2700 	/*
2701 	 * If an exclusive group is already on, no other hardware
2702 	 * events can go on.
2703 	 */
2704 	if (cpuctx->exclusive)
2705 		return 0;
2706 	/*
2707 	 * If this group is exclusive and there are already
2708 	 * events on the CPU, it can't go on.
2709 	 */
2710 	if (event->attr.exclusive && !list_empty(get_event_list(event)))
2711 		return 0;
2712 	/*
2713 	 * Otherwise, try to add it if all previous groups were able
2714 	 * to go on.
2715 	 */
2716 	return can_add_hw;
2717 }
2718 
add_event_to_ctx(struct perf_event * event,struct perf_event_context * ctx)2719 static void add_event_to_ctx(struct perf_event *event,
2720 			       struct perf_event_context *ctx)
2721 {
2722 	list_add_event(event, ctx);
2723 	perf_group_attach(event);
2724 }
2725 
2726 static void ctx_sched_out(struct perf_event_context *ctx,
2727 			  struct perf_cpu_context *cpuctx,
2728 			  enum event_type_t event_type);
2729 static void
2730 ctx_sched_in(struct perf_event_context *ctx,
2731 	     struct perf_cpu_context *cpuctx,
2732 	     enum event_type_t event_type,
2733 	     struct task_struct *task);
2734 
task_ctx_sched_out(struct perf_cpu_context * cpuctx,struct perf_event_context * ctx,enum event_type_t event_type)2735 static void task_ctx_sched_out(struct perf_cpu_context *cpuctx,
2736 			       struct perf_event_context *ctx,
2737 			       enum event_type_t event_type)
2738 {
2739 	if (!cpuctx->task_ctx)
2740 		return;
2741 
2742 	if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2743 		return;
2744 
2745 	ctx_sched_out(ctx, cpuctx, event_type);
2746 }
2747 
perf_event_sched_in(struct perf_cpu_context * cpuctx,struct perf_event_context * ctx,struct task_struct * task)2748 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2749 				struct perf_event_context *ctx,
2750 				struct task_struct *task)
2751 {
2752 	cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
2753 	if (ctx)
2754 		ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
2755 	cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
2756 	if (ctx)
2757 		ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
2758 }
2759 
2760 /*
2761  * We want to maintain the following priority of scheduling:
2762  *  - CPU pinned (EVENT_CPU | EVENT_PINNED)
2763  *  - task pinned (EVENT_PINNED)
2764  *  - CPU flexible (EVENT_CPU | EVENT_FLEXIBLE)
2765  *  - task flexible (EVENT_FLEXIBLE).
2766  *
2767  * In order to avoid unscheduling and scheduling back in everything every
2768  * time an event is added, only do it for the groups of equal priority and
2769  * below.
2770  *
2771  * This can be called after a batch operation on task events, in which case
2772  * event_type is a bit mask of the types of events involved. For CPU events,
2773  * event_type is only either EVENT_PINNED or EVENT_FLEXIBLE.
2774  */
ctx_resched(struct perf_cpu_context * cpuctx,struct perf_event_context * task_ctx,enum event_type_t event_type)2775 static void ctx_resched(struct perf_cpu_context *cpuctx,
2776 			struct perf_event_context *task_ctx,
2777 			enum event_type_t event_type)
2778 {
2779 	enum event_type_t ctx_event_type;
2780 	bool cpu_event = !!(event_type & EVENT_CPU);
2781 
2782 	/*
2783 	 * If pinned groups are involved, flexible groups also need to be
2784 	 * scheduled out.
2785 	 */
2786 	if (event_type & EVENT_PINNED)
2787 		event_type |= EVENT_FLEXIBLE;
2788 
2789 	ctx_event_type = event_type & EVENT_ALL;
2790 
2791 	perf_pmu_disable(cpuctx->ctx.pmu);
2792 	if (task_ctx)
2793 		task_ctx_sched_out(cpuctx, task_ctx, event_type);
2794 
2795 	/*
2796 	 * Decide which cpu ctx groups to schedule out based on the types
2797 	 * of events that caused rescheduling:
2798 	 *  - EVENT_CPU: schedule out corresponding groups;
2799 	 *  - EVENT_PINNED task events: schedule out EVENT_FLEXIBLE groups;
2800 	 *  - otherwise, do nothing more.
2801 	 */
2802 	if (cpu_event)
2803 		cpu_ctx_sched_out(cpuctx, ctx_event_type);
2804 	else if (ctx_event_type & EVENT_PINNED)
2805 		cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2806 
2807 	perf_event_sched_in(cpuctx, task_ctx, current);
2808 	perf_pmu_enable(cpuctx->ctx.pmu);
2809 }
2810 
perf_pmu_resched(struct pmu * pmu)2811 void perf_pmu_resched(struct pmu *pmu)
2812 {
2813 	struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2814 	struct perf_event_context *task_ctx = cpuctx->task_ctx;
2815 
2816 	perf_ctx_lock(cpuctx, task_ctx);
2817 	ctx_resched(cpuctx, task_ctx, EVENT_ALL|EVENT_CPU);
2818 	perf_ctx_unlock(cpuctx, task_ctx);
2819 }
2820 
2821 /*
2822  * Cross CPU call to install and enable a performance event
2823  *
2824  * Very similar to remote_function() + event_function() but cannot assume that
2825  * things like ctx->is_active and cpuctx->task_ctx are set.
2826  */
__perf_install_in_context(void * info)2827 static int  __perf_install_in_context(void *info)
2828 {
2829 	struct perf_event *event = info;
2830 	struct perf_event_context *ctx = event->ctx;
2831 	struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2832 	struct perf_event_context *task_ctx = cpuctx->task_ctx;
2833 	bool reprogram = true;
2834 	int ret = 0;
2835 
2836 	raw_spin_lock(&cpuctx->ctx.lock);
2837 	if (ctx->task) {
2838 		raw_spin_lock(&ctx->lock);
2839 		task_ctx = ctx;
2840 
2841 		reprogram = (ctx->task == current);
2842 
2843 		/*
2844 		 * If the task is running, it must be running on this CPU,
2845 		 * otherwise we cannot reprogram things.
2846 		 *
2847 		 * If its not running, we don't care, ctx->lock will
2848 		 * serialize against it becoming runnable.
2849 		 */
2850 		if (task_curr(ctx->task) && !reprogram) {
2851 			ret = -ESRCH;
2852 			goto unlock;
2853 		}
2854 
2855 		WARN_ON_ONCE(reprogram && cpuctx->task_ctx && cpuctx->task_ctx != ctx);
2856 	} else if (task_ctx) {
2857 		raw_spin_lock(&task_ctx->lock);
2858 	}
2859 
2860 #ifdef CONFIG_CGROUP_PERF
2861 	if (event->state > PERF_EVENT_STATE_OFF && is_cgroup_event(event)) {
2862 		/*
2863 		 * If the current cgroup doesn't match the event's
2864 		 * cgroup, we should not try to schedule it.
2865 		 */
2866 		struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
2867 		reprogram = cgroup_is_descendant(cgrp->css.cgroup,
2868 					event->cgrp->css.cgroup);
2869 	}
2870 #endif
2871 
2872 	if (reprogram) {
2873 		ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2874 		add_event_to_ctx(event, ctx);
2875 		ctx_resched(cpuctx, task_ctx, get_event_type(event));
2876 	} else {
2877 		add_event_to_ctx(event, ctx);
2878 	}
2879 
2880 unlock:
2881 	perf_ctx_unlock(cpuctx, task_ctx);
2882 
2883 	return ret;
2884 }
2885 
2886 static bool exclusive_event_installable(struct perf_event *event,
2887 					struct perf_event_context *ctx);
2888 
2889 /*
2890  * Attach a performance event to a context.
2891  *
2892  * Very similar to event_function_call, see comment there.
2893  */
2894 static void
perf_install_in_context(struct perf_event_context * ctx,struct perf_event * event,int cpu)2895 perf_install_in_context(struct perf_event_context *ctx,
2896 			struct perf_event *event,
2897 			int cpu)
2898 {
2899 	struct task_struct *task = READ_ONCE(ctx->task);
2900 
2901 	lockdep_assert_held(&ctx->mutex);
2902 
2903 	WARN_ON_ONCE(!exclusive_event_installable(event, ctx));
2904 
2905 	if (event->cpu != -1)
2906 		event->cpu = cpu;
2907 
2908 	/*
2909 	 * Ensures that if we can observe event->ctx, both the event and ctx
2910 	 * will be 'complete'. See perf_iterate_sb_cpu().
2911 	 */
2912 	smp_store_release(&event->ctx, ctx);
2913 
2914 	/*
2915 	 * perf_event_attr::disabled events will not run and can be initialized
2916 	 * without IPI. Except when this is the first event for the context, in
2917 	 * that case we need the magic of the IPI to set ctx->is_active.
2918 	 *
2919 	 * The IOC_ENABLE that is sure to follow the creation of a disabled
2920 	 * event will issue the IPI and reprogram the hardware.
2921 	 */
2922 	if (__perf_effective_state(event) == PERF_EVENT_STATE_OFF && ctx->nr_events) {
2923 		raw_spin_lock_irq(&ctx->lock);
2924 		if (ctx->task == TASK_TOMBSTONE) {
2925 			raw_spin_unlock_irq(&ctx->lock);
2926 			return;
2927 		}
2928 		add_event_to_ctx(event, ctx);
2929 		raw_spin_unlock_irq(&ctx->lock);
2930 		return;
2931 	}
2932 
2933 	if (!task) {
2934 		cpu_function_call(cpu, __perf_install_in_context, event);
2935 		return;
2936 	}
2937 
2938 	/*
2939 	 * Should not happen, we validate the ctx is still alive before calling.
2940 	 */
2941 	if (WARN_ON_ONCE(task == TASK_TOMBSTONE))
2942 		return;
2943 
2944 	/*
2945 	 * Installing events is tricky because we cannot rely on ctx->is_active
2946 	 * to be set in case this is the nr_events 0 -> 1 transition.
2947 	 *
2948 	 * Instead we use task_curr(), which tells us if the task is running.
2949 	 * However, since we use task_curr() outside of rq::lock, we can race
2950 	 * against the actual state. This means the result can be wrong.
2951 	 *
2952 	 * If we get a false positive, we retry, this is harmless.
2953 	 *
2954 	 * If we get a false negative, things are complicated. If we are after
2955 	 * perf_event_context_sched_in() ctx::lock will serialize us, and the
2956 	 * value must be correct. If we're before, it doesn't matter since
2957 	 * perf_event_context_sched_in() will program the counter.
2958 	 *
2959 	 * However, this hinges on the remote context switch having observed
2960 	 * our task->perf_event_ctxp[] store, such that it will in fact take
2961 	 * ctx::lock in perf_event_context_sched_in().
2962 	 *
2963 	 * We do this by task_function_call(), if the IPI fails to hit the task
2964 	 * we know any future context switch of task must see the
2965 	 * perf_event_ctpx[] store.
2966 	 */
2967 
2968 	/*
2969 	 * This smp_mb() orders the task->perf_event_ctxp[] store with the
2970 	 * task_cpu() load, such that if the IPI then does not find the task
2971 	 * running, a future context switch of that task must observe the
2972 	 * store.
2973 	 */
2974 	smp_mb();
2975 again:
2976 	if (!task_function_call(task, __perf_install_in_context, event))
2977 		return;
2978 
2979 	raw_spin_lock_irq(&ctx->lock);
2980 	task = ctx->task;
2981 	if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) {
2982 		/*
2983 		 * Cannot happen because we already checked above (which also
2984 		 * cannot happen), and we hold ctx->mutex, which serializes us
2985 		 * against perf_event_exit_task_context().
2986 		 */
2987 		raw_spin_unlock_irq(&ctx->lock);
2988 		return;
2989 	}
2990 	/*
2991 	 * If the task is not running, ctx->lock will avoid it becoming so,
2992 	 * thus we can safely install the event.
2993 	 */
2994 	if (task_curr(task)) {
2995 		raw_spin_unlock_irq(&ctx->lock);
2996 		goto again;
2997 	}
2998 	add_event_to_ctx(event, ctx);
2999 	raw_spin_unlock_irq(&ctx->lock);
3000 }
3001 
3002 /*
3003  * Cross CPU call to enable a performance event
3004  */
__perf_event_enable(struct perf_event * event,struct perf_cpu_context * cpuctx,struct perf_event_context * ctx,void * info)3005 static void __perf_event_enable(struct perf_event *event,
3006 				struct perf_cpu_context *cpuctx,
3007 				struct perf_event_context *ctx,
3008 				void *info)
3009 {
3010 	struct perf_event *leader = event->group_leader;
3011 	struct perf_event_context *task_ctx;
3012 
3013 	if (event->state >= PERF_EVENT_STATE_INACTIVE ||
3014 	    event->state <= PERF_EVENT_STATE_ERROR)
3015 		return;
3016 
3017 	if (ctx->is_active)
3018 		ctx_sched_out(ctx, cpuctx, EVENT_TIME);
3019 
3020 	perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
3021 	perf_cgroup_event_enable(event, ctx);
3022 
3023 	if (!ctx->is_active)
3024 		return;
3025 
3026 	if (!event_filter_match(event)) {
3027 		ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
3028 		return;
3029 	}
3030 
3031 	/*
3032 	 * If the event is in a group and isn't the group leader,
3033 	 * then don't put it on unless the group is on.
3034 	 */
3035 	if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE) {
3036 		ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
3037 		return;
3038 	}
3039 
3040 	task_ctx = cpuctx->task_ctx;
3041 	if (ctx->task)
3042 		WARN_ON_ONCE(task_ctx != ctx);
3043 
3044 	ctx_resched(cpuctx, task_ctx, get_event_type(event));
3045 }
3046 
3047 /*
3048  * Enable an event.
3049  *
3050  * If event->ctx is a cloned context, callers must make sure that
3051  * every task struct that event->ctx->task could possibly point to
3052  * remains valid.  This condition is satisfied when called through
3053  * perf_event_for_each_child or perf_event_for_each as described
3054  * for perf_event_disable.
3055  */
_perf_event_enable(struct perf_event * event)3056 static void _perf_event_enable(struct perf_event *event)
3057 {
3058 	struct perf_event_context *ctx = event->ctx;
3059 
3060 	raw_spin_lock_irq(&ctx->lock);
3061 	if (event->state >= PERF_EVENT_STATE_INACTIVE ||
3062 	    event->state <  PERF_EVENT_STATE_ERROR) {
3063 out:
3064 		raw_spin_unlock_irq(&ctx->lock);
3065 		return;
3066 	}
3067 
3068 	/*
3069 	 * If the event is in error state, clear that first.
3070 	 *
3071 	 * That way, if we see the event in error state below, we know that it
3072 	 * has gone back into error state, as distinct from the task having
3073 	 * been scheduled away before the cross-call arrived.
3074 	 */
3075 	if (event->state == PERF_EVENT_STATE_ERROR) {
3076 		/*
3077 		 * Detached SIBLING events cannot leave ERROR state.
3078 		 */
3079 		if (event->event_caps & PERF_EV_CAP_SIBLING &&
3080 		    event->group_leader == event)
3081 			goto out;
3082 
3083 		event->state = PERF_EVENT_STATE_OFF;
3084 	}
3085 	raw_spin_unlock_irq(&ctx->lock);
3086 
3087 	event_function_call(event, __perf_event_enable, NULL);
3088 }
3089 
3090 /*
3091  * See perf_event_disable();
3092  */
perf_event_enable(struct perf_event * event)3093 void perf_event_enable(struct perf_event *event)
3094 {
3095 	struct perf_event_context *ctx;
3096 
3097 	ctx = perf_event_ctx_lock(event);
3098 	_perf_event_enable(event);
3099 	perf_event_ctx_unlock(event, ctx);
3100 }
3101 EXPORT_SYMBOL_GPL(perf_event_enable);
3102 
3103 struct stop_event_data {
3104 	struct perf_event	*event;
3105 	unsigned int		restart;
3106 };
3107 
__perf_event_stop(void * info)3108 static int __perf_event_stop(void *info)
3109 {
3110 	struct stop_event_data *sd = info;
3111 	struct perf_event *event = sd->event;
3112 
3113 	/* if it's already INACTIVE, do nothing */
3114 	if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3115 		return 0;
3116 
3117 	/* matches smp_wmb() in event_sched_in() */
3118 	smp_rmb();
3119 
3120 	/*
3121 	 * There is a window with interrupts enabled before we get here,
3122 	 * so we need to check again lest we try to stop another CPU's event.
3123 	 */
3124 	if (READ_ONCE(event->oncpu) != smp_processor_id())
3125 		return -EAGAIN;
3126 
3127 	event->pmu->stop(event, PERF_EF_UPDATE);
3128 
3129 	/*
3130 	 * May race with the actual stop (through perf_pmu_output_stop()),
3131 	 * but it is only used for events with AUX ring buffer, and such
3132 	 * events will refuse to restart because of rb::aux_mmap_count==0,
3133 	 * see comments in perf_aux_output_begin().
3134 	 *
3135 	 * Since this is happening on an event-local CPU, no trace is lost
3136 	 * while restarting.
3137 	 */
3138 	if (sd->restart)
3139 		event->pmu->start(event, 0);
3140 
3141 	return 0;
3142 }
3143 
perf_event_stop(struct perf_event * event,int restart)3144 static int perf_event_stop(struct perf_event *event, int restart)
3145 {
3146 	struct stop_event_data sd = {
3147 		.event		= event,
3148 		.restart	= restart,
3149 	};
3150 	int ret = 0;
3151 
3152 	do {
3153 		if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3154 			return 0;
3155 
3156 		/* matches smp_wmb() in event_sched_in() */
3157 		smp_rmb();
3158 
3159 		/*
3160 		 * We only want to restart ACTIVE events, so if the event goes
3161 		 * inactive here (event->oncpu==-1), there's nothing more to do;
3162 		 * fall through with ret==-ENXIO.
3163 		 */
3164 		ret = cpu_function_call(READ_ONCE(event->oncpu),
3165 					__perf_event_stop, &sd);
3166 	} while (ret == -EAGAIN);
3167 
3168 	return ret;
3169 }
3170 
3171 /*
3172  * In order to contain the amount of racy and tricky in the address filter
3173  * configuration management, it is a two part process:
3174  *
3175  * (p1) when userspace mappings change as a result of (1) or (2) or (3) below,
3176  *      we update the addresses of corresponding vmas in
3177  *	event::addr_filter_ranges array and bump the event::addr_filters_gen;
3178  * (p2) when an event is scheduled in (pmu::add), it calls
3179  *      perf_event_addr_filters_sync() which calls pmu::addr_filters_sync()
3180  *      if the generation has changed since the previous call.
3181  *
3182  * If (p1) happens while the event is active, we restart it to force (p2).
3183  *
3184  * (1) perf_addr_filters_apply(): adjusting filters' offsets based on
3185  *     pre-existing mappings, called once when new filters arrive via SET_FILTER
3186  *     ioctl;
3187  * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly
3188  *     registered mapping, called for every new mmap(), with mm::mmap_lock down
3189  *     for reading;
3190  * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process
3191  *     of exec.
3192  */
perf_event_addr_filters_sync(struct perf_event * event)3193 void perf_event_addr_filters_sync(struct perf_event *event)
3194 {
3195 	struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
3196 
3197 	if (!has_addr_filter(event))
3198 		return;
3199 
3200 	raw_spin_lock(&ifh->lock);
3201 	if (event->addr_filters_gen != event->hw.addr_filters_gen) {
3202 		event->pmu->addr_filters_sync(event);
3203 		event->hw.addr_filters_gen = event->addr_filters_gen;
3204 	}
3205 	raw_spin_unlock(&ifh->lock);
3206 }
3207 EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync);
3208 
_perf_event_refresh(struct perf_event * event,int refresh)3209 static int _perf_event_refresh(struct perf_event *event, int refresh)
3210 {
3211 	/*
3212 	 * not supported on inherited events
3213 	 */
3214 	if (event->attr.inherit || !is_sampling_event(event))
3215 		return -EINVAL;
3216 
3217 	atomic_add(refresh, &event->event_limit);
3218 	_perf_event_enable(event);
3219 
3220 	return 0;
3221 }
3222 
3223 /*
3224  * See perf_event_disable()
3225  */
perf_event_refresh(struct perf_event * event,int refresh)3226 int perf_event_refresh(struct perf_event *event, int refresh)
3227 {
3228 	struct perf_event_context *ctx;
3229 	int ret;
3230 
3231 	ctx = perf_event_ctx_lock(event);
3232 	ret = _perf_event_refresh(event, refresh);
3233 	perf_event_ctx_unlock(event, ctx);
3234 
3235 	return ret;
3236 }
3237 EXPORT_SYMBOL_GPL(perf_event_refresh);
3238 
perf_event_modify_breakpoint(struct perf_event * bp,struct perf_event_attr * attr)3239 static int perf_event_modify_breakpoint(struct perf_event *bp,
3240 					 struct perf_event_attr *attr)
3241 {
3242 	int err;
3243 
3244 	_perf_event_disable(bp);
3245 
3246 	err = modify_user_hw_breakpoint_check(bp, attr, true);
3247 
3248 	if (!bp->attr.disabled)
3249 		_perf_event_enable(bp);
3250 
3251 	return err;
3252 }
3253 
perf_event_modify_attr(struct perf_event * event,struct perf_event_attr * attr)3254 static int perf_event_modify_attr(struct perf_event *event,
3255 				  struct perf_event_attr *attr)
3256 {
3257 	if (event->attr.type != attr->type)
3258 		return -EINVAL;
3259 
3260 	switch (event->attr.type) {
3261 	case PERF_TYPE_BREAKPOINT:
3262 		return perf_event_modify_breakpoint(event, attr);
3263 	default:
3264 		/* Place holder for future additions. */
3265 		return -EOPNOTSUPP;
3266 	}
3267 }
3268 
ctx_sched_out(struct perf_event_context * ctx,struct perf_cpu_context * cpuctx,enum event_type_t event_type)3269 static void ctx_sched_out(struct perf_event_context *ctx,
3270 			  struct perf_cpu_context *cpuctx,
3271 			  enum event_type_t event_type)
3272 {
3273 	struct perf_event *event, *tmp;
3274 	int is_active = ctx->is_active;
3275 
3276 	lockdep_assert_held(&ctx->lock);
3277 
3278 	if (likely(!ctx->nr_events)) {
3279 		/*
3280 		 * See __perf_remove_from_context().
3281 		 */
3282 		WARN_ON_ONCE(ctx->is_active);
3283 		if (ctx->task)
3284 			WARN_ON_ONCE(cpuctx->task_ctx);
3285 		return;
3286 	}
3287 
3288 	/*
3289 	 * Always update time if it was set; not only when it changes.
3290 	 * Otherwise we can 'forget' to update time for any but the last
3291 	 * context we sched out. For example:
3292 	 *
3293 	 *   ctx_sched_out(.event_type = EVENT_FLEXIBLE)
3294 	 *   ctx_sched_out(.event_type = EVENT_PINNED)
3295 	 *
3296 	 * would only update time for the pinned events.
3297 	 */
3298 	if (is_active & EVENT_TIME) {
3299 		/* update (and stop) ctx time */
3300 		update_context_time(ctx);
3301 		update_cgrp_time_from_cpuctx(cpuctx, ctx == &cpuctx->ctx);
3302 		/*
3303 		 * CPU-release for the below ->is_active store,
3304 		 * see __load_acquire() in perf_event_time_now()
3305 		 */
3306 		barrier();
3307 	}
3308 
3309 	ctx->is_active &= ~event_type;
3310 	if (!(ctx->is_active & EVENT_ALL))
3311 		ctx->is_active = 0;
3312 
3313 	if (ctx->task) {
3314 		WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3315 		if (!ctx->is_active)
3316 			cpuctx->task_ctx = NULL;
3317 	}
3318 
3319 	is_active ^= ctx->is_active; /* changed bits */
3320 
3321 	if (!ctx->nr_active || !(is_active & EVENT_ALL))
3322 		return;
3323 
3324 	perf_pmu_disable(ctx->pmu);
3325 	if (is_active & EVENT_PINNED) {
3326 		list_for_each_entry_safe(event, tmp, &ctx->pinned_active, active_list)
3327 			group_sched_out(event, cpuctx, ctx);
3328 	}
3329 
3330 	if (is_active & EVENT_FLEXIBLE) {
3331 		list_for_each_entry_safe(event, tmp, &ctx->flexible_active, active_list)
3332 			group_sched_out(event, cpuctx, ctx);
3333 
3334 		/*
3335 		 * Since we cleared EVENT_FLEXIBLE, also clear
3336 		 * rotate_necessary, is will be reset by
3337 		 * ctx_flexible_sched_in() when needed.
3338 		 */
3339 		ctx->rotate_necessary = 0;
3340 	}
3341 	perf_pmu_enable(ctx->pmu);
3342 }
3343 
3344 /*
3345  * Test whether two contexts are equivalent, i.e. whether they have both been
3346  * cloned from the same version of the same context.
3347  *
3348  * Equivalence is measured using a generation number in the context that is
3349  * incremented on each modification to it; see unclone_ctx(), list_add_event()
3350  * and list_del_event().
3351  */
context_equiv(struct perf_event_context * ctx1,struct perf_event_context * ctx2)3352 static int context_equiv(struct perf_event_context *ctx1,
3353 			 struct perf_event_context *ctx2)
3354 {
3355 	lockdep_assert_held(&ctx1->lock);
3356 	lockdep_assert_held(&ctx2->lock);
3357 
3358 	/* Pinning disables the swap optimization */
3359 	if (ctx1->pin_count || ctx2->pin_count)
3360 		return 0;
3361 
3362 	/* If ctx1 is the parent of ctx2 */
3363 	if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
3364 		return 1;
3365 
3366 	/* If ctx2 is the parent of ctx1 */
3367 	if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
3368 		return 1;
3369 
3370 	/*
3371 	 * If ctx1 and ctx2 have the same parent; we flatten the parent
3372 	 * hierarchy, see perf_event_init_context().
3373 	 */
3374 	if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
3375 			ctx1->parent_gen == ctx2->parent_gen)
3376 		return 1;
3377 
3378 	/* Unmatched */
3379 	return 0;
3380 }
3381 
__perf_event_sync_stat(struct perf_event * event,struct perf_event * next_event)3382 static void __perf_event_sync_stat(struct perf_event *event,
3383 				     struct perf_event *next_event)
3384 {
3385 	u64 value;
3386 
3387 	if (!event->attr.inherit_stat)
3388 		return;
3389 
3390 	/*
3391 	 * Update the event value, we cannot use perf_event_read()
3392 	 * because we're in the middle of a context switch and have IRQs
3393 	 * disabled, which upsets smp_call_function_single(), however
3394 	 * we know the event must be on the current CPU, therefore we
3395 	 * don't need to use it.
3396 	 */
3397 	if (event->state == PERF_EVENT_STATE_ACTIVE)
3398 		event->pmu->read(event);
3399 
3400 	perf_event_update_time(event);
3401 
3402 	/*
3403 	 * In order to keep per-task stats reliable we need to flip the event
3404 	 * values when we flip the contexts.
3405 	 */
3406 	value = local64_read(&next_event->count);
3407 	value = local64_xchg(&event->count, value);
3408 	local64_set(&next_event->count, value);
3409 
3410 	swap(event->total_time_enabled, next_event->total_time_enabled);
3411 	swap(event->total_time_running, next_event->total_time_running);
3412 
3413 	/*
3414 	 * Since we swizzled the values, update the user visible data too.
3415 	 */
3416 	perf_event_update_userpage(event);
3417 	perf_event_update_userpage(next_event);
3418 }
3419 
perf_event_sync_stat(struct perf_event_context * ctx,struct perf_event_context * next_ctx)3420 static void perf_event_sync_stat(struct perf_event_context *ctx,
3421 				   struct perf_event_context *next_ctx)
3422 {
3423 	struct perf_event *event, *next_event;
3424 
3425 	if (!ctx->nr_stat)
3426 		return;
3427 
3428 	update_context_time(ctx);
3429 
3430 	event = list_first_entry(&ctx->event_list,
3431 				   struct perf_event, event_entry);
3432 
3433 	next_event = list_first_entry(&next_ctx->event_list,
3434 					struct perf_event, event_entry);
3435 
3436 	while (&event->event_entry != &ctx->event_list &&
3437 	       &next_event->event_entry != &next_ctx->event_list) {
3438 
3439 		__perf_event_sync_stat(event, next_event);
3440 
3441 		event = list_next_entry(event, event_entry);
3442 		next_event = list_next_entry(next_event, event_entry);
3443 	}
3444 }
3445 
perf_event_context_sched_out(struct task_struct * task,int ctxn,struct task_struct * next)3446 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
3447 					 struct task_struct *next)
3448 {
3449 	struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
3450 	struct perf_event_context *next_ctx;
3451 	struct perf_event_context *parent, *next_parent;
3452 	struct perf_cpu_context *cpuctx;
3453 	int do_switch = 1;
3454 	struct pmu *pmu;
3455 
3456 	if (likely(!ctx))
3457 		return;
3458 
3459 	pmu = ctx->pmu;
3460 	cpuctx = __get_cpu_context(ctx);
3461 	if (!cpuctx->task_ctx)
3462 		return;
3463 
3464 	rcu_read_lock();
3465 	next_ctx = next->perf_event_ctxp[ctxn];
3466 	if (!next_ctx)
3467 		goto unlock;
3468 
3469 	parent = rcu_dereference(ctx->parent_ctx);
3470 	next_parent = rcu_dereference(next_ctx->parent_ctx);
3471 
3472 	/* If neither context have a parent context; they cannot be clones. */
3473 	if (!parent && !next_parent)
3474 		goto unlock;
3475 
3476 	if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
3477 		/*
3478 		 * Looks like the two contexts are clones, so we might be
3479 		 * able to optimize the context switch.  We lock both
3480 		 * contexts and check that they are clones under the
3481 		 * lock (including re-checking that neither has been
3482 		 * uncloned in the meantime).  It doesn't matter which
3483 		 * order we take the locks because no other cpu could
3484 		 * be trying to lock both of these tasks.
3485 		 */
3486 		raw_spin_lock(&ctx->lock);
3487 		raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
3488 		if (context_equiv(ctx, next_ctx)) {
3489 
3490 			WRITE_ONCE(ctx->task, next);
3491 			WRITE_ONCE(next_ctx->task, task);
3492 
3493 			perf_pmu_disable(pmu);
3494 
3495 			if (cpuctx->sched_cb_usage && pmu->sched_task)
3496 				pmu->sched_task(ctx, false);
3497 
3498 			/*
3499 			 * PMU specific parts of task perf context can require
3500 			 * additional synchronization. As an example of such
3501 			 * synchronization see implementation details of Intel
3502 			 * LBR call stack data profiling;
3503 			 */
3504 			if (pmu->swap_task_ctx)
3505 				pmu->swap_task_ctx(ctx, next_ctx);
3506 			else
3507 				swap(ctx->task_ctx_data, next_ctx->task_ctx_data);
3508 
3509 			perf_pmu_enable(pmu);
3510 
3511 			/*
3512 			 * RCU_INIT_POINTER here is safe because we've not
3513 			 * modified the ctx and the above modification of
3514 			 * ctx->task and ctx->task_ctx_data are immaterial
3515 			 * since those values are always verified under
3516 			 * ctx->lock which we're now holding.
3517 			 */
3518 			RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], next_ctx);
3519 			RCU_INIT_POINTER(next->perf_event_ctxp[ctxn], ctx);
3520 
3521 			do_switch = 0;
3522 
3523 			perf_event_sync_stat(ctx, next_ctx);
3524 		}
3525 		raw_spin_unlock(&next_ctx->lock);
3526 		raw_spin_unlock(&ctx->lock);
3527 	}
3528 unlock:
3529 	rcu_read_unlock();
3530 
3531 	if (do_switch) {
3532 		raw_spin_lock(&ctx->lock);
3533 		perf_pmu_disable(pmu);
3534 
3535 		if (cpuctx->sched_cb_usage && pmu->sched_task)
3536 			pmu->sched_task(ctx, false);
3537 		task_ctx_sched_out(cpuctx, ctx, EVENT_ALL);
3538 
3539 		perf_pmu_enable(pmu);
3540 		raw_spin_unlock(&ctx->lock);
3541 	}
3542 }
3543 
3544 static DEFINE_PER_CPU(struct list_head, sched_cb_list);
3545 
perf_sched_cb_dec(struct pmu * pmu)3546 void perf_sched_cb_dec(struct pmu *pmu)
3547 {
3548 	struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
3549 
3550 	this_cpu_dec(perf_sched_cb_usages);
3551 
3552 	if (!--cpuctx->sched_cb_usage)
3553 		list_del(&cpuctx->sched_cb_entry);
3554 }
3555 
3556 
perf_sched_cb_inc(struct pmu * pmu)3557 void perf_sched_cb_inc(struct pmu *pmu)
3558 {
3559 	struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
3560 
3561 	if (!cpuctx->sched_cb_usage++)
3562 		list_add(&cpuctx->sched_cb_entry, this_cpu_ptr(&sched_cb_list));
3563 
3564 	this_cpu_inc(perf_sched_cb_usages);
3565 }
3566 
3567 /*
3568  * This function provides the context switch callback to the lower code
3569  * layer. It is invoked ONLY when the context switch callback is enabled.
3570  *
3571  * This callback is relevant even to per-cpu events; for example multi event
3572  * PEBS requires this to provide PID/TID information. This requires we flush
3573  * all queued PEBS records before we context switch to a new task.
3574  */
__perf_pmu_sched_task(struct perf_cpu_context * cpuctx,bool sched_in)3575 static void __perf_pmu_sched_task(struct perf_cpu_context *cpuctx, bool sched_in)
3576 {
3577 	struct pmu *pmu;
3578 
3579 	pmu = cpuctx->ctx.pmu; /* software PMUs will not have sched_task */
3580 
3581 	if (WARN_ON_ONCE(!pmu->sched_task))
3582 		return;
3583 
3584 	perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3585 	perf_pmu_disable(pmu);
3586 
3587 	pmu->sched_task(cpuctx->task_ctx, sched_in);
3588 
3589 	perf_pmu_enable(pmu);
3590 	perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3591 }
3592 
perf_pmu_sched_task(struct task_struct * prev,struct task_struct * next,bool sched_in)3593 static void perf_pmu_sched_task(struct task_struct *prev,
3594 				struct task_struct *next,
3595 				bool sched_in)
3596 {
3597 	struct perf_cpu_context *cpuctx;
3598 
3599 	if (prev == next)
3600 		return;
3601 
3602 	list_for_each_entry(cpuctx, this_cpu_ptr(&sched_cb_list), sched_cb_entry) {
3603 		/* will be handled in perf_event_context_sched_in/out */
3604 		if (cpuctx->task_ctx)
3605 			continue;
3606 
3607 		__perf_pmu_sched_task(cpuctx, sched_in);
3608 	}
3609 }
3610 
3611 static void perf_event_switch(struct task_struct *task,
3612 			      struct task_struct *next_prev, bool sched_in);
3613 
3614 #define for_each_task_context_nr(ctxn)					\
3615 	for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
3616 
3617 /*
3618  * Called from scheduler to remove the events of the current task,
3619  * with interrupts disabled.
3620  *
3621  * We stop each event and update the event value in event->count.
3622  *
3623  * This does not protect us against NMI, but disable()
3624  * sets the disabled bit in the control field of event _before_
3625  * accessing the event control register. If a NMI hits, then it will
3626  * not restart the event.
3627  */
__perf_event_task_sched_out(struct task_struct * task,struct task_struct * next)3628 void __perf_event_task_sched_out(struct task_struct *task,
3629 				 struct task_struct *next)
3630 {
3631 	int ctxn;
3632 
3633 	if (__this_cpu_read(perf_sched_cb_usages))
3634 		perf_pmu_sched_task(task, next, false);
3635 
3636 	if (atomic_read(&nr_switch_events))
3637 		perf_event_switch(task, next, false);
3638 
3639 	for_each_task_context_nr(ctxn)
3640 		perf_event_context_sched_out(task, ctxn, next);
3641 
3642 	/*
3643 	 * if cgroup events exist on this CPU, then we need
3644 	 * to check if we have to switch out PMU state.
3645 	 * cgroup event are system-wide mode only
3646 	 */
3647 	if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3648 		perf_cgroup_sched_out(task, next);
3649 }
3650 
3651 /*
3652  * Called with IRQs disabled
3653  */
cpu_ctx_sched_out(struct perf_cpu_context * cpuctx,enum event_type_t event_type)3654 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
3655 			      enum event_type_t event_type)
3656 {
3657 	ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
3658 }
3659 
perf_less_group_idx(const void * l,const void * r)3660 static bool perf_less_group_idx(const void *l, const void *r)
3661 {
3662 	const struct perf_event *le = *(const struct perf_event **)l;
3663 	const struct perf_event *re = *(const struct perf_event **)r;
3664 
3665 	return le->group_index < re->group_index;
3666 }
3667 
swap_ptr(void * l,void * r)3668 static void swap_ptr(void *l, void *r)
3669 {
3670 	void **lp = l, **rp = r;
3671 
3672 	swap(*lp, *rp);
3673 }
3674 
3675 static const struct min_heap_callbacks perf_min_heap = {
3676 	.elem_size = sizeof(struct perf_event *),
3677 	.less = perf_less_group_idx,
3678 	.swp = swap_ptr,
3679 };
3680 
__heap_add(struct min_heap * heap,struct perf_event * event)3681 static void __heap_add(struct min_heap *heap, struct perf_event *event)
3682 {
3683 	struct perf_event **itrs = heap->data;
3684 
3685 	if (event) {
3686 		itrs[heap->nr] = event;
3687 		heap->nr++;
3688 	}
3689 }
3690 
visit_groups_merge(struct perf_cpu_context * cpuctx,struct perf_event_groups * groups,int cpu,int (* func)(struct perf_event *,void *),void * data)3691 static noinline int visit_groups_merge(struct perf_cpu_context *cpuctx,
3692 				struct perf_event_groups *groups, int cpu,
3693 				int (*func)(struct perf_event *, void *),
3694 				void *data)
3695 {
3696 #ifdef CONFIG_CGROUP_PERF
3697 	struct cgroup_subsys_state *css = NULL;
3698 #endif
3699 	/* Space for per CPU and/or any CPU event iterators. */
3700 	struct perf_event *itrs[2];
3701 	struct min_heap event_heap;
3702 	struct perf_event **evt;
3703 	int ret;
3704 
3705 	if (cpuctx) {
3706 		event_heap = (struct min_heap){
3707 			.data = cpuctx->heap,
3708 			.nr = 0,
3709 			.size = cpuctx->heap_size,
3710 		};
3711 
3712 		lockdep_assert_held(&cpuctx->ctx.lock);
3713 
3714 #ifdef CONFIG_CGROUP_PERF
3715 		if (cpuctx->cgrp)
3716 			css = &cpuctx->cgrp->css;
3717 #endif
3718 	} else {
3719 		event_heap = (struct min_heap){
3720 			.data = itrs,
3721 			.nr = 0,
3722 			.size = ARRAY_SIZE(itrs),
3723 		};
3724 		/* Events not within a CPU context may be on any CPU. */
3725 		__heap_add(&event_heap, perf_event_groups_first(groups, -1, NULL));
3726 	}
3727 	evt = event_heap.data;
3728 
3729 	__heap_add(&event_heap, perf_event_groups_first(groups, cpu, NULL));
3730 
3731 #ifdef CONFIG_CGROUP_PERF
3732 	for (; css; css = css->parent)
3733 		__heap_add(&event_heap, perf_event_groups_first(groups, cpu, css->cgroup));
3734 #endif
3735 
3736 	min_heapify_all(&event_heap, &perf_min_heap);
3737 
3738 	while (event_heap.nr) {
3739 		ret = func(*evt, data);
3740 		if (ret)
3741 			return ret;
3742 
3743 		*evt = perf_event_groups_next(*evt);
3744 		if (*evt)
3745 			min_heapify(&event_heap, 0, &perf_min_heap);
3746 		else
3747 			min_heap_pop(&event_heap, &perf_min_heap);
3748 	}
3749 
3750 	return 0;
3751 }
3752 
3753 /*
3754  * Because the userpage is strictly per-event (there is no concept of context,
3755  * so there cannot be a context indirection), every userpage must be updated
3756  * when context time starts :-(
3757  *
3758  * IOW, we must not miss EVENT_TIME edges.
3759  */
event_update_userpage(struct perf_event * event)3760 static inline bool event_update_userpage(struct perf_event *event)
3761 {
3762 	if (likely(!atomic_read(&event->mmap_count)))
3763 		return false;
3764 
3765 	perf_event_update_time(event);
3766 	perf_event_update_userpage(event);
3767 
3768 	return true;
3769 }
3770 
group_update_userpage(struct perf_event * group_event)3771 static inline void group_update_userpage(struct perf_event *group_event)
3772 {
3773 	struct perf_event *event;
3774 
3775 	if (!event_update_userpage(group_event))
3776 		return;
3777 
3778 	for_each_sibling_event(event, group_event)
3779 		event_update_userpage(event);
3780 }
3781 
merge_sched_in(struct perf_event * event,void * data)3782 static int merge_sched_in(struct perf_event *event, void *data)
3783 {
3784 	struct perf_event_context *ctx = event->ctx;
3785 	struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3786 	int *can_add_hw = data;
3787 
3788 	if (event->state <= PERF_EVENT_STATE_OFF)
3789 		return 0;
3790 
3791 	if (!event_filter_match(event))
3792 		return 0;
3793 
3794 	if (group_can_go_on(event, cpuctx, *can_add_hw)) {
3795 		if (!group_sched_in(event, cpuctx, ctx))
3796 			list_add_tail(&event->active_list, get_event_list(event));
3797 	}
3798 
3799 	if (event->state == PERF_EVENT_STATE_INACTIVE) {
3800 		*can_add_hw = 0;
3801 		if (event->attr.pinned) {
3802 			perf_cgroup_event_disable(event, ctx);
3803 			perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
3804 		} else {
3805 			ctx->rotate_necessary = 1;
3806 			perf_mux_hrtimer_restart(cpuctx);
3807 			group_update_userpage(event);
3808 		}
3809 	}
3810 
3811 	return 0;
3812 }
3813 
3814 static void
ctx_pinned_sched_in(struct perf_event_context * ctx,struct perf_cpu_context * cpuctx)3815 ctx_pinned_sched_in(struct perf_event_context *ctx,
3816 		    struct perf_cpu_context *cpuctx)
3817 {
3818 	int can_add_hw = 1;
3819 
3820 	if (ctx != &cpuctx->ctx)
3821 		cpuctx = NULL;
3822 
3823 	visit_groups_merge(cpuctx, &ctx->pinned_groups,
3824 			   smp_processor_id(),
3825 			   merge_sched_in, &can_add_hw);
3826 }
3827 
3828 static void
ctx_flexible_sched_in(struct perf_event_context * ctx,struct perf_cpu_context * cpuctx)3829 ctx_flexible_sched_in(struct perf_event_context *ctx,
3830 		      struct perf_cpu_context *cpuctx)
3831 {
3832 	int can_add_hw = 1;
3833 
3834 	if (ctx != &cpuctx->ctx)
3835 		cpuctx = NULL;
3836 
3837 	visit_groups_merge(cpuctx, &ctx->flexible_groups,
3838 			   smp_processor_id(),
3839 			   merge_sched_in, &can_add_hw);
3840 }
3841 
3842 static void
ctx_sched_in(struct perf_event_context * ctx,struct perf_cpu_context * cpuctx,enum event_type_t event_type,struct task_struct * task)3843 ctx_sched_in(struct perf_event_context *ctx,
3844 	     struct perf_cpu_context *cpuctx,
3845 	     enum event_type_t event_type,
3846 	     struct task_struct *task)
3847 {
3848 	int is_active = ctx->is_active;
3849 
3850 	lockdep_assert_held(&ctx->lock);
3851 
3852 	if (likely(!ctx->nr_events))
3853 		return;
3854 
3855 	if (!(is_active & EVENT_TIME)) {
3856 		/* start ctx time */
3857 		__update_context_time(ctx, false);
3858 		perf_cgroup_set_timestamp(task, ctx);
3859 		/*
3860 		 * CPU-release for the below ->is_active store,
3861 		 * see __load_acquire() in perf_event_time_now()
3862 		 */
3863 		barrier();
3864 	}
3865 
3866 	ctx->is_active |= (event_type | EVENT_TIME);
3867 	if (ctx->task) {
3868 		if (!is_active)
3869 			cpuctx->task_ctx = ctx;
3870 		else
3871 			WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3872 	}
3873 
3874 	is_active ^= ctx->is_active; /* changed bits */
3875 
3876 	/*
3877 	 * First go through the list and put on any pinned groups
3878 	 * in order to give them the best chance of going on.
3879 	 */
3880 	if (is_active & EVENT_PINNED)
3881 		ctx_pinned_sched_in(ctx, cpuctx);
3882 
3883 	/* Then walk through the lower prio flexible groups */
3884 	if (is_active & EVENT_FLEXIBLE)
3885 		ctx_flexible_sched_in(ctx, cpuctx);
3886 }
3887 
cpu_ctx_sched_in(struct perf_cpu_context * cpuctx,enum event_type_t event_type,struct task_struct * task)3888 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
3889 			     enum event_type_t event_type,
3890 			     struct task_struct *task)
3891 {
3892 	struct perf_event_context *ctx = &cpuctx->ctx;
3893 
3894 	ctx_sched_in(ctx, cpuctx, event_type, task);
3895 }
3896 
perf_event_context_sched_in(struct perf_event_context * ctx,struct task_struct * task)3897 static void perf_event_context_sched_in(struct perf_event_context *ctx,
3898 					struct task_struct *task)
3899 {
3900 	struct perf_cpu_context *cpuctx;
3901 	struct pmu *pmu = ctx->pmu;
3902 
3903 	cpuctx = __get_cpu_context(ctx);
3904 	if (cpuctx->task_ctx == ctx) {
3905 		if (cpuctx->sched_cb_usage)
3906 			__perf_pmu_sched_task(cpuctx, true);
3907 		return;
3908 	}
3909 
3910 	perf_ctx_lock(cpuctx, ctx);
3911 	/*
3912 	 * We must check ctx->nr_events while holding ctx->lock, such
3913 	 * that we serialize against perf_install_in_context().
3914 	 */
3915 	if (!ctx->nr_events)
3916 		goto unlock;
3917 
3918 	perf_pmu_disable(pmu);
3919 	/*
3920 	 * We want to keep the following priority order:
3921 	 * cpu pinned (that don't need to move), task pinned,
3922 	 * cpu flexible, task flexible.
3923 	 *
3924 	 * However, if task's ctx is not carrying any pinned
3925 	 * events, no need to flip the cpuctx's events around.
3926 	 */
3927 	if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree))
3928 		cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3929 	perf_event_sched_in(cpuctx, ctx, task);
3930 
3931 	if (cpuctx->sched_cb_usage && pmu->sched_task)
3932 		pmu->sched_task(cpuctx->task_ctx, true);
3933 
3934 	perf_pmu_enable(pmu);
3935 
3936 unlock:
3937 	perf_ctx_unlock(cpuctx, ctx);
3938 }
3939 
3940 /*
3941  * Called from scheduler to add the events of the current task
3942  * with interrupts disabled.
3943  *
3944  * We restore the event value and then enable it.
3945  *
3946  * This does not protect us against NMI, but enable()
3947  * sets the enabled bit in the control field of event _before_
3948  * accessing the event control register. If a NMI hits, then it will
3949  * keep the event running.
3950  */
__perf_event_task_sched_in(struct task_struct * prev,struct task_struct * task)3951 void __perf_event_task_sched_in(struct task_struct *prev,
3952 				struct task_struct *task)
3953 {
3954 	struct perf_event_context *ctx;
3955 	int ctxn;
3956 
3957 	/*
3958 	 * If cgroup events exist on this CPU, then we need to check if we have
3959 	 * to switch in PMU state; cgroup event are system-wide mode only.
3960 	 *
3961 	 * Since cgroup events are CPU events, we must schedule these in before
3962 	 * we schedule in the task events.
3963 	 */
3964 	if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3965 		perf_cgroup_sched_in(prev, task);
3966 
3967 	for_each_task_context_nr(ctxn) {
3968 		ctx = task->perf_event_ctxp[ctxn];
3969 		if (likely(!ctx))
3970 			continue;
3971 
3972 		perf_event_context_sched_in(ctx, task);
3973 	}
3974 
3975 	if (atomic_read(&nr_switch_events))
3976 		perf_event_switch(task, prev, true);
3977 
3978 	if (__this_cpu_read(perf_sched_cb_usages))
3979 		perf_pmu_sched_task(prev, task, true);
3980 }
3981 
perf_calculate_period(struct perf_event * event,u64 nsec,u64 count)3982 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
3983 {
3984 	u64 frequency = event->attr.sample_freq;
3985 	u64 sec = NSEC_PER_SEC;
3986 	u64 divisor, dividend;
3987 
3988 	int count_fls, nsec_fls, frequency_fls, sec_fls;
3989 
3990 	count_fls = fls64(count);
3991 	nsec_fls = fls64(nsec);
3992 	frequency_fls = fls64(frequency);
3993 	sec_fls = 30;
3994 
3995 	/*
3996 	 * We got @count in @nsec, with a target of sample_freq HZ
3997 	 * the target period becomes:
3998 	 *
3999 	 *             @count * 10^9
4000 	 * period = -------------------
4001 	 *          @nsec * sample_freq
4002 	 *
4003 	 */
4004 
4005 	/*
4006 	 * Reduce accuracy by one bit such that @a and @b converge
4007 	 * to a similar magnitude.
4008 	 */
4009 #define REDUCE_FLS(a, b)		\
4010 do {					\
4011 	if (a##_fls > b##_fls) {	\
4012 		a >>= 1;		\
4013 		a##_fls--;		\
4014 	} else {			\
4015 		b >>= 1;		\
4016 		b##_fls--;		\
4017 	}				\
4018 } while (0)
4019 
4020 	/*
4021 	 * Reduce accuracy until either term fits in a u64, then proceed with
4022 	 * the other, so that finally we can do a u64/u64 division.
4023 	 */
4024 	while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
4025 		REDUCE_FLS(nsec, frequency);
4026 		REDUCE_FLS(sec, count);
4027 	}
4028 
4029 	if (count_fls + sec_fls > 64) {
4030 		divisor = nsec * frequency;
4031 
4032 		while (count_fls + sec_fls > 64) {
4033 			REDUCE_FLS(count, sec);
4034 			divisor >>= 1;
4035 		}
4036 
4037 		dividend = count * sec;
4038 	} else {
4039 		dividend = count * sec;
4040 
4041 		while (nsec_fls + frequency_fls > 64) {
4042 			REDUCE_FLS(nsec, frequency);
4043 			dividend >>= 1;
4044 		}
4045 
4046 		divisor = nsec * frequency;
4047 	}
4048 
4049 	if (!divisor)
4050 		return dividend;
4051 
4052 	return div64_u64(dividend, divisor);
4053 }
4054 
4055 static DEFINE_PER_CPU(int, perf_throttled_count);
4056 static DEFINE_PER_CPU(u64, perf_throttled_seq);
4057 
perf_adjust_period(struct perf_event * event,u64 nsec,u64 count,bool disable)4058 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
4059 {
4060 	struct hw_perf_event *hwc = &event->hw;
4061 	s64 period, sample_period;
4062 	s64 delta;
4063 
4064 	period = perf_calculate_period(event, nsec, count);
4065 
4066 	delta = (s64)(period - hwc->sample_period);
4067 	delta = (delta + 7) / 8; /* low pass filter */
4068 
4069 	sample_period = hwc->sample_period + delta;
4070 
4071 	if (!sample_period)
4072 		sample_period = 1;
4073 
4074 	hwc->sample_period = sample_period;
4075 
4076 	if (local64_read(&hwc->period_left) > 8*sample_period) {
4077 		if (disable)
4078 			event->pmu->stop(event, PERF_EF_UPDATE);
4079 
4080 		local64_set(&hwc->period_left, 0);
4081 
4082 		if (disable)
4083 			event->pmu->start(event, PERF_EF_RELOAD);
4084 	}
4085 }
4086 
4087 /*
4088  * combine freq adjustment with unthrottling to avoid two passes over the
4089  * events. At the same time, make sure, having freq events does not change
4090  * the rate of unthrottling as that would introduce bias.
4091  */
perf_adjust_freq_unthr_context(struct perf_event_context * ctx,int needs_unthr)4092 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
4093 					   int needs_unthr)
4094 {
4095 	struct perf_event *event;
4096 	struct hw_perf_event *hwc;
4097 	u64 now, period = TICK_NSEC;
4098 	s64 delta;
4099 
4100 	/*
4101 	 * only need to iterate over all events iff:
4102 	 * - context have events in frequency mode (needs freq adjust)
4103 	 * - there are events to unthrottle on this cpu
4104 	 */
4105 	if (!(ctx->nr_freq || needs_unthr))
4106 		return;
4107 
4108 	raw_spin_lock(&ctx->lock);
4109 	perf_pmu_disable(ctx->pmu);
4110 
4111 	list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
4112 		if (event->state != PERF_EVENT_STATE_ACTIVE)
4113 			continue;
4114 
4115 		if (!event_filter_match(event))
4116 			continue;
4117 
4118 		perf_pmu_disable(event->pmu);
4119 
4120 		hwc = &event->hw;
4121 
4122 		if (hwc->interrupts == MAX_INTERRUPTS) {
4123 			hwc->interrupts = 0;
4124 			perf_log_throttle(event, 1);
4125 			event->pmu->start(event, 0);
4126 		}
4127 
4128 		if (!event->attr.freq || !event->attr.sample_freq)
4129 			goto next;
4130 
4131 		/*
4132 		 * stop the event and update event->count
4133 		 */
4134 		event->pmu->stop(event, PERF_EF_UPDATE);
4135 
4136 		now = local64_read(&event->count);
4137 		delta = now - hwc->freq_count_stamp;
4138 		hwc->freq_count_stamp = now;
4139 
4140 		/*
4141 		 * restart the event
4142 		 * reload only if value has changed
4143 		 * we have stopped the event so tell that
4144 		 * to perf_adjust_period() to avoid stopping it
4145 		 * twice.
4146 		 */
4147 		if (delta > 0)
4148 			perf_adjust_period(event, period, delta, false);
4149 
4150 		event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
4151 	next:
4152 		perf_pmu_enable(event->pmu);
4153 	}
4154 
4155 	perf_pmu_enable(ctx->pmu);
4156 	raw_spin_unlock(&ctx->lock);
4157 }
4158 
4159 /*
4160  * Move @event to the tail of the @ctx's elegible events.
4161  */
rotate_ctx(struct perf_event_context * ctx,struct perf_event * event)4162 static void rotate_ctx(struct perf_event_context *ctx, struct perf_event *event)
4163 {
4164 	/*
4165 	 * Rotate the first entry last of non-pinned groups. Rotation might be
4166 	 * disabled by the inheritance code.
4167 	 */
4168 	if (ctx->rotate_disable)
4169 		return;
4170 
4171 	perf_event_groups_delete(&ctx->flexible_groups, event);
4172 	perf_event_groups_insert(&ctx->flexible_groups, event);
4173 }
4174 
4175 /* pick an event from the flexible_groups to rotate */
4176 static inline struct perf_event *
ctx_event_to_rotate(struct perf_event_context * ctx)4177 ctx_event_to_rotate(struct perf_event_context *ctx)
4178 {
4179 	struct perf_event *event;
4180 
4181 	/* pick the first active flexible event */
4182 	event = list_first_entry_or_null(&ctx->flexible_active,
4183 					 struct perf_event, active_list);
4184 
4185 	/* if no active flexible event, pick the first event */
4186 	if (!event) {
4187 		event = rb_entry_safe(rb_first(&ctx->flexible_groups.tree),
4188 				      typeof(*event), group_node);
4189 	}
4190 
4191 	/*
4192 	 * Unconditionally clear rotate_necessary; if ctx_flexible_sched_in()
4193 	 * finds there are unschedulable events, it will set it again.
4194 	 */
4195 	ctx->rotate_necessary = 0;
4196 
4197 	return event;
4198 }
4199 
perf_rotate_context(struct perf_cpu_context * cpuctx)4200 static bool perf_rotate_context(struct perf_cpu_context *cpuctx)
4201 {
4202 	struct perf_event *cpu_event = NULL, *task_event = NULL;
4203 	struct perf_event_context *task_ctx = NULL;
4204 	int cpu_rotate, task_rotate;
4205 
4206 	/*
4207 	 * Since we run this from IRQ context, nobody can install new
4208 	 * events, thus the event count values are stable.
4209 	 */
4210 
4211 	cpu_rotate = cpuctx->ctx.rotate_necessary;
4212 	task_ctx = cpuctx->task_ctx;
4213 	task_rotate = task_ctx ? task_ctx->rotate_necessary : 0;
4214 
4215 	if (!(cpu_rotate || task_rotate))
4216 		return false;
4217 
4218 	perf_ctx_lock(cpuctx, cpuctx->task_ctx);
4219 	perf_pmu_disable(cpuctx->ctx.pmu);
4220 
4221 	if (task_rotate)
4222 		task_event = ctx_event_to_rotate(task_ctx);
4223 	if (cpu_rotate)
4224 		cpu_event = ctx_event_to_rotate(&cpuctx->ctx);
4225 
4226 	/*
4227 	 * As per the order given at ctx_resched() first 'pop' task flexible
4228 	 * and then, if needed CPU flexible.
4229 	 */
4230 	if (task_event || (task_ctx && cpu_event))
4231 		ctx_sched_out(task_ctx, cpuctx, EVENT_FLEXIBLE);
4232 	if (cpu_event)
4233 		cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
4234 
4235 	if (task_event)
4236 		rotate_ctx(task_ctx, task_event);
4237 	if (cpu_event)
4238 		rotate_ctx(&cpuctx->ctx, cpu_event);
4239 
4240 	perf_event_sched_in(cpuctx, task_ctx, current);
4241 
4242 	perf_pmu_enable(cpuctx->ctx.pmu);
4243 	perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
4244 
4245 	return true;
4246 }
4247 
perf_event_task_tick(void)4248 void perf_event_task_tick(void)
4249 {
4250 	struct list_head *head = this_cpu_ptr(&active_ctx_list);
4251 	struct perf_event_context *ctx, *tmp;
4252 	int throttled;
4253 
4254 	lockdep_assert_irqs_disabled();
4255 
4256 	__this_cpu_inc(perf_throttled_seq);
4257 	throttled = __this_cpu_xchg(perf_throttled_count, 0);
4258 	tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
4259 
4260 	list_for_each_entry_safe(ctx, tmp, head, active_ctx_list)
4261 		perf_adjust_freq_unthr_context(ctx, throttled);
4262 }
4263 
event_enable_on_exec(struct perf_event * event,struct perf_event_context * ctx)4264 static int event_enable_on_exec(struct perf_event *event,
4265 				struct perf_event_context *ctx)
4266 {
4267 	if (!event->attr.enable_on_exec)
4268 		return 0;
4269 
4270 	event->attr.enable_on_exec = 0;
4271 	if (event->state >= PERF_EVENT_STATE_INACTIVE)
4272 		return 0;
4273 
4274 	perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
4275 
4276 	return 1;
4277 }
4278 
4279 /*
4280  * Enable all of a task's events that have been marked enable-on-exec.
4281  * This expects task == current.
4282  */
perf_event_enable_on_exec(int ctxn)4283 static void perf_event_enable_on_exec(int ctxn)
4284 {
4285 	struct perf_event_context *ctx, *clone_ctx = NULL;
4286 	enum event_type_t event_type = 0;
4287 	struct perf_cpu_context *cpuctx;
4288 	struct perf_event *event;
4289 	unsigned long flags;
4290 	int enabled = 0;
4291 
4292 	local_irq_save(flags);
4293 	ctx = current->perf_event_ctxp[ctxn];
4294 	if (!ctx || !ctx->nr_events)
4295 		goto out;
4296 
4297 	cpuctx = __get_cpu_context(ctx);
4298 	perf_ctx_lock(cpuctx, ctx);
4299 	ctx_sched_out(ctx, cpuctx, EVENT_TIME);
4300 	list_for_each_entry(event, &ctx->event_list, event_entry) {
4301 		enabled |= event_enable_on_exec(event, ctx);
4302 		event_type |= get_event_type(event);
4303 	}
4304 
4305 	/*
4306 	 * Unclone and reschedule this context if we enabled any event.
4307 	 */
4308 	if (enabled) {
4309 		clone_ctx = unclone_ctx(ctx);
4310 		ctx_resched(cpuctx, ctx, event_type);
4311 	} else {
4312 		ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
4313 	}
4314 	perf_ctx_unlock(cpuctx, ctx);
4315 
4316 out:
4317 	local_irq_restore(flags);
4318 
4319 	if (clone_ctx)
4320 		put_ctx(clone_ctx);
4321 }
4322 
4323 struct perf_read_data {
4324 	struct perf_event *event;
4325 	bool group;
4326 	int ret;
4327 };
4328 
__perf_event_read_cpu(struct perf_event * event,int event_cpu)4329 static int __perf_event_read_cpu(struct perf_event *event, int event_cpu)
4330 {
4331 	u16 local_pkg, event_pkg;
4332 
4333 	if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) {
4334 		int local_cpu = smp_processor_id();
4335 
4336 		event_pkg = topology_physical_package_id(event_cpu);
4337 		local_pkg = topology_physical_package_id(local_cpu);
4338 
4339 		if (event_pkg == local_pkg)
4340 			return local_cpu;
4341 	}
4342 
4343 	return event_cpu;
4344 }
4345 
4346 /*
4347  * Cross CPU call to read the hardware event
4348  */
__perf_event_read(void * info)4349 static void __perf_event_read(void *info)
4350 {
4351 	struct perf_read_data *data = info;
4352 	struct perf_event *sub, *event = data->event;
4353 	struct perf_event_context *ctx = event->ctx;
4354 	struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
4355 	struct pmu *pmu = event->pmu;
4356 
4357 	/*
4358 	 * If this is a task context, we need to check whether it is
4359 	 * the current task context of this cpu.  If not it has been
4360 	 * scheduled out before the smp call arrived.  In that case
4361 	 * event->count would have been updated to a recent sample
4362 	 * when the event was scheduled out.
4363 	 */
4364 	if (ctx->task && cpuctx->task_ctx != ctx)
4365 		return;
4366 
4367 	raw_spin_lock(&ctx->lock);
4368 	if (ctx->is_active & EVENT_TIME) {
4369 		update_context_time(ctx);
4370 		update_cgrp_time_from_event(event);
4371 	}
4372 
4373 	perf_event_update_time(event);
4374 	if (data->group)
4375 		perf_event_update_sibling_time(event);
4376 
4377 	if (event->state != PERF_EVENT_STATE_ACTIVE)
4378 		goto unlock;
4379 
4380 	if (!data->group) {
4381 		pmu->read(event);
4382 		data->ret = 0;
4383 		goto unlock;
4384 	}
4385 
4386 	pmu->start_txn(pmu, PERF_PMU_TXN_READ);
4387 
4388 	pmu->read(event);
4389 
4390 	for_each_sibling_event(sub, event) {
4391 		if (sub->state == PERF_EVENT_STATE_ACTIVE) {
4392 			/*
4393 			 * Use sibling's PMU rather than @event's since
4394 			 * sibling could be on different (eg: software) PMU.
4395 			 */
4396 			sub->pmu->read(sub);
4397 		}
4398 	}
4399 
4400 	data->ret = pmu->commit_txn(pmu);
4401 
4402 unlock:
4403 	raw_spin_unlock(&ctx->lock);
4404 }
4405 
perf_event_count(struct perf_event * event)4406 static inline u64 perf_event_count(struct perf_event *event)
4407 {
4408 	return local64_read(&event->count) + atomic64_read(&event->child_count);
4409 }
4410 
calc_timer_values(struct perf_event * event,u64 * now,u64 * enabled,u64 * running)4411 static void calc_timer_values(struct perf_event *event,
4412 				u64 *now,
4413 				u64 *enabled,
4414 				u64 *running)
4415 {
4416 	u64 ctx_time;
4417 
4418 	*now = perf_clock();
4419 	ctx_time = perf_event_time_now(event, *now);
4420 	__perf_update_times(event, ctx_time, enabled, running);
4421 }
4422 
4423 /*
4424  * NMI-safe method to read a local event, that is an event that
4425  * is:
4426  *   - either for the current task, or for this CPU
4427  *   - does not have inherit set, for inherited task events
4428  *     will not be local and we cannot read them atomically
4429  *   - must not have a pmu::count method
4430  */
perf_event_read_local(struct perf_event * event,u64 * value,u64 * enabled,u64 * running)4431 int perf_event_read_local(struct perf_event *event, u64 *value,
4432 			  u64 *enabled, u64 *running)
4433 {
4434 	unsigned long flags;
4435 	int ret = 0;
4436 
4437 	/*
4438 	 * Disabling interrupts avoids all counter scheduling (context
4439 	 * switches, timer based rotation and IPIs).
4440 	 */
4441 	local_irq_save(flags);
4442 
4443 	/*
4444 	 * It must not be an event with inherit set, we cannot read
4445 	 * all child counters from atomic context.
4446 	 */
4447 	if (event->attr.inherit) {
4448 		ret = -EOPNOTSUPP;
4449 		goto out;
4450 	}
4451 
4452 	/* If this is a per-task event, it must be for current */
4453 	if ((event->attach_state & PERF_ATTACH_TASK) &&
4454 	    event->hw.target != current) {
4455 		ret = -EINVAL;
4456 		goto out;
4457 	}
4458 
4459 	/* If this is a per-CPU event, it must be for this CPU */
4460 	if (!(event->attach_state & PERF_ATTACH_TASK) &&
4461 	    event->cpu != smp_processor_id()) {
4462 		ret = -EINVAL;
4463 		goto out;
4464 	}
4465 
4466 	/* If this is a pinned event it must be running on this CPU */
4467 	if (event->attr.pinned && event->oncpu != smp_processor_id()) {
4468 		ret = -EBUSY;
4469 		goto out;
4470 	}
4471 
4472 	/*
4473 	 * If the event is currently on this CPU, its either a per-task event,
4474 	 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
4475 	 * oncpu == -1).
4476 	 */
4477 	if (event->oncpu == smp_processor_id())
4478 		event->pmu->read(event);
4479 
4480 	*value = local64_read(&event->count);
4481 	if (enabled || running) {
4482 		u64 __enabled, __running, __now;;
4483 
4484 		calc_timer_values(event, &__now, &__enabled, &__running);
4485 		if (enabled)
4486 			*enabled = __enabled;
4487 		if (running)
4488 			*running = __running;
4489 	}
4490 out:
4491 	local_irq_restore(flags);
4492 
4493 	return ret;
4494 }
4495 
perf_event_read(struct perf_event * event,bool group)4496 static int perf_event_read(struct perf_event *event, bool group)
4497 {
4498 	enum perf_event_state state = READ_ONCE(event->state);
4499 	int event_cpu, ret = 0;
4500 
4501 	/*
4502 	 * If event is enabled and currently active on a CPU, update the
4503 	 * value in the event structure:
4504 	 */
4505 again:
4506 	if (state == PERF_EVENT_STATE_ACTIVE) {
4507 		struct perf_read_data data;
4508 
4509 		/*
4510 		 * Orders the ->state and ->oncpu loads such that if we see
4511 		 * ACTIVE we must also see the right ->oncpu.
4512 		 *
4513 		 * Matches the smp_wmb() from event_sched_in().
4514 		 */
4515 		smp_rmb();
4516 
4517 		event_cpu = READ_ONCE(event->oncpu);
4518 		if ((unsigned)event_cpu >= nr_cpu_ids)
4519 			return 0;
4520 
4521 		data = (struct perf_read_data){
4522 			.event = event,
4523 			.group = group,
4524 			.ret = 0,
4525 		};
4526 
4527 		preempt_disable();
4528 		event_cpu = __perf_event_read_cpu(event, event_cpu);
4529 
4530 		/*
4531 		 * Purposely ignore the smp_call_function_single() return
4532 		 * value.
4533 		 *
4534 		 * If event_cpu isn't a valid CPU it means the event got
4535 		 * scheduled out and that will have updated the event count.
4536 		 *
4537 		 * Therefore, either way, we'll have an up-to-date event count
4538 		 * after this.
4539 		 */
4540 		(void)smp_call_function_single(event_cpu, __perf_event_read, &data, 1);
4541 		preempt_enable();
4542 		ret = data.ret;
4543 
4544 	} else if (state == PERF_EVENT_STATE_INACTIVE) {
4545 		struct perf_event_context *ctx = event->ctx;
4546 		unsigned long flags;
4547 
4548 		raw_spin_lock_irqsave(&ctx->lock, flags);
4549 		state = event->state;
4550 		if (state != PERF_EVENT_STATE_INACTIVE) {
4551 			raw_spin_unlock_irqrestore(&ctx->lock, flags);
4552 			goto again;
4553 		}
4554 
4555 		/*
4556 		 * May read while context is not active (e.g., thread is
4557 		 * blocked), in that case we cannot update context time
4558 		 */
4559 		if (ctx->is_active & EVENT_TIME) {
4560 			update_context_time(ctx);
4561 			update_cgrp_time_from_event(event);
4562 		}
4563 
4564 		perf_event_update_time(event);
4565 		if (group)
4566 			perf_event_update_sibling_time(event);
4567 		raw_spin_unlock_irqrestore(&ctx->lock, flags);
4568 	}
4569 
4570 	return ret;
4571 }
4572 
4573 /*
4574  * Initialize the perf_event context in a task_struct:
4575  */
__perf_event_init_context(struct perf_event_context * ctx)4576 static void __perf_event_init_context(struct perf_event_context *ctx)
4577 {
4578 	raw_spin_lock_init(&ctx->lock);
4579 	mutex_init(&ctx->mutex);
4580 	INIT_LIST_HEAD(&ctx->active_ctx_list);
4581 	perf_event_groups_init(&ctx->pinned_groups);
4582 	perf_event_groups_init(&ctx->flexible_groups);
4583 	INIT_LIST_HEAD(&ctx->event_list);
4584 	INIT_LIST_HEAD(&ctx->pinned_active);
4585 	INIT_LIST_HEAD(&ctx->flexible_active);
4586 	refcount_set(&ctx->refcount, 1);
4587 }
4588 
4589 static struct perf_event_context *
alloc_perf_context(struct pmu * pmu,struct task_struct * task)4590 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
4591 {
4592 	struct perf_event_context *ctx;
4593 
4594 	ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
4595 	if (!ctx)
4596 		return NULL;
4597 
4598 	__perf_event_init_context(ctx);
4599 	if (task)
4600 		ctx->task = get_task_struct(task);
4601 	ctx->pmu = pmu;
4602 
4603 	return ctx;
4604 }
4605 
4606 static struct task_struct *
find_lively_task_by_vpid(pid_t vpid)4607 find_lively_task_by_vpid(pid_t vpid)
4608 {
4609 	struct task_struct *task;
4610 
4611 	rcu_read_lock();
4612 	if (!vpid)
4613 		task = current;
4614 	else
4615 		task = find_task_by_vpid(vpid);
4616 	if (task)
4617 		get_task_struct(task);
4618 	rcu_read_unlock();
4619 
4620 	if (!task)
4621 		return ERR_PTR(-ESRCH);
4622 
4623 	return task;
4624 }
4625 
4626 /*
4627  * Returns a matching context with refcount and pincount.
4628  */
4629 static struct perf_event_context *
find_get_context(struct pmu * pmu,struct task_struct * task,struct perf_event * event)4630 find_get_context(struct pmu *pmu, struct task_struct *task,
4631 		struct perf_event *event)
4632 {
4633 	struct perf_event_context *ctx, *clone_ctx = NULL;
4634 	struct perf_cpu_context *cpuctx;
4635 	void *task_ctx_data = NULL;
4636 	unsigned long flags;
4637 	int ctxn, err;
4638 	int cpu = event->cpu;
4639 
4640 	if (!task) {
4641 		/* Must be root to operate on a CPU event: */
4642 		err = perf_allow_cpu(&event->attr);
4643 		if (err)
4644 			return ERR_PTR(err);
4645 
4646 		cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
4647 		ctx = &cpuctx->ctx;
4648 		get_ctx(ctx);
4649 		raw_spin_lock_irqsave(&ctx->lock, flags);
4650 		++ctx->pin_count;
4651 		raw_spin_unlock_irqrestore(&ctx->lock, flags);
4652 
4653 		return ctx;
4654 	}
4655 
4656 	err = -EINVAL;
4657 	ctxn = pmu->task_ctx_nr;
4658 	if (ctxn < 0)
4659 		goto errout;
4660 
4661 	if (event->attach_state & PERF_ATTACH_TASK_DATA) {
4662 		task_ctx_data = alloc_task_ctx_data(pmu);
4663 		if (!task_ctx_data) {
4664 			err = -ENOMEM;
4665 			goto errout;
4666 		}
4667 	}
4668 
4669 retry:
4670 	ctx = perf_lock_task_context(task, ctxn, &flags);
4671 	if (ctx) {
4672 		clone_ctx = unclone_ctx(ctx);
4673 		++ctx->pin_count;
4674 
4675 		if (task_ctx_data && !ctx->task_ctx_data) {
4676 			ctx->task_ctx_data = task_ctx_data;
4677 			task_ctx_data = NULL;
4678 		}
4679 		raw_spin_unlock_irqrestore(&ctx->lock, flags);
4680 
4681 		if (clone_ctx)
4682 			put_ctx(clone_ctx);
4683 	} else {
4684 		ctx = alloc_perf_context(pmu, task);
4685 		err = -ENOMEM;
4686 		if (!ctx)
4687 			goto errout;
4688 
4689 		if (task_ctx_data) {
4690 			ctx->task_ctx_data = task_ctx_data;
4691 			task_ctx_data = NULL;
4692 		}
4693 
4694 		err = 0;
4695 		mutex_lock(&task->perf_event_mutex);
4696 		/*
4697 		 * If it has already passed perf_event_exit_task().
4698 		 * we must see PF_EXITING, it takes this mutex too.
4699 		 */
4700 		if (task->flags & PF_EXITING)
4701 			err = -ESRCH;
4702 		else if (task->perf_event_ctxp[ctxn])
4703 			err = -EAGAIN;
4704 		else {
4705 			get_ctx(ctx);
4706 			++ctx->pin_count;
4707 			rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
4708 		}
4709 		mutex_unlock(&task->perf_event_mutex);
4710 
4711 		if (unlikely(err)) {
4712 			put_ctx(ctx);
4713 
4714 			if (err == -EAGAIN)
4715 				goto retry;
4716 			goto errout;
4717 		}
4718 	}
4719 
4720 	free_task_ctx_data(pmu, task_ctx_data);
4721 	return ctx;
4722 
4723 errout:
4724 	free_task_ctx_data(pmu, task_ctx_data);
4725 	return ERR_PTR(err);
4726 }
4727 
4728 static void perf_event_free_filter(struct perf_event *event);
4729 static void perf_event_free_bpf_prog(struct perf_event *event);
4730 
free_event_rcu(struct rcu_head * head)4731 static void free_event_rcu(struct rcu_head *head)
4732 {
4733 	struct perf_event *event;
4734 
4735 	event = container_of(head, struct perf_event, rcu_head);
4736 	if (event->ns)
4737 		put_pid_ns(event->ns);
4738 	perf_event_free_filter(event);
4739 	kfree(event);
4740 }
4741 
4742 static void ring_buffer_attach(struct perf_event *event,
4743 			       struct perf_buffer *rb);
4744 
detach_sb_event(struct perf_event * event)4745 static void detach_sb_event(struct perf_event *event)
4746 {
4747 	struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
4748 
4749 	raw_spin_lock(&pel->lock);
4750 	list_del_rcu(&event->sb_list);
4751 	raw_spin_unlock(&pel->lock);
4752 }
4753 
is_sb_event(struct perf_event * event)4754 static bool is_sb_event(struct perf_event *event)
4755 {
4756 	struct perf_event_attr *attr = &event->attr;
4757 
4758 	if (event->parent)
4759 		return false;
4760 
4761 	if (event->attach_state & PERF_ATTACH_TASK)
4762 		return false;
4763 
4764 	if (attr->mmap || attr->mmap_data || attr->mmap2 ||
4765 	    attr->comm || attr->comm_exec ||
4766 	    attr->task || attr->ksymbol ||
4767 	    attr->context_switch || attr->text_poke ||
4768 	    attr->bpf_event)
4769 		return true;
4770 	return false;
4771 }
4772 
unaccount_pmu_sb_event(struct perf_event * event)4773 static void unaccount_pmu_sb_event(struct perf_event *event)
4774 {
4775 	if (is_sb_event(event))
4776 		detach_sb_event(event);
4777 }
4778 
unaccount_event_cpu(struct perf_event * event,int cpu)4779 static void unaccount_event_cpu(struct perf_event *event, int cpu)
4780 {
4781 	if (event->parent)
4782 		return;
4783 
4784 	if (is_cgroup_event(event))
4785 		atomic_dec(&per_cpu(perf_cgroup_events, cpu));
4786 }
4787 
4788 #ifdef CONFIG_NO_HZ_FULL
4789 static DEFINE_SPINLOCK(nr_freq_lock);
4790 #endif
4791 
unaccount_freq_event_nohz(void)4792 static void unaccount_freq_event_nohz(void)
4793 {
4794 #ifdef CONFIG_NO_HZ_FULL
4795 	spin_lock(&nr_freq_lock);
4796 	if (atomic_dec_and_test(&nr_freq_events))
4797 		tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS);
4798 	spin_unlock(&nr_freq_lock);
4799 #endif
4800 }
4801 
unaccount_freq_event(void)4802 static void unaccount_freq_event(void)
4803 {
4804 	if (tick_nohz_full_enabled())
4805 		unaccount_freq_event_nohz();
4806 	else
4807 		atomic_dec(&nr_freq_events);
4808 }
4809 
unaccount_event(struct perf_event * event)4810 static void unaccount_event(struct perf_event *event)
4811 {
4812 	bool dec = false;
4813 
4814 	if (event->parent)
4815 		return;
4816 
4817 	if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB))
4818 		dec = true;
4819 	if (event->attr.mmap || event->attr.mmap_data)
4820 		atomic_dec(&nr_mmap_events);
4821 	if (event->attr.comm)
4822 		atomic_dec(&nr_comm_events);
4823 	if (event->attr.namespaces)
4824 		atomic_dec(&nr_namespaces_events);
4825 	if (event->attr.cgroup)
4826 		atomic_dec(&nr_cgroup_events);
4827 	if (event->attr.task)
4828 		atomic_dec(&nr_task_events);
4829 	if (event->attr.freq)
4830 		unaccount_freq_event();
4831 	if (event->attr.context_switch) {
4832 		dec = true;
4833 		atomic_dec(&nr_switch_events);
4834 	}
4835 	if (is_cgroup_event(event))
4836 		dec = true;
4837 	if (has_branch_stack(event))
4838 		dec = true;
4839 	if (event->attr.ksymbol)
4840 		atomic_dec(&nr_ksymbol_events);
4841 	if (event->attr.bpf_event)
4842 		atomic_dec(&nr_bpf_events);
4843 	if (event->attr.text_poke)
4844 		atomic_dec(&nr_text_poke_events);
4845 
4846 	if (dec) {
4847 		if (!atomic_add_unless(&perf_sched_count, -1, 1))
4848 			schedule_delayed_work(&perf_sched_work, HZ);
4849 	}
4850 
4851 	unaccount_event_cpu(event, event->cpu);
4852 
4853 	unaccount_pmu_sb_event(event);
4854 }
4855 
perf_sched_delayed(struct work_struct * work)4856 static void perf_sched_delayed(struct work_struct *work)
4857 {
4858 	mutex_lock(&perf_sched_mutex);
4859 	if (atomic_dec_and_test(&perf_sched_count))
4860 		static_branch_disable(&perf_sched_events);
4861 	mutex_unlock(&perf_sched_mutex);
4862 }
4863 
4864 /*
4865  * The following implement mutual exclusion of events on "exclusive" pmus
4866  * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
4867  * at a time, so we disallow creating events that might conflict, namely:
4868  *
4869  *  1) cpu-wide events in the presence of per-task events,
4870  *  2) per-task events in the presence of cpu-wide events,
4871  *  3) two matching events on the same context.
4872  *
4873  * The former two cases are handled in the allocation path (perf_event_alloc(),
4874  * _free_event()), the latter -- before the first perf_install_in_context().
4875  */
exclusive_event_init(struct perf_event * event)4876 static int exclusive_event_init(struct perf_event *event)
4877 {
4878 	struct pmu *pmu = event->pmu;
4879 
4880 	if (!is_exclusive_pmu(pmu))
4881 		return 0;
4882 
4883 	/*
4884 	 * Prevent co-existence of per-task and cpu-wide events on the
4885 	 * same exclusive pmu.
4886 	 *
4887 	 * Negative pmu::exclusive_cnt means there are cpu-wide
4888 	 * events on this "exclusive" pmu, positive means there are
4889 	 * per-task events.
4890 	 *
4891 	 * Since this is called in perf_event_alloc() path, event::ctx
4892 	 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
4893 	 * to mean "per-task event", because unlike other attach states it
4894 	 * never gets cleared.
4895 	 */
4896 	if (event->attach_state & PERF_ATTACH_TASK) {
4897 		if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
4898 			return -EBUSY;
4899 	} else {
4900 		if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
4901 			return -EBUSY;
4902 	}
4903 
4904 	return 0;
4905 }
4906 
exclusive_event_destroy(struct perf_event * event)4907 static void exclusive_event_destroy(struct perf_event *event)
4908 {
4909 	struct pmu *pmu = event->pmu;
4910 
4911 	if (!is_exclusive_pmu(pmu))
4912 		return;
4913 
4914 	/* see comment in exclusive_event_init() */
4915 	if (event->attach_state & PERF_ATTACH_TASK)
4916 		atomic_dec(&pmu->exclusive_cnt);
4917 	else
4918 		atomic_inc(&pmu->exclusive_cnt);
4919 }
4920 
exclusive_event_match(struct perf_event * e1,struct perf_event * e2)4921 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
4922 {
4923 	if ((e1->pmu == e2->pmu) &&
4924 	    (e1->cpu == e2->cpu ||
4925 	     e1->cpu == -1 ||
4926 	     e2->cpu == -1))
4927 		return true;
4928 	return false;
4929 }
4930 
exclusive_event_installable(struct perf_event * event,struct perf_event_context * ctx)4931 static bool exclusive_event_installable(struct perf_event *event,
4932 					struct perf_event_context *ctx)
4933 {
4934 	struct perf_event *iter_event;
4935 	struct pmu *pmu = event->pmu;
4936 
4937 	lockdep_assert_held(&ctx->mutex);
4938 
4939 	if (!is_exclusive_pmu(pmu))
4940 		return true;
4941 
4942 	list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
4943 		if (exclusive_event_match(iter_event, event))
4944 			return false;
4945 	}
4946 
4947 	return true;
4948 }
4949 
4950 static void perf_addr_filters_splice(struct perf_event *event,
4951 				       struct list_head *head);
4952 
_free_event(struct perf_event * event)4953 static void _free_event(struct perf_event *event)
4954 {
4955 	irq_work_sync(&event->pending);
4956 
4957 	unaccount_event(event);
4958 
4959 	security_perf_event_free(event);
4960 
4961 	if (event->rb) {
4962 		/*
4963 		 * Can happen when we close an event with re-directed output.
4964 		 *
4965 		 * Since we have a 0 refcount, perf_mmap_close() will skip
4966 		 * over us; possibly making our ring_buffer_put() the last.
4967 		 */
4968 		mutex_lock(&event->mmap_mutex);
4969 		ring_buffer_attach(event, NULL);
4970 		mutex_unlock(&event->mmap_mutex);
4971 	}
4972 
4973 	if (is_cgroup_event(event))
4974 		perf_detach_cgroup(event);
4975 
4976 	if (!event->parent) {
4977 		if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
4978 			put_callchain_buffers();
4979 	}
4980 
4981 	perf_event_free_bpf_prog(event);
4982 	perf_addr_filters_splice(event, NULL);
4983 	kfree(event->addr_filter_ranges);
4984 
4985 	if (event->destroy)
4986 		event->destroy(event);
4987 
4988 	/*
4989 	 * Must be after ->destroy(), due to uprobe_perf_close() using
4990 	 * hw.target.
4991 	 */
4992 	if (event->hw.target)
4993 		put_task_struct(event->hw.target);
4994 
4995 	/*
4996 	 * perf_event_free_task() relies on put_ctx() being 'last', in particular
4997 	 * all task references must be cleaned up.
4998 	 */
4999 	if (event->ctx)
5000 		put_ctx(event->ctx);
5001 
5002 	exclusive_event_destroy(event);
5003 	module_put(event->pmu->module);
5004 
5005 	call_rcu(&event->rcu_head, free_event_rcu);
5006 }
5007 
5008 /*
5009  * Used to free events which have a known refcount of 1, such as in error paths
5010  * where the event isn't exposed yet and inherited events.
5011  */
free_event(struct perf_event * event)5012 static void free_event(struct perf_event *event)
5013 {
5014 	if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
5015 				"unexpected event refcount: %ld; ptr=%p\n",
5016 				atomic_long_read(&event->refcount), event)) {
5017 		/* leak to avoid use-after-free */
5018 		return;
5019 	}
5020 
5021 	_free_event(event);
5022 }
5023 
5024 /*
5025  * Remove user event from the owner task.
5026  */
perf_remove_from_owner(struct perf_event * event)5027 static void perf_remove_from_owner(struct perf_event *event)
5028 {
5029 	struct task_struct *owner;
5030 
5031 	rcu_read_lock();
5032 	/*
5033 	 * Matches the smp_store_release() in perf_event_exit_task(). If we
5034 	 * observe !owner it means the list deletion is complete and we can
5035 	 * indeed free this event, otherwise we need to serialize on
5036 	 * owner->perf_event_mutex.
5037 	 */
5038 	owner = READ_ONCE(event->owner);
5039 	if (owner) {
5040 		/*
5041 		 * Since delayed_put_task_struct() also drops the last
5042 		 * task reference we can safely take a new reference
5043 		 * while holding the rcu_read_lock().
5044 		 */
5045 		get_task_struct(owner);
5046 	}
5047 	rcu_read_unlock();
5048 
5049 	if (owner) {
5050 		/*
5051 		 * If we're here through perf_event_exit_task() we're already
5052 		 * holding ctx->mutex which would be an inversion wrt. the
5053 		 * normal lock order.
5054 		 *
5055 		 * However we can safely take this lock because its the child
5056 		 * ctx->mutex.
5057 		 */
5058 		mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
5059 
5060 		/*
5061 		 * We have to re-check the event->owner field, if it is cleared
5062 		 * we raced with perf_event_exit_task(), acquiring the mutex
5063 		 * ensured they're done, and we can proceed with freeing the
5064 		 * event.
5065 		 */
5066 		if (event->owner) {
5067 			list_del_init(&event->owner_entry);
5068 			smp_store_release(&event->owner, NULL);
5069 		}
5070 		mutex_unlock(&owner->perf_event_mutex);
5071 		put_task_struct(owner);
5072 	}
5073 }
5074 
put_event(struct perf_event * event)5075 static void put_event(struct perf_event *event)
5076 {
5077 	if (!atomic_long_dec_and_test(&event->refcount))
5078 		return;
5079 
5080 	_free_event(event);
5081 }
5082 
5083 /*
5084  * Kill an event dead; while event:refcount will preserve the event
5085  * object, it will not preserve its functionality. Once the last 'user'
5086  * gives up the object, we'll destroy the thing.
5087  */
perf_event_release_kernel(struct perf_event * event)5088 int perf_event_release_kernel(struct perf_event *event)
5089 {
5090 	struct perf_event_context *ctx = event->ctx;
5091 	struct perf_event *child, *tmp;
5092 	LIST_HEAD(free_list);
5093 
5094 	/*
5095 	 * If we got here through err_file: fput(event_file); we will not have
5096 	 * attached to a context yet.
5097 	 */
5098 	if (!ctx) {
5099 		WARN_ON_ONCE(event->attach_state &
5100 				(PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
5101 		goto no_ctx;
5102 	}
5103 
5104 	if (!is_kernel_event(event))
5105 		perf_remove_from_owner(event);
5106 
5107 	ctx = perf_event_ctx_lock(event);
5108 	WARN_ON_ONCE(ctx->parent_ctx);
5109 	perf_remove_from_context(event, DETACH_GROUP);
5110 
5111 	raw_spin_lock_irq(&ctx->lock);
5112 	/*
5113 	 * Mark this event as STATE_DEAD, there is no external reference to it
5114 	 * anymore.
5115 	 *
5116 	 * Anybody acquiring event->child_mutex after the below loop _must_
5117 	 * also see this, most importantly inherit_event() which will avoid
5118 	 * placing more children on the list.
5119 	 *
5120 	 * Thus this guarantees that we will in fact observe and kill _ALL_
5121 	 * child events.
5122 	 */
5123 	event->state = PERF_EVENT_STATE_DEAD;
5124 	raw_spin_unlock_irq(&ctx->lock);
5125 
5126 	perf_event_ctx_unlock(event, ctx);
5127 
5128 again:
5129 	mutex_lock(&event->child_mutex);
5130 	list_for_each_entry(child, &event->child_list, child_list) {
5131 
5132 		/*
5133 		 * Cannot change, child events are not migrated, see the
5134 		 * comment with perf_event_ctx_lock_nested().
5135 		 */
5136 		ctx = READ_ONCE(child->ctx);
5137 		/*
5138 		 * Since child_mutex nests inside ctx::mutex, we must jump
5139 		 * through hoops. We start by grabbing a reference on the ctx.
5140 		 *
5141 		 * Since the event cannot get freed while we hold the
5142 		 * child_mutex, the context must also exist and have a !0
5143 		 * reference count.
5144 		 */
5145 		get_ctx(ctx);
5146 
5147 		/*
5148 		 * Now that we have a ctx ref, we can drop child_mutex, and
5149 		 * acquire ctx::mutex without fear of it going away. Then we
5150 		 * can re-acquire child_mutex.
5151 		 */
5152 		mutex_unlock(&event->child_mutex);
5153 		mutex_lock(&ctx->mutex);
5154 		mutex_lock(&event->child_mutex);
5155 
5156 		/*
5157 		 * Now that we hold ctx::mutex and child_mutex, revalidate our
5158 		 * state, if child is still the first entry, it didn't get freed
5159 		 * and we can continue doing so.
5160 		 */
5161 		tmp = list_first_entry_or_null(&event->child_list,
5162 					       struct perf_event, child_list);
5163 		if (tmp == child) {
5164 			perf_remove_from_context(child, DETACH_GROUP);
5165 			list_move(&child->child_list, &free_list);
5166 			/*
5167 			 * This matches the refcount bump in inherit_event();
5168 			 * this can't be the last reference.
5169 			 */
5170 			put_event(event);
5171 		}
5172 
5173 		mutex_unlock(&event->child_mutex);
5174 		mutex_unlock(&ctx->mutex);
5175 		put_ctx(ctx);
5176 		goto again;
5177 	}
5178 	mutex_unlock(&event->child_mutex);
5179 
5180 	list_for_each_entry_safe(child, tmp, &free_list, child_list) {
5181 		void *var = &child->ctx->refcount;
5182 
5183 		list_del(&child->child_list);
5184 		free_event(child);
5185 
5186 		/*
5187 		 * Wake any perf_event_free_task() waiting for this event to be
5188 		 * freed.
5189 		 */
5190 		smp_mb(); /* pairs with wait_var_event() */
5191 		wake_up_var(var);
5192 	}
5193 
5194 no_ctx:
5195 	put_event(event); /* Must be the 'last' reference */
5196 	return 0;
5197 }
5198 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
5199 
5200 /*
5201  * Called when the last reference to the file is gone.
5202  */
perf_release(struct inode * inode,struct file * file)5203 static int perf_release(struct inode *inode, struct file *file)
5204 {
5205 	perf_event_release_kernel(file->private_data);
5206 	return 0;
5207 }
5208 
__perf_event_read_value(struct perf_event * event,u64 * enabled,u64 * running)5209 static u64 __perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5210 {
5211 	struct perf_event *child;
5212 	u64 total = 0;
5213 
5214 	*enabled = 0;
5215 	*running = 0;
5216 
5217 	mutex_lock(&event->child_mutex);
5218 
5219 	(void)perf_event_read(event, false);
5220 	total += perf_event_count(event);
5221 
5222 	*enabled += event->total_time_enabled +
5223 			atomic64_read(&event->child_total_time_enabled);
5224 	*running += event->total_time_running +
5225 			atomic64_read(&event->child_total_time_running);
5226 
5227 	list_for_each_entry(child, &event->child_list, child_list) {
5228 		(void)perf_event_read(child, false);
5229 		total += perf_event_count(child);
5230 		*enabled += child->total_time_enabled;
5231 		*running += child->total_time_running;
5232 	}
5233 	mutex_unlock(&event->child_mutex);
5234 
5235 	return total;
5236 }
5237 
perf_event_read_value(struct perf_event * event,u64 * enabled,u64 * running)5238 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5239 {
5240 	struct perf_event_context *ctx;
5241 	u64 count;
5242 
5243 	ctx = perf_event_ctx_lock(event);
5244 	count = __perf_event_read_value(event, enabled, running);
5245 	perf_event_ctx_unlock(event, ctx);
5246 
5247 	return count;
5248 }
5249 EXPORT_SYMBOL_GPL(perf_event_read_value);
5250 
__perf_read_group_add(struct perf_event * leader,u64 read_format,u64 * values)5251 static int __perf_read_group_add(struct perf_event *leader,
5252 					u64 read_format, u64 *values)
5253 {
5254 	struct perf_event_context *ctx = leader->ctx;
5255 	struct perf_event *sub, *parent;
5256 	unsigned long flags;
5257 	int n = 1; /* skip @nr */
5258 	int ret;
5259 
5260 	ret = perf_event_read(leader, true);
5261 	if (ret)
5262 		return ret;
5263 
5264 	raw_spin_lock_irqsave(&ctx->lock, flags);
5265 	/*
5266 	 * Verify the grouping between the parent and child (inherited)
5267 	 * events is still in tact.
5268 	 *
5269 	 * Specifically:
5270 	 *  - leader->ctx->lock pins leader->sibling_list
5271 	 *  - parent->child_mutex pins parent->child_list
5272 	 *  - parent->ctx->mutex pins parent->sibling_list
5273 	 *
5274 	 * Because parent->ctx != leader->ctx (and child_list nests inside
5275 	 * ctx->mutex), group destruction is not atomic between children, also
5276 	 * see perf_event_release_kernel(). Additionally, parent can grow the
5277 	 * group.
5278 	 *
5279 	 * Therefore it is possible to have parent and child groups in a
5280 	 * different configuration and summing over such a beast makes no sense
5281 	 * what so ever.
5282 	 *
5283 	 * Reject this.
5284 	 */
5285 	parent = leader->parent;
5286 	if (parent &&
5287 	    (parent->group_generation != leader->group_generation ||
5288 	     parent->nr_siblings != leader->nr_siblings)) {
5289 		ret = -ECHILD;
5290 		goto unlock;
5291 	}
5292 
5293 	/*
5294 	 * Since we co-schedule groups, {enabled,running} times of siblings
5295 	 * will be identical to those of the leader, so we only publish one
5296 	 * set.
5297 	 */
5298 	if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5299 		values[n++] += leader->total_time_enabled +
5300 			atomic64_read(&leader->child_total_time_enabled);
5301 	}
5302 
5303 	if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5304 		values[n++] += leader->total_time_running +
5305 			atomic64_read(&leader->child_total_time_running);
5306 	}
5307 
5308 	/*
5309 	 * Write {count,id} tuples for every sibling.
5310 	 */
5311 	values[n++] += perf_event_count(leader);
5312 	if (read_format & PERF_FORMAT_ID)
5313 		values[n++] = primary_event_id(leader);
5314 	if (read_format & PERF_FORMAT_LOST)
5315 		values[n++] = atomic64_read(&leader->lost_samples);
5316 
5317 	for_each_sibling_event(sub, leader) {
5318 		values[n++] += perf_event_count(sub);
5319 		if (read_format & PERF_FORMAT_ID)
5320 			values[n++] = primary_event_id(sub);
5321 		if (read_format & PERF_FORMAT_LOST)
5322 			values[n++] = atomic64_read(&sub->lost_samples);
5323 	}
5324 
5325 unlock:
5326 	raw_spin_unlock_irqrestore(&ctx->lock, flags);
5327 	return ret;
5328 }
5329 
perf_read_group(struct perf_event * event,u64 read_format,char __user * buf)5330 static int perf_read_group(struct perf_event *event,
5331 				   u64 read_format, char __user *buf)
5332 {
5333 	struct perf_event *leader = event->group_leader, *child;
5334 	struct perf_event_context *ctx = leader->ctx;
5335 	int ret;
5336 	u64 *values;
5337 
5338 	lockdep_assert_held(&ctx->mutex);
5339 
5340 	values = kzalloc(event->read_size, GFP_KERNEL);
5341 	if (!values)
5342 		return -ENOMEM;
5343 
5344 	values[0] = 1 + leader->nr_siblings;
5345 
5346 	mutex_lock(&leader->child_mutex);
5347 
5348 	ret = __perf_read_group_add(leader, read_format, values);
5349 	if (ret)
5350 		goto unlock;
5351 
5352 	list_for_each_entry(child, &leader->child_list, child_list) {
5353 		ret = __perf_read_group_add(child, read_format, values);
5354 		if (ret)
5355 			goto unlock;
5356 	}
5357 
5358 	mutex_unlock(&leader->child_mutex);
5359 
5360 	ret = event->read_size;
5361 	if (copy_to_user(buf, values, event->read_size))
5362 		ret = -EFAULT;
5363 	goto out;
5364 
5365 unlock:
5366 	mutex_unlock(&leader->child_mutex);
5367 out:
5368 	kfree(values);
5369 	return ret;
5370 }
5371 
perf_read_one(struct perf_event * event,u64 read_format,char __user * buf)5372 static int perf_read_one(struct perf_event *event,
5373 				 u64 read_format, char __user *buf)
5374 {
5375 	u64 enabled, running;
5376 	u64 values[5];
5377 	int n = 0;
5378 
5379 	values[n++] = __perf_event_read_value(event, &enabled, &running);
5380 	if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
5381 		values[n++] = enabled;
5382 	if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
5383 		values[n++] = running;
5384 	if (read_format & PERF_FORMAT_ID)
5385 		values[n++] = primary_event_id(event);
5386 	if (read_format & PERF_FORMAT_LOST)
5387 		values[n++] = atomic64_read(&event->lost_samples);
5388 
5389 	if (copy_to_user(buf, values, n * sizeof(u64)))
5390 		return -EFAULT;
5391 
5392 	return n * sizeof(u64);
5393 }
5394 
is_event_hup(struct perf_event * event)5395 static bool is_event_hup(struct perf_event *event)
5396 {
5397 	bool no_children;
5398 
5399 	if (event->state > PERF_EVENT_STATE_EXIT)
5400 		return false;
5401 
5402 	mutex_lock(&event->child_mutex);
5403 	no_children = list_empty(&event->child_list);
5404 	mutex_unlock(&event->child_mutex);
5405 	return no_children;
5406 }
5407 
5408 /*
5409  * Read the performance event - simple non blocking version for now
5410  */
5411 static ssize_t
__perf_read(struct perf_event * event,char __user * buf,size_t count)5412 __perf_read(struct perf_event *event, char __user *buf, size_t count)
5413 {
5414 	u64 read_format = event->attr.read_format;
5415 	int ret;
5416 
5417 	/*
5418 	 * Return end-of-file for a read on an event that is in
5419 	 * error state (i.e. because it was pinned but it couldn't be
5420 	 * scheduled on to the CPU at some point).
5421 	 */
5422 	if (event->state == PERF_EVENT_STATE_ERROR)
5423 		return 0;
5424 
5425 	if (count < event->read_size)
5426 		return -ENOSPC;
5427 
5428 	WARN_ON_ONCE(event->ctx->parent_ctx);
5429 	if (read_format & PERF_FORMAT_GROUP)
5430 		ret = perf_read_group(event, read_format, buf);
5431 	else
5432 		ret = perf_read_one(event, read_format, buf);
5433 
5434 	return ret;
5435 }
5436 
5437 static ssize_t
perf_read(struct file * file,char __user * buf,size_t count,loff_t * ppos)5438 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
5439 {
5440 	struct perf_event *event = file->private_data;
5441 	struct perf_event_context *ctx;
5442 	int ret;
5443 
5444 	ret = security_perf_event_read(event);
5445 	if (ret)
5446 		return ret;
5447 
5448 	ctx = perf_event_ctx_lock(event);
5449 	ret = __perf_read(event, buf, count);
5450 	perf_event_ctx_unlock(event, ctx);
5451 
5452 	return ret;
5453 }
5454 
perf_poll(struct file * file,poll_table * wait)5455 static __poll_t perf_poll(struct file *file, poll_table *wait)
5456 {
5457 	struct perf_event *event = file->private_data;
5458 	struct perf_buffer *rb;
5459 	__poll_t events = EPOLLHUP;
5460 
5461 	poll_wait(file, &event->waitq, wait);
5462 
5463 	if (is_event_hup(event))
5464 		return events;
5465 
5466 	/*
5467 	 * Pin the event->rb by taking event->mmap_mutex; otherwise
5468 	 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
5469 	 */
5470 	mutex_lock(&event->mmap_mutex);
5471 	rb = event->rb;
5472 	if (rb)
5473 		events = atomic_xchg(&rb->poll, 0);
5474 	mutex_unlock(&event->mmap_mutex);
5475 	return events;
5476 }
5477 
_perf_event_reset(struct perf_event * event)5478 static void _perf_event_reset(struct perf_event *event)
5479 {
5480 	(void)perf_event_read(event, false);
5481 	local64_set(&event->count, 0);
5482 	perf_event_update_userpage(event);
5483 }
5484 
5485 /* Assume it's not an event with inherit set. */
perf_event_pause(struct perf_event * event,bool reset)5486 u64 perf_event_pause(struct perf_event *event, bool reset)
5487 {
5488 	struct perf_event_context *ctx;
5489 	u64 count;
5490 
5491 	ctx = perf_event_ctx_lock(event);
5492 	WARN_ON_ONCE(event->attr.inherit);
5493 	_perf_event_disable(event);
5494 	count = local64_read(&event->count);
5495 	if (reset)
5496 		local64_set(&event->count, 0);
5497 	perf_event_ctx_unlock(event, ctx);
5498 
5499 	return count;
5500 }
5501 EXPORT_SYMBOL_GPL(perf_event_pause);
5502 
5503 /*
5504  * Holding the top-level event's child_mutex means that any
5505  * descendant process that has inherited this event will block
5506  * in perf_event_exit_event() if it goes to exit, thus satisfying the
5507  * task existence requirements of perf_event_enable/disable.
5508  */
perf_event_for_each_child(struct perf_event * event,void (* func)(struct perf_event *))5509 static void perf_event_for_each_child(struct perf_event *event,
5510 					void (*func)(struct perf_event *))
5511 {
5512 	struct perf_event *child;
5513 
5514 	WARN_ON_ONCE(event->ctx->parent_ctx);
5515 
5516 	mutex_lock(&event->child_mutex);
5517 	func(event);
5518 	list_for_each_entry(child, &event->child_list, child_list)
5519 		func(child);
5520 	mutex_unlock(&event->child_mutex);
5521 }
5522 
perf_event_for_each(struct perf_event * event,void (* func)(struct perf_event *))5523 static void perf_event_for_each(struct perf_event *event,
5524 				  void (*func)(struct perf_event *))
5525 {
5526 	struct perf_event_context *ctx = event->ctx;
5527 	struct perf_event *sibling;
5528 
5529 	lockdep_assert_held(&ctx->mutex);
5530 
5531 	event = event->group_leader;
5532 
5533 	perf_event_for_each_child(event, func);
5534 	for_each_sibling_event(sibling, event)
5535 		perf_event_for_each_child(sibling, func);
5536 }
5537 
__perf_event_period(struct perf_event * event,struct perf_cpu_context * cpuctx,struct perf_event_context * ctx,void * info)5538 static void __perf_event_period(struct perf_event *event,
5539 				struct perf_cpu_context *cpuctx,
5540 				struct perf_event_context *ctx,
5541 				void *info)
5542 {
5543 	u64 value = *((u64 *)info);
5544 	bool active;
5545 
5546 	if (event->attr.freq) {
5547 		event->attr.sample_freq = value;
5548 	} else {
5549 		event->attr.sample_period = value;
5550 		event->hw.sample_period = value;
5551 	}
5552 
5553 	active = (event->state == PERF_EVENT_STATE_ACTIVE);
5554 	if (active) {
5555 		perf_pmu_disable(ctx->pmu);
5556 		/*
5557 		 * We could be throttled; unthrottle now to avoid the tick
5558 		 * trying to unthrottle while we already re-started the event.
5559 		 */
5560 		if (event->hw.interrupts == MAX_INTERRUPTS) {
5561 			event->hw.interrupts = 0;
5562 			perf_log_throttle(event, 1);
5563 		}
5564 		event->pmu->stop(event, PERF_EF_UPDATE);
5565 	}
5566 
5567 	local64_set(&event->hw.period_left, 0);
5568 
5569 	if (active) {
5570 		event->pmu->start(event, PERF_EF_RELOAD);
5571 		perf_pmu_enable(ctx->pmu);
5572 	}
5573 }
5574 
perf_event_check_period(struct perf_event * event,u64 value)5575 static int perf_event_check_period(struct perf_event *event, u64 value)
5576 {
5577 	return event->pmu->check_period(event, value);
5578 }
5579 
_perf_event_period(struct perf_event * event,u64 value)5580 static int _perf_event_period(struct perf_event *event, u64 value)
5581 {
5582 	if (!is_sampling_event(event))
5583 		return -EINVAL;
5584 
5585 	if (!value)
5586 		return -EINVAL;
5587 
5588 	if (event->attr.freq && value > sysctl_perf_event_sample_rate)
5589 		return -EINVAL;
5590 
5591 	if (perf_event_check_period(event, value))
5592 		return -EINVAL;
5593 
5594 	if (!event->attr.freq && (value & (1ULL << 63)))
5595 		return -EINVAL;
5596 
5597 	event_function_call(event, __perf_event_period, &value);
5598 
5599 	return 0;
5600 }
5601 
perf_event_period(struct perf_event * event,u64 value)5602 int perf_event_period(struct perf_event *event, u64 value)
5603 {
5604 	struct perf_event_context *ctx;
5605 	int ret;
5606 
5607 	ctx = perf_event_ctx_lock(event);
5608 	ret = _perf_event_period(event, value);
5609 	perf_event_ctx_unlock(event, ctx);
5610 
5611 	return ret;
5612 }
5613 EXPORT_SYMBOL_GPL(perf_event_period);
5614 
5615 static const struct file_operations perf_fops;
5616 
perf_fget_light(int fd,struct fd * p)5617 static inline int perf_fget_light(int fd, struct fd *p)
5618 {
5619 	struct fd f = fdget(fd);
5620 	if (!f.file)
5621 		return -EBADF;
5622 
5623 	if (f.file->f_op != &perf_fops) {
5624 		fdput(f);
5625 		return -EBADF;
5626 	}
5627 	*p = f;
5628 	return 0;
5629 }
5630 
5631 static int perf_event_set_output(struct perf_event *event,
5632 				 struct perf_event *output_event);
5633 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
5634 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd);
5635 static int perf_copy_attr(struct perf_event_attr __user *uattr,
5636 			  struct perf_event_attr *attr);
5637 
_perf_ioctl(struct perf_event * event,unsigned int cmd,unsigned long arg)5638 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
5639 {
5640 	void (*func)(struct perf_event *);
5641 	u32 flags = arg;
5642 
5643 	switch (cmd) {
5644 	case PERF_EVENT_IOC_ENABLE:
5645 		func = _perf_event_enable;
5646 		break;
5647 	case PERF_EVENT_IOC_DISABLE:
5648 		func = _perf_event_disable;
5649 		break;
5650 	case PERF_EVENT_IOC_RESET:
5651 		func = _perf_event_reset;
5652 		break;
5653 
5654 	case PERF_EVENT_IOC_REFRESH:
5655 		return _perf_event_refresh(event, arg);
5656 
5657 	case PERF_EVENT_IOC_PERIOD:
5658 	{
5659 		u64 value;
5660 
5661 		if (copy_from_user(&value, (u64 __user *)arg, sizeof(value)))
5662 			return -EFAULT;
5663 
5664 		return _perf_event_period(event, value);
5665 	}
5666 	case PERF_EVENT_IOC_ID:
5667 	{
5668 		u64 id = primary_event_id(event);
5669 
5670 		if (copy_to_user((void __user *)arg, &id, sizeof(id)))
5671 			return -EFAULT;
5672 		return 0;
5673 	}
5674 
5675 	case PERF_EVENT_IOC_SET_OUTPUT:
5676 	{
5677 		int ret;
5678 		if (arg != -1) {
5679 			struct perf_event *output_event;
5680 			struct fd output;
5681 			ret = perf_fget_light(arg, &output);
5682 			if (ret)
5683 				return ret;
5684 			output_event = output.file->private_data;
5685 			ret = perf_event_set_output(event, output_event);
5686 			fdput(output);
5687 		} else {
5688 			ret = perf_event_set_output(event, NULL);
5689 		}
5690 		return ret;
5691 	}
5692 
5693 	case PERF_EVENT_IOC_SET_FILTER:
5694 		return perf_event_set_filter(event, (void __user *)arg);
5695 
5696 	case PERF_EVENT_IOC_SET_BPF:
5697 		return perf_event_set_bpf_prog(event, arg);
5698 
5699 	case PERF_EVENT_IOC_PAUSE_OUTPUT: {
5700 		struct perf_buffer *rb;
5701 
5702 		rcu_read_lock();
5703 		rb = rcu_dereference(event->rb);
5704 		if (!rb || !rb->nr_pages) {
5705 			rcu_read_unlock();
5706 			return -EINVAL;
5707 		}
5708 		rb_toggle_paused(rb, !!arg);
5709 		rcu_read_unlock();
5710 		return 0;
5711 	}
5712 
5713 	case PERF_EVENT_IOC_QUERY_BPF:
5714 		return perf_event_query_prog_array(event, (void __user *)arg);
5715 
5716 	case PERF_EVENT_IOC_MODIFY_ATTRIBUTES: {
5717 		struct perf_event_attr new_attr;
5718 		int err = perf_copy_attr((struct perf_event_attr __user *)arg,
5719 					 &new_attr);
5720 
5721 		if (err)
5722 			return err;
5723 
5724 		return perf_event_modify_attr(event,  &new_attr);
5725 	}
5726 	default:
5727 		return -ENOTTY;
5728 	}
5729 
5730 	if (flags & PERF_IOC_FLAG_GROUP)
5731 		perf_event_for_each(event, func);
5732 	else
5733 		perf_event_for_each_child(event, func);
5734 
5735 	return 0;
5736 }
5737 
perf_ioctl(struct file * file,unsigned int cmd,unsigned long arg)5738 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
5739 {
5740 	struct perf_event *event = file->private_data;
5741 	struct perf_event_context *ctx;
5742 	long ret;
5743 
5744 	/* Treat ioctl like writes as it is likely a mutating operation. */
5745 	ret = security_perf_event_write(event);
5746 	if (ret)
5747 		return ret;
5748 
5749 	ctx = perf_event_ctx_lock(event);
5750 	ret = _perf_ioctl(event, cmd, arg);
5751 	perf_event_ctx_unlock(event, ctx);
5752 
5753 	return ret;
5754 }
5755 
5756 #ifdef CONFIG_COMPAT
perf_compat_ioctl(struct file * file,unsigned int cmd,unsigned long arg)5757 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
5758 				unsigned long arg)
5759 {
5760 	switch (_IOC_NR(cmd)) {
5761 	case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
5762 	case _IOC_NR(PERF_EVENT_IOC_ID):
5763 	case _IOC_NR(PERF_EVENT_IOC_QUERY_BPF):
5764 	case _IOC_NR(PERF_EVENT_IOC_MODIFY_ATTRIBUTES):
5765 		/* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
5766 		if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
5767 			cmd &= ~IOCSIZE_MASK;
5768 			cmd |= sizeof(void *) << IOCSIZE_SHIFT;
5769 		}
5770 		break;
5771 	}
5772 	return perf_ioctl(file, cmd, arg);
5773 }
5774 #else
5775 # define perf_compat_ioctl NULL
5776 #endif
5777 
perf_event_task_enable(void)5778 int perf_event_task_enable(void)
5779 {
5780 	struct perf_event_context *ctx;
5781 	struct perf_event *event;
5782 
5783 	mutex_lock(&current->perf_event_mutex);
5784 	list_for_each_entry(event, &current->perf_event_list, owner_entry) {
5785 		ctx = perf_event_ctx_lock(event);
5786 		perf_event_for_each_child(event, _perf_event_enable);
5787 		perf_event_ctx_unlock(event, ctx);
5788 	}
5789 	mutex_unlock(&current->perf_event_mutex);
5790 
5791 	return 0;
5792 }
5793 
perf_event_task_disable(void)5794 int perf_event_task_disable(void)
5795 {
5796 	struct perf_event_context *ctx;
5797 	struct perf_event *event;
5798 
5799 	mutex_lock(&current->perf_event_mutex);
5800 	list_for_each_entry(event, &current->perf_event_list, owner_entry) {
5801 		ctx = perf_event_ctx_lock(event);
5802 		perf_event_for_each_child(event, _perf_event_disable);
5803 		perf_event_ctx_unlock(event, ctx);
5804 	}
5805 	mutex_unlock(&current->perf_event_mutex);
5806 
5807 	return 0;
5808 }
5809 
perf_event_index(struct perf_event * event)5810 static int perf_event_index(struct perf_event *event)
5811 {
5812 	if (event->hw.state & PERF_HES_STOPPED)
5813 		return 0;
5814 
5815 	if (event->state != PERF_EVENT_STATE_ACTIVE)
5816 		return 0;
5817 
5818 	return event->pmu->event_idx(event);
5819 }
5820 
perf_event_init_userpage(struct perf_event * event)5821 static void perf_event_init_userpage(struct perf_event *event)
5822 {
5823 	struct perf_event_mmap_page *userpg;
5824 	struct perf_buffer *rb;
5825 
5826 	rcu_read_lock();
5827 	rb = rcu_dereference(event->rb);
5828 	if (!rb)
5829 		goto unlock;
5830 
5831 	userpg = rb->user_page;
5832 
5833 	/* Allow new userspace to detect that bit 0 is deprecated */
5834 	userpg->cap_bit0_is_deprecated = 1;
5835 	userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
5836 	userpg->data_offset = PAGE_SIZE;
5837 	userpg->data_size = perf_data_size(rb);
5838 
5839 unlock:
5840 	rcu_read_unlock();
5841 }
5842 
arch_perf_update_userpage(struct perf_event * event,struct perf_event_mmap_page * userpg,u64 now)5843 void __weak arch_perf_update_userpage(
5844 	struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
5845 {
5846 }
5847 
5848 /*
5849  * Callers need to ensure there can be no nesting of this function, otherwise
5850  * the seqlock logic goes bad. We can not serialize this because the arch
5851  * code calls this from NMI context.
5852  */
perf_event_update_userpage(struct perf_event * event)5853 void perf_event_update_userpage(struct perf_event *event)
5854 {
5855 	struct perf_event_mmap_page *userpg;
5856 	struct perf_buffer *rb;
5857 	u64 enabled, running, now;
5858 
5859 	rcu_read_lock();
5860 	rb = rcu_dereference(event->rb);
5861 	if (!rb)
5862 		goto unlock;
5863 
5864 	/*
5865 	 * compute total_time_enabled, total_time_running
5866 	 * based on snapshot values taken when the event
5867 	 * was last scheduled in.
5868 	 *
5869 	 * we cannot simply called update_context_time()
5870 	 * because of locking issue as we can be called in
5871 	 * NMI context
5872 	 */
5873 	calc_timer_values(event, &now, &enabled, &running);
5874 
5875 	userpg = rb->user_page;
5876 	/*
5877 	 * Disable preemption to guarantee consistent time stamps are stored to
5878 	 * the user page.
5879 	 */
5880 	preempt_disable();
5881 	++userpg->lock;
5882 	barrier();
5883 	userpg->index = perf_event_index(event);
5884 	userpg->offset = perf_event_count(event);
5885 	if (userpg->index)
5886 		userpg->offset -= local64_read(&event->hw.prev_count);
5887 
5888 	userpg->time_enabled = enabled +
5889 			atomic64_read(&event->child_total_time_enabled);
5890 
5891 	userpg->time_running = running +
5892 			atomic64_read(&event->child_total_time_running);
5893 
5894 	arch_perf_update_userpage(event, userpg, now);
5895 
5896 	barrier();
5897 	++userpg->lock;
5898 	preempt_enable();
5899 unlock:
5900 	rcu_read_unlock();
5901 }
5902 EXPORT_SYMBOL_GPL(perf_event_update_userpage);
5903 
perf_mmap_fault(struct vm_fault * vmf)5904 static vm_fault_t perf_mmap_fault(struct vm_fault *vmf)
5905 {
5906 	struct perf_event *event = vmf->vma->vm_file->private_data;
5907 	struct perf_buffer *rb;
5908 	vm_fault_t ret = VM_FAULT_SIGBUS;
5909 
5910 	if (vmf->flags & FAULT_FLAG_MKWRITE) {
5911 		if (vmf->pgoff == 0)
5912 			ret = 0;
5913 		return ret;
5914 	}
5915 
5916 	rcu_read_lock();
5917 	rb = rcu_dereference(event->rb);
5918 	if (!rb)
5919 		goto unlock;
5920 
5921 	if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
5922 		goto unlock;
5923 
5924 	vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
5925 	if (!vmf->page)
5926 		goto unlock;
5927 
5928 	get_page(vmf->page);
5929 	vmf->page->mapping = vmf->vma->vm_file->f_mapping;
5930 	vmf->page->index   = vmf->pgoff;
5931 
5932 	ret = 0;
5933 unlock:
5934 	rcu_read_unlock();
5935 
5936 	return ret;
5937 }
5938 
ring_buffer_attach(struct perf_event * event,struct perf_buffer * rb)5939 static void ring_buffer_attach(struct perf_event *event,
5940 			       struct perf_buffer *rb)
5941 {
5942 	struct perf_buffer *old_rb = NULL;
5943 	unsigned long flags;
5944 
5945 	WARN_ON_ONCE(event->parent);
5946 
5947 	if (event->rb) {
5948 		/*
5949 		 * Should be impossible, we set this when removing
5950 		 * event->rb_entry and wait/clear when adding event->rb_entry.
5951 		 */
5952 		WARN_ON_ONCE(event->rcu_pending);
5953 
5954 		old_rb = event->rb;
5955 		spin_lock_irqsave(&old_rb->event_lock, flags);
5956 		list_del_rcu(&event->rb_entry);
5957 		spin_unlock_irqrestore(&old_rb->event_lock, flags);
5958 
5959 		event->rcu_batches = get_state_synchronize_rcu();
5960 		event->rcu_pending = 1;
5961 	}
5962 
5963 	if (rb) {
5964 		if (event->rcu_pending) {
5965 			cond_synchronize_rcu(event->rcu_batches);
5966 			event->rcu_pending = 0;
5967 		}
5968 
5969 		spin_lock_irqsave(&rb->event_lock, flags);
5970 		list_add_rcu(&event->rb_entry, &rb->event_list);
5971 		spin_unlock_irqrestore(&rb->event_lock, flags);
5972 	}
5973 
5974 	/*
5975 	 * Avoid racing with perf_mmap_close(AUX): stop the event
5976 	 * before swizzling the event::rb pointer; if it's getting
5977 	 * unmapped, its aux_mmap_count will be 0 and it won't
5978 	 * restart. See the comment in __perf_pmu_output_stop().
5979 	 *
5980 	 * Data will inevitably be lost when set_output is done in
5981 	 * mid-air, but then again, whoever does it like this is
5982 	 * not in for the data anyway.
5983 	 */
5984 	if (has_aux(event))
5985 		perf_event_stop(event, 0);
5986 
5987 	rcu_assign_pointer(event->rb, rb);
5988 
5989 	if (old_rb) {
5990 		ring_buffer_put(old_rb);
5991 		/*
5992 		 * Since we detached before setting the new rb, so that we
5993 		 * could attach the new rb, we could have missed a wakeup.
5994 		 * Provide it now.
5995 		 */
5996 		wake_up_all(&event->waitq);
5997 	}
5998 }
5999 
ring_buffer_wakeup(struct perf_event * event)6000 static void ring_buffer_wakeup(struct perf_event *event)
6001 {
6002 	struct perf_buffer *rb;
6003 
6004 	if (event->parent)
6005 		event = event->parent;
6006 
6007 	rcu_read_lock();
6008 	rb = rcu_dereference(event->rb);
6009 	if (rb) {
6010 		list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
6011 			wake_up_all(&event->waitq);
6012 	}
6013 	rcu_read_unlock();
6014 }
6015 
ring_buffer_get(struct perf_event * event)6016 struct perf_buffer *ring_buffer_get(struct perf_event *event)
6017 {
6018 	struct perf_buffer *rb;
6019 
6020 	if (event->parent)
6021 		event = event->parent;
6022 
6023 	rcu_read_lock();
6024 	rb = rcu_dereference(event->rb);
6025 	if (rb) {
6026 		if (!refcount_inc_not_zero(&rb->refcount))
6027 			rb = NULL;
6028 	}
6029 	rcu_read_unlock();
6030 
6031 	return rb;
6032 }
6033 
ring_buffer_put(struct perf_buffer * rb)6034 void ring_buffer_put(struct perf_buffer *rb)
6035 {
6036 	if (!refcount_dec_and_test(&rb->refcount))
6037 		return;
6038 
6039 	WARN_ON_ONCE(!list_empty(&rb->event_list));
6040 
6041 	call_rcu(&rb->rcu_head, rb_free_rcu);
6042 }
6043 
perf_mmap_open(struct vm_area_struct * vma)6044 static void perf_mmap_open(struct vm_area_struct *vma)
6045 {
6046 	struct perf_event *event = vma->vm_file->private_data;
6047 
6048 	atomic_inc(&event->mmap_count);
6049 	atomic_inc(&event->rb->mmap_count);
6050 
6051 	if (vma->vm_pgoff)
6052 		atomic_inc(&event->rb->aux_mmap_count);
6053 
6054 	if (event->pmu->event_mapped)
6055 		event->pmu->event_mapped(event, vma->vm_mm);
6056 }
6057 
6058 static void perf_pmu_output_stop(struct perf_event *event);
6059 
6060 /*
6061  * A buffer can be mmap()ed multiple times; either directly through the same
6062  * event, or through other events by use of perf_event_set_output().
6063  *
6064  * In order to undo the VM accounting done by perf_mmap() we need to destroy
6065  * the buffer here, where we still have a VM context. This means we need
6066  * to detach all events redirecting to us.
6067  */
perf_mmap_close(struct vm_area_struct * vma)6068 static void perf_mmap_close(struct vm_area_struct *vma)
6069 {
6070 	struct perf_event *event = vma->vm_file->private_data;
6071 	struct perf_buffer *rb = ring_buffer_get(event);
6072 	struct user_struct *mmap_user = rb->mmap_user;
6073 	int mmap_locked = rb->mmap_locked;
6074 	unsigned long size = perf_data_size(rb);
6075 	bool detach_rest = false;
6076 
6077 	if (event->pmu->event_unmapped)
6078 		event->pmu->event_unmapped(event, vma->vm_mm);
6079 
6080 	/*
6081 	 * rb->aux_mmap_count will always drop before rb->mmap_count and
6082 	 * event->mmap_count, so it is ok to use event->mmap_mutex to
6083 	 * serialize with perf_mmap here.
6084 	 */
6085 	if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
6086 	    atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
6087 		/*
6088 		 * Stop all AUX events that are writing to this buffer,
6089 		 * so that we can free its AUX pages and corresponding PMU
6090 		 * data. Note that after rb::aux_mmap_count dropped to zero,
6091 		 * they won't start any more (see perf_aux_output_begin()).
6092 		 */
6093 		perf_pmu_output_stop(event);
6094 
6095 		/* now it's safe to free the pages */
6096 		atomic_long_sub(rb->aux_nr_pages - rb->aux_mmap_locked, &mmap_user->locked_vm);
6097 		atomic64_sub(rb->aux_mmap_locked, &vma->vm_mm->pinned_vm);
6098 
6099 		/* this has to be the last one */
6100 		rb_free_aux(rb);
6101 		WARN_ON_ONCE(refcount_read(&rb->aux_refcount));
6102 
6103 		mutex_unlock(&event->mmap_mutex);
6104 	}
6105 
6106 	if (atomic_dec_and_test(&rb->mmap_count))
6107 		detach_rest = true;
6108 
6109 	if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
6110 		goto out_put;
6111 
6112 	ring_buffer_attach(event, NULL);
6113 	mutex_unlock(&event->mmap_mutex);
6114 
6115 	/* If there's still other mmap()s of this buffer, we're done. */
6116 	if (!detach_rest)
6117 		goto out_put;
6118 
6119 	/*
6120 	 * No other mmap()s, detach from all other events that might redirect
6121 	 * into the now unreachable buffer. Somewhat complicated by the
6122 	 * fact that rb::event_lock otherwise nests inside mmap_mutex.
6123 	 */
6124 again:
6125 	rcu_read_lock();
6126 	list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
6127 		if (!atomic_long_inc_not_zero(&event->refcount)) {
6128 			/*
6129 			 * This event is en-route to free_event() which will
6130 			 * detach it and remove it from the list.
6131 			 */
6132 			continue;
6133 		}
6134 		rcu_read_unlock();
6135 
6136 		mutex_lock(&event->mmap_mutex);
6137 		/*
6138 		 * Check we didn't race with perf_event_set_output() which can
6139 		 * swizzle the rb from under us while we were waiting to
6140 		 * acquire mmap_mutex.
6141 		 *
6142 		 * If we find a different rb; ignore this event, a next
6143 		 * iteration will no longer find it on the list. We have to
6144 		 * still restart the iteration to make sure we're not now
6145 		 * iterating the wrong list.
6146 		 */
6147 		if (event->rb == rb)
6148 			ring_buffer_attach(event, NULL);
6149 
6150 		mutex_unlock(&event->mmap_mutex);
6151 		put_event(event);
6152 
6153 		/*
6154 		 * Restart the iteration; either we're on the wrong list or
6155 		 * destroyed its integrity by doing a deletion.
6156 		 */
6157 		goto again;
6158 	}
6159 	rcu_read_unlock();
6160 
6161 	/*
6162 	 * It could be there's still a few 0-ref events on the list; they'll
6163 	 * get cleaned up by free_event() -- they'll also still have their
6164 	 * ref on the rb and will free it whenever they are done with it.
6165 	 *
6166 	 * Aside from that, this buffer is 'fully' detached and unmapped,
6167 	 * undo the VM accounting.
6168 	 */
6169 
6170 	atomic_long_sub((size >> PAGE_SHIFT) + 1 - mmap_locked,
6171 			&mmap_user->locked_vm);
6172 	atomic64_sub(mmap_locked, &vma->vm_mm->pinned_vm);
6173 	free_uid(mmap_user);
6174 
6175 out_put:
6176 	ring_buffer_put(rb); /* could be last */
6177 }
6178 
6179 static const struct vm_operations_struct perf_mmap_vmops = {
6180 	.open		= perf_mmap_open,
6181 	.close		= perf_mmap_close, /* non mergeable */
6182 	.fault		= perf_mmap_fault,
6183 	.page_mkwrite	= perf_mmap_fault,
6184 };
6185 
perf_mmap(struct file * file,struct vm_area_struct * vma)6186 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
6187 {
6188 	struct perf_event *event = file->private_data;
6189 	unsigned long user_locked, user_lock_limit;
6190 	struct user_struct *user = current_user();
6191 	struct perf_buffer *rb = NULL;
6192 	unsigned long locked, lock_limit;
6193 	unsigned long vma_size;
6194 	unsigned long nr_pages;
6195 	long user_extra = 0, extra = 0;
6196 	int ret = 0, flags = 0;
6197 
6198 	/*
6199 	 * Don't allow mmap() of inherited per-task counters. This would
6200 	 * create a performance issue due to all children writing to the
6201 	 * same rb.
6202 	 */
6203 	if (event->cpu == -1 && event->attr.inherit)
6204 		return -EINVAL;
6205 
6206 	if (!(vma->vm_flags & VM_SHARED))
6207 		return -EINVAL;
6208 
6209 	ret = security_perf_event_read(event);
6210 	if (ret)
6211 		return ret;
6212 
6213 	vma_size = vma->vm_end - vma->vm_start;
6214 
6215 	if (vma->vm_pgoff == 0) {
6216 		nr_pages = (vma_size / PAGE_SIZE) - 1;
6217 	} else {
6218 		/*
6219 		 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
6220 		 * mapped, all subsequent mappings should have the same size
6221 		 * and offset. Must be above the normal perf buffer.
6222 		 */
6223 		u64 aux_offset, aux_size;
6224 
6225 		if (!event->rb)
6226 			return -EINVAL;
6227 
6228 		nr_pages = vma_size / PAGE_SIZE;
6229 
6230 		mutex_lock(&event->mmap_mutex);
6231 		ret = -EINVAL;
6232 
6233 		rb = event->rb;
6234 		if (!rb)
6235 			goto aux_unlock;
6236 
6237 		aux_offset = READ_ONCE(rb->user_page->aux_offset);
6238 		aux_size = READ_ONCE(rb->user_page->aux_size);
6239 
6240 		if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
6241 			goto aux_unlock;
6242 
6243 		if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
6244 			goto aux_unlock;
6245 
6246 		/* already mapped with a different offset */
6247 		if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
6248 			goto aux_unlock;
6249 
6250 		if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
6251 			goto aux_unlock;
6252 
6253 		/* already mapped with a different size */
6254 		if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
6255 			goto aux_unlock;
6256 
6257 		if (!is_power_of_2(nr_pages))
6258 			goto aux_unlock;
6259 
6260 		if (!atomic_inc_not_zero(&rb->mmap_count))
6261 			goto aux_unlock;
6262 
6263 		if (rb_has_aux(rb)) {
6264 			atomic_inc(&rb->aux_mmap_count);
6265 			ret = 0;
6266 			goto unlock;
6267 		}
6268 
6269 		atomic_set(&rb->aux_mmap_count, 1);
6270 		user_extra = nr_pages;
6271 
6272 		goto accounting;
6273 	}
6274 
6275 	/*
6276 	 * If we have rb pages ensure they're a power-of-two number, so we
6277 	 * can do bitmasks instead of modulo.
6278 	 */
6279 	if (nr_pages != 0 && !is_power_of_2(nr_pages))
6280 		return -EINVAL;
6281 
6282 	if (vma_size != PAGE_SIZE * (1 + nr_pages))
6283 		return -EINVAL;
6284 
6285 	WARN_ON_ONCE(event->ctx->parent_ctx);
6286 again:
6287 	mutex_lock(&event->mmap_mutex);
6288 	if (event->rb) {
6289 		if (data_page_nr(event->rb) != nr_pages) {
6290 			ret = -EINVAL;
6291 			goto unlock;
6292 		}
6293 
6294 		if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
6295 			/*
6296 			 * Raced against perf_mmap_close(); remove the
6297 			 * event and try again.
6298 			 */
6299 			ring_buffer_attach(event, NULL);
6300 			mutex_unlock(&event->mmap_mutex);
6301 			goto again;
6302 		}
6303 
6304 		goto unlock;
6305 	}
6306 
6307 	user_extra = nr_pages + 1;
6308 
6309 accounting:
6310 	user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
6311 
6312 	/*
6313 	 * Increase the limit linearly with more CPUs:
6314 	 */
6315 	user_lock_limit *= num_online_cpus();
6316 
6317 	user_locked = atomic_long_read(&user->locked_vm);
6318 
6319 	/*
6320 	 * sysctl_perf_event_mlock may have changed, so that
6321 	 *     user->locked_vm > user_lock_limit
6322 	 */
6323 	if (user_locked > user_lock_limit)
6324 		user_locked = user_lock_limit;
6325 	user_locked += user_extra;
6326 
6327 	if (user_locked > user_lock_limit) {
6328 		/*
6329 		 * charge locked_vm until it hits user_lock_limit;
6330 		 * charge the rest from pinned_vm
6331 		 */
6332 		extra = user_locked - user_lock_limit;
6333 		user_extra -= extra;
6334 	}
6335 
6336 	lock_limit = rlimit(RLIMIT_MEMLOCK);
6337 	lock_limit >>= PAGE_SHIFT;
6338 	locked = atomic64_read(&vma->vm_mm->pinned_vm) + extra;
6339 
6340 	if ((locked > lock_limit) && perf_is_paranoid() &&
6341 		!capable(CAP_IPC_LOCK)) {
6342 		ret = -EPERM;
6343 		goto unlock;
6344 	}
6345 
6346 	WARN_ON(!rb && event->rb);
6347 
6348 	if (vma->vm_flags & VM_WRITE)
6349 		flags |= RING_BUFFER_WRITABLE;
6350 
6351 	if (!rb) {
6352 		rb = rb_alloc(nr_pages,
6353 			      event->attr.watermark ? event->attr.wakeup_watermark : 0,
6354 			      event->cpu, flags);
6355 
6356 		if (!rb) {
6357 			ret = -ENOMEM;
6358 			goto unlock;
6359 		}
6360 
6361 		atomic_set(&rb->mmap_count, 1);
6362 		rb->mmap_user = get_current_user();
6363 		rb->mmap_locked = extra;
6364 
6365 		ring_buffer_attach(event, rb);
6366 
6367 		perf_event_update_time(event);
6368 		perf_event_init_userpage(event);
6369 		perf_event_update_userpage(event);
6370 	} else {
6371 		ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
6372 				   event->attr.aux_watermark, flags);
6373 		if (!ret)
6374 			rb->aux_mmap_locked = extra;
6375 	}
6376 
6377 unlock:
6378 	if (!ret) {
6379 		atomic_long_add(user_extra, &user->locked_vm);
6380 		atomic64_add(extra, &vma->vm_mm->pinned_vm);
6381 
6382 		atomic_inc(&event->mmap_count);
6383 	} else if (rb) {
6384 		atomic_dec(&rb->mmap_count);
6385 	}
6386 aux_unlock:
6387 	mutex_unlock(&event->mmap_mutex);
6388 
6389 	/*
6390 	 * Since pinned accounting is per vm we cannot allow fork() to copy our
6391 	 * vma.
6392 	 */
6393 	vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
6394 	vma->vm_ops = &perf_mmap_vmops;
6395 
6396 	if (event->pmu->event_mapped)
6397 		event->pmu->event_mapped(event, vma->vm_mm);
6398 
6399 	return ret;
6400 }
6401 
perf_fasync(int fd,struct file * filp,int on)6402 static int perf_fasync(int fd, struct file *filp, int on)
6403 {
6404 	struct inode *inode = file_inode(filp);
6405 	struct perf_event *event = filp->private_data;
6406 	int retval;
6407 
6408 	inode_lock(inode);
6409 	retval = fasync_helper(fd, filp, on, &event->fasync);
6410 	inode_unlock(inode);
6411 
6412 	if (retval < 0)
6413 		return retval;
6414 
6415 	return 0;
6416 }
6417 
6418 static const struct file_operations perf_fops = {
6419 	.llseek			= no_llseek,
6420 	.release		= perf_release,
6421 	.read			= perf_read,
6422 	.poll			= perf_poll,
6423 	.unlocked_ioctl		= perf_ioctl,
6424 	.compat_ioctl		= perf_compat_ioctl,
6425 	.mmap			= perf_mmap,
6426 	.fasync			= perf_fasync,
6427 };
6428 
6429 /*
6430  * Perf event wakeup
6431  *
6432  * If there's data, ensure we set the poll() state and publish everything
6433  * to user-space before waking everybody up.
6434  */
6435 
perf_event_fasync(struct perf_event * event)6436 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
6437 {
6438 	/* only the parent has fasync state */
6439 	if (event->parent)
6440 		event = event->parent;
6441 	return &event->fasync;
6442 }
6443 
perf_event_wakeup(struct perf_event * event)6444 void perf_event_wakeup(struct perf_event *event)
6445 {
6446 	ring_buffer_wakeup(event);
6447 
6448 	if (event->pending_kill) {
6449 		kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
6450 		event->pending_kill = 0;
6451 	}
6452 }
6453 
perf_pending_event_disable(struct perf_event * event)6454 static void perf_pending_event_disable(struct perf_event *event)
6455 {
6456 	int cpu = READ_ONCE(event->pending_disable);
6457 
6458 	if (cpu < 0)
6459 		return;
6460 
6461 	if (cpu == smp_processor_id()) {
6462 		WRITE_ONCE(event->pending_disable, -1);
6463 		perf_event_disable_local(event);
6464 		return;
6465 	}
6466 
6467 	/*
6468 	 *  CPU-A			CPU-B
6469 	 *
6470 	 *  perf_event_disable_inatomic()
6471 	 *    @pending_disable = CPU-A;
6472 	 *    irq_work_queue();
6473 	 *
6474 	 *  sched-out
6475 	 *    @pending_disable = -1;
6476 	 *
6477 	 *				sched-in
6478 	 *				perf_event_disable_inatomic()
6479 	 *				  @pending_disable = CPU-B;
6480 	 *				  irq_work_queue(); // FAILS
6481 	 *
6482 	 *  irq_work_run()
6483 	 *    perf_pending_event()
6484 	 *
6485 	 * But the event runs on CPU-B and wants disabling there.
6486 	 */
6487 	irq_work_queue_on(&event->pending, cpu);
6488 }
6489 
perf_pending_event(struct irq_work * entry)6490 static void perf_pending_event(struct irq_work *entry)
6491 {
6492 	struct perf_event *event = container_of(entry, struct perf_event, pending);
6493 	int rctx;
6494 
6495 	rctx = perf_swevent_get_recursion_context();
6496 	/*
6497 	 * If we 'fail' here, that's OK, it means recursion is already disabled
6498 	 * and we won't recurse 'further'.
6499 	 */
6500 
6501 	perf_pending_event_disable(event);
6502 
6503 	if (event->pending_wakeup) {
6504 		event->pending_wakeup = 0;
6505 		perf_event_wakeup(event);
6506 	}
6507 
6508 	if (rctx >= 0)
6509 		perf_swevent_put_recursion_context(rctx);
6510 }
6511 
6512 /*
6513  * We assume there is only KVM supporting the callbacks.
6514  * Later on, we might change it to a list if there is
6515  * another virtualization implementation supporting the callbacks.
6516  */
6517 struct perf_guest_info_callbacks __rcu *perf_guest_cbs;
6518 
perf_register_guest_info_callbacks(struct perf_guest_info_callbacks * cbs)6519 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6520 {
6521 	if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs)))
6522 		return -EBUSY;
6523 
6524 	rcu_assign_pointer(perf_guest_cbs, cbs);
6525 	return 0;
6526 }
6527 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
6528 
perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks * cbs)6529 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6530 {
6531 	if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs) != cbs))
6532 		return -EINVAL;
6533 
6534 	rcu_assign_pointer(perf_guest_cbs, NULL);
6535 	synchronize_rcu();
6536 	return 0;
6537 }
6538 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
6539 
6540 static void
perf_output_sample_regs(struct perf_output_handle * handle,struct pt_regs * regs,u64 mask)6541 perf_output_sample_regs(struct perf_output_handle *handle,
6542 			struct pt_regs *regs, u64 mask)
6543 {
6544 	int bit;
6545 	DECLARE_BITMAP(_mask, 64);
6546 
6547 	bitmap_from_u64(_mask, mask);
6548 	for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) {
6549 		u64 val;
6550 
6551 		val = perf_reg_value(regs, bit);
6552 		perf_output_put(handle, val);
6553 	}
6554 }
6555 
perf_sample_regs_user(struct perf_regs * regs_user,struct pt_regs * regs)6556 static void perf_sample_regs_user(struct perf_regs *regs_user,
6557 				  struct pt_regs *regs)
6558 {
6559 	if (user_mode(regs)) {
6560 		regs_user->abi = perf_reg_abi(current);
6561 		regs_user->regs = regs;
6562 	} else if (!(current->flags & PF_KTHREAD)) {
6563 		perf_get_regs_user(regs_user, regs);
6564 	} else {
6565 		regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
6566 		regs_user->regs = NULL;
6567 	}
6568 }
6569 
perf_sample_regs_intr(struct perf_regs * regs_intr,struct pt_regs * regs)6570 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
6571 				  struct pt_regs *regs)
6572 {
6573 	regs_intr->regs = regs;
6574 	regs_intr->abi  = perf_reg_abi(current);
6575 }
6576 
6577 
6578 /*
6579  * Get remaining task size from user stack pointer.
6580  *
6581  * It'd be better to take stack vma map and limit this more
6582  * precisely, but there's no way to get it safely under interrupt,
6583  * so using TASK_SIZE as limit.
6584  */
perf_ustack_task_size(struct pt_regs * regs)6585 static u64 perf_ustack_task_size(struct pt_regs *regs)
6586 {
6587 	unsigned long addr = perf_user_stack_pointer(regs);
6588 
6589 	if (!addr || addr >= TASK_SIZE)
6590 		return 0;
6591 
6592 	return TASK_SIZE - addr;
6593 }
6594 
6595 static u16
perf_sample_ustack_size(u16 stack_size,u16 header_size,struct pt_regs * regs)6596 perf_sample_ustack_size(u16 stack_size, u16 header_size,
6597 			struct pt_regs *regs)
6598 {
6599 	u64 task_size;
6600 
6601 	/* No regs, no stack pointer, no dump. */
6602 	if (!regs)
6603 		return 0;
6604 
6605 	/*
6606 	 * Check if we fit in with the requested stack size into the:
6607 	 * - TASK_SIZE
6608 	 *   If we don't, we limit the size to the TASK_SIZE.
6609 	 *
6610 	 * - remaining sample size
6611 	 *   If we don't, we customize the stack size to
6612 	 *   fit in to the remaining sample size.
6613 	 */
6614 
6615 	task_size  = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
6616 	stack_size = min(stack_size, (u16) task_size);
6617 
6618 	/* Current header size plus static size and dynamic size. */
6619 	header_size += 2 * sizeof(u64);
6620 
6621 	/* Do we fit in with the current stack dump size? */
6622 	if ((u16) (header_size + stack_size) < header_size) {
6623 		/*
6624 		 * If we overflow the maximum size for the sample,
6625 		 * we customize the stack dump size to fit in.
6626 		 */
6627 		stack_size = USHRT_MAX - header_size - sizeof(u64);
6628 		stack_size = round_up(stack_size, sizeof(u64));
6629 	}
6630 
6631 	return stack_size;
6632 }
6633 
6634 static void
perf_output_sample_ustack(struct perf_output_handle * handle,u64 dump_size,struct pt_regs * regs)6635 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
6636 			  struct pt_regs *regs)
6637 {
6638 	/* Case of a kernel thread, nothing to dump */
6639 	if (!regs) {
6640 		u64 size = 0;
6641 		perf_output_put(handle, size);
6642 	} else {
6643 		unsigned long sp;
6644 		unsigned int rem;
6645 		u64 dyn_size;
6646 		mm_segment_t fs;
6647 
6648 		/*
6649 		 * We dump:
6650 		 * static size
6651 		 *   - the size requested by user or the best one we can fit
6652 		 *     in to the sample max size
6653 		 * data
6654 		 *   - user stack dump data
6655 		 * dynamic size
6656 		 *   - the actual dumped size
6657 		 */
6658 
6659 		/* Static size. */
6660 		perf_output_put(handle, dump_size);
6661 
6662 		/* Data. */
6663 		sp = perf_user_stack_pointer(regs);
6664 		fs = force_uaccess_begin();
6665 		rem = __output_copy_user(handle, (void *) sp, dump_size);
6666 		force_uaccess_end(fs);
6667 		dyn_size = dump_size - rem;
6668 
6669 		perf_output_skip(handle, rem);
6670 
6671 		/* Dynamic size. */
6672 		perf_output_put(handle, dyn_size);
6673 	}
6674 }
6675 
perf_prepare_sample_aux(struct perf_event * event,struct perf_sample_data * data,size_t size)6676 static unsigned long perf_prepare_sample_aux(struct perf_event *event,
6677 					  struct perf_sample_data *data,
6678 					  size_t size)
6679 {
6680 	struct perf_event *sampler = event->aux_event;
6681 	struct perf_buffer *rb;
6682 
6683 	data->aux_size = 0;
6684 
6685 	if (!sampler)
6686 		goto out;
6687 
6688 	if (WARN_ON_ONCE(READ_ONCE(sampler->state) != PERF_EVENT_STATE_ACTIVE))
6689 		goto out;
6690 
6691 	if (WARN_ON_ONCE(READ_ONCE(sampler->oncpu) != smp_processor_id()))
6692 		goto out;
6693 
6694 	rb = ring_buffer_get(sampler);
6695 	if (!rb)
6696 		goto out;
6697 
6698 	/*
6699 	 * If this is an NMI hit inside sampling code, don't take
6700 	 * the sample. See also perf_aux_sample_output().
6701 	 */
6702 	if (READ_ONCE(rb->aux_in_sampling)) {
6703 		data->aux_size = 0;
6704 	} else {
6705 		size = min_t(size_t, size, perf_aux_size(rb));
6706 		data->aux_size = ALIGN(size, sizeof(u64));
6707 	}
6708 	ring_buffer_put(rb);
6709 
6710 out:
6711 	return data->aux_size;
6712 }
6713 
perf_pmu_snapshot_aux(struct perf_buffer * rb,struct perf_event * event,struct perf_output_handle * handle,unsigned long size)6714 long perf_pmu_snapshot_aux(struct perf_buffer *rb,
6715 			   struct perf_event *event,
6716 			   struct perf_output_handle *handle,
6717 			   unsigned long size)
6718 {
6719 	unsigned long flags;
6720 	long ret;
6721 
6722 	/*
6723 	 * Normal ->start()/->stop() callbacks run in IRQ mode in scheduler
6724 	 * paths. If we start calling them in NMI context, they may race with
6725 	 * the IRQ ones, that is, for example, re-starting an event that's just
6726 	 * been stopped, which is why we're using a separate callback that
6727 	 * doesn't change the event state.
6728 	 *
6729 	 * IRQs need to be disabled to prevent IPIs from racing with us.
6730 	 */
6731 	local_irq_save(flags);
6732 	/*
6733 	 * Guard against NMI hits inside the critical section;
6734 	 * see also perf_prepare_sample_aux().
6735 	 */
6736 	WRITE_ONCE(rb->aux_in_sampling, 1);
6737 	barrier();
6738 
6739 	ret = event->pmu->snapshot_aux(event, handle, size);
6740 
6741 	barrier();
6742 	WRITE_ONCE(rb->aux_in_sampling, 0);
6743 	local_irq_restore(flags);
6744 
6745 	return ret;
6746 }
6747 
perf_aux_sample_output(struct perf_event * event,struct perf_output_handle * handle,struct perf_sample_data * data)6748 static void perf_aux_sample_output(struct perf_event *event,
6749 				   struct perf_output_handle *handle,
6750 				   struct perf_sample_data *data)
6751 {
6752 	struct perf_event *sampler = event->aux_event;
6753 	struct perf_buffer *rb;
6754 	unsigned long pad;
6755 	long size;
6756 
6757 	if (WARN_ON_ONCE(!sampler || !data->aux_size))
6758 		return;
6759 
6760 	rb = ring_buffer_get(sampler);
6761 	if (!rb)
6762 		return;
6763 
6764 	size = perf_pmu_snapshot_aux(rb, sampler, handle, data->aux_size);
6765 
6766 	/*
6767 	 * An error here means that perf_output_copy() failed (returned a
6768 	 * non-zero surplus that it didn't copy), which in its current
6769 	 * enlightened implementation is not possible. If that changes, we'd
6770 	 * like to know.
6771 	 */
6772 	if (WARN_ON_ONCE(size < 0))
6773 		goto out_put;
6774 
6775 	/*
6776 	 * The pad comes from ALIGN()ing data->aux_size up to u64 in
6777 	 * perf_prepare_sample_aux(), so should not be more than that.
6778 	 */
6779 	pad = data->aux_size - size;
6780 	if (WARN_ON_ONCE(pad >= sizeof(u64)))
6781 		pad = 8;
6782 
6783 	if (pad) {
6784 		u64 zero = 0;
6785 		perf_output_copy(handle, &zero, pad);
6786 	}
6787 
6788 out_put:
6789 	ring_buffer_put(rb);
6790 }
6791 
__perf_event_header__init_id(struct perf_event_header * header,struct perf_sample_data * data,struct perf_event * event)6792 static void __perf_event_header__init_id(struct perf_event_header *header,
6793 					 struct perf_sample_data *data,
6794 					 struct perf_event *event)
6795 {
6796 	u64 sample_type = event->attr.sample_type;
6797 
6798 	data->type = sample_type;
6799 	header->size += event->id_header_size;
6800 
6801 	if (sample_type & PERF_SAMPLE_TID) {
6802 		/* namespace issues */
6803 		data->tid_entry.pid = perf_event_pid(event, current);
6804 		data->tid_entry.tid = perf_event_tid(event, current);
6805 	}
6806 
6807 	if (sample_type & PERF_SAMPLE_TIME)
6808 		data->time = perf_event_clock(event);
6809 
6810 	if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
6811 		data->id = primary_event_id(event);
6812 
6813 	if (sample_type & PERF_SAMPLE_STREAM_ID)
6814 		data->stream_id = event->id;
6815 
6816 	if (sample_type & PERF_SAMPLE_CPU) {
6817 		data->cpu_entry.cpu	 = raw_smp_processor_id();
6818 		data->cpu_entry.reserved = 0;
6819 	}
6820 }
6821 
perf_event_header__init_id(struct perf_event_header * header,struct perf_sample_data * data,struct perf_event * event)6822 void perf_event_header__init_id(struct perf_event_header *header,
6823 				struct perf_sample_data *data,
6824 				struct perf_event *event)
6825 {
6826 	if (event->attr.sample_id_all)
6827 		__perf_event_header__init_id(header, data, event);
6828 }
6829 
__perf_event__output_id_sample(struct perf_output_handle * handle,struct perf_sample_data * data)6830 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
6831 					   struct perf_sample_data *data)
6832 {
6833 	u64 sample_type = data->type;
6834 
6835 	if (sample_type & PERF_SAMPLE_TID)
6836 		perf_output_put(handle, data->tid_entry);
6837 
6838 	if (sample_type & PERF_SAMPLE_TIME)
6839 		perf_output_put(handle, data->time);
6840 
6841 	if (sample_type & PERF_SAMPLE_ID)
6842 		perf_output_put(handle, data->id);
6843 
6844 	if (sample_type & PERF_SAMPLE_STREAM_ID)
6845 		perf_output_put(handle, data->stream_id);
6846 
6847 	if (sample_type & PERF_SAMPLE_CPU)
6848 		perf_output_put(handle, data->cpu_entry);
6849 
6850 	if (sample_type & PERF_SAMPLE_IDENTIFIER)
6851 		perf_output_put(handle, data->id);
6852 }
6853 
perf_event__output_id_sample(struct perf_event * event,struct perf_output_handle * handle,struct perf_sample_data * sample)6854 void perf_event__output_id_sample(struct perf_event *event,
6855 				  struct perf_output_handle *handle,
6856 				  struct perf_sample_data *sample)
6857 {
6858 	if (event->attr.sample_id_all)
6859 		__perf_event__output_id_sample(handle, sample);
6860 }
6861 
perf_output_read_one(struct perf_output_handle * handle,struct perf_event * event,u64 enabled,u64 running)6862 static void perf_output_read_one(struct perf_output_handle *handle,
6863 				 struct perf_event *event,
6864 				 u64 enabled, u64 running)
6865 {
6866 	u64 read_format = event->attr.read_format;
6867 	u64 values[5];
6868 	int n = 0;
6869 
6870 	values[n++] = perf_event_count(event);
6871 	if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
6872 		values[n++] = enabled +
6873 			atomic64_read(&event->child_total_time_enabled);
6874 	}
6875 	if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
6876 		values[n++] = running +
6877 			atomic64_read(&event->child_total_time_running);
6878 	}
6879 	if (read_format & PERF_FORMAT_ID)
6880 		values[n++] = primary_event_id(event);
6881 	if (read_format & PERF_FORMAT_LOST)
6882 		values[n++] = atomic64_read(&event->lost_samples);
6883 
6884 	__output_copy(handle, values, n * sizeof(u64));
6885 }
6886 
perf_output_read_group(struct perf_output_handle * handle,struct perf_event * event,u64 enabled,u64 running)6887 static void perf_output_read_group(struct perf_output_handle *handle,
6888 			    struct perf_event *event,
6889 			    u64 enabled, u64 running)
6890 {
6891 	struct perf_event *leader = event->group_leader, *sub;
6892 	u64 read_format = event->attr.read_format;
6893 	u64 values[6];
6894 	int n = 0;
6895 
6896 	values[n++] = 1 + leader->nr_siblings;
6897 
6898 	if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
6899 		values[n++] = enabled;
6900 
6901 	if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
6902 		values[n++] = running;
6903 
6904 	if ((leader != event) &&
6905 	    (leader->state == PERF_EVENT_STATE_ACTIVE))
6906 		leader->pmu->read(leader);
6907 
6908 	values[n++] = perf_event_count(leader);
6909 	if (read_format & PERF_FORMAT_ID)
6910 		values[n++] = primary_event_id(leader);
6911 	if (read_format & PERF_FORMAT_LOST)
6912 		values[n++] = atomic64_read(&leader->lost_samples);
6913 
6914 	__output_copy(handle, values, n * sizeof(u64));
6915 
6916 	for_each_sibling_event(sub, leader) {
6917 		n = 0;
6918 
6919 		if ((sub != event) &&
6920 		    (sub->state == PERF_EVENT_STATE_ACTIVE))
6921 			sub->pmu->read(sub);
6922 
6923 		values[n++] = perf_event_count(sub);
6924 		if (read_format & PERF_FORMAT_ID)
6925 			values[n++] = primary_event_id(sub);
6926 		if (read_format & PERF_FORMAT_LOST)
6927 			values[n++] = atomic64_read(&sub->lost_samples);
6928 
6929 		__output_copy(handle, values, n * sizeof(u64));
6930 	}
6931 }
6932 
6933 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
6934 				 PERF_FORMAT_TOTAL_TIME_RUNNING)
6935 
6936 /*
6937  * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
6938  *
6939  * The problem is that its both hard and excessively expensive to iterate the
6940  * child list, not to mention that its impossible to IPI the children running
6941  * on another CPU, from interrupt/NMI context.
6942  */
perf_output_read(struct perf_output_handle * handle,struct perf_event * event)6943 static void perf_output_read(struct perf_output_handle *handle,
6944 			     struct perf_event *event)
6945 {
6946 	u64 enabled = 0, running = 0, now;
6947 	u64 read_format = event->attr.read_format;
6948 
6949 	/*
6950 	 * compute total_time_enabled, total_time_running
6951 	 * based on snapshot values taken when the event
6952 	 * was last scheduled in.
6953 	 *
6954 	 * we cannot simply called update_context_time()
6955 	 * because of locking issue as we are called in
6956 	 * NMI context
6957 	 */
6958 	if (read_format & PERF_FORMAT_TOTAL_TIMES)
6959 		calc_timer_values(event, &now, &enabled, &running);
6960 
6961 	if (event->attr.read_format & PERF_FORMAT_GROUP)
6962 		perf_output_read_group(handle, event, enabled, running);
6963 	else
6964 		perf_output_read_one(handle, event, enabled, running);
6965 }
6966 
perf_sample_save_hw_index(struct perf_event * event)6967 static inline bool perf_sample_save_hw_index(struct perf_event *event)
6968 {
6969 	return event->attr.branch_sample_type & PERF_SAMPLE_BRANCH_HW_INDEX;
6970 }
6971 
perf_output_sample(struct perf_output_handle * handle,struct perf_event_header * header,struct perf_sample_data * data,struct perf_event * event)6972 void perf_output_sample(struct perf_output_handle *handle,
6973 			struct perf_event_header *header,
6974 			struct perf_sample_data *data,
6975 			struct perf_event *event)
6976 {
6977 	u64 sample_type = data->type;
6978 
6979 	perf_output_put(handle, *header);
6980 
6981 	if (sample_type & PERF_SAMPLE_IDENTIFIER)
6982 		perf_output_put(handle, data->id);
6983 
6984 	if (sample_type & PERF_SAMPLE_IP)
6985 		perf_output_put(handle, data->ip);
6986 
6987 	if (sample_type & PERF_SAMPLE_TID)
6988 		perf_output_put(handle, data->tid_entry);
6989 
6990 	if (sample_type & PERF_SAMPLE_TIME)
6991 		perf_output_put(handle, data->time);
6992 
6993 	if (sample_type & PERF_SAMPLE_ADDR)
6994 		perf_output_put(handle, data->addr);
6995 
6996 	if (sample_type & PERF_SAMPLE_ID)
6997 		perf_output_put(handle, data->id);
6998 
6999 	if (sample_type & PERF_SAMPLE_STREAM_ID)
7000 		perf_output_put(handle, data->stream_id);
7001 
7002 	if (sample_type & PERF_SAMPLE_CPU)
7003 		perf_output_put(handle, data->cpu_entry);
7004 
7005 	if (sample_type & PERF_SAMPLE_PERIOD)
7006 		perf_output_put(handle, data->period);
7007 
7008 	if (sample_type & PERF_SAMPLE_READ)
7009 		perf_output_read(handle, event);
7010 
7011 	if (sample_type & PERF_SAMPLE_CALLCHAIN) {
7012 		int size = 1;
7013 
7014 		size += data->callchain->nr;
7015 		size *= sizeof(u64);
7016 		__output_copy(handle, data->callchain, size);
7017 	}
7018 
7019 	if (sample_type & PERF_SAMPLE_RAW) {
7020 		struct perf_raw_record *raw = data->raw;
7021 
7022 		if (raw) {
7023 			struct perf_raw_frag *frag = &raw->frag;
7024 
7025 			perf_output_put(handle, raw->size);
7026 			do {
7027 				if (frag->copy) {
7028 					__output_custom(handle, frag->copy,
7029 							frag->data, frag->size);
7030 				} else {
7031 					__output_copy(handle, frag->data,
7032 						      frag->size);
7033 				}
7034 				if (perf_raw_frag_last(frag))
7035 					break;
7036 				frag = frag->next;
7037 			} while (1);
7038 			if (frag->pad)
7039 				__output_skip(handle, NULL, frag->pad);
7040 		} else {
7041 			struct {
7042 				u32	size;
7043 				u32	data;
7044 			} raw = {
7045 				.size = sizeof(u32),
7046 				.data = 0,
7047 			};
7048 			perf_output_put(handle, raw);
7049 		}
7050 	}
7051 
7052 	if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
7053 		if (data->br_stack) {
7054 			size_t size;
7055 
7056 			size = data->br_stack->nr
7057 			     * sizeof(struct perf_branch_entry);
7058 
7059 			perf_output_put(handle, data->br_stack->nr);
7060 			if (perf_sample_save_hw_index(event))
7061 				perf_output_put(handle, data->br_stack->hw_idx);
7062 			perf_output_copy(handle, data->br_stack->entries, size);
7063 		} else {
7064 			/*
7065 			 * we always store at least the value of nr
7066 			 */
7067 			u64 nr = 0;
7068 			perf_output_put(handle, nr);
7069 		}
7070 	}
7071 
7072 	if (sample_type & PERF_SAMPLE_REGS_USER) {
7073 		u64 abi = data->regs_user.abi;
7074 
7075 		/*
7076 		 * If there are no regs to dump, notice it through
7077 		 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
7078 		 */
7079 		perf_output_put(handle, abi);
7080 
7081 		if (abi) {
7082 			u64 mask = event->attr.sample_regs_user;
7083 			perf_output_sample_regs(handle,
7084 						data->regs_user.regs,
7085 						mask);
7086 		}
7087 	}
7088 
7089 	if (sample_type & PERF_SAMPLE_STACK_USER) {
7090 		perf_output_sample_ustack(handle,
7091 					  data->stack_user_size,
7092 					  data->regs_user.regs);
7093 	}
7094 
7095 	if (sample_type & PERF_SAMPLE_WEIGHT)
7096 		perf_output_put(handle, data->weight);
7097 
7098 	if (sample_type & PERF_SAMPLE_DATA_SRC)
7099 		perf_output_put(handle, data->data_src.val);
7100 
7101 	if (sample_type & PERF_SAMPLE_TRANSACTION)
7102 		perf_output_put(handle, data->txn);
7103 
7104 	if (sample_type & PERF_SAMPLE_REGS_INTR) {
7105 		u64 abi = data->regs_intr.abi;
7106 		/*
7107 		 * If there are no regs to dump, notice it through
7108 		 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
7109 		 */
7110 		perf_output_put(handle, abi);
7111 
7112 		if (abi) {
7113 			u64 mask = event->attr.sample_regs_intr;
7114 
7115 			perf_output_sample_regs(handle,
7116 						data->regs_intr.regs,
7117 						mask);
7118 		}
7119 	}
7120 
7121 	if (sample_type & PERF_SAMPLE_PHYS_ADDR)
7122 		perf_output_put(handle, data->phys_addr);
7123 
7124 	if (sample_type & PERF_SAMPLE_CGROUP)
7125 		perf_output_put(handle, data->cgroup);
7126 
7127 	if (sample_type & PERF_SAMPLE_AUX) {
7128 		perf_output_put(handle, data->aux_size);
7129 
7130 		if (data->aux_size)
7131 			perf_aux_sample_output(event, handle, data);
7132 	}
7133 
7134 	if (!event->attr.watermark) {
7135 		int wakeup_events = event->attr.wakeup_events;
7136 
7137 		if (wakeup_events) {
7138 			struct perf_buffer *rb = handle->rb;
7139 			int events = local_inc_return(&rb->events);
7140 
7141 			if (events >= wakeup_events) {
7142 				local_sub(wakeup_events, &rb->events);
7143 				local_inc(&rb->wakeup);
7144 			}
7145 		}
7146 	}
7147 }
7148 
perf_virt_to_phys(u64 virt)7149 static u64 perf_virt_to_phys(u64 virt)
7150 {
7151 	u64 phys_addr = 0;
7152 
7153 	if (!virt)
7154 		return 0;
7155 
7156 	if (virt >= TASK_SIZE) {
7157 		/* If it's vmalloc()d memory, leave phys_addr as 0 */
7158 		if (virt_addr_valid((void *)(uintptr_t)virt) &&
7159 		    !(virt >= VMALLOC_START && virt < VMALLOC_END))
7160 			phys_addr = (u64)virt_to_phys((void *)(uintptr_t)virt);
7161 	} else {
7162 		/*
7163 		 * Walking the pages tables for user address.
7164 		 * Interrupts are disabled, so it prevents any tear down
7165 		 * of the page tables.
7166 		 * Try IRQ-safe get_user_page_fast_only first.
7167 		 * If failed, leave phys_addr as 0.
7168 		 */
7169 		if (current->mm != NULL) {
7170 			struct page *p;
7171 
7172 			pagefault_disable();
7173 			if (get_user_page_fast_only(virt, 0, &p)) {
7174 				phys_addr = page_to_phys(p) + virt % PAGE_SIZE;
7175 				put_page(p);
7176 			}
7177 			pagefault_enable();
7178 		}
7179 	}
7180 
7181 	return phys_addr;
7182 }
7183 
7184 static struct perf_callchain_entry __empty_callchain = { .nr = 0, };
7185 
7186 struct perf_callchain_entry *
perf_callchain(struct perf_event * event,struct pt_regs * regs)7187 perf_callchain(struct perf_event *event, struct pt_regs *regs)
7188 {
7189 	bool kernel = !event->attr.exclude_callchain_kernel;
7190 	bool user   = !event->attr.exclude_callchain_user;
7191 	/* Disallow cross-task user callchains. */
7192 	bool crosstask = event->ctx->task && event->ctx->task != current;
7193 	const u32 max_stack = event->attr.sample_max_stack;
7194 	struct perf_callchain_entry *callchain;
7195 
7196 	if (!kernel && !user)
7197 		return &__empty_callchain;
7198 
7199 	callchain = get_perf_callchain(regs, 0, kernel, user,
7200 				       max_stack, crosstask, true);
7201 	return callchain ?: &__empty_callchain;
7202 }
7203 
perf_prepare_sample(struct perf_event_header * header,struct perf_sample_data * data,struct perf_event * event,struct pt_regs * regs)7204 void perf_prepare_sample(struct perf_event_header *header,
7205 			 struct perf_sample_data *data,
7206 			 struct perf_event *event,
7207 			 struct pt_regs *regs)
7208 {
7209 	u64 sample_type = event->attr.sample_type;
7210 
7211 	header->type = PERF_RECORD_SAMPLE;
7212 	header->size = sizeof(*header) + event->header_size;
7213 
7214 	header->misc = 0;
7215 	header->misc |= perf_misc_flags(regs);
7216 
7217 	__perf_event_header__init_id(header, data, event);
7218 
7219 	if (sample_type & PERF_SAMPLE_IP)
7220 		data->ip = perf_instruction_pointer(regs);
7221 
7222 	if (sample_type & PERF_SAMPLE_CALLCHAIN) {
7223 		int size = 1;
7224 
7225 		if (!(sample_type & __PERF_SAMPLE_CALLCHAIN_EARLY))
7226 			data->callchain = perf_callchain(event, regs);
7227 
7228 		size += data->callchain->nr;
7229 
7230 		header->size += size * sizeof(u64);
7231 	}
7232 
7233 	if (sample_type & PERF_SAMPLE_RAW) {
7234 		struct perf_raw_record *raw = data->raw;
7235 		int size;
7236 
7237 		if (raw) {
7238 			struct perf_raw_frag *frag = &raw->frag;
7239 			u32 sum = 0;
7240 
7241 			do {
7242 				sum += frag->size;
7243 				if (perf_raw_frag_last(frag))
7244 					break;
7245 				frag = frag->next;
7246 			} while (1);
7247 
7248 			size = round_up(sum + sizeof(u32), sizeof(u64));
7249 			raw->size = size - sizeof(u32);
7250 			frag->pad = raw->size - sum;
7251 		} else {
7252 			size = sizeof(u64);
7253 		}
7254 
7255 		header->size += size;
7256 	}
7257 
7258 	if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
7259 		int size = sizeof(u64); /* nr */
7260 		if (data->br_stack) {
7261 			if (perf_sample_save_hw_index(event))
7262 				size += sizeof(u64);
7263 
7264 			size += data->br_stack->nr
7265 			      * sizeof(struct perf_branch_entry);
7266 		}
7267 		header->size += size;
7268 	}
7269 
7270 	if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
7271 		perf_sample_regs_user(&data->regs_user, regs);
7272 
7273 	if (sample_type & PERF_SAMPLE_REGS_USER) {
7274 		/* regs dump ABI info */
7275 		int size = sizeof(u64);
7276 
7277 		if (data->regs_user.regs) {
7278 			u64 mask = event->attr.sample_regs_user;
7279 			size += hweight64(mask) * sizeof(u64);
7280 		}
7281 
7282 		header->size += size;
7283 	}
7284 
7285 	if (sample_type & PERF_SAMPLE_STACK_USER) {
7286 		/*
7287 		 * Either we need PERF_SAMPLE_STACK_USER bit to be always
7288 		 * processed as the last one or have additional check added
7289 		 * in case new sample type is added, because we could eat
7290 		 * up the rest of the sample size.
7291 		 */
7292 		u16 stack_size = event->attr.sample_stack_user;
7293 		u16 size = sizeof(u64);
7294 
7295 		stack_size = perf_sample_ustack_size(stack_size, header->size,
7296 						     data->regs_user.regs);
7297 
7298 		/*
7299 		 * If there is something to dump, add space for the dump
7300 		 * itself and for the field that tells the dynamic size,
7301 		 * which is how many have been actually dumped.
7302 		 */
7303 		if (stack_size)
7304 			size += sizeof(u64) + stack_size;
7305 
7306 		data->stack_user_size = stack_size;
7307 		header->size += size;
7308 	}
7309 
7310 	if (sample_type & PERF_SAMPLE_REGS_INTR) {
7311 		/* regs dump ABI info */
7312 		int size = sizeof(u64);
7313 
7314 		perf_sample_regs_intr(&data->regs_intr, regs);
7315 
7316 		if (data->regs_intr.regs) {
7317 			u64 mask = event->attr.sample_regs_intr;
7318 
7319 			size += hweight64(mask) * sizeof(u64);
7320 		}
7321 
7322 		header->size += size;
7323 	}
7324 
7325 	if (sample_type & PERF_SAMPLE_PHYS_ADDR)
7326 		data->phys_addr = perf_virt_to_phys(data->addr);
7327 
7328 #ifdef CONFIG_CGROUP_PERF
7329 	if (sample_type & PERF_SAMPLE_CGROUP) {
7330 		struct cgroup *cgrp;
7331 
7332 		/* protected by RCU */
7333 		cgrp = task_css_check(current, perf_event_cgrp_id, 1)->cgroup;
7334 		data->cgroup = cgroup_id(cgrp);
7335 	}
7336 #endif
7337 
7338 	if (sample_type & PERF_SAMPLE_AUX) {
7339 		u64 size;
7340 
7341 		header->size += sizeof(u64); /* size */
7342 
7343 		/*
7344 		 * Given the 16bit nature of header::size, an AUX sample can
7345 		 * easily overflow it, what with all the preceding sample bits.
7346 		 * Make sure this doesn't happen by using up to U16_MAX bytes
7347 		 * per sample in total (rounded down to 8 byte boundary).
7348 		 */
7349 		size = min_t(size_t, U16_MAX - header->size,
7350 			     event->attr.aux_sample_size);
7351 		size = rounddown(size, 8);
7352 		size = perf_prepare_sample_aux(event, data, size);
7353 
7354 		WARN_ON_ONCE(size + header->size > U16_MAX);
7355 		header->size += size;
7356 	}
7357 	/*
7358 	 * If you're adding more sample types here, you likely need to do
7359 	 * something about the overflowing header::size, like repurpose the
7360 	 * lowest 3 bits of size, which should be always zero at the moment.
7361 	 * This raises a more important question, do we really need 512k sized
7362 	 * samples and why, so good argumentation is in order for whatever you
7363 	 * do here next.
7364 	 */
7365 	WARN_ON_ONCE(header->size & 7);
7366 }
7367 
7368 static __always_inline int
__perf_event_output(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs,int (* output_begin)(struct perf_output_handle *,struct perf_sample_data *,struct perf_event *,unsigned int))7369 __perf_event_output(struct perf_event *event,
7370 		    struct perf_sample_data *data,
7371 		    struct pt_regs *regs,
7372 		    int (*output_begin)(struct perf_output_handle *,
7373 					struct perf_sample_data *,
7374 					struct perf_event *,
7375 					unsigned int))
7376 {
7377 	struct perf_output_handle handle;
7378 	struct perf_event_header header;
7379 	int err;
7380 
7381 	/* protect the callchain buffers */
7382 	rcu_read_lock();
7383 
7384 	perf_prepare_sample(&header, data, event, regs);
7385 
7386 	err = output_begin(&handle, data, event, header.size);
7387 	if (err)
7388 		goto exit;
7389 
7390 	perf_output_sample(&handle, &header, data, event);
7391 
7392 	perf_output_end(&handle);
7393 
7394 exit:
7395 	rcu_read_unlock();
7396 	return err;
7397 }
7398 
7399 void
perf_event_output_forward(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)7400 perf_event_output_forward(struct perf_event *event,
7401 			 struct perf_sample_data *data,
7402 			 struct pt_regs *regs)
7403 {
7404 	__perf_event_output(event, data, regs, perf_output_begin_forward);
7405 }
7406 
7407 void
perf_event_output_backward(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)7408 perf_event_output_backward(struct perf_event *event,
7409 			   struct perf_sample_data *data,
7410 			   struct pt_regs *regs)
7411 {
7412 	__perf_event_output(event, data, regs, perf_output_begin_backward);
7413 }
7414 
7415 int
perf_event_output(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)7416 perf_event_output(struct perf_event *event,
7417 		  struct perf_sample_data *data,
7418 		  struct pt_regs *regs)
7419 {
7420 	return __perf_event_output(event, data, regs, perf_output_begin);
7421 }
7422 
7423 /*
7424  * read event_id
7425  */
7426 
7427 struct perf_read_event {
7428 	struct perf_event_header	header;
7429 
7430 	u32				pid;
7431 	u32				tid;
7432 };
7433 
7434 static void
perf_event_read_event(struct perf_event * event,struct task_struct * task)7435 perf_event_read_event(struct perf_event *event,
7436 			struct task_struct *task)
7437 {
7438 	struct perf_output_handle handle;
7439 	struct perf_sample_data sample;
7440 	struct perf_read_event read_event = {
7441 		.header = {
7442 			.type = PERF_RECORD_READ,
7443 			.misc = 0,
7444 			.size = sizeof(read_event) + event->read_size,
7445 		},
7446 		.pid = perf_event_pid(event, task),
7447 		.tid = perf_event_tid(event, task),
7448 	};
7449 	int ret;
7450 
7451 	perf_event_header__init_id(&read_event.header, &sample, event);
7452 	ret = perf_output_begin(&handle, &sample, event, read_event.header.size);
7453 	if (ret)
7454 		return;
7455 
7456 	perf_output_put(&handle, read_event);
7457 	perf_output_read(&handle, event);
7458 	perf_event__output_id_sample(event, &handle, &sample);
7459 
7460 	perf_output_end(&handle);
7461 }
7462 
7463 typedef void (perf_iterate_f)(struct perf_event *event, void *data);
7464 
7465 static void
perf_iterate_ctx(struct perf_event_context * ctx,perf_iterate_f output,void * data,bool all)7466 perf_iterate_ctx(struct perf_event_context *ctx,
7467 		   perf_iterate_f output,
7468 		   void *data, bool all)
7469 {
7470 	struct perf_event *event;
7471 
7472 	list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
7473 		if (!all) {
7474 			if (event->state < PERF_EVENT_STATE_INACTIVE)
7475 				continue;
7476 			if (!event_filter_match(event))
7477 				continue;
7478 		}
7479 
7480 		output(event, data);
7481 	}
7482 }
7483 
perf_iterate_sb_cpu(perf_iterate_f output,void * data)7484 static void perf_iterate_sb_cpu(perf_iterate_f output, void *data)
7485 {
7486 	struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events);
7487 	struct perf_event *event;
7488 
7489 	list_for_each_entry_rcu(event, &pel->list, sb_list) {
7490 		/*
7491 		 * Skip events that are not fully formed yet; ensure that
7492 		 * if we observe event->ctx, both event and ctx will be
7493 		 * complete enough. See perf_install_in_context().
7494 		 */
7495 		if (!smp_load_acquire(&event->ctx))
7496 			continue;
7497 
7498 		if (event->state < PERF_EVENT_STATE_INACTIVE)
7499 			continue;
7500 		if (!event_filter_match(event))
7501 			continue;
7502 		output(event, data);
7503 	}
7504 }
7505 
7506 /*
7507  * Iterate all events that need to receive side-band events.
7508  *
7509  * For new callers; ensure that account_pmu_sb_event() includes
7510  * your event, otherwise it might not get delivered.
7511  */
7512 static void
perf_iterate_sb(perf_iterate_f output,void * data,struct perf_event_context * task_ctx)7513 perf_iterate_sb(perf_iterate_f output, void *data,
7514 	       struct perf_event_context *task_ctx)
7515 {
7516 	struct perf_event_context *ctx;
7517 	int ctxn;
7518 
7519 	rcu_read_lock();
7520 	preempt_disable();
7521 
7522 	/*
7523 	 * If we have task_ctx != NULL we only notify the task context itself.
7524 	 * The task_ctx is set only for EXIT events before releasing task
7525 	 * context.
7526 	 */
7527 	if (task_ctx) {
7528 		perf_iterate_ctx(task_ctx, output, data, false);
7529 		goto done;
7530 	}
7531 
7532 	perf_iterate_sb_cpu(output, data);
7533 
7534 	for_each_task_context_nr(ctxn) {
7535 		ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
7536 		if (ctx)
7537 			perf_iterate_ctx(ctx, output, data, false);
7538 	}
7539 done:
7540 	preempt_enable();
7541 	rcu_read_unlock();
7542 }
7543 
7544 /*
7545  * Clear all file-based filters at exec, they'll have to be
7546  * re-instated when/if these objects are mmapped again.
7547  */
perf_event_addr_filters_exec(struct perf_event * event,void * data)7548 static void perf_event_addr_filters_exec(struct perf_event *event, void *data)
7549 {
7550 	struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
7551 	struct perf_addr_filter *filter;
7552 	unsigned int restart = 0, count = 0;
7553 	unsigned long flags;
7554 
7555 	if (!has_addr_filter(event))
7556 		return;
7557 
7558 	raw_spin_lock_irqsave(&ifh->lock, flags);
7559 	list_for_each_entry(filter, &ifh->list, entry) {
7560 		if (filter->path.dentry) {
7561 			event->addr_filter_ranges[count].start = 0;
7562 			event->addr_filter_ranges[count].size = 0;
7563 			restart++;
7564 		}
7565 
7566 		count++;
7567 	}
7568 
7569 	if (restart)
7570 		event->addr_filters_gen++;
7571 	raw_spin_unlock_irqrestore(&ifh->lock, flags);
7572 
7573 	if (restart)
7574 		perf_event_stop(event, 1);
7575 }
7576 
perf_event_exec(void)7577 void perf_event_exec(void)
7578 {
7579 	struct perf_event_context *ctx;
7580 	int ctxn;
7581 
7582 	rcu_read_lock();
7583 	for_each_task_context_nr(ctxn) {
7584 		ctx = current->perf_event_ctxp[ctxn];
7585 		if (!ctx)
7586 			continue;
7587 
7588 		perf_event_enable_on_exec(ctxn);
7589 
7590 		perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL,
7591 				   true);
7592 	}
7593 	rcu_read_unlock();
7594 }
7595 
7596 struct remote_output {
7597 	struct perf_buffer	*rb;
7598 	int			err;
7599 };
7600 
__perf_event_output_stop(struct perf_event * event,void * data)7601 static void __perf_event_output_stop(struct perf_event *event, void *data)
7602 {
7603 	struct perf_event *parent = event->parent;
7604 	struct remote_output *ro = data;
7605 	struct perf_buffer *rb = ro->rb;
7606 	struct stop_event_data sd = {
7607 		.event	= event,
7608 	};
7609 
7610 	if (!has_aux(event))
7611 		return;
7612 
7613 	if (!parent)
7614 		parent = event;
7615 
7616 	/*
7617 	 * In case of inheritance, it will be the parent that links to the
7618 	 * ring-buffer, but it will be the child that's actually using it.
7619 	 *
7620 	 * We are using event::rb to determine if the event should be stopped,
7621 	 * however this may race with ring_buffer_attach() (through set_output),
7622 	 * which will make us skip the event that actually needs to be stopped.
7623 	 * So ring_buffer_attach() has to stop an aux event before re-assigning
7624 	 * its rb pointer.
7625 	 */
7626 	if (rcu_dereference(parent->rb) == rb)
7627 		ro->err = __perf_event_stop(&sd);
7628 }
7629 
__perf_pmu_output_stop(void * info)7630 static int __perf_pmu_output_stop(void *info)
7631 {
7632 	struct perf_event *event = info;
7633 	struct pmu *pmu = event->ctx->pmu;
7634 	struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
7635 	struct remote_output ro = {
7636 		.rb	= event->rb,
7637 	};
7638 
7639 	rcu_read_lock();
7640 	perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false);
7641 	if (cpuctx->task_ctx)
7642 		perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop,
7643 				   &ro, false);
7644 	rcu_read_unlock();
7645 
7646 	return ro.err;
7647 }
7648 
perf_pmu_output_stop(struct perf_event * event)7649 static void perf_pmu_output_stop(struct perf_event *event)
7650 {
7651 	struct perf_event *iter;
7652 	int err, cpu;
7653 
7654 restart:
7655 	rcu_read_lock();
7656 	list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
7657 		/*
7658 		 * For per-CPU events, we need to make sure that neither they
7659 		 * nor their children are running; for cpu==-1 events it's
7660 		 * sufficient to stop the event itself if it's active, since
7661 		 * it can't have children.
7662 		 */
7663 		cpu = iter->cpu;
7664 		if (cpu == -1)
7665 			cpu = READ_ONCE(iter->oncpu);
7666 
7667 		if (cpu == -1)
7668 			continue;
7669 
7670 		err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
7671 		if (err == -EAGAIN) {
7672 			rcu_read_unlock();
7673 			goto restart;
7674 		}
7675 	}
7676 	rcu_read_unlock();
7677 }
7678 
7679 /*
7680  * task tracking -- fork/exit
7681  *
7682  * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
7683  */
7684 
7685 struct perf_task_event {
7686 	struct task_struct		*task;
7687 	struct perf_event_context	*task_ctx;
7688 
7689 	struct {
7690 		struct perf_event_header	header;
7691 
7692 		u32				pid;
7693 		u32				ppid;
7694 		u32				tid;
7695 		u32				ptid;
7696 		u64				time;
7697 	} event_id;
7698 };
7699 
perf_event_task_match(struct perf_event * event)7700 static int perf_event_task_match(struct perf_event *event)
7701 {
7702 	return event->attr.comm  || event->attr.mmap ||
7703 	       event->attr.mmap2 || event->attr.mmap_data ||
7704 	       event->attr.task;
7705 }
7706 
perf_event_task_output(struct perf_event * event,void * data)7707 static void perf_event_task_output(struct perf_event *event,
7708 				   void *data)
7709 {
7710 	struct perf_task_event *task_event = data;
7711 	struct perf_output_handle handle;
7712 	struct perf_sample_data	sample;
7713 	struct task_struct *task = task_event->task;
7714 	int ret, size = task_event->event_id.header.size;
7715 
7716 	if (!perf_event_task_match(event))
7717 		return;
7718 
7719 	perf_event_header__init_id(&task_event->event_id.header, &sample, event);
7720 
7721 	ret = perf_output_begin(&handle, &sample, event,
7722 				task_event->event_id.header.size);
7723 	if (ret)
7724 		goto out;
7725 
7726 	task_event->event_id.pid = perf_event_pid(event, task);
7727 	task_event->event_id.tid = perf_event_tid(event, task);
7728 
7729 	if (task_event->event_id.header.type == PERF_RECORD_EXIT) {
7730 		task_event->event_id.ppid = perf_event_pid(event,
7731 							task->real_parent);
7732 		task_event->event_id.ptid = perf_event_pid(event,
7733 							task->real_parent);
7734 	} else {  /* PERF_RECORD_FORK */
7735 		task_event->event_id.ppid = perf_event_pid(event, current);
7736 		task_event->event_id.ptid = perf_event_tid(event, current);
7737 	}
7738 
7739 	task_event->event_id.time = perf_event_clock(event);
7740 
7741 	perf_output_put(&handle, task_event->event_id);
7742 
7743 	perf_event__output_id_sample(event, &handle, &sample);
7744 
7745 	perf_output_end(&handle);
7746 out:
7747 	task_event->event_id.header.size = size;
7748 }
7749 
perf_event_task(struct task_struct * task,struct perf_event_context * task_ctx,int new)7750 static void perf_event_task(struct task_struct *task,
7751 			      struct perf_event_context *task_ctx,
7752 			      int new)
7753 {
7754 	struct perf_task_event task_event;
7755 
7756 	if (!atomic_read(&nr_comm_events) &&
7757 	    !atomic_read(&nr_mmap_events) &&
7758 	    !atomic_read(&nr_task_events))
7759 		return;
7760 
7761 	task_event = (struct perf_task_event){
7762 		.task	  = task,
7763 		.task_ctx = task_ctx,
7764 		.event_id    = {
7765 			.header = {
7766 				.type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
7767 				.misc = 0,
7768 				.size = sizeof(task_event.event_id),
7769 			},
7770 			/* .pid  */
7771 			/* .ppid */
7772 			/* .tid  */
7773 			/* .ptid */
7774 			/* .time */
7775 		},
7776 	};
7777 
7778 	perf_iterate_sb(perf_event_task_output,
7779 		       &task_event,
7780 		       task_ctx);
7781 }
7782 
perf_event_fork(struct task_struct * task)7783 void perf_event_fork(struct task_struct *task)
7784 {
7785 	perf_event_task(task, NULL, 1);
7786 	perf_event_namespaces(task);
7787 }
7788 
7789 /*
7790  * comm tracking
7791  */
7792 
7793 struct perf_comm_event {
7794 	struct task_struct	*task;
7795 	char			*comm;
7796 	int			comm_size;
7797 
7798 	struct {
7799 		struct perf_event_header	header;
7800 
7801 		u32				pid;
7802 		u32				tid;
7803 	} event_id;
7804 };
7805 
perf_event_comm_match(struct perf_event * event)7806 static int perf_event_comm_match(struct perf_event *event)
7807 {
7808 	return event->attr.comm;
7809 }
7810 
perf_event_comm_output(struct perf_event * event,void * data)7811 static void perf_event_comm_output(struct perf_event *event,
7812 				   void *data)
7813 {
7814 	struct perf_comm_event *comm_event = data;
7815 	struct perf_output_handle handle;
7816 	struct perf_sample_data sample;
7817 	int size = comm_event->event_id.header.size;
7818 	int ret;
7819 
7820 	if (!perf_event_comm_match(event))
7821 		return;
7822 
7823 	perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
7824 	ret = perf_output_begin(&handle, &sample, event,
7825 				comm_event->event_id.header.size);
7826 
7827 	if (ret)
7828 		goto out;
7829 
7830 	comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
7831 	comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
7832 
7833 	perf_output_put(&handle, comm_event->event_id);
7834 	__output_copy(&handle, comm_event->comm,
7835 				   comm_event->comm_size);
7836 
7837 	perf_event__output_id_sample(event, &handle, &sample);
7838 
7839 	perf_output_end(&handle);
7840 out:
7841 	comm_event->event_id.header.size = size;
7842 }
7843 
perf_event_comm_event(struct perf_comm_event * comm_event)7844 static void perf_event_comm_event(struct perf_comm_event *comm_event)
7845 {
7846 	char comm[TASK_COMM_LEN];
7847 	unsigned int size;
7848 
7849 	memset(comm, 0, sizeof(comm));
7850 	strlcpy(comm, comm_event->task->comm, sizeof(comm));
7851 	size = ALIGN(strlen(comm)+1, sizeof(u64));
7852 
7853 	comm_event->comm = comm;
7854 	comm_event->comm_size = size;
7855 
7856 	comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
7857 
7858 	perf_iterate_sb(perf_event_comm_output,
7859 		       comm_event,
7860 		       NULL);
7861 }
7862 
perf_event_comm(struct task_struct * task,bool exec)7863 void perf_event_comm(struct task_struct *task, bool exec)
7864 {
7865 	struct perf_comm_event comm_event;
7866 
7867 	if (!atomic_read(&nr_comm_events))
7868 		return;
7869 
7870 	comm_event = (struct perf_comm_event){
7871 		.task	= task,
7872 		/* .comm      */
7873 		/* .comm_size */
7874 		.event_id  = {
7875 			.header = {
7876 				.type = PERF_RECORD_COMM,
7877 				.misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
7878 				/* .size */
7879 			},
7880 			/* .pid */
7881 			/* .tid */
7882 		},
7883 	};
7884 
7885 	perf_event_comm_event(&comm_event);
7886 }
7887 
7888 /*
7889  * namespaces tracking
7890  */
7891 
7892 struct perf_namespaces_event {
7893 	struct task_struct		*task;
7894 
7895 	struct {
7896 		struct perf_event_header	header;
7897 
7898 		u32				pid;
7899 		u32				tid;
7900 		u64				nr_namespaces;
7901 		struct perf_ns_link_info	link_info[NR_NAMESPACES];
7902 	} event_id;
7903 };
7904 
perf_event_namespaces_match(struct perf_event * event)7905 static int perf_event_namespaces_match(struct perf_event *event)
7906 {
7907 	return event->attr.namespaces;
7908 }
7909 
perf_event_namespaces_output(struct perf_event * event,void * data)7910 static void perf_event_namespaces_output(struct perf_event *event,
7911 					 void *data)
7912 {
7913 	struct perf_namespaces_event *namespaces_event = data;
7914 	struct perf_output_handle handle;
7915 	struct perf_sample_data sample;
7916 	u16 header_size = namespaces_event->event_id.header.size;
7917 	int ret;
7918 
7919 	if (!perf_event_namespaces_match(event))
7920 		return;
7921 
7922 	perf_event_header__init_id(&namespaces_event->event_id.header,
7923 				   &sample, event);
7924 	ret = perf_output_begin(&handle, &sample, event,
7925 				namespaces_event->event_id.header.size);
7926 	if (ret)
7927 		goto out;
7928 
7929 	namespaces_event->event_id.pid = perf_event_pid(event,
7930 							namespaces_event->task);
7931 	namespaces_event->event_id.tid = perf_event_tid(event,
7932 							namespaces_event->task);
7933 
7934 	perf_output_put(&handle, namespaces_event->event_id);
7935 
7936 	perf_event__output_id_sample(event, &handle, &sample);
7937 
7938 	perf_output_end(&handle);
7939 out:
7940 	namespaces_event->event_id.header.size = header_size;
7941 }
7942 
perf_fill_ns_link_info(struct perf_ns_link_info * ns_link_info,struct task_struct * task,const struct proc_ns_operations * ns_ops)7943 static void perf_fill_ns_link_info(struct perf_ns_link_info *ns_link_info,
7944 				   struct task_struct *task,
7945 				   const struct proc_ns_operations *ns_ops)
7946 {
7947 	struct path ns_path;
7948 	struct inode *ns_inode;
7949 	int error;
7950 
7951 	error = ns_get_path(&ns_path, task, ns_ops);
7952 	if (!error) {
7953 		ns_inode = ns_path.dentry->d_inode;
7954 		ns_link_info->dev = new_encode_dev(ns_inode->i_sb->s_dev);
7955 		ns_link_info->ino = ns_inode->i_ino;
7956 		path_put(&ns_path);
7957 	}
7958 }
7959 
perf_event_namespaces(struct task_struct * task)7960 void perf_event_namespaces(struct task_struct *task)
7961 {
7962 	struct perf_namespaces_event namespaces_event;
7963 	struct perf_ns_link_info *ns_link_info;
7964 
7965 	if (!atomic_read(&nr_namespaces_events))
7966 		return;
7967 
7968 	namespaces_event = (struct perf_namespaces_event){
7969 		.task	= task,
7970 		.event_id  = {
7971 			.header = {
7972 				.type = PERF_RECORD_NAMESPACES,
7973 				.misc = 0,
7974 				.size = sizeof(namespaces_event.event_id),
7975 			},
7976 			/* .pid */
7977 			/* .tid */
7978 			.nr_namespaces = NR_NAMESPACES,
7979 			/* .link_info[NR_NAMESPACES] */
7980 		},
7981 	};
7982 
7983 	ns_link_info = namespaces_event.event_id.link_info;
7984 
7985 	perf_fill_ns_link_info(&ns_link_info[MNT_NS_INDEX],
7986 			       task, &mntns_operations);
7987 
7988 #ifdef CONFIG_USER_NS
7989 	perf_fill_ns_link_info(&ns_link_info[USER_NS_INDEX],
7990 			       task, &userns_operations);
7991 #endif
7992 #ifdef CONFIG_NET_NS
7993 	perf_fill_ns_link_info(&ns_link_info[NET_NS_INDEX],
7994 			       task, &netns_operations);
7995 #endif
7996 #ifdef CONFIG_UTS_NS
7997 	perf_fill_ns_link_info(&ns_link_info[UTS_NS_INDEX],
7998 			       task, &utsns_operations);
7999 #endif
8000 #ifdef CONFIG_IPC_NS
8001 	perf_fill_ns_link_info(&ns_link_info[IPC_NS_INDEX],
8002 			       task, &ipcns_operations);
8003 #endif
8004 #ifdef CONFIG_PID_NS
8005 	perf_fill_ns_link_info(&ns_link_info[PID_NS_INDEX],
8006 			       task, &pidns_operations);
8007 #endif
8008 #ifdef CONFIG_CGROUPS
8009 	perf_fill_ns_link_info(&ns_link_info[CGROUP_NS_INDEX],
8010 			       task, &cgroupns_operations);
8011 #endif
8012 
8013 	perf_iterate_sb(perf_event_namespaces_output,
8014 			&namespaces_event,
8015 			NULL);
8016 }
8017 
8018 /*
8019  * cgroup tracking
8020  */
8021 #ifdef CONFIG_CGROUP_PERF
8022 
8023 struct perf_cgroup_event {
8024 	char				*path;
8025 	int				path_size;
8026 	struct {
8027 		struct perf_event_header	header;
8028 		u64				id;
8029 		char				path[];
8030 	} event_id;
8031 };
8032 
perf_event_cgroup_match(struct perf_event * event)8033 static int perf_event_cgroup_match(struct perf_event *event)
8034 {
8035 	return event->attr.cgroup;
8036 }
8037 
perf_event_cgroup_output(struct perf_event * event,void * data)8038 static void perf_event_cgroup_output(struct perf_event *event, void *data)
8039 {
8040 	struct perf_cgroup_event *cgroup_event = data;
8041 	struct perf_output_handle handle;
8042 	struct perf_sample_data sample;
8043 	u16 header_size = cgroup_event->event_id.header.size;
8044 	int ret;
8045 
8046 	if (!perf_event_cgroup_match(event))
8047 		return;
8048 
8049 	perf_event_header__init_id(&cgroup_event->event_id.header,
8050 				   &sample, event);
8051 	ret = perf_output_begin(&handle, &sample, event,
8052 				cgroup_event->event_id.header.size);
8053 	if (ret)
8054 		goto out;
8055 
8056 	perf_output_put(&handle, cgroup_event->event_id);
8057 	__output_copy(&handle, cgroup_event->path, cgroup_event->path_size);
8058 
8059 	perf_event__output_id_sample(event, &handle, &sample);
8060 
8061 	perf_output_end(&handle);
8062 out:
8063 	cgroup_event->event_id.header.size = header_size;
8064 }
8065 
perf_event_cgroup(struct cgroup * cgrp)8066 static void perf_event_cgroup(struct cgroup *cgrp)
8067 {
8068 	struct perf_cgroup_event cgroup_event;
8069 	char path_enomem[16] = "//enomem";
8070 	char *pathname;
8071 	size_t size;
8072 
8073 	if (!atomic_read(&nr_cgroup_events))
8074 		return;
8075 
8076 	cgroup_event = (struct perf_cgroup_event){
8077 		.event_id  = {
8078 			.header = {
8079 				.type = PERF_RECORD_CGROUP,
8080 				.misc = 0,
8081 				.size = sizeof(cgroup_event.event_id),
8082 			},
8083 			.id = cgroup_id(cgrp),
8084 		},
8085 	};
8086 
8087 	pathname = kmalloc(PATH_MAX, GFP_KERNEL);
8088 	if (pathname == NULL) {
8089 		cgroup_event.path = path_enomem;
8090 	} else {
8091 		/* just to be sure to have enough space for alignment */
8092 		cgroup_path(cgrp, pathname, PATH_MAX - sizeof(u64));
8093 		cgroup_event.path = pathname;
8094 	}
8095 
8096 	/*
8097 	 * Since our buffer works in 8 byte units we need to align our string
8098 	 * size to a multiple of 8. However, we must guarantee the tail end is
8099 	 * zero'd out to avoid leaking random bits to userspace.
8100 	 */
8101 	size = strlen(cgroup_event.path) + 1;
8102 	while (!IS_ALIGNED(size, sizeof(u64)))
8103 		cgroup_event.path[size++] = '\0';
8104 
8105 	cgroup_event.event_id.header.size += size;
8106 	cgroup_event.path_size = size;
8107 
8108 	perf_iterate_sb(perf_event_cgroup_output,
8109 			&cgroup_event,
8110 			NULL);
8111 
8112 	kfree(pathname);
8113 }
8114 
8115 #endif
8116 
8117 /*
8118  * mmap tracking
8119  */
8120 
8121 struct perf_mmap_event {
8122 	struct vm_area_struct	*vma;
8123 
8124 	const char		*file_name;
8125 	int			file_size;
8126 	int			maj, min;
8127 	u64			ino;
8128 	u64			ino_generation;
8129 	u32			prot, flags;
8130 
8131 	struct {
8132 		struct perf_event_header	header;
8133 
8134 		u32				pid;
8135 		u32				tid;
8136 		u64				start;
8137 		u64				len;
8138 		u64				pgoff;
8139 	} event_id;
8140 };
8141 
perf_event_mmap_match(struct perf_event * event,void * data)8142 static int perf_event_mmap_match(struct perf_event *event,
8143 				 void *data)
8144 {
8145 	struct perf_mmap_event *mmap_event = data;
8146 	struct vm_area_struct *vma = mmap_event->vma;
8147 	int executable = vma->vm_flags & VM_EXEC;
8148 
8149 	return (!executable && event->attr.mmap_data) ||
8150 	       (executable && (event->attr.mmap || event->attr.mmap2));
8151 }
8152 
perf_event_mmap_output(struct perf_event * event,void * data)8153 static void perf_event_mmap_output(struct perf_event *event,
8154 				   void *data)
8155 {
8156 	struct perf_mmap_event *mmap_event = data;
8157 	struct perf_output_handle handle;
8158 	struct perf_sample_data sample;
8159 	int size = mmap_event->event_id.header.size;
8160 	u32 type = mmap_event->event_id.header.type;
8161 	int ret;
8162 
8163 	if (!perf_event_mmap_match(event, data))
8164 		return;
8165 
8166 	if (event->attr.mmap2) {
8167 		mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
8168 		mmap_event->event_id.header.size += sizeof(mmap_event->maj);
8169 		mmap_event->event_id.header.size += sizeof(mmap_event->min);
8170 		mmap_event->event_id.header.size += sizeof(mmap_event->ino);
8171 		mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
8172 		mmap_event->event_id.header.size += sizeof(mmap_event->prot);
8173 		mmap_event->event_id.header.size += sizeof(mmap_event->flags);
8174 	}
8175 
8176 	perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
8177 	ret = perf_output_begin(&handle, &sample, event,
8178 				mmap_event->event_id.header.size);
8179 	if (ret)
8180 		goto out;
8181 
8182 	mmap_event->event_id.pid = perf_event_pid(event, current);
8183 	mmap_event->event_id.tid = perf_event_tid(event, current);
8184 
8185 	perf_output_put(&handle, mmap_event->event_id);
8186 
8187 	if (event->attr.mmap2) {
8188 		perf_output_put(&handle, mmap_event->maj);
8189 		perf_output_put(&handle, mmap_event->min);
8190 		perf_output_put(&handle, mmap_event->ino);
8191 		perf_output_put(&handle, mmap_event->ino_generation);
8192 		perf_output_put(&handle, mmap_event->prot);
8193 		perf_output_put(&handle, mmap_event->flags);
8194 	}
8195 
8196 	__output_copy(&handle, mmap_event->file_name,
8197 				   mmap_event->file_size);
8198 
8199 	perf_event__output_id_sample(event, &handle, &sample);
8200 
8201 	perf_output_end(&handle);
8202 out:
8203 	mmap_event->event_id.header.size = size;
8204 	mmap_event->event_id.header.type = type;
8205 }
8206 
perf_event_mmap_event(struct perf_mmap_event * mmap_event)8207 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
8208 {
8209 	struct vm_area_struct *vma = mmap_event->vma;
8210 	struct file *file = vma->vm_file;
8211 	int maj = 0, min = 0;
8212 	u64 ino = 0, gen = 0;
8213 	u32 prot = 0, flags = 0;
8214 	unsigned int size;
8215 	char tmp[16];
8216 	char *buf = NULL;
8217 	char *name;
8218 
8219 	if (vma->vm_flags & VM_READ)
8220 		prot |= PROT_READ;
8221 	if (vma->vm_flags & VM_WRITE)
8222 		prot |= PROT_WRITE;
8223 	if (vma->vm_flags & VM_EXEC)
8224 		prot |= PROT_EXEC;
8225 
8226 	if (vma->vm_flags & VM_MAYSHARE)
8227 		flags = MAP_SHARED;
8228 	else
8229 		flags = MAP_PRIVATE;
8230 
8231 	if (vma->vm_flags & VM_DENYWRITE)
8232 		flags |= MAP_DENYWRITE;
8233 	if (vma->vm_flags & VM_MAYEXEC)
8234 		flags |= MAP_EXECUTABLE;
8235 	if (vma->vm_flags & VM_LOCKED)
8236 		flags |= MAP_LOCKED;
8237 	if (is_vm_hugetlb_page(vma))
8238 		flags |= MAP_HUGETLB;
8239 
8240 	if (file) {
8241 		struct inode *inode;
8242 		dev_t dev;
8243 
8244 		buf = kmalloc(PATH_MAX, GFP_KERNEL);
8245 		if (!buf) {
8246 			name = "//enomem";
8247 			goto cpy_name;
8248 		}
8249 		/*
8250 		 * d_path() works from the end of the rb backwards, so we
8251 		 * need to add enough zero bytes after the string to handle
8252 		 * the 64bit alignment we do later.
8253 		 */
8254 		name = file_path(file, buf, PATH_MAX - sizeof(u64));
8255 		if (IS_ERR(name)) {
8256 			name = "//toolong";
8257 			goto cpy_name;
8258 		}
8259 		inode = file_inode(vma->vm_file);
8260 		dev = inode->i_sb->s_dev;
8261 		ino = inode->i_ino;
8262 		gen = inode->i_generation;
8263 		maj = MAJOR(dev);
8264 		min = MINOR(dev);
8265 
8266 		goto got_name;
8267 	} else {
8268 		if (vma->vm_ops && vma->vm_ops->name) {
8269 			name = (char *) vma->vm_ops->name(vma);
8270 			if (name)
8271 				goto cpy_name;
8272 		}
8273 
8274 		name = (char *)arch_vma_name(vma);
8275 		if (name)
8276 			goto cpy_name;
8277 
8278 		if (vma->vm_start <= vma->vm_mm->start_brk &&
8279 				vma->vm_end >= vma->vm_mm->brk) {
8280 			name = "[heap]";
8281 			goto cpy_name;
8282 		}
8283 		if (vma->vm_start <= vma->vm_mm->start_stack &&
8284 				vma->vm_end >= vma->vm_mm->start_stack) {
8285 			name = "[stack]";
8286 			goto cpy_name;
8287 		}
8288 
8289 		name = "//anon";
8290 		goto cpy_name;
8291 	}
8292 
8293 cpy_name:
8294 	strlcpy(tmp, name, sizeof(tmp));
8295 	name = tmp;
8296 got_name:
8297 	/*
8298 	 * Since our buffer works in 8 byte units we need to align our string
8299 	 * size to a multiple of 8. However, we must guarantee the tail end is
8300 	 * zero'd out to avoid leaking random bits to userspace.
8301 	 */
8302 	size = strlen(name)+1;
8303 	while (!IS_ALIGNED(size, sizeof(u64)))
8304 		name[size++] = '\0';
8305 
8306 	mmap_event->file_name = name;
8307 	mmap_event->file_size = size;
8308 	mmap_event->maj = maj;
8309 	mmap_event->min = min;
8310 	mmap_event->ino = ino;
8311 	mmap_event->ino_generation = gen;
8312 	mmap_event->prot = prot;
8313 	mmap_event->flags = flags;
8314 
8315 	if (!(vma->vm_flags & VM_EXEC))
8316 		mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
8317 
8318 	mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
8319 
8320 	perf_iterate_sb(perf_event_mmap_output,
8321 		       mmap_event,
8322 		       NULL);
8323 
8324 	kfree(buf);
8325 }
8326 
8327 /*
8328  * Check whether inode and address range match filter criteria.
8329  */
perf_addr_filter_match(struct perf_addr_filter * filter,struct file * file,unsigned long offset,unsigned long size)8330 static bool perf_addr_filter_match(struct perf_addr_filter *filter,
8331 				     struct file *file, unsigned long offset,
8332 				     unsigned long size)
8333 {
8334 	/* d_inode(NULL) won't be equal to any mapped user-space file */
8335 	if (!filter->path.dentry)
8336 		return false;
8337 
8338 	if (d_inode(filter->path.dentry) != file_inode(file))
8339 		return false;
8340 
8341 	if (filter->offset > offset + size)
8342 		return false;
8343 
8344 	if (filter->offset + filter->size < offset)
8345 		return false;
8346 
8347 	return true;
8348 }
8349 
perf_addr_filter_vma_adjust(struct perf_addr_filter * filter,struct vm_area_struct * vma,struct perf_addr_filter_range * fr)8350 static bool perf_addr_filter_vma_adjust(struct perf_addr_filter *filter,
8351 					struct vm_area_struct *vma,
8352 					struct perf_addr_filter_range *fr)
8353 {
8354 	unsigned long vma_size = vma->vm_end - vma->vm_start;
8355 	unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
8356 	struct file *file = vma->vm_file;
8357 
8358 	if (!perf_addr_filter_match(filter, file, off, vma_size))
8359 		return false;
8360 
8361 	if (filter->offset < off) {
8362 		fr->start = vma->vm_start;
8363 		fr->size = min(vma_size, filter->size - (off - filter->offset));
8364 	} else {
8365 		fr->start = vma->vm_start + filter->offset - off;
8366 		fr->size = min(vma->vm_end - fr->start, filter->size);
8367 	}
8368 
8369 	return true;
8370 }
8371 
__perf_addr_filters_adjust(struct perf_event * event,void * data)8372 static void __perf_addr_filters_adjust(struct perf_event *event, void *data)
8373 {
8374 	struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
8375 	struct vm_area_struct *vma = data;
8376 	struct perf_addr_filter *filter;
8377 	unsigned int restart = 0, count = 0;
8378 	unsigned long flags;
8379 
8380 	if (!has_addr_filter(event))
8381 		return;
8382 
8383 	if (!vma->vm_file)
8384 		return;
8385 
8386 	raw_spin_lock_irqsave(&ifh->lock, flags);
8387 	list_for_each_entry(filter, &ifh->list, entry) {
8388 		if (perf_addr_filter_vma_adjust(filter, vma,
8389 						&event->addr_filter_ranges[count]))
8390 			restart++;
8391 
8392 		count++;
8393 	}
8394 
8395 	if (restart)
8396 		event->addr_filters_gen++;
8397 	raw_spin_unlock_irqrestore(&ifh->lock, flags);
8398 
8399 	if (restart)
8400 		perf_event_stop(event, 1);
8401 }
8402 
8403 /*
8404  * Adjust all task's events' filters to the new vma
8405  */
perf_addr_filters_adjust(struct vm_area_struct * vma)8406 static void perf_addr_filters_adjust(struct vm_area_struct *vma)
8407 {
8408 	struct perf_event_context *ctx;
8409 	int ctxn;
8410 
8411 	/*
8412 	 * Data tracing isn't supported yet and as such there is no need
8413 	 * to keep track of anything that isn't related to executable code:
8414 	 */
8415 	if (!(vma->vm_flags & VM_EXEC))
8416 		return;
8417 
8418 	rcu_read_lock();
8419 	for_each_task_context_nr(ctxn) {
8420 		ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
8421 		if (!ctx)
8422 			continue;
8423 
8424 		perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true);
8425 	}
8426 	rcu_read_unlock();
8427 }
8428 
perf_event_mmap(struct vm_area_struct * vma)8429 void perf_event_mmap(struct vm_area_struct *vma)
8430 {
8431 	struct perf_mmap_event mmap_event;
8432 
8433 	if (!atomic_read(&nr_mmap_events))
8434 		return;
8435 
8436 	mmap_event = (struct perf_mmap_event){
8437 		.vma	= vma,
8438 		/* .file_name */
8439 		/* .file_size */
8440 		.event_id  = {
8441 			.header = {
8442 				.type = PERF_RECORD_MMAP,
8443 				.misc = PERF_RECORD_MISC_USER,
8444 				/* .size */
8445 			},
8446 			/* .pid */
8447 			/* .tid */
8448 			.start  = vma->vm_start,
8449 			.len    = vma->vm_end - vma->vm_start,
8450 			.pgoff  = (u64)vma->vm_pgoff << PAGE_SHIFT,
8451 		},
8452 		/* .maj (attr_mmap2 only) */
8453 		/* .min (attr_mmap2 only) */
8454 		/* .ino (attr_mmap2 only) */
8455 		/* .ino_generation (attr_mmap2 only) */
8456 		/* .prot (attr_mmap2 only) */
8457 		/* .flags (attr_mmap2 only) */
8458 	};
8459 
8460 	perf_addr_filters_adjust(vma);
8461 	perf_event_mmap_event(&mmap_event);
8462 }
8463 
perf_event_aux_event(struct perf_event * event,unsigned long head,unsigned long size,u64 flags)8464 void perf_event_aux_event(struct perf_event *event, unsigned long head,
8465 			  unsigned long size, u64 flags)
8466 {
8467 	struct perf_output_handle handle;
8468 	struct perf_sample_data sample;
8469 	struct perf_aux_event {
8470 		struct perf_event_header	header;
8471 		u64				offset;
8472 		u64				size;
8473 		u64				flags;
8474 	} rec = {
8475 		.header = {
8476 			.type = PERF_RECORD_AUX,
8477 			.misc = 0,
8478 			.size = sizeof(rec),
8479 		},
8480 		.offset		= head,
8481 		.size		= size,
8482 		.flags		= flags,
8483 	};
8484 	int ret;
8485 
8486 	perf_event_header__init_id(&rec.header, &sample, event);
8487 	ret = perf_output_begin(&handle, &sample, event, rec.header.size);
8488 
8489 	if (ret)
8490 		return;
8491 
8492 	perf_output_put(&handle, rec);
8493 	perf_event__output_id_sample(event, &handle, &sample);
8494 
8495 	perf_output_end(&handle);
8496 }
8497 
8498 /*
8499  * Lost/dropped samples logging
8500  */
perf_log_lost_samples(struct perf_event * event,u64 lost)8501 void perf_log_lost_samples(struct perf_event *event, u64 lost)
8502 {
8503 	struct perf_output_handle handle;
8504 	struct perf_sample_data sample;
8505 	int ret;
8506 
8507 	struct {
8508 		struct perf_event_header	header;
8509 		u64				lost;
8510 	} lost_samples_event = {
8511 		.header = {
8512 			.type = PERF_RECORD_LOST_SAMPLES,
8513 			.misc = 0,
8514 			.size = sizeof(lost_samples_event),
8515 		},
8516 		.lost		= lost,
8517 	};
8518 
8519 	perf_event_header__init_id(&lost_samples_event.header, &sample, event);
8520 
8521 	ret = perf_output_begin(&handle, &sample, event,
8522 				lost_samples_event.header.size);
8523 	if (ret)
8524 		return;
8525 
8526 	perf_output_put(&handle, lost_samples_event);
8527 	perf_event__output_id_sample(event, &handle, &sample);
8528 	perf_output_end(&handle);
8529 }
8530 
8531 /*
8532  * context_switch tracking
8533  */
8534 
8535 struct perf_switch_event {
8536 	struct task_struct	*task;
8537 	struct task_struct	*next_prev;
8538 
8539 	struct {
8540 		struct perf_event_header	header;
8541 		u32				next_prev_pid;
8542 		u32				next_prev_tid;
8543 	} event_id;
8544 };
8545 
perf_event_switch_match(struct perf_event * event)8546 static int perf_event_switch_match(struct perf_event *event)
8547 {
8548 	return event->attr.context_switch;
8549 }
8550 
perf_event_switch_output(struct perf_event * event,void * data)8551 static void perf_event_switch_output(struct perf_event *event, void *data)
8552 {
8553 	struct perf_switch_event *se = data;
8554 	struct perf_output_handle handle;
8555 	struct perf_sample_data sample;
8556 	int ret;
8557 
8558 	if (!perf_event_switch_match(event))
8559 		return;
8560 
8561 	/* Only CPU-wide events are allowed to see next/prev pid/tid */
8562 	if (event->ctx->task) {
8563 		se->event_id.header.type = PERF_RECORD_SWITCH;
8564 		se->event_id.header.size = sizeof(se->event_id.header);
8565 	} else {
8566 		se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
8567 		se->event_id.header.size = sizeof(se->event_id);
8568 		se->event_id.next_prev_pid =
8569 					perf_event_pid(event, se->next_prev);
8570 		se->event_id.next_prev_tid =
8571 					perf_event_tid(event, se->next_prev);
8572 	}
8573 
8574 	perf_event_header__init_id(&se->event_id.header, &sample, event);
8575 
8576 	ret = perf_output_begin(&handle, &sample, event, se->event_id.header.size);
8577 	if (ret)
8578 		return;
8579 
8580 	if (event->ctx->task)
8581 		perf_output_put(&handle, se->event_id.header);
8582 	else
8583 		perf_output_put(&handle, se->event_id);
8584 
8585 	perf_event__output_id_sample(event, &handle, &sample);
8586 
8587 	perf_output_end(&handle);
8588 }
8589 
perf_event_switch(struct task_struct * task,struct task_struct * next_prev,bool sched_in)8590 static void perf_event_switch(struct task_struct *task,
8591 			      struct task_struct *next_prev, bool sched_in)
8592 {
8593 	struct perf_switch_event switch_event;
8594 
8595 	/* N.B. caller checks nr_switch_events != 0 */
8596 
8597 	switch_event = (struct perf_switch_event){
8598 		.task		= task,
8599 		.next_prev	= next_prev,
8600 		.event_id	= {
8601 			.header = {
8602 				/* .type */
8603 				.misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
8604 				/* .size */
8605 			},
8606 			/* .next_prev_pid */
8607 			/* .next_prev_tid */
8608 		},
8609 	};
8610 
8611 	if (!sched_in && task->state == TASK_RUNNING)
8612 		switch_event.event_id.header.misc |=
8613 				PERF_RECORD_MISC_SWITCH_OUT_PREEMPT;
8614 
8615 	perf_iterate_sb(perf_event_switch_output,
8616 		       &switch_event,
8617 		       NULL);
8618 }
8619 
8620 /*
8621  * IRQ throttle logging
8622  */
8623 
perf_log_throttle(struct perf_event * event,int enable)8624 static void perf_log_throttle(struct perf_event *event, int enable)
8625 {
8626 	struct perf_output_handle handle;
8627 	struct perf_sample_data sample;
8628 	int ret;
8629 
8630 	struct {
8631 		struct perf_event_header	header;
8632 		u64				time;
8633 		u64				id;
8634 		u64				stream_id;
8635 	} throttle_event = {
8636 		.header = {
8637 			.type = PERF_RECORD_THROTTLE,
8638 			.misc = 0,
8639 			.size = sizeof(throttle_event),
8640 		},
8641 		.time		= perf_event_clock(event),
8642 		.id		= primary_event_id(event),
8643 		.stream_id	= event->id,
8644 	};
8645 
8646 	if (enable)
8647 		throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
8648 
8649 	perf_event_header__init_id(&throttle_event.header, &sample, event);
8650 
8651 	ret = perf_output_begin(&handle, &sample, event,
8652 				throttle_event.header.size);
8653 	if (ret)
8654 		return;
8655 
8656 	perf_output_put(&handle, throttle_event);
8657 	perf_event__output_id_sample(event, &handle, &sample);
8658 	perf_output_end(&handle);
8659 }
8660 
8661 /*
8662  * ksymbol register/unregister tracking
8663  */
8664 
8665 struct perf_ksymbol_event {
8666 	const char	*name;
8667 	int		name_len;
8668 	struct {
8669 		struct perf_event_header        header;
8670 		u64				addr;
8671 		u32				len;
8672 		u16				ksym_type;
8673 		u16				flags;
8674 	} event_id;
8675 };
8676 
perf_event_ksymbol_match(struct perf_event * event)8677 static int perf_event_ksymbol_match(struct perf_event *event)
8678 {
8679 	return event->attr.ksymbol;
8680 }
8681 
perf_event_ksymbol_output(struct perf_event * event,void * data)8682 static void perf_event_ksymbol_output(struct perf_event *event, void *data)
8683 {
8684 	struct perf_ksymbol_event *ksymbol_event = data;
8685 	struct perf_output_handle handle;
8686 	struct perf_sample_data sample;
8687 	int ret;
8688 
8689 	if (!perf_event_ksymbol_match(event))
8690 		return;
8691 
8692 	perf_event_header__init_id(&ksymbol_event->event_id.header,
8693 				   &sample, event);
8694 	ret = perf_output_begin(&handle, &sample, event,
8695 				ksymbol_event->event_id.header.size);
8696 	if (ret)
8697 		return;
8698 
8699 	perf_output_put(&handle, ksymbol_event->event_id);
8700 	__output_copy(&handle, ksymbol_event->name, ksymbol_event->name_len);
8701 	perf_event__output_id_sample(event, &handle, &sample);
8702 
8703 	perf_output_end(&handle);
8704 }
8705 
perf_event_ksymbol(u16 ksym_type,u64 addr,u32 len,bool unregister,const char * sym)8706 void perf_event_ksymbol(u16 ksym_type, u64 addr, u32 len, bool unregister,
8707 			const char *sym)
8708 {
8709 	struct perf_ksymbol_event ksymbol_event;
8710 	char name[KSYM_NAME_LEN];
8711 	u16 flags = 0;
8712 	int name_len;
8713 
8714 	if (!atomic_read(&nr_ksymbol_events))
8715 		return;
8716 
8717 	if (ksym_type >= PERF_RECORD_KSYMBOL_TYPE_MAX ||
8718 	    ksym_type == PERF_RECORD_KSYMBOL_TYPE_UNKNOWN)
8719 		goto err;
8720 
8721 	strlcpy(name, sym, KSYM_NAME_LEN);
8722 	name_len = strlen(name) + 1;
8723 	while (!IS_ALIGNED(name_len, sizeof(u64)))
8724 		name[name_len++] = '\0';
8725 	BUILD_BUG_ON(KSYM_NAME_LEN % sizeof(u64));
8726 
8727 	if (unregister)
8728 		flags |= PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER;
8729 
8730 	ksymbol_event = (struct perf_ksymbol_event){
8731 		.name = name,
8732 		.name_len = name_len,
8733 		.event_id = {
8734 			.header = {
8735 				.type = PERF_RECORD_KSYMBOL,
8736 				.size = sizeof(ksymbol_event.event_id) +
8737 					name_len,
8738 			},
8739 			.addr = addr,
8740 			.len = len,
8741 			.ksym_type = ksym_type,
8742 			.flags = flags,
8743 		},
8744 	};
8745 
8746 	perf_iterate_sb(perf_event_ksymbol_output, &ksymbol_event, NULL);
8747 	return;
8748 err:
8749 	WARN_ONCE(1, "%s: Invalid KSYMBOL type 0x%x\n", __func__, ksym_type);
8750 }
8751 
8752 /*
8753  * bpf program load/unload tracking
8754  */
8755 
8756 struct perf_bpf_event {
8757 	struct bpf_prog	*prog;
8758 	struct {
8759 		struct perf_event_header        header;
8760 		u16				type;
8761 		u16				flags;
8762 		u32				id;
8763 		u8				tag[BPF_TAG_SIZE];
8764 	} event_id;
8765 };
8766 
perf_event_bpf_match(struct perf_event * event)8767 static int perf_event_bpf_match(struct perf_event *event)
8768 {
8769 	return event->attr.bpf_event;
8770 }
8771 
perf_event_bpf_output(struct perf_event * event,void * data)8772 static void perf_event_bpf_output(struct perf_event *event, void *data)
8773 {
8774 	struct perf_bpf_event *bpf_event = data;
8775 	struct perf_output_handle handle;
8776 	struct perf_sample_data sample;
8777 	int ret;
8778 
8779 	if (!perf_event_bpf_match(event))
8780 		return;
8781 
8782 	perf_event_header__init_id(&bpf_event->event_id.header,
8783 				   &sample, event);
8784 	ret = perf_output_begin(&handle, &sample, event,
8785 				bpf_event->event_id.header.size);
8786 	if (ret)
8787 		return;
8788 
8789 	perf_output_put(&handle, bpf_event->event_id);
8790 	perf_event__output_id_sample(event, &handle, &sample);
8791 
8792 	perf_output_end(&handle);
8793 }
8794 
perf_event_bpf_emit_ksymbols(struct bpf_prog * prog,enum perf_bpf_event_type type)8795 static void perf_event_bpf_emit_ksymbols(struct bpf_prog *prog,
8796 					 enum perf_bpf_event_type type)
8797 {
8798 	bool unregister = type == PERF_BPF_EVENT_PROG_UNLOAD;
8799 	int i;
8800 
8801 	if (prog->aux->func_cnt == 0) {
8802 		perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF,
8803 				   (u64)(unsigned long)prog->bpf_func,
8804 				   prog->jited_len, unregister,
8805 				   prog->aux->ksym.name);
8806 	} else {
8807 		for (i = 0; i < prog->aux->func_cnt; i++) {
8808 			struct bpf_prog *subprog = prog->aux->func[i];
8809 
8810 			perf_event_ksymbol(
8811 				PERF_RECORD_KSYMBOL_TYPE_BPF,
8812 				(u64)(unsigned long)subprog->bpf_func,
8813 				subprog->jited_len, unregister,
8814 				subprog->aux->ksym.name);
8815 		}
8816 	}
8817 }
8818 
perf_event_bpf_event(struct bpf_prog * prog,enum perf_bpf_event_type type,u16 flags)8819 void perf_event_bpf_event(struct bpf_prog *prog,
8820 			  enum perf_bpf_event_type type,
8821 			  u16 flags)
8822 {
8823 	struct perf_bpf_event bpf_event;
8824 
8825 	if (type <= PERF_BPF_EVENT_UNKNOWN ||
8826 	    type >= PERF_BPF_EVENT_MAX)
8827 		return;
8828 
8829 	switch (type) {
8830 	case PERF_BPF_EVENT_PROG_LOAD:
8831 	case PERF_BPF_EVENT_PROG_UNLOAD:
8832 		if (atomic_read(&nr_ksymbol_events))
8833 			perf_event_bpf_emit_ksymbols(prog, type);
8834 		break;
8835 	default:
8836 		break;
8837 	}
8838 
8839 	if (!atomic_read(&nr_bpf_events))
8840 		return;
8841 
8842 	bpf_event = (struct perf_bpf_event){
8843 		.prog = prog,
8844 		.event_id = {
8845 			.header = {
8846 				.type = PERF_RECORD_BPF_EVENT,
8847 				.size = sizeof(bpf_event.event_id),
8848 			},
8849 			.type = type,
8850 			.flags = flags,
8851 			.id = prog->aux->id,
8852 		},
8853 	};
8854 
8855 	BUILD_BUG_ON(BPF_TAG_SIZE % sizeof(u64));
8856 
8857 	memcpy(bpf_event.event_id.tag, prog->tag, BPF_TAG_SIZE);
8858 	perf_iterate_sb(perf_event_bpf_output, &bpf_event, NULL);
8859 }
8860 
8861 struct perf_text_poke_event {
8862 	const void		*old_bytes;
8863 	const void		*new_bytes;
8864 	size_t			pad;
8865 	u16			old_len;
8866 	u16			new_len;
8867 
8868 	struct {
8869 		struct perf_event_header	header;
8870 
8871 		u64				addr;
8872 	} event_id;
8873 };
8874 
perf_event_text_poke_match(struct perf_event * event)8875 static int perf_event_text_poke_match(struct perf_event *event)
8876 {
8877 	return event->attr.text_poke;
8878 }
8879 
perf_event_text_poke_output(struct perf_event * event,void * data)8880 static void perf_event_text_poke_output(struct perf_event *event, void *data)
8881 {
8882 	struct perf_text_poke_event *text_poke_event = data;
8883 	struct perf_output_handle handle;
8884 	struct perf_sample_data sample;
8885 	u64 padding = 0;
8886 	int ret;
8887 
8888 	if (!perf_event_text_poke_match(event))
8889 		return;
8890 
8891 	perf_event_header__init_id(&text_poke_event->event_id.header, &sample, event);
8892 
8893 	ret = perf_output_begin(&handle, &sample, event,
8894 				text_poke_event->event_id.header.size);
8895 	if (ret)
8896 		return;
8897 
8898 	perf_output_put(&handle, text_poke_event->event_id);
8899 	perf_output_put(&handle, text_poke_event->old_len);
8900 	perf_output_put(&handle, text_poke_event->new_len);
8901 
8902 	__output_copy(&handle, text_poke_event->old_bytes, text_poke_event->old_len);
8903 	__output_copy(&handle, text_poke_event->new_bytes, text_poke_event->new_len);
8904 
8905 	if (text_poke_event->pad)
8906 		__output_copy(&handle, &padding, text_poke_event->pad);
8907 
8908 	perf_event__output_id_sample(event, &handle, &sample);
8909 
8910 	perf_output_end(&handle);
8911 }
8912 
perf_event_text_poke(const void * addr,const void * old_bytes,size_t old_len,const void * new_bytes,size_t new_len)8913 void perf_event_text_poke(const void *addr, const void *old_bytes,
8914 			  size_t old_len, const void *new_bytes, size_t new_len)
8915 {
8916 	struct perf_text_poke_event text_poke_event;
8917 	size_t tot, pad;
8918 
8919 	if (!atomic_read(&nr_text_poke_events))
8920 		return;
8921 
8922 	tot  = sizeof(text_poke_event.old_len) + old_len;
8923 	tot += sizeof(text_poke_event.new_len) + new_len;
8924 	pad  = ALIGN(tot, sizeof(u64)) - tot;
8925 
8926 	text_poke_event = (struct perf_text_poke_event){
8927 		.old_bytes    = old_bytes,
8928 		.new_bytes    = new_bytes,
8929 		.pad          = pad,
8930 		.old_len      = old_len,
8931 		.new_len      = new_len,
8932 		.event_id  = {
8933 			.header = {
8934 				.type = PERF_RECORD_TEXT_POKE,
8935 				.misc = PERF_RECORD_MISC_KERNEL,
8936 				.size = sizeof(text_poke_event.event_id) + tot + pad,
8937 			},
8938 			.addr = (unsigned long)addr,
8939 		},
8940 	};
8941 
8942 	perf_iterate_sb(perf_event_text_poke_output, &text_poke_event, NULL);
8943 }
8944 
perf_event_itrace_started(struct perf_event * event)8945 void perf_event_itrace_started(struct perf_event *event)
8946 {
8947 	event->attach_state |= PERF_ATTACH_ITRACE;
8948 }
8949 
perf_log_itrace_start(struct perf_event * event)8950 static void perf_log_itrace_start(struct perf_event *event)
8951 {
8952 	struct perf_output_handle handle;
8953 	struct perf_sample_data sample;
8954 	struct perf_aux_event {
8955 		struct perf_event_header        header;
8956 		u32				pid;
8957 		u32				tid;
8958 	} rec;
8959 	int ret;
8960 
8961 	if (event->parent)
8962 		event = event->parent;
8963 
8964 	if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
8965 	    event->attach_state & PERF_ATTACH_ITRACE)
8966 		return;
8967 
8968 	rec.header.type	= PERF_RECORD_ITRACE_START;
8969 	rec.header.misc	= 0;
8970 	rec.header.size	= sizeof(rec);
8971 	rec.pid	= perf_event_pid(event, current);
8972 	rec.tid	= perf_event_tid(event, current);
8973 
8974 	perf_event_header__init_id(&rec.header, &sample, event);
8975 	ret = perf_output_begin(&handle, &sample, event, rec.header.size);
8976 
8977 	if (ret)
8978 		return;
8979 
8980 	perf_output_put(&handle, rec);
8981 	perf_event__output_id_sample(event, &handle, &sample);
8982 
8983 	perf_output_end(&handle);
8984 }
8985 
8986 static int
__perf_event_account_interrupt(struct perf_event * event,int throttle)8987 __perf_event_account_interrupt(struct perf_event *event, int throttle)
8988 {
8989 	struct hw_perf_event *hwc = &event->hw;
8990 	int ret = 0;
8991 	u64 seq;
8992 
8993 	seq = __this_cpu_read(perf_throttled_seq);
8994 	if (seq != hwc->interrupts_seq) {
8995 		hwc->interrupts_seq = seq;
8996 		hwc->interrupts = 1;
8997 	} else {
8998 		hwc->interrupts++;
8999 		if (unlikely(throttle &&
9000 			     hwc->interrupts > max_samples_per_tick)) {
9001 			__this_cpu_inc(perf_throttled_count);
9002 			tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
9003 			hwc->interrupts = MAX_INTERRUPTS;
9004 			perf_log_throttle(event, 0);
9005 			ret = 1;
9006 		}
9007 	}
9008 
9009 	if (event->attr.freq) {
9010 		u64 now = perf_clock();
9011 		s64 delta = now - hwc->freq_time_stamp;
9012 
9013 		hwc->freq_time_stamp = now;
9014 
9015 		if (delta > 0 && delta < 2*TICK_NSEC)
9016 			perf_adjust_period(event, delta, hwc->last_period, true);
9017 	}
9018 
9019 	return ret;
9020 }
9021 
perf_event_account_interrupt(struct perf_event * event)9022 int perf_event_account_interrupt(struct perf_event *event)
9023 {
9024 	return __perf_event_account_interrupt(event, 1);
9025 }
9026 
9027 /*
9028  * Generic event overflow handling, sampling.
9029  */
9030 
__perf_event_overflow(struct perf_event * event,int throttle,struct perf_sample_data * data,struct pt_regs * regs)9031 static int __perf_event_overflow(struct perf_event *event,
9032 				   int throttle, struct perf_sample_data *data,
9033 				   struct pt_regs *regs)
9034 {
9035 	int events = atomic_read(&event->event_limit);
9036 	int ret = 0;
9037 
9038 	/*
9039 	 * Non-sampling counters might still use the PMI to fold short
9040 	 * hardware counters, ignore those.
9041 	 */
9042 	if (unlikely(!is_sampling_event(event)))
9043 		return 0;
9044 
9045 	ret = __perf_event_account_interrupt(event, throttle);
9046 
9047 	/*
9048 	 * XXX event_limit might not quite work as expected on inherited
9049 	 * events
9050 	 */
9051 
9052 	event->pending_kill = POLL_IN;
9053 	if (events && atomic_dec_and_test(&event->event_limit)) {
9054 		ret = 1;
9055 		event->pending_kill = POLL_HUP;
9056 
9057 		perf_event_disable_inatomic(event);
9058 	}
9059 
9060 	READ_ONCE(event->overflow_handler)(event, data, regs);
9061 
9062 	if (*perf_event_fasync(event) && event->pending_kill) {
9063 		event->pending_wakeup = 1;
9064 		irq_work_queue(&event->pending);
9065 	}
9066 
9067 	return ret;
9068 }
9069 
perf_event_overflow(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)9070 int perf_event_overflow(struct perf_event *event,
9071 			  struct perf_sample_data *data,
9072 			  struct pt_regs *regs)
9073 {
9074 	return __perf_event_overflow(event, 1, data, regs);
9075 }
9076 
9077 /*
9078  * Generic software event infrastructure
9079  */
9080 
9081 struct swevent_htable {
9082 	struct swevent_hlist		*swevent_hlist;
9083 	struct mutex			hlist_mutex;
9084 	int				hlist_refcount;
9085 
9086 	/* Recursion avoidance in each contexts */
9087 	int				recursion[PERF_NR_CONTEXTS];
9088 };
9089 
9090 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
9091 
9092 /*
9093  * We directly increment event->count and keep a second value in
9094  * event->hw.period_left to count intervals. This period event
9095  * is kept in the range [-sample_period, 0] so that we can use the
9096  * sign as trigger.
9097  */
9098 
perf_swevent_set_period(struct perf_event * event)9099 u64 perf_swevent_set_period(struct perf_event *event)
9100 {
9101 	struct hw_perf_event *hwc = &event->hw;
9102 	u64 period = hwc->last_period;
9103 	u64 nr, offset;
9104 	s64 old, val;
9105 
9106 	hwc->last_period = hwc->sample_period;
9107 
9108 again:
9109 	old = val = local64_read(&hwc->period_left);
9110 	if (val < 0)
9111 		return 0;
9112 
9113 	nr = div64_u64(period + val, period);
9114 	offset = nr * period;
9115 	val -= offset;
9116 	if (local64_cmpxchg(&hwc->period_left, old, val) != old)
9117 		goto again;
9118 
9119 	return nr;
9120 }
9121 
perf_swevent_overflow(struct perf_event * event,u64 overflow,struct perf_sample_data * data,struct pt_regs * regs)9122 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
9123 				    struct perf_sample_data *data,
9124 				    struct pt_regs *regs)
9125 {
9126 	struct hw_perf_event *hwc = &event->hw;
9127 	int throttle = 0;
9128 
9129 	if (!overflow)
9130 		overflow = perf_swevent_set_period(event);
9131 
9132 	if (hwc->interrupts == MAX_INTERRUPTS)
9133 		return;
9134 
9135 	for (; overflow; overflow--) {
9136 		if (__perf_event_overflow(event, throttle,
9137 					    data, regs)) {
9138 			/*
9139 			 * We inhibit the overflow from happening when
9140 			 * hwc->interrupts == MAX_INTERRUPTS.
9141 			 */
9142 			break;
9143 		}
9144 		throttle = 1;
9145 	}
9146 }
9147 
perf_swevent_event(struct perf_event * event,u64 nr,struct perf_sample_data * data,struct pt_regs * regs)9148 static void perf_swevent_event(struct perf_event *event, u64 nr,
9149 			       struct perf_sample_data *data,
9150 			       struct pt_regs *regs)
9151 {
9152 	struct hw_perf_event *hwc = &event->hw;
9153 
9154 	local64_add(nr, &event->count);
9155 
9156 	if (!regs)
9157 		return;
9158 
9159 	if (!is_sampling_event(event))
9160 		return;
9161 
9162 	if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
9163 		data->period = nr;
9164 		return perf_swevent_overflow(event, 1, data, regs);
9165 	} else
9166 		data->period = event->hw.last_period;
9167 
9168 	if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
9169 		return perf_swevent_overflow(event, 1, data, regs);
9170 
9171 	if (local64_add_negative(nr, &hwc->period_left))
9172 		return;
9173 
9174 	perf_swevent_overflow(event, 0, data, regs);
9175 }
9176 
perf_exclude_event(struct perf_event * event,struct pt_regs * regs)9177 static int perf_exclude_event(struct perf_event *event,
9178 			      struct pt_regs *regs)
9179 {
9180 	if (event->hw.state & PERF_HES_STOPPED)
9181 		return 1;
9182 
9183 	if (regs) {
9184 		if (event->attr.exclude_user && user_mode(regs))
9185 			return 1;
9186 
9187 		if (event->attr.exclude_kernel && !user_mode(regs))
9188 			return 1;
9189 	}
9190 
9191 	return 0;
9192 }
9193 
perf_swevent_match(struct perf_event * event,enum perf_type_id type,u32 event_id,struct perf_sample_data * data,struct pt_regs * regs)9194 static int perf_swevent_match(struct perf_event *event,
9195 				enum perf_type_id type,
9196 				u32 event_id,
9197 				struct perf_sample_data *data,
9198 				struct pt_regs *regs)
9199 {
9200 	if (event->attr.type != type)
9201 		return 0;
9202 
9203 	if (event->attr.config != event_id)
9204 		return 0;
9205 
9206 	if (perf_exclude_event(event, regs))
9207 		return 0;
9208 
9209 	return 1;
9210 }
9211 
swevent_hash(u64 type,u32 event_id)9212 static inline u64 swevent_hash(u64 type, u32 event_id)
9213 {
9214 	u64 val = event_id | (type << 32);
9215 
9216 	return hash_64(val, SWEVENT_HLIST_BITS);
9217 }
9218 
9219 static inline struct hlist_head *
__find_swevent_head(struct swevent_hlist * hlist,u64 type,u32 event_id)9220 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
9221 {
9222 	u64 hash = swevent_hash(type, event_id);
9223 
9224 	return &hlist->heads[hash];
9225 }
9226 
9227 /* For the read side: events when they trigger */
9228 static inline struct hlist_head *
find_swevent_head_rcu(struct swevent_htable * swhash,u64 type,u32 event_id)9229 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
9230 {
9231 	struct swevent_hlist *hlist;
9232 
9233 	hlist = rcu_dereference(swhash->swevent_hlist);
9234 	if (!hlist)
9235 		return NULL;
9236 
9237 	return __find_swevent_head(hlist, type, event_id);
9238 }
9239 
9240 /* For the event head insertion and removal in the hlist */
9241 static inline struct hlist_head *
find_swevent_head(struct swevent_htable * swhash,struct perf_event * event)9242 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
9243 {
9244 	struct swevent_hlist *hlist;
9245 	u32 event_id = event->attr.config;
9246 	u64 type = event->attr.type;
9247 
9248 	/*
9249 	 * Event scheduling is always serialized against hlist allocation
9250 	 * and release. Which makes the protected version suitable here.
9251 	 * The context lock guarantees that.
9252 	 */
9253 	hlist = rcu_dereference_protected(swhash->swevent_hlist,
9254 					  lockdep_is_held(&event->ctx->lock));
9255 	if (!hlist)
9256 		return NULL;
9257 
9258 	return __find_swevent_head(hlist, type, event_id);
9259 }
9260 
do_perf_sw_event(enum perf_type_id type,u32 event_id,u64 nr,struct perf_sample_data * data,struct pt_regs * regs)9261 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
9262 				    u64 nr,
9263 				    struct perf_sample_data *data,
9264 				    struct pt_regs *regs)
9265 {
9266 	struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9267 	struct perf_event *event;
9268 	struct hlist_head *head;
9269 
9270 	rcu_read_lock();
9271 	head = find_swevent_head_rcu(swhash, type, event_id);
9272 	if (!head)
9273 		goto end;
9274 
9275 	hlist_for_each_entry_rcu(event, head, hlist_entry) {
9276 		if (perf_swevent_match(event, type, event_id, data, regs))
9277 			perf_swevent_event(event, nr, data, regs);
9278 	}
9279 end:
9280 	rcu_read_unlock();
9281 }
9282 
9283 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
9284 
perf_swevent_get_recursion_context(void)9285 int perf_swevent_get_recursion_context(void)
9286 {
9287 	struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9288 
9289 	return get_recursion_context(swhash->recursion);
9290 }
9291 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
9292 
perf_swevent_put_recursion_context(int rctx)9293 void perf_swevent_put_recursion_context(int rctx)
9294 {
9295 	struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9296 
9297 	put_recursion_context(swhash->recursion, rctx);
9298 }
9299 
___perf_sw_event(u32 event_id,u64 nr,struct pt_regs * regs,u64 addr)9300 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
9301 {
9302 	struct perf_sample_data data;
9303 
9304 	if (WARN_ON_ONCE(!regs))
9305 		return;
9306 
9307 	perf_sample_data_init(&data, addr, 0);
9308 	do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
9309 }
9310 
__perf_sw_event(u32 event_id,u64 nr,struct pt_regs * regs,u64 addr)9311 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
9312 {
9313 	int rctx;
9314 
9315 	preempt_disable_notrace();
9316 	rctx = perf_swevent_get_recursion_context();
9317 	if (unlikely(rctx < 0))
9318 		goto fail;
9319 
9320 	___perf_sw_event(event_id, nr, regs, addr);
9321 
9322 	perf_swevent_put_recursion_context(rctx);
9323 fail:
9324 	preempt_enable_notrace();
9325 }
9326 
perf_swevent_read(struct perf_event * event)9327 static void perf_swevent_read(struct perf_event *event)
9328 {
9329 }
9330 
perf_swevent_add(struct perf_event * event,int flags)9331 static int perf_swevent_add(struct perf_event *event, int flags)
9332 {
9333 	struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9334 	struct hw_perf_event *hwc = &event->hw;
9335 	struct hlist_head *head;
9336 
9337 	if (is_sampling_event(event)) {
9338 		hwc->last_period = hwc->sample_period;
9339 		perf_swevent_set_period(event);
9340 	}
9341 
9342 	hwc->state = !(flags & PERF_EF_START);
9343 
9344 	head = find_swevent_head(swhash, event);
9345 	if (WARN_ON_ONCE(!head))
9346 		return -EINVAL;
9347 
9348 	hlist_add_head_rcu(&event->hlist_entry, head);
9349 	perf_event_update_userpage(event);
9350 
9351 	return 0;
9352 }
9353 
perf_swevent_del(struct perf_event * event,int flags)9354 static void perf_swevent_del(struct perf_event *event, int flags)
9355 {
9356 	hlist_del_rcu(&event->hlist_entry);
9357 }
9358 
perf_swevent_start(struct perf_event * event,int flags)9359 static void perf_swevent_start(struct perf_event *event, int flags)
9360 {
9361 	event->hw.state = 0;
9362 }
9363 
perf_swevent_stop(struct perf_event * event,int flags)9364 static void perf_swevent_stop(struct perf_event *event, int flags)
9365 {
9366 	event->hw.state = PERF_HES_STOPPED;
9367 }
9368 
9369 /* Deref the hlist from the update side */
9370 static inline struct swevent_hlist *
swevent_hlist_deref(struct swevent_htable * swhash)9371 swevent_hlist_deref(struct swevent_htable *swhash)
9372 {
9373 	return rcu_dereference_protected(swhash->swevent_hlist,
9374 					 lockdep_is_held(&swhash->hlist_mutex));
9375 }
9376 
swevent_hlist_release(struct swevent_htable * swhash)9377 static void swevent_hlist_release(struct swevent_htable *swhash)
9378 {
9379 	struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
9380 
9381 	if (!hlist)
9382 		return;
9383 
9384 	RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
9385 	kfree_rcu(hlist, rcu_head);
9386 }
9387 
swevent_hlist_put_cpu(int cpu)9388 static void swevent_hlist_put_cpu(int cpu)
9389 {
9390 	struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9391 
9392 	mutex_lock(&swhash->hlist_mutex);
9393 
9394 	if (!--swhash->hlist_refcount)
9395 		swevent_hlist_release(swhash);
9396 
9397 	mutex_unlock(&swhash->hlist_mutex);
9398 }
9399 
swevent_hlist_put(void)9400 static void swevent_hlist_put(void)
9401 {
9402 	int cpu;
9403 
9404 	for_each_possible_cpu(cpu)
9405 		swevent_hlist_put_cpu(cpu);
9406 }
9407 
swevent_hlist_get_cpu(int cpu)9408 static int swevent_hlist_get_cpu(int cpu)
9409 {
9410 	struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9411 	int err = 0;
9412 
9413 	mutex_lock(&swhash->hlist_mutex);
9414 	if (!swevent_hlist_deref(swhash) &&
9415 	    cpumask_test_cpu(cpu, perf_online_mask)) {
9416 		struct swevent_hlist *hlist;
9417 
9418 		hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
9419 		if (!hlist) {
9420 			err = -ENOMEM;
9421 			goto exit;
9422 		}
9423 		rcu_assign_pointer(swhash->swevent_hlist, hlist);
9424 	}
9425 	swhash->hlist_refcount++;
9426 exit:
9427 	mutex_unlock(&swhash->hlist_mutex);
9428 
9429 	return err;
9430 }
9431 
swevent_hlist_get(void)9432 static int swevent_hlist_get(void)
9433 {
9434 	int err, cpu, failed_cpu;
9435 
9436 	mutex_lock(&pmus_lock);
9437 	for_each_possible_cpu(cpu) {
9438 		err = swevent_hlist_get_cpu(cpu);
9439 		if (err) {
9440 			failed_cpu = cpu;
9441 			goto fail;
9442 		}
9443 	}
9444 	mutex_unlock(&pmus_lock);
9445 	return 0;
9446 fail:
9447 	for_each_possible_cpu(cpu) {
9448 		if (cpu == failed_cpu)
9449 			break;
9450 		swevent_hlist_put_cpu(cpu);
9451 	}
9452 	mutex_unlock(&pmus_lock);
9453 	return err;
9454 }
9455 
9456 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
9457 
sw_perf_event_destroy(struct perf_event * event)9458 static void sw_perf_event_destroy(struct perf_event *event)
9459 {
9460 	u64 event_id = event->attr.config;
9461 
9462 	WARN_ON(event->parent);
9463 
9464 	static_key_slow_dec(&perf_swevent_enabled[event_id]);
9465 	swevent_hlist_put();
9466 }
9467 
perf_swevent_init(struct perf_event * event)9468 static int perf_swevent_init(struct perf_event *event)
9469 {
9470 	u64 event_id = event->attr.config;
9471 
9472 	if (event->attr.type != PERF_TYPE_SOFTWARE)
9473 		return -ENOENT;
9474 
9475 	/*
9476 	 * no branch sampling for software events
9477 	 */
9478 	if (has_branch_stack(event))
9479 		return -EOPNOTSUPP;
9480 
9481 	switch (event_id) {
9482 	case PERF_COUNT_SW_CPU_CLOCK:
9483 	case PERF_COUNT_SW_TASK_CLOCK:
9484 		return -ENOENT;
9485 
9486 	default:
9487 		break;
9488 	}
9489 
9490 	if (event_id >= PERF_COUNT_SW_MAX)
9491 		return -ENOENT;
9492 
9493 	if (!event->parent) {
9494 		int err;
9495 
9496 		err = swevent_hlist_get();
9497 		if (err)
9498 			return err;
9499 
9500 		static_key_slow_inc(&perf_swevent_enabled[event_id]);
9501 		event->destroy = sw_perf_event_destroy;
9502 	}
9503 
9504 	return 0;
9505 }
9506 
9507 static struct pmu perf_swevent = {
9508 	.task_ctx_nr	= perf_sw_context,
9509 
9510 	.capabilities	= PERF_PMU_CAP_NO_NMI,
9511 
9512 	.event_init	= perf_swevent_init,
9513 	.add		= perf_swevent_add,
9514 	.del		= perf_swevent_del,
9515 	.start		= perf_swevent_start,
9516 	.stop		= perf_swevent_stop,
9517 	.read		= perf_swevent_read,
9518 };
9519 
9520 #ifdef CONFIG_EVENT_TRACING
9521 
perf_tp_filter_match(struct perf_event * event,struct perf_sample_data * data)9522 static int perf_tp_filter_match(struct perf_event *event,
9523 				struct perf_sample_data *data)
9524 {
9525 	void *record = data->raw->frag.data;
9526 
9527 	/* only top level events have filters set */
9528 	if (event->parent)
9529 		event = event->parent;
9530 
9531 	if (likely(!event->filter) || filter_match_preds(event->filter, record))
9532 		return 1;
9533 	return 0;
9534 }
9535 
perf_tp_event_match(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)9536 static int perf_tp_event_match(struct perf_event *event,
9537 				struct perf_sample_data *data,
9538 				struct pt_regs *regs)
9539 {
9540 	if (event->hw.state & PERF_HES_STOPPED)
9541 		return 0;
9542 	/*
9543 	 * If exclude_kernel, only trace user-space tracepoints (uprobes)
9544 	 */
9545 	if (event->attr.exclude_kernel && !user_mode(regs))
9546 		return 0;
9547 
9548 	if (!perf_tp_filter_match(event, data))
9549 		return 0;
9550 
9551 	return 1;
9552 }
9553 
perf_trace_run_bpf_submit(void * raw_data,int size,int rctx,struct trace_event_call * call,u64 count,struct pt_regs * regs,struct hlist_head * head,struct task_struct * task)9554 void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx,
9555 			       struct trace_event_call *call, u64 count,
9556 			       struct pt_regs *regs, struct hlist_head *head,
9557 			       struct task_struct *task)
9558 {
9559 	if (bpf_prog_array_valid(call)) {
9560 		*(struct pt_regs **)raw_data = regs;
9561 		if (!trace_call_bpf(call, raw_data) || hlist_empty(head)) {
9562 			perf_swevent_put_recursion_context(rctx);
9563 			return;
9564 		}
9565 	}
9566 	perf_tp_event(call->event.type, count, raw_data, size, regs, head,
9567 		      rctx, task);
9568 }
9569 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit);
9570 
perf_tp_event(u16 event_type,u64 count,void * record,int entry_size,struct pt_regs * regs,struct hlist_head * head,int rctx,struct task_struct * task)9571 void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size,
9572 		   struct pt_regs *regs, struct hlist_head *head, int rctx,
9573 		   struct task_struct *task)
9574 {
9575 	struct perf_sample_data data;
9576 	struct perf_event *event;
9577 
9578 	struct perf_raw_record raw = {
9579 		.frag = {
9580 			.size = entry_size,
9581 			.data = record,
9582 		},
9583 	};
9584 
9585 	perf_sample_data_init(&data, 0, 0);
9586 	data.raw = &raw;
9587 
9588 	perf_trace_buf_update(record, event_type);
9589 
9590 	hlist_for_each_entry_rcu(event, head, hlist_entry) {
9591 		if (perf_tp_event_match(event, &data, regs))
9592 			perf_swevent_event(event, count, &data, regs);
9593 	}
9594 
9595 	/*
9596 	 * If we got specified a target task, also iterate its context and
9597 	 * deliver this event there too.
9598 	 */
9599 	if (task && task != current) {
9600 		struct perf_event_context *ctx;
9601 		struct trace_entry *entry = record;
9602 
9603 		rcu_read_lock();
9604 		ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
9605 		if (!ctx)
9606 			goto unlock;
9607 
9608 		list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
9609 			if (event->cpu != smp_processor_id())
9610 				continue;
9611 			if (event->attr.type != PERF_TYPE_TRACEPOINT)
9612 				continue;
9613 			if (event->attr.config != entry->type)
9614 				continue;
9615 			if (perf_tp_event_match(event, &data, regs))
9616 				perf_swevent_event(event, count, &data, regs);
9617 		}
9618 unlock:
9619 		rcu_read_unlock();
9620 	}
9621 
9622 	perf_swevent_put_recursion_context(rctx);
9623 }
9624 EXPORT_SYMBOL_GPL(perf_tp_event);
9625 
tp_perf_event_destroy(struct perf_event * event)9626 static void tp_perf_event_destroy(struct perf_event *event)
9627 {
9628 	perf_trace_destroy(event);
9629 }
9630 
perf_tp_event_init(struct perf_event * event)9631 static int perf_tp_event_init(struct perf_event *event)
9632 {
9633 	int err;
9634 
9635 	if (event->attr.type != PERF_TYPE_TRACEPOINT)
9636 		return -ENOENT;
9637 
9638 	/*
9639 	 * no branch sampling for tracepoint events
9640 	 */
9641 	if (has_branch_stack(event))
9642 		return -EOPNOTSUPP;
9643 
9644 	err = perf_trace_init(event);
9645 	if (err)
9646 		return err;
9647 
9648 	event->destroy = tp_perf_event_destroy;
9649 
9650 	return 0;
9651 }
9652 
9653 static struct pmu perf_tracepoint = {
9654 	.task_ctx_nr	= perf_sw_context,
9655 
9656 	.event_init	= perf_tp_event_init,
9657 	.add		= perf_trace_add,
9658 	.del		= perf_trace_del,
9659 	.start		= perf_swevent_start,
9660 	.stop		= perf_swevent_stop,
9661 	.read		= perf_swevent_read,
9662 };
9663 
9664 #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS)
9665 /*
9666  * Flags in config, used by dynamic PMU kprobe and uprobe
9667  * The flags should match following PMU_FORMAT_ATTR().
9668  *
9669  * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe
9670  *                               if not set, create kprobe/uprobe
9671  *
9672  * The following values specify a reference counter (or semaphore in the
9673  * terminology of tools like dtrace, systemtap, etc.) Userspace Statically
9674  * Defined Tracepoints (USDT). Currently, we use 40 bit for the offset.
9675  *
9676  * PERF_UPROBE_REF_CTR_OFFSET_BITS	# of bits in config as th offset
9677  * PERF_UPROBE_REF_CTR_OFFSET_SHIFT	# of bits to shift left
9678  */
9679 enum perf_probe_config {
9680 	PERF_PROBE_CONFIG_IS_RETPROBE = 1U << 0,  /* [k,u]retprobe */
9681 	PERF_UPROBE_REF_CTR_OFFSET_BITS = 32,
9682 	PERF_UPROBE_REF_CTR_OFFSET_SHIFT = 64 - PERF_UPROBE_REF_CTR_OFFSET_BITS,
9683 };
9684 
9685 PMU_FORMAT_ATTR(retprobe, "config:0");
9686 #endif
9687 
9688 #ifdef CONFIG_KPROBE_EVENTS
9689 static struct attribute *kprobe_attrs[] = {
9690 	&format_attr_retprobe.attr,
9691 	NULL,
9692 };
9693 
9694 static struct attribute_group kprobe_format_group = {
9695 	.name = "format",
9696 	.attrs = kprobe_attrs,
9697 };
9698 
9699 static const struct attribute_group *kprobe_attr_groups[] = {
9700 	&kprobe_format_group,
9701 	NULL,
9702 };
9703 
9704 static int perf_kprobe_event_init(struct perf_event *event);
9705 static struct pmu perf_kprobe = {
9706 	.task_ctx_nr	= perf_sw_context,
9707 	.event_init	= perf_kprobe_event_init,
9708 	.add		= perf_trace_add,
9709 	.del		= perf_trace_del,
9710 	.start		= perf_swevent_start,
9711 	.stop		= perf_swevent_stop,
9712 	.read		= perf_swevent_read,
9713 	.attr_groups	= kprobe_attr_groups,
9714 };
9715 
perf_kprobe_event_init(struct perf_event * event)9716 static int perf_kprobe_event_init(struct perf_event *event)
9717 {
9718 	int err;
9719 	bool is_retprobe;
9720 
9721 	if (event->attr.type != perf_kprobe.type)
9722 		return -ENOENT;
9723 
9724 	if (!perfmon_capable())
9725 		return -EACCES;
9726 
9727 	/*
9728 	 * no branch sampling for probe events
9729 	 */
9730 	if (has_branch_stack(event))
9731 		return -EOPNOTSUPP;
9732 
9733 	is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
9734 	err = perf_kprobe_init(event, is_retprobe);
9735 	if (err)
9736 		return err;
9737 
9738 	event->destroy = perf_kprobe_destroy;
9739 
9740 	return 0;
9741 }
9742 #endif /* CONFIG_KPROBE_EVENTS */
9743 
9744 #ifdef CONFIG_UPROBE_EVENTS
9745 PMU_FORMAT_ATTR(ref_ctr_offset, "config:32-63");
9746 
9747 static struct attribute *uprobe_attrs[] = {
9748 	&format_attr_retprobe.attr,
9749 	&format_attr_ref_ctr_offset.attr,
9750 	NULL,
9751 };
9752 
9753 static struct attribute_group uprobe_format_group = {
9754 	.name = "format",
9755 	.attrs = uprobe_attrs,
9756 };
9757 
9758 static const struct attribute_group *uprobe_attr_groups[] = {
9759 	&uprobe_format_group,
9760 	NULL,
9761 };
9762 
9763 static int perf_uprobe_event_init(struct perf_event *event);
9764 static struct pmu perf_uprobe = {
9765 	.task_ctx_nr	= perf_sw_context,
9766 	.event_init	= perf_uprobe_event_init,
9767 	.add		= perf_trace_add,
9768 	.del		= perf_trace_del,
9769 	.start		= perf_swevent_start,
9770 	.stop		= perf_swevent_stop,
9771 	.read		= perf_swevent_read,
9772 	.attr_groups	= uprobe_attr_groups,
9773 };
9774 
perf_uprobe_event_init(struct perf_event * event)9775 static int perf_uprobe_event_init(struct perf_event *event)
9776 {
9777 	int err;
9778 	unsigned long ref_ctr_offset;
9779 	bool is_retprobe;
9780 
9781 	if (event->attr.type != perf_uprobe.type)
9782 		return -ENOENT;
9783 
9784 	if (!perfmon_capable())
9785 		return -EACCES;
9786 
9787 	/*
9788 	 * no branch sampling for probe events
9789 	 */
9790 	if (has_branch_stack(event))
9791 		return -EOPNOTSUPP;
9792 
9793 	is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
9794 	ref_ctr_offset = event->attr.config >> PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
9795 	err = perf_uprobe_init(event, ref_ctr_offset, is_retprobe);
9796 	if (err)
9797 		return err;
9798 
9799 	event->destroy = perf_uprobe_destroy;
9800 
9801 	return 0;
9802 }
9803 #endif /* CONFIG_UPROBE_EVENTS */
9804 
perf_tp_register(void)9805 static inline void perf_tp_register(void)
9806 {
9807 	perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
9808 #ifdef CONFIG_KPROBE_EVENTS
9809 	perf_pmu_register(&perf_kprobe, "kprobe", -1);
9810 #endif
9811 #ifdef CONFIG_UPROBE_EVENTS
9812 	perf_pmu_register(&perf_uprobe, "uprobe", -1);
9813 #endif
9814 }
9815 
perf_event_free_filter(struct perf_event * event)9816 static void perf_event_free_filter(struct perf_event *event)
9817 {
9818 	ftrace_profile_free_filter(event);
9819 }
9820 
9821 #ifdef CONFIG_BPF_SYSCALL
bpf_overflow_handler(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)9822 static void bpf_overflow_handler(struct perf_event *event,
9823 				 struct perf_sample_data *data,
9824 				 struct pt_regs *regs)
9825 {
9826 	struct bpf_perf_event_data_kern ctx = {
9827 		.data = data,
9828 		.event = event,
9829 	};
9830 	int ret = 0;
9831 
9832 	ctx.regs = perf_arch_bpf_user_pt_regs(regs);
9833 	if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1))
9834 		goto out;
9835 	rcu_read_lock();
9836 	ret = BPF_PROG_RUN(event->prog, &ctx);
9837 	rcu_read_unlock();
9838 out:
9839 	__this_cpu_dec(bpf_prog_active);
9840 	if (!ret)
9841 		return;
9842 
9843 	event->orig_overflow_handler(event, data, regs);
9844 }
9845 
perf_event_set_bpf_handler(struct perf_event * event,u32 prog_fd)9846 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
9847 {
9848 	struct bpf_prog *prog;
9849 
9850 	if (event->overflow_handler_context)
9851 		/* hw breakpoint or kernel counter */
9852 		return -EINVAL;
9853 
9854 	if (event->prog)
9855 		return -EEXIST;
9856 
9857 	prog = bpf_prog_get_type(prog_fd, BPF_PROG_TYPE_PERF_EVENT);
9858 	if (IS_ERR(prog))
9859 		return PTR_ERR(prog);
9860 
9861 	if (event->attr.precise_ip &&
9862 	    prog->call_get_stack &&
9863 	    (!(event->attr.sample_type & __PERF_SAMPLE_CALLCHAIN_EARLY) ||
9864 	     event->attr.exclude_callchain_kernel ||
9865 	     event->attr.exclude_callchain_user)) {
9866 		/*
9867 		 * On perf_event with precise_ip, calling bpf_get_stack()
9868 		 * may trigger unwinder warnings and occasional crashes.
9869 		 * bpf_get_[stack|stackid] works around this issue by using
9870 		 * callchain attached to perf_sample_data. If the
9871 		 * perf_event does not full (kernel and user) callchain
9872 		 * attached to perf_sample_data, do not allow attaching BPF
9873 		 * program that calls bpf_get_[stack|stackid].
9874 		 */
9875 		bpf_prog_put(prog);
9876 		return -EPROTO;
9877 	}
9878 
9879 	event->prog = prog;
9880 	event->orig_overflow_handler = READ_ONCE(event->overflow_handler);
9881 	WRITE_ONCE(event->overflow_handler, bpf_overflow_handler);
9882 	return 0;
9883 }
9884 
perf_event_free_bpf_handler(struct perf_event * event)9885 static void perf_event_free_bpf_handler(struct perf_event *event)
9886 {
9887 	struct bpf_prog *prog = event->prog;
9888 
9889 	if (!prog)
9890 		return;
9891 
9892 	WRITE_ONCE(event->overflow_handler, event->orig_overflow_handler);
9893 	event->prog = NULL;
9894 	bpf_prog_put(prog);
9895 }
9896 #else
perf_event_set_bpf_handler(struct perf_event * event,u32 prog_fd)9897 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
9898 {
9899 	return -EOPNOTSUPP;
9900 }
perf_event_free_bpf_handler(struct perf_event * event)9901 static void perf_event_free_bpf_handler(struct perf_event *event)
9902 {
9903 }
9904 #endif
9905 
9906 /*
9907  * returns true if the event is a tracepoint, or a kprobe/upprobe created
9908  * with perf_event_open()
9909  */
perf_event_is_tracing(struct perf_event * event)9910 static inline bool perf_event_is_tracing(struct perf_event *event)
9911 {
9912 	if (event->pmu == &perf_tracepoint)
9913 		return true;
9914 #ifdef CONFIG_KPROBE_EVENTS
9915 	if (event->pmu == &perf_kprobe)
9916 		return true;
9917 #endif
9918 #ifdef CONFIG_UPROBE_EVENTS
9919 	if (event->pmu == &perf_uprobe)
9920 		return true;
9921 #endif
9922 	return false;
9923 }
9924 
perf_event_set_bpf_prog(struct perf_event * event,u32 prog_fd)9925 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
9926 {
9927 	bool is_kprobe, is_tracepoint, is_syscall_tp;
9928 	struct bpf_prog *prog;
9929 	int ret;
9930 
9931 	if (!perf_event_is_tracing(event))
9932 		return perf_event_set_bpf_handler(event, prog_fd);
9933 
9934 	is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_UKPROBE;
9935 	is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT;
9936 	is_syscall_tp = is_syscall_trace_event(event->tp_event);
9937 	if (!is_kprobe && !is_tracepoint && !is_syscall_tp)
9938 		/* bpf programs can only be attached to u/kprobe or tracepoint */
9939 		return -EINVAL;
9940 
9941 	prog = bpf_prog_get(prog_fd);
9942 	if (IS_ERR(prog))
9943 		return PTR_ERR(prog);
9944 
9945 	if ((is_kprobe && prog->type != BPF_PROG_TYPE_KPROBE) ||
9946 	    (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT) ||
9947 	    (is_syscall_tp && prog->type != BPF_PROG_TYPE_TRACEPOINT)) {
9948 		/* valid fd, but invalid bpf program type */
9949 		bpf_prog_put(prog);
9950 		return -EINVAL;
9951 	}
9952 
9953 	/* Kprobe override only works for kprobes, not uprobes. */
9954 	if (prog->kprobe_override &&
9955 	    !(event->tp_event->flags & TRACE_EVENT_FL_KPROBE)) {
9956 		bpf_prog_put(prog);
9957 		return -EINVAL;
9958 	}
9959 
9960 	if (is_tracepoint || is_syscall_tp) {
9961 		int off = trace_event_get_offsets(event->tp_event);
9962 
9963 		if (prog->aux->max_ctx_offset > off) {
9964 			bpf_prog_put(prog);
9965 			return -EACCES;
9966 		}
9967 	}
9968 
9969 	ret = perf_event_attach_bpf_prog(event, prog);
9970 	if (ret)
9971 		bpf_prog_put(prog);
9972 	return ret;
9973 }
9974 
perf_event_free_bpf_prog(struct perf_event * event)9975 static void perf_event_free_bpf_prog(struct perf_event *event)
9976 {
9977 	if (!perf_event_is_tracing(event)) {
9978 		perf_event_free_bpf_handler(event);
9979 		return;
9980 	}
9981 	perf_event_detach_bpf_prog(event);
9982 }
9983 
9984 #else
9985 
perf_tp_register(void)9986 static inline void perf_tp_register(void)
9987 {
9988 }
9989 
perf_event_free_filter(struct perf_event * event)9990 static void perf_event_free_filter(struct perf_event *event)
9991 {
9992 }
9993 
perf_event_set_bpf_prog(struct perf_event * event,u32 prog_fd)9994 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
9995 {
9996 	return -ENOENT;
9997 }
9998 
perf_event_free_bpf_prog(struct perf_event * event)9999 static void perf_event_free_bpf_prog(struct perf_event *event)
10000 {
10001 }
10002 #endif /* CONFIG_EVENT_TRACING */
10003 
10004 #ifdef CONFIG_HAVE_HW_BREAKPOINT
perf_bp_event(struct perf_event * bp,void * data)10005 void perf_bp_event(struct perf_event *bp, void *data)
10006 {
10007 	struct perf_sample_data sample;
10008 	struct pt_regs *regs = data;
10009 
10010 	perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
10011 
10012 	if (!bp->hw.state && !perf_exclude_event(bp, regs))
10013 		perf_swevent_event(bp, 1, &sample, regs);
10014 }
10015 #endif
10016 
10017 /*
10018  * Allocate a new address filter
10019  */
10020 static struct perf_addr_filter *
perf_addr_filter_new(struct perf_event * event,struct list_head * filters)10021 perf_addr_filter_new(struct perf_event *event, struct list_head *filters)
10022 {
10023 	int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu);
10024 	struct perf_addr_filter *filter;
10025 
10026 	filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node);
10027 	if (!filter)
10028 		return NULL;
10029 
10030 	INIT_LIST_HEAD(&filter->entry);
10031 	list_add_tail(&filter->entry, filters);
10032 
10033 	return filter;
10034 }
10035 
free_filters_list(struct list_head * filters)10036 static void free_filters_list(struct list_head *filters)
10037 {
10038 	struct perf_addr_filter *filter, *iter;
10039 
10040 	list_for_each_entry_safe(filter, iter, filters, entry) {
10041 		path_put(&filter->path);
10042 		list_del(&filter->entry);
10043 		kfree(filter);
10044 	}
10045 }
10046 
10047 /*
10048  * Free existing address filters and optionally install new ones
10049  */
perf_addr_filters_splice(struct perf_event * event,struct list_head * head)10050 static void perf_addr_filters_splice(struct perf_event *event,
10051 				     struct list_head *head)
10052 {
10053 	unsigned long flags;
10054 	LIST_HEAD(list);
10055 
10056 	if (!has_addr_filter(event))
10057 		return;
10058 
10059 	/* don't bother with children, they don't have their own filters */
10060 	if (event->parent)
10061 		return;
10062 
10063 	raw_spin_lock_irqsave(&event->addr_filters.lock, flags);
10064 
10065 	list_splice_init(&event->addr_filters.list, &list);
10066 	if (head)
10067 		list_splice(head, &event->addr_filters.list);
10068 
10069 	raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags);
10070 
10071 	free_filters_list(&list);
10072 }
10073 
10074 /*
10075  * Scan through mm's vmas and see if one of them matches the
10076  * @filter; if so, adjust filter's address range.
10077  * Called with mm::mmap_lock down for reading.
10078  */
perf_addr_filter_apply(struct perf_addr_filter * filter,struct mm_struct * mm,struct perf_addr_filter_range * fr)10079 static void perf_addr_filter_apply(struct perf_addr_filter *filter,
10080 				   struct mm_struct *mm,
10081 				   struct perf_addr_filter_range *fr)
10082 {
10083 	struct vm_area_struct *vma;
10084 
10085 	for (vma = mm->mmap; vma; vma = vma->vm_next) {
10086 		if (!vma->vm_file)
10087 			continue;
10088 
10089 		if (perf_addr_filter_vma_adjust(filter, vma, fr))
10090 			return;
10091 	}
10092 }
10093 
10094 /*
10095  * Update event's address range filters based on the
10096  * task's existing mappings, if any.
10097  */
perf_event_addr_filters_apply(struct perf_event * event)10098 static void perf_event_addr_filters_apply(struct perf_event *event)
10099 {
10100 	struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
10101 	struct task_struct *task = READ_ONCE(event->ctx->task);
10102 	struct perf_addr_filter *filter;
10103 	struct mm_struct *mm = NULL;
10104 	unsigned int count = 0;
10105 	unsigned long flags;
10106 
10107 	/*
10108 	 * We may observe TASK_TOMBSTONE, which means that the event tear-down
10109 	 * will stop on the parent's child_mutex that our caller is also holding
10110 	 */
10111 	if (task == TASK_TOMBSTONE)
10112 		return;
10113 
10114 	if (ifh->nr_file_filters) {
10115 		mm = get_task_mm(task);
10116 		if (!mm)
10117 			goto restart;
10118 
10119 		mmap_read_lock(mm);
10120 	}
10121 
10122 	raw_spin_lock_irqsave(&ifh->lock, flags);
10123 	list_for_each_entry(filter, &ifh->list, entry) {
10124 		if (filter->path.dentry) {
10125 			/*
10126 			 * Adjust base offset if the filter is associated to a
10127 			 * binary that needs to be mapped:
10128 			 */
10129 			event->addr_filter_ranges[count].start = 0;
10130 			event->addr_filter_ranges[count].size = 0;
10131 
10132 			perf_addr_filter_apply(filter, mm, &event->addr_filter_ranges[count]);
10133 		} else {
10134 			event->addr_filter_ranges[count].start = filter->offset;
10135 			event->addr_filter_ranges[count].size  = filter->size;
10136 		}
10137 
10138 		count++;
10139 	}
10140 
10141 	event->addr_filters_gen++;
10142 	raw_spin_unlock_irqrestore(&ifh->lock, flags);
10143 
10144 	if (ifh->nr_file_filters) {
10145 		mmap_read_unlock(mm);
10146 
10147 		mmput(mm);
10148 	}
10149 
10150 restart:
10151 	perf_event_stop(event, 1);
10152 }
10153 
10154 /*
10155  * Address range filtering: limiting the data to certain
10156  * instruction address ranges. Filters are ioctl()ed to us from
10157  * userspace as ascii strings.
10158  *
10159  * Filter string format:
10160  *
10161  * ACTION RANGE_SPEC
10162  * where ACTION is one of the
10163  *  * "filter": limit the trace to this region
10164  *  * "start": start tracing from this address
10165  *  * "stop": stop tracing at this address/region;
10166  * RANGE_SPEC is
10167  *  * for kernel addresses: <start address>[/<size>]
10168  *  * for object files:     <start address>[/<size>]@</path/to/object/file>
10169  *
10170  * if <size> is not specified or is zero, the range is treated as a single
10171  * address; not valid for ACTION=="filter".
10172  */
10173 enum {
10174 	IF_ACT_NONE = -1,
10175 	IF_ACT_FILTER,
10176 	IF_ACT_START,
10177 	IF_ACT_STOP,
10178 	IF_SRC_FILE,
10179 	IF_SRC_KERNEL,
10180 	IF_SRC_FILEADDR,
10181 	IF_SRC_KERNELADDR,
10182 };
10183 
10184 enum {
10185 	IF_STATE_ACTION = 0,
10186 	IF_STATE_SOURCE,
10187 	IF_STATE_END,
10188 };
10189 
10190 static const match_table_t if_tokens = {
10191 	{ IF_ACT_FILTER,	"filter" },
10192 	{ IF_ACT_START,		"start" },
10193 	{ IF_ACT_STOP,		"stop" },
10194 	{ IF_SRC_FILE,		"%u/%u@%s" },
10195 	{ IF_SRC_KERNEL,	"%u/%u" },
10196 	{ IF_SRC_FILEADDR,	"%u@%s" },
10197 	{ IF_SRC_KERNELADDR,	"%u" },
10198 	{ IF_ACT_NONE,		NULL },
10199 };
10200 
10201 /*
10202  * Address filter string parser
10203  */
10204 static int
perf_event_parse_addr_filter(struct perf_event * event,char * fstr,struct list_head * filters)10205 perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
10206 			     struct list_head *filters)
10207 {
10208 	struct perf_addr_filter *filter = NULL;
10209 	char *start, *orig, *filename = NULL;
10210 	substring_t args[MAX_OPT_ARGS];
10211 	int state = IF_STATE_ACTION, token;
10212 	unsigned int kernel = 0;
10213 	int ret = -EINVAL;
10214 
10215 	orig = fstr = kstrdup(fstr, GFP_KERNEL);
10216 	if (!fstr)
10217 		return -ENOMEM;
10218 
10219 	while ((start = strsep(&fstr, " ,\n")) != NULL) {
10220 		static const enum perf_addr_filter_action_t actions[] = {
10221 			[IF_ACT_FILTER]	= PERF_ADDR_FILTER_ACTION_FILTER,
10222 			[IF_ACT_START]	= PERF_ADDR_FILTER_ACTION_START,
10223 			[IF_ACT_STOP]	= PERF_ADDR_FILTER_ACTION_STOP,
10224 		};
10225 		ret = -EINVAL;
10226 
10227 		if (!*start)
10228 			continue;
10229 
10230 		/* filter definition begins */
10231 		if (state == IF_STATE_ACTION) {
10232 			filter = perf_addr_filter_new(event, filters);
10233 			if (!filter)
10234 				goto fail;
10235 		}
10236 
10237 		token = match_token(start, if_tokens, args);
10238 		switch (token) {
10239 		case IF_ACT_FILTER:
10240 		case IF_ACT_START:
10241 		case IF_ACT_STOP:
10242 			if (state != IF_STATE_ACTION)
10243 				goto fail;
10244 
10245 			filter->action = actions[token];
10246 			state = IF_STATE_SOURCE;
10247 			break;
10248 
10249 		case IF_SRC_KERNELADDR:
10250 		case IF_SRC_KERNEL:
10251 			kernel = 1;
10252 			fallthrough;
10253 
10254 		case IF_SRC_FILEADDR:
10255 		case IF_SRC_FILE:
10256 			if (state != IF_STATE_SOURCE)
10257 				goto fail;
10258 
10259 			*args[0].to = 0;
10260 			ret = kstrtoul(args[0].from, 0, &filter->offset);
10261 			if (ret)
10262 				goto fail;
10263 
10264 			if (token == IF_SRC_KERNEL || token == IF_SRC_FILE) {
10265 				*args[1].to = 0;
10266 				ret = kstrtoul(args[1].from, 0, &filter->size);
10267 				if (ret)
10268 					goto fail;
10269 			}
10270 
10271 			if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) {
10272 				int fpos = token == IF_SRC_FILE ? 2 : 1;
10273 
10274 				kfree(filename);
10275 				filename = match_strdup(&args[fpos]);
10276 				if (!filename) {
10277 					ret = -ENOMEM;
10278 					goto fail;
10279 				}
10280 			}
10281 
10282 			state = IF_STATE_END;
10283 			break;
10284 
10285 		default:
10286 			goto fail;
10287 		}
10288 
10289 		/*
10290 		 * Filter definition is fully parsed, validate and install it.
10291 		 * Make sure that it doesn't contradict itself or the event's
10292 		 * attribute.
10293 		 */
10294 		if (state == IF_STATE_END) {
10295 			ret = -EINVAL;
10296 			if (kernel && event->attr.exclude_kernel)
10297 				goto fail;
10298 
10299 			/*
10300 			 * ACTION "filter" must have a non-zero length region
10301 			 * specified.
10302 			 */
10303 			if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER &&
10304 			    !filter->size)
10305 				goto fail;
10306 
10307 			if (!kernel) {
10308 				if (!filename)
10309 					goto fail;
10310 
10311 				/*
10312 				 * For now, we only support file-based filters
10313 				 * in per-task events; doing so for CPU-wide
10314 				 * events requires additional context switching
10315 				 * trickery, since same object code will be
10316 				 * mapped at different virtual addresses in
10317 				 * different processes.
10318 				 */
10319 				ret = -EOPNOTSUPP;
10320 				if (!event->ctx->task)
10321 					goto fail;
10322 
10323 				/* look up the path and grab its inode */
10324 				ret = kern_path(filename, LOOKUP_FOLLOW,
10325 						&filter->path);
10326 				if (ret)
10327 					goto fail;
10328 
10329 				ret = -EINVAL;
10330 				if (!filter->path.dentry ||
10331 				    !S_ISREG(d_inode(filter->path.dentry)
10332 					     ->i_mode))
10333 					goto fail;
10334 
10335 				event->addr_filters.nr_file_filters++;
10336 			}
10337 
10338 			/* ready to consume more filters */
10339 			kfree(filename);
10340 			filename = NULL;
10341 			state = IF_STATE_ACTION;
10342 			filter = NULL;
10343 			kernel = 0;
10344 		}
10345 	}
10346 
10347 	if (state != IF_STATE_ACTION)
10348 		goto fail;
10349 
10350 	kfree(filename);
10351 	kfree(orig);
10352 
10353 	return 0;
10354 
10355 fail:
10356 	kfree(filename);
10357 	free_filters_list(filters);
10358 	kfree(orig);
10359 
10360 	return ret;
10361 }
10362 
10363 static int
perf_event_set_addr_filter(struct perf_event * event,char * filter_str)10364 perf_event_set_addr_filter(struct perf_event *event, char *filter_str)
10365 {
10366 	LIST_HEAD(filters);
10367 	int ret;
10368 
10369 	/*
10370 	 * Since this is called in perf_ioctl() path, we're already holding
10371 	 * ctx::mutex.
10372 	 */
10373 	lockdep_assert_held(&event->ctx->mutex);
10374 
10375 	if (WARN_ON_ONCE(event->parent))
10376 		return -EINVAL;
10377 
10378 	ret = perf_event_parse_addr_filter(event, filter_str, &filters);
10379 	if (ret)
10380 		goto fail_clear_files;
10381 
10382 	ret = event->pmu->addr_filters_validate(&filters);
10383 	if (ret)
10384 		goto fail_free_filters;
10385 
10386 	/* remove existing filters, if any */
10387 	perf_addr_filters_splice(event, &filters);
10388 
10389 	/* install new filters */
10390 	perf_event_for_each_child(event, perf_event_addr_filters_apply);
10391 
10392 	return ret;
10393 
10394 fail_free_filters:
10395 	free_filters_list(&filters);
10396 
10397 fail_clear_files:
10398 	event->addr_filters.nr_file_filters = 0;
10399 
10400 	return ret;
10401 }
10402 
perf_event_set_filter(struct perf_event * event,void __user * arg)10403 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
10404 {
10405 	int ret = -EINVAL;
10406 	char *filter_str;
10407 
10408 	filter_str = strndup_user(arg, PAGE_SIZE);
10409 	if (IS_ERR(filter_str))
10410 		return PTR_ERR(filter_str);
10411 
10412 #ifdef CONFIG_EVENT_TRACING
10413 	if (perf_event_is_tracing(event)) {
10414 		struct perf_event_context *ctx = event->ctx;
10415 
10416 		/*
10417 		 * Beware, here be dragons!!
10418 		 *
10419 		 * the tracepoint muck will deadlock against ctx->mutex, but
10420 		 * the tracepoint stuff does not actually need it. So
10421 		 * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we
10422 		 * already have a reference on ctx.
10423 		 *
10424 		 * This can result in event getting moved to a different ctx,
10425 		 * but that does not affect the tracepoint state.
10426 		 */
10427 		mutex_unlock(&ctx->mutex);
10428 		ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
10429 		mutex_lock(&ctx->mutex);
10430 	} else
10431 #endif
10432 	if (has_addr_filter(event))
10433 		ret = perf_event_set_addr_filter(event, filter_str);
10434 
10435 	kfree(filter_str);
10436 	return ret;
10437 }
10438 
10439 /*
10440  * hrtimer based swevent callback
10441  */
10442 
perf_swevent_hrtimer(struct hrtimer * hrtimer)10443 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
10444 {
10445 	enum hrtimer_restart ret = HRTIMER_RESTART;
10446 	struct perf_sample_data data;
10447 	struct pt_regs *regs;
10448 	struct perf_event *event;
10449 	u64 period;
10450 
10451 	event = container_of(hrtimer, struct perf_event, hw.hrtimer);
10452 
10453 	if (event->state != PERF_EVENT_STATE_ACTIVE)
10454 		return HRTIMER_NORESTART;
10455 
10456 	event->pmu->read(event);
10457 
10458 	perf_sample_data_init(&data, 0, event->hw.last_period);
10459 	regs = get_irq_regs();
10460 
10461 	if (regs && !perf_exclude_event(event, regs)) {
10462 		if (!(event->attr.exclude_idle && is_idle_task(current)))
10463 			if (__perf_event_overflow(event, 1, &data, regs))
10464 				ret = HRTIMER_NORESTART;
10465 	}
10466 
10467 	period = max_t(u64, 10000, event->hw.sample_period);
10468 	hrtimer_forward_now(hrtimer, ns_to_ktime(period));
10469 
10470 	return ret;
10471 }
10472 
perf_swevent_start_hrtimer(struct perf_event * event)10473 static void perf_swevent_start_hrtimer(struct perf_event *event)
10474 {
10475 	struct hw_perf_event *hwc = &event->hw;
10476 	s64 period;
10477 
10478 	if (!is_sampling_event(event))
10479 		return;
10480 
10481 	period = local64_read(&hwc->period_left);
10482 	if (period) {
10483 		if (period < 0)
10484 			period = 10000;
10485 
10486 		local64_set(&hwc->period_left, 0);
10487 	} else {
10488 		period = max_t(u64, 10000, hwc->sample_period);
10489 	}
10490 	hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
10491 		      HRTIMER_MODE_REL_PINNED_HARD);
10492 }
10493 
perf_swevent_cancel_hrtimer(struct perf_event * event)10494 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
10495 {
10496 	struct hw_perf_event *hwc = &event->hw;
10497 
10498 	if (is_sampling_event(event)) {
10499 		ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
10500 		local64_set(&hwc->period_left, ktime_to_ns(remaining));
10501 
10502 		hrtimer_cancel(&hwc->hrtimer);
10503 	}
10504 }
10505 
perf_swevent_init_hrtimer(struct perf_event * event)10506 static void perf_swevent_init_hrtimer(struct perf_event *event)
10507 {
10508 	struct hw_perf_event *hwc = &event->hw;
10509 
10510 	if (!is_sampling_event(event))
10511 		return;
10512 
10513 	hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
10514 	hwc->hrtimer.function = perf_swevent_hrtimer;
10515 
10516 	/*
10517 	 * Since hrtimers have a fixed rate, we can do a static freq->period
10518 	 * mapping and avoid the whole period adjust feedback stuff.
10519 	 */
10520 	if (event->attr.freq) {
10521 		long freq = event->attr.sample_freq;
10522 
10523 		event->attr.sample_period = NSEC_PER_SEC / freq;
10524 		hwc->sample_period = event->attr.sample_period;
10525 		local64_set(&hwc->period_left, hwc->sample_period);
10526 		hwc->last_period = hwc->sample_period;
10527 		event->attr.freq = 0;
10528 	}
10529 }
10530 
10531 /*
10532  * Software event: cpu wall time clock
10533  */
10534 
cpu_clock_event_update(struct perf_event * event)10535 static void cpu_clock_event_update(struct perf_event *event)
10536 {
10537 	s64 prev;
10538 	u64 now;
10539 
10540 	now = local_clock();
10541 	prev = local64_xchg(&event->hw.prev_count, now);
10542 	local64_add(now - prev, &event->count);
10543 }
10544 
cpu_clock_event_start(struct perf_event * event,int flags)10545 static void cpu_clock_event_start(struct perf_event *event, int flags)
10546 {
10547 	local64_set(&event->hw.prev_count, local_clock());
10548 	perf_swevent_start_hrtimer(event);
10549 }
10550 
cpu_clock_event_stop(struct perf_event * event,int flags)10551 static void cpu_clock_event_stop(struct perf_event *event, int flags)
10552 {
10553 	perf_swevent_cancel_hrtimer(event);
10554 	cpu_clock_event_update(event);
10555 }
10556 
cpu_clock_event_add(struct perf_event * event,int flags)10557 static int cpu_clock_event_add(struct perf_event *event, int flags)
10558 {
10559 	if (flags & PERF_EF_START)
10560 		cpu_clock_event_start(event, flags);
10561 	perf_event_update_userpage(event);
10562 
10563 	return 0;
10564 }
10565 
cpu_clock_event_del(struct perf_event * event,int flags)10566 static void cpu_clock_event_del(struct perf_event *event, int flags)
10567 {
10568 	cpu_clock_event_stop(event, flags);
10569 }
10570 
cpu_clock_event_read(struct perf_event * event)10571 static void cpu_clock_event_read(struct perf_event *event)
10572 {
10573 	cpu_clock_event_update(event);
10574 }
10575 
cpu_clock_event_init(struct perf_event * event)10576 static int cpu_clock_event_init(struct perf_event *event)
10577 {
10578 	if (event->attr.type != PERF_TYPE_SOFTWARE)
10579 		return -ENOENT;
10580 
10581 	if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
10582 		return -ENOENT;
10583 
10584 	/*
10585 	 * no branch sampling for software events
10586 	 */
10587 	if (has_branch_stack(event))
10588 		return -EOPNOTSUPP;
10589 
10590 	perf_swevent_init_hrtimer(event);
10591 
10592 	return 0;
10593 }
10594 
10595 static struct pmu perf_cpu_clock = {
10596 	.task_ctx_nr	= perf_sw_context,
10597 
10598 	.capabilities	= PERF_PMU_CAP_NO_NMI,
10599 
10600 	.event_init	= cpu_clock_event_init,
10601 	.add		= cpu_clock_event_add,
10602 	.del		= cpu_clock_event_del,
10603 	.start		= cpu_clock_event_start,
10604 	.stop		= cpu_clock_event_stop,
10605 	.read		= cpu_clock_event_read,
10606 };
10607 
10608 /*
10609  * Software event: task time clock
10610  */
10611 
task_clock_event_update(struct perf_event * event,u64 now)10612 static void task_clock_event_update(struct perf_event *event, u64 now)
10613 {
10614 	u64 prev;
10615 	s64 delta;
10616 
10617 	prev = local64_xchg(&event->hw.prev_count, now);
10618 	delta = now - prev;
10619 	local64_add(delta, &event->count);
10620 }
10621 
task_clock_event_start(struct perf_event * event,int flags)10622 static void task_clock_event_start(struct perf_event *event, int flags)
10623 {
10624 	local64_set(&event->hw.prev_count, event->ctx->time);
10625 	perf_swevent_start_hrtimer(event);
10626 }
10627 
task_clock_event_stop(struct perf_event * event,int flags)10628 static void task_clock_event_stop(struct perf_event *event, int flags)
10629 {
10630 	perf_swevent_cancel_hrtimer(event);
10631 	task_clock_event_update(event, event->ctx->time);
10632 }
10633 
task_clock_event_add(struct perf_event * event,int flags)10634 static int task_clock_event_add(struct perf_event *event, int flags)
10635 {
10636 	if (flags & PERF_EF_START)
10637 		task_clock_event_start(event, flags);
10638 	perf_event_update_userpage(event);
10639 
10640 	return 0;
10641 }
10642 
task_clock_event_del(struct perf_event * event,int flags)10643 static void task_clock_event_del(struct perf_event *event, int flags)
10644 {
10645 	task_clock_event_stop(event, PERF_EF_UPDATE);
10646 }
10647 
task_clock_event_read(struct perf_event * event)10648 static void task_clock_event_read(struct perf_event *event)
10649 {
10650 	u64 now = perf_clock();
10651 	u64 delta = now - event->ctx->timestamp;
10652 	u64 time = event->ctx->time + delta;
10653 
10654 	task_clock_event_update(event, time);
10655 }
10656 
task_clock_event_init(struct perf_event * event)10657 static int task_clock_event_init(struct perf_event *event)
10658 {
10659 	if (event->attr.type != PERF_TYPE_SOFTWARE)
10660 		return -ENOENT;
10661 
10662 	if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
10663 		return -ENOENT;
10664 
10665 	/*
10666 	 * no branch sampling for software events
10667 	 */
10668 	if (has_branch_stack(event))
10669 		return -EOPNOTSUPP;
10670 
10671 	perf_swevent_init_hrtimer(event);
10672 
10673 	return 0;
10674 }
10675 
10676 static struct pmu perf_task_clock = {
10677 	.task_ctx_nr	= perf_sw_context,
10678 
10679 	.capabilities	= PERF_PMU_CAP_NO_NMI,
10680 
10681 	.event_init	= task_clock_event_init,
10682 	.add		= task_clock_event_add,
10683 	.del		= task_clock_event_del,
10684 	.start		= task_clock_event_start,
10685 	.stop		= task_clock_event_stop,
10686 	.read		= task_clock_event_read,
10687 };
10688 
perf_pmu_nop_void(struct pmu * pmu)10689 static void perf_pmu_nop_void(struct pmu *pmu)
10690 {
10691 }
10692 
perf_pmu_nop_txn(struct pmu * pmu,unsigned int flags)10693 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
10694 {
10695 }
10696 
perf_pmu_nop_int(struct pmu * pmu)10697 static int perf_pmu_nop_int(struct pmu *pmu)
10698 {
10699 	return 0;
10700 }
10701 
perf_event_nop_int(struct perf_event * event,u64 value)10702 static int perf_event_nop_int(struct perf_event *event, u64 value)
10703 {
10704 	return 0;
10705 }
10706 
10707 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
10708 
perf_pmu_start_txn(struct pmu * pmu,unsigned int flags)10709 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
10710 {
10711 	__this_cpu_write(nop_txn_flags, flags);
10712 
10713 	if (flags & ~PERF_PMU_TXN_ADD)
10714 		return;
10715 
10716 	perf_pmu_disable(pmu);
10717 }
10718 
perf_pmu_commit_txn(struct pmu * pmu)10719 static int perf_pmu_commit_txn(struct pmu *pmu)
10720 {
10721 	unsigned int flags = __this_cpu_read(nop_txn_flags);
10722 
10723 	__this_cpu_write(nop_txn_flags, 0);
10724 
10725 	if (flags & ~PERF_PMU_TXN_ADD)
10726 		return 0;
10727 
10728 	perf_pmu_enable(pmu);
10729 	return 0;
10730 }
10731 
perf_pmu_cancel_txn(struct pmu * pmu)10732 static void perf_pmu_cancel_txn(struct pmu *pmu)
10733 {
10734 	unsigned int flags =  __this_cpu_read(nop_txn_flags);
10735 
10736 	__this_cpu_write(nop_txn_flags, 0);
10737 
10738 	if (flags & ~PERF_PMU_TXN_ADD)
10739 		return;
10740 
10741 	perf_pmu_enable(pmu);
10742 }
10743 
perf_event_idx_default(struct perf_event * event)10744 static int perf_event_idx_default(struct perf_event *event)
10745 {
10746 	return 0;
10747 }
10748 
10749 /*
10750  * Ensures all contexts with the same task_ctx_nr have the same
10751  * pmu_cpu_context too.
10752  */
find_pmu_context(int ctxn)10753 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
10754 {
10755 	struct pmu *pmu;
10756 
10757 	if (ctxn < 0)
10758 		return NULL;
10759 
10760 	list_for_each_entry(pmu, &pmus, entry) {
10761 		if (pmu->task_ctx_nr == ctxn)
10762 			return pmu->pmu_cpu_context;
10763 	}
10764 
10765 	return NULL;
10766 }
10767 
free_pmu_context(struct pmu * pmu)10768 static void free_pmu_context(struct pmu *pmu)
10769 {
10770 	/*
10771 	 * Static contexts such as perf_sw_context have a global lifetime
10772 	 * and may be shared between different PMUs. Avoid freeing them
10773 	 * when a single PMU is going away.
10774 	 */
10775 	if (pmu->task_ctx_nr > perf_invalid_context)
10776 		return;
10777 
10778 	free_percpu(pmu->pmu_cpu_context);
10779 }
10780 
10781 /*
10782  * Let userspace know that this PMU supports address range filtering:
10783  */
nr_addr_filters_show(struct device * dev,struct device_attribute * attr,char * page)10784 static ssize_t nr_addr_filters_show(struct device *dev,
10785 				    struct device_attribute *attr,
10786 				    char *page)
10787 {
10788 	struct pmu *pmu = dev_get_drvdata(dev);
10789 
10790 	return snprintf(page, PAGE_SIZE - 1, "%d\n", pmu->nr_addr_filters);
10791 }
10792 DEVICE_ATTR_RO(nr_addr_filters);
10793 
10794 static struct idr pmu_idr;
10795 
10796 static ssize_t
type_show(struct device * dev,struct device_attribute * attr,char * page)10797 type_show(struct device *dev, struct device_attribute *attr, char *page)
10798 {
10799 	struct pmu *pmu = dev_get_drvdata(dev);
10800 
10801 	return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
10802 }
10803 static DEVICE_ATTR_RO(type);
10804 
10805 static ssize_t
perf_event_mux_interval_ms_show(struct device * dev,struct device_attribute * attr,char * page)10806 perf_event_mux_interval_ms_show(struct device *dev,
10807 				struct device_attribute *attr,
10808 				char *page)
10809 {
10810 	struct pmu *pmu = dev_get_drvdata(dev);
10811 
10812 	return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
10813 }
10814 
10815 static DEFINE_MUTEX(mux_interval_mutex);
10816 
10817 static ssize_t
perf_event_mux_interval_ms_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)10818 perf_event_mux_interval_ms_store(struct device *dev,
10819 				 struct device_attribute *attr,
10820 				 const char *buf, size_t count)
10821 {
10822 	struct pmu *pmu = dev_get_drvdata(dev);
10823 	int timer, cpu, ret;
10824 
10825 	ret = kstrtoint(buf, 0, &timer);
10826 	if (ret)
10827 		return ret;
10828 
10829 	if (timer < 1)
10830 		return -EINVAL;
10831 
10832 	/* same value, noting to do */
10833 	if (timer == pmu->hrtimer_interval_ms)
10834 		return count;
10835 
10836 	mutex_lock(&mux_interval_mutex);
10837 	pmu->hrtimer_interval_ms = timer;
10838 
10839 	/* update all cpuctx for this PMU */
10840 	cpus_read_lock();
10841 	for_each_online_cpu(cpu) {
10842 		struct perf_cpu_context *cpuctx;
10843 		cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
10844 		cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
10845 
10846 		cpu_function_call(cpu, perf_mux_hrtimer_restart_ipi, cpuctx);
10847 	}
10848 	cpus_read_unlock();
10849 	mutex_unlock(&mux_interval_mutex);
10850 
10851 	return count;
10852 }
10853 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
10854 
10855 static struct attribute *pmu_dev_attrs[] = {
10856 	&dev_attr_type.attr,
10857 	&dev_attr_perf_event_mux_interval_ms.attr,
10858 	NULL,
10859 };
10860 ATTRIBUTE_GROUPS(pmu_dev);
10861 
10862 static int pmu_bus_running;
10863 static struct bus_type pmu_bus = {
10864 	.name		= "event_source",
10865 	.dev_groups	= pmu_dev_groups,
10866 };
10867 
pmu_dev_release(struct device * dev)10868 static void pmu_dev_release(struct device *dev)
10869 {
10870 	kfree(dev);
10871 }
10872 
pmu_dev_alloc(struct pmu * pmu)10873 static int pmu_dev_alloc(struct pmu *pmu)
10874 {
10875 	int ret = -ENOMEM;
10876 
10877 	pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
10878 	if (!pmu->dev)
10879 		goto out;
10880 
10881 	pmu->dev->groups = pmu->attr_groups;
10882 	device_initialize(pmu->dev);
10883 
10884 	dev_set_drvdata(pmu->dev, pmu);
10885 	pmu->dev->bus = &pmu_bus;
10886 	pmu->dev->release = pmu_dev_release;
10887 
10888 	ret = dev_set_name(pmu->dev, "%s", pmu->name);
10889 	if (ret)
10890 		goto free_dev;
10891 
10892 	ret = device_add(pmu->dev);
10893 	if (ret)
10894 		goto free_dev;
10895 
10896 	/* For PMUs with address filters, throw in an extra attribute: */
10897 	if (pmu->nr_addr_filters)
10898 		ret = device_create_file(pmu->dev, &dev_attr_nr_addr_filters);
10899 
10900 	if (ret)
10901 		goto del_dev;
10902 
10903 	if (pmu->attr_update)
10904 		ret = sysfs_update_groups(&pmu->dev->kobj, pmu->attr_update);
10905 
10906 	if (ret)
10907 		goto del_dev;
10908 
10909 out:
10910 	return ret;
10911 
10912 del_dev:
10913 	device_del(pmu->dev);
10914 
10915 free_dev:
10916 	put_device(pmu->dev);
10917 	goto out;
10918 }
10919 
10920 static struct lock_class_key cpuctx_mutex;
10921 static struct lock_class_key cpuctx_lock;
10922 
perf_pmu_register(struct pmu * pmu,const char * name,int type)10923 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
10924 {
10925 	int cpu, ret, max = PERF_TYPE_MAX;
10926 
10927 	mutex_lock(&pmus_lock);
10928 	ret = -ENOMEM;
10929 	pmu->pmu_disable_count = alloc_percpu(int);
10930 	if (!pmu->pmu_disable_count)
10931 		goto unlock;
10932 
10933 	pmu->type = -1;
10934 	if (!name)
10935 		goto skip_type;
10936 	pmu->name = name;
10937 
10938 	if (type != PERF_TYPE_SOFTWARE) {
10939 		if (type >= 0)
10940 			max = type;
10941 
10942 		ret = idr_alloc(&pmu_idr, pmu, max, 0, GFP_KERNEL);
10943 		if (ret < 0)
10944 			goto free_pdc;
10945 
10946 		WARN_ON(type >= 0 && ret != type);
10947 
10948 		type = ret;
10949 	}
10950 	pmu->type = type;
10951 
10952 	if (pmu_bus_running) {
10953 		ret = pmu_dev_alloc(pmu);
10954 		if (ret)
10955 			goto free_idr;
10956 	}
10957 
10958 skip_type:
10959 	if (pmu->task_ctx_nr == perf_hw_context) {
10960 		static int hw_context_taken = 0;
10961 
10962 		/*
10963 		 * Other than systems with heterogeneous CPUs, it never makes
10964 		 * sense for two PMUs to share perf_hw_context. PMUs which are
10965 		 * uncore must use perf_invalid_context.
10966 		 */
10967 		if (WARN_ON_ONCE(hw_context_taken &&
10968 		    !(pmu->capabilities & PERF_PMU_CAP_HETEROGENEOUS_CPUS)))
10969 			pmu->task_ctx_nr = perf_invalid_context;
10970 
10971 		hw_context_taken = 1;
10972 	}
10973 
10974 	pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
10975 	if (pmu->pmu_cpu_context)
10976 		goto got_cpu_context;
10977 
10978 	ret = -ENOMEM;
10979 	pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
10980 	if (!pmu->pmu_cpu_context)
10981 		goto free_dev;
10982 
10983 	for_each_possible_cpu(cpu) {
10984 		struct perf_cpu_context *cpuctx;
10985 
10986 		cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
10987 		__perf_event_init_context(&cpuctx->ctx);
10988 		lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
10989 		lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
10990 		cpuctx->ctx.pmu = pmu;
10991 		cpuctx->online = cpumask_test_cpu(cpu, perf_online_mask);
10992 
10993 		__perf_mux_hrtimer_init(cpuctx, cpu);
10994 
10995 		cpuctx->heap_size = ARRAY_SIZE(cpuctx->heap_default);
10996 		cpuctx->heap = cpuctx->heap_default;
10997 	}
10998 
10999 got_cpu_context:
11000 	if (!pmu->start_txn) {
11001 		if (pmu->pmu_enable) {
11002 			/*
11003 			 * If we have pmu_enable/pmu_disable calls, install
11004 			 * transaction stubs that use that to try and batch
11005 			 * hardware accesses.
11006 			 */
11007 			pmu->start_txn  = perf_pmu_start_txn;
11008 			pmu->commit_txn = perf_pmu_commit_txn;
11009 			pmu->cancel_txn = perf_pmu_cancel_txn;
11010 		} else {
11011 			pmu->start_txn  = perf_pmu_nop_txn;
11012 			pmu->commit_txn = perf_pmu_nop_int;
11013 			pmu->cancel_txn = perf_pmu_nop_void;
11014 		}
11015 	}
11016 
11017 	if (!pmu->pmu_enable) {
11018 		pmu->pmu_enable  = perf_pmu_nop_void;
11019 		pmu->pmu_disable = perf_pmu_nop_void;
11020 	}
11021 
11022 	if (!pmu->check_period)
11023 		pmu->check_period = perf_event_nop_int;
11024 
11025 	if (!pmu->event_idx)
11026 		pmu->event_idx = perf_event_idx_default;
11027 
11028 	/*
11029 	 * Ensure the TYPE_SOFTWARE PMUs are at the head of the list,
11030 	 * since these cannot be in the IDR. This way the linear search
11031 	 * is fast, provided a valid software event is provided.
11032 	 */
11033 	if (type == PERF_TYPE_SOFTWARE || !name)
11034 		list_add_rcu(&pmu->entry, &pmus);
11035 	else
11036 		list_add_tail_rcu(&pmu->entry, &pmus);
11037 
11038 	atomic_set(&pmu->exclusive_cnt, 0);
11039 	ret = 0;
11040 unlock:
11041 	mutex_unlock(&pmus_lock);
11042 
11043 	return ret;
11044 
11045 free_dev:
11046 	device_del(pmu->dev);
11047 	put_device(pmu->dev);
11048 
11049 free_idr:
11050 	if (pmu->type != PERF_TYPE_SOFTWARE)
11051 		idr_remove(&pmu_idr, pmu->type);
11052 
11053 free_pdc:
11054 	free_percpu(pmu->pmu_disable_count);
11055 	goto unlock;
11056 }
11057 EXPORT_SYMBOL_GPL(perf_pmu_register);
11058 
perf_pmu_unregister(struct pmu * pmu)11059 void perf_pmu_unregister(struct pmu *pmu)
11060 {
11061 	mutex_lock(&pmus_lock);
11062 	list_del_rcu(&pmu->entry);
11063 
11064 	/*
11065 	 * We dereference the pmu list under both SRCU and regular RCU, so
11066 	 * synchronize against both of those.
11067 	 */
11068 	synchronize_srcu(&pmus_srcu);
11069 	synchronize_rcu();
11070 
11071 	free_percpu(pmu->pmu_disable_count);
11072 	if (pmu->type != PERF_TYPE_SOFTWARE)
11073 		idr_remove(&pmu_idr, pmu->type);
11074 	if (pmu_bus_running) {
11075 		if (pmu->nr_addr_filters)
11076 			device_remove_file(pmu->dev, &dev_attr_nr_addr_filters);
11077 		device_del(pmu->dev);
11078 		put_device(pmu->dev);
11079 	}
11080 	free_pmu_context(pmu);
11081 	mutex_unlock(&pmus_lock);
11082 }
11083 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
11084 
has_extended_regs(struct perf_event * event)11085 static inline bool has_extended_regs(struct perf_event *event)
11086 {
11087 	return (event->attr.sample_regs_user & PERF_REG_EXTENDED_MASK) ||
11088 	       (event->attr.sample_regs_intr & PERF_REG_EXTENDED_MASK);
11089 }
11090 
perf_try_init_event(struct pmu * pmu,struct perf_event * event)11091 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
11092 {
11093 	struct perf_event_context *ctx = NULL;
11094 	int ret;
11095 
11096 	if (!try_module_get(pmu->module))
11097 		return -ENODEV;
11098 
11099 	/*
11100 	 * A number of pmu->event_init() methods iterate the sibling_list to,
11101 	 * for example, validate if the group fits on the PMU. Therefore,
11102 	 * if this is a sibling event, acquire the ctx->mutex to protect
11103 	 * the sibling_list.
11104 	 */
11105 	if (event->group_leader != event && pmu->task_ctx_nr != perf_sw_context) {
11106 		/*
11107 		 * This ctx->mutex can nest when we're called through
11108 		 * inheritance. See the perf_event_ctx_lock_nested() comment.
11109 		 */
11110 		ctx = perf_event_ctx_lock_nested(event->group_leader,
11111 						 SINGLE_DEPTH_NESTING);
11112 		BUG_ON(!ctx);
11113 	}
11114 
11115 	event->pmu = pmu;
11116 	ret = pmu->event_init(event);
11117 
11118 	if (ctx)
11119 		perf_event_ctx_unlock(event->group_leader, ctx);
11120 
11121 	if (!ret) {
11122 		if (!(pmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS) &&
11123 		    has_extended_regs(event))
11124 			ret = -EOPNOTSUPP;
11125 
11126 		if (pmu->capabilities & PERF_PMU_CAP_NO_EXCLUDE &&
11127 		    event_has_any_exclude_flag(event))
11128 			ret = -EINVAL;
11129 
11130 		if (ret && event->destroy)
11131 			event->destroy(event);
11132 	}
11133 
11134 	if (ret)
11135 		module_put(pmu->module);
11136 
11137 	return ret;
11138 }
11139 
perf_init_event(struct perf_event * event)11140 static struct pmu *perf_init_event(struct perf_event *event)
11141 {
11142 	int idx, type, ret;
11143 	struct pmu *pmu;
11144 
11145 	idx = srcu_read_lock(&pmus_srcu);
11146 
11147 	/* Try parent's PMU first: */
11148 	if (event->parent && event->parent->pmu) {
11149 		pmu = event->parent->pmu;
11150 		ret = perf_try_init_event(pmu, event);
11151 		if (!ret)
11152 			goto unlock;
11153 	}
11154 
11155 	/*
11156 	 * PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE
11157 	 * are often aliases for PERF_TYPE_RAW.
11158 	 */
11159 	type = event->attr.type;
11160 	if (type == PERF_TYPE_HARDWARE || type == PERF_TYPE_HW_CACHE)
11161 		type = PERF_TYPE_RAW;
11162 
11163 again:
11164 	rcu_read_lock();
11165 	pmu = idr_find(&pmu_idr, type);
11166 	rcu_read_unlock();
11167 	if (pmu) {
11168 		ret = perf_try_init_event(pmu, event);
11169 		if (ret == -ENOENT && event->attr.type != type) {
11170 			type = event->attr.type;
11171 			goto again;
11172 		}
11173 
11174 		if (ret)
11175 			pmu = ERR_PTR(ret);
11176 
11177 		goto unlock;
11178 	}
11179 
11180 	list_for_each_entry_rcu(pmu, &pmus, entry, lockdep_is_held(&pmus_srcu)) {
11181 		ret = perf_try_init_event(pmu, event);
11182 		if (!ret)
11183 			goto unlock;
11184 
11185 		if (ret != -ENOENT) {
11186 			pmu = ERR_PTR(ret);
11187 			goto unlock;
11188 		}
11189 	}
11190 	pmu = ERR_PTR(-ENOENT);
11191 unlock:
11192 	srcu_read_unlock(&pmus_srcu, idx);
11193 
11194 	return pmu;
11195 }
11196 
attach_sb_event(struct perf_event * event)11197 static void attach_sb_event(struct perf_event *event)
11198 {
11199 	struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
11200 
11201 	raw_spin_lock(&pel->lock);
11202 	list_add_rcu(&event->sb_list, &pel->list);
11203 	raw_spin_unlock(&pel->lock);
11204 }
11205 
11206 /*
11207  * We keep a list of all !task (and therefore per-cpu) events
11208  * that need to receive side-band records.
11209  *
11210  * This avoids having to scan all the various PMU per-cpu contexts
11211  * looking for them.
11212  */
account_pmu_sb_event(struct perf_event * event)11213 static void account_pmu_sb_event(struct perf_event *event)
11214 {
11215 	if (is_sb_event(event))
11216 		attach_sb_event(event);
11217 }
11218 
account_event_cpu(struct perf_event * event,int cpu)11219 static void account_event_cpu(struct perf_event *event, int cpu)
11220 {
11221 	if (event->parent)
11222 		return;
11223 
11224 	if (is_cgroup_event(event))
11225 		atomic_inc(&per_cpu(perf_cgroup_events, cpu));
11226 }
11227 
11228 /* Freq events need the tick to stay alive (see perf_event_task_tick). */
account_freq_event_nohz(void)11229 static void account_freq_event_nohz(void)
11230 {
11231 #ifdef CONFIG_NO_HZ_FULL
11232 	/* Lock so we don't race with concurrent unaccount */
11233 	spin_lock(&nr_freq_lock);
11234 	if (atomic_inc_return(&nr_freq_events) == 1)
11235 		tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS);
11236 	spin_unlock(&nr_freq_lock);
11237 #endif
11238 }
11239 
account_freq_event(void)11240 static void account_freq_event(void)
11241 {
11242 	if (tick_nohz_full_enabled())
11243 		account_freq_event_nohz();
11244 	else
11245 		atomic_inc(&nr_freq_events);
11246 }
11247 
11248 
account_event(struct perf_event * event)11249 static void account_event(struct perf_event *event)
11250 {
11251 	bool inc = false;
11252 
11253 	if (event->parent)
11254 		return;
11255 
11256 	if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB))
11257 		inc = true;
11258 	if (event->attr.mmap || event->attr.mmap_data)
11259 		atomic_inc(&nr_mmap_events);
11260 	if (event->attr.comm)
11261 		atomic_inc(&nr_comm_events);
11262 	if (event->attr.namespaces)
11263 		atomic_inc(&nr_namespaces_events);
11264 	if (event->attr.cgroup)
11265 		atomic_inc(&nr_cgroup_events);
11266 	if (event->attr.task)
11267 		atomic_inc(&nr_task_events);
11268 	if (event->attr.freq)
11269 		account_freq_event();
11270 	if (event->attr.context_switch) {
11271 		atomic_inc(&nr_switch_events);
11272 		inc = true;
11273 	}
11274 	if (has_branch_stack(event))
11275 		inc = true;
11276 	if (is_cgroup_event(event))
11277 		inc = true;
11278 	if (event->attr.ksymbol)
11279 		atomic_inc(&nr_ksymbol_events);
11280 	if (event->attr.bpf_event)
11281 		atomic_inc(&nr_bpf_events);
11282 	if (event->attr.text_poke)
11283 		atomic_inc(&nr_text_poke_events);
11284 
11285 	if (inc) {
11286 		/*
11287 		 * We need the mutex here because static_branch_enable()
11288 		 * must complete *before* the perf_sched_count increment
11289 		 * becomes visible.
11290 		 */
11291 		if (atomic_inc_not_zero(&perf_sched_count))
11292 			goto enabled;
11293 
11294 		mutex_lock(&perf_sched_mutex);
11295 		if (!atomic_read(&perf_sched_count)) {
11296 			static_branch_enable(&perf_sched_events);
11297 			/*
11298 			 * Guarantee that all CPUs observe they key change and
11299 			 * call the perf scheduling hooks before proceeding to
11300 			 * install events that need them.
11301 			 */
11302 			synchronize_rcu();
11303 		}
11304 		/*
11305 		 * Now that we have waited for the sync_sched(), allow further
11306 		 * increments to by-pass the mutex.
11307 		 */
11308 		atomic_inc(&perf_sched_count);
11309 		mutex_unlock(&perf_sched_mutex);
11310 	}
11311 enabled:
11312 
11313 	account_event_cpu(event, event->cpu);
11314 
11315 	account_pmu_sb_event(event);
11316 }
11317 
11318 /*
11319  * Allocate and initialize an event structure
11320  */
11321 static struct perf_event *
perf_event_alloc(struct perf_event_attr * attr,int cpu,struct task_struct * task,struct perf_event * group_leader,struct perf_event * parent_event,perf_overflow_handler_t overflow_handler,void * context,int cgroup_fd)11322 perf_event_alloc(struct perf_event_attr *attr, int cpu,
11323 		 struct task_struct *task,
11324 		 struct perf_event *group_leader,
11325 		 struct perf_event *parent_event,
11326 		 perf_overflow_handler_t overflow_handler,
11327 		 void *context, int cgroup_fd)
11328 {
11329 	struct pmu *pmu;
11330 	struct perf_event *event;
11331 	struct hw_perf_event *hwc;
11332 	long err = -EINVAL;
11333 
11334 	if ((unsigned)cpu >= nr_cpu_ids) {
11335 		if (!task || cpu != -1)
11336 			return ERR_PTR(-EINVAL);
11337 	}
11338 
11339 	event = kzalloc(sizeof(*event), GFP_KERNEL);
11340 	if (!event)
11341 		return ERR_PTR(-ENOMEM);
11342 
11343 	/*
11344 	 * Single events are their own group leaders, with an
11345 	 * empty sibling list:
11346 	 */
11347 	if (!group_leader)
11348 		group_leader = event;
11349 
11350 	mutex_init(&event->child_mutex);
11351 	INIT_LIST_HEAD(&event->child_list);
11352 
11353 	INIT_LIST_HEAD(&event->event_entry);
11354 	INIT_LIST_HEAD(&event->sibling_list);
11355 	INIT_LIST_HEAD(&event->active_list);
11356 	init_event_group(event);
11357 	INIT_LIST_HEAD(&event->rb_entry);
11358 	INIT_LIST_HEAD(&event->active_entry);
11359 	INIT_LIST_HEAD(&event->addr_filters.list);
11360 	INIT_HLIST_NODE(&event->hlist_entry);
11361 
11362 
11363 	init_waitqueue_head(&event->waitq);
11364 	event->pending_disable = -1;
11365 	init_irq_work(&event->pending, perf_pending_event);
11366 
11367 	mutex_init(&event->mmap_mutex);
11368 	raw_spin_lock_init(&event->addr_filters.lock);
11369 
11370 	atomic_long_set(&event->refcount, 1);
11371 	event->cpu		= cpu;
11372 	event->attr		= *attr;
11373 	event->group_leader	= group_leader;
11374 	event->pmu		= NULL;
11375 	event->oncpu		= -1;
11376 
11377 	event->parent		= parent_event;
11378 
11379 	event->ns		= get_pid_ns(task_active_pid_ns(current));
11380 	event->id		= atomic64_inc_return(&perf_event_id);
11381 
11382 	event->state		= PERF_EVENT_STATE_INACTIVE;
11383 
11384 	if (task) {
11385 		event->attach_state = PERF_ATTACH_TASK;
11386 		/*
11387 		 * XXX pmu::event_init needs to know what task to account to
11388 		 * and we cannot use the ctx information because we need the
11389 		 * pmu before we get a ctx.
11390 		 */
11391 		event->hw.target = get_task_struct(task);
11392 	}
11393 
11394 	event->clock = &local_clock;
11395 	if (parent_event)
11396 		event->clock = parent_event->clock;
11397 
11398 	if (!overflow_handler && parent_event) {
11399 		overflow_handler = parent_event->overflow_handler;
11400 		context = parent_event->overflow_handler_context;
11401 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING)
11402 		if (overflow_handler == bpf_overflow_handler) {
11403 			struct bpf_prog *prog = parent_event->prog;
11404 
11405 			bpf_prog_inc(prog);
11406 			event->prog = prog;
11407 			event->orig_overflow_handler =
11408 				parent_event->orig_overflow_handler;
11409 		}
11410 #endif
11411 	}
11412 
11413 	if (overflow_handler) {
11414 		event->overflow_handler	= overflow_handler;
11415 		event->overflow_handler_context = context;
11416 	} else if (is_write_backward(event)){
11417 		event->overflow_handler = perf_event_output_backward;
11418 		event->overflow_handler_context = NULL;
11419 	} else {
11420 		event->overflow_handler = perf_event_output_forward;
11421 		event->overflow_handler_context = NULL;
11422 	}
11423 
11424 	perf_event__state_init(event);
11425 
11426 	pmu = NULL;
11427 
11428 	hwc = &event->hw;
11429 	hwc->sample_period = attr->sample_period;
11430 	if (attr->freq && attr->sample_freq)
11431 		hwc->sample_period = 1;
11432 	hwc->last_period = hwc->sample_period;
11433 
11434 	local64_set(&hwc->period_left, hwc->sample_period);
11435 
11436 	/*
11437 	 * We currently do not support PERF_SAMPLE_READ on inherited events.
11438 	 * See perf_output_read().
11439 	 */
11440 	if (attr->inherit && (attr->sample_type & PERF_SAMPLE_READ))
11441 		goto err_ns;
11442 
11443 	if (!has_branch_stack(event))
11444 		event->attr.branch_sample_type = 0;
11445 
11446 	pmu = perf_init_event(event);
11447 	if (IS_ERR(pmu)) {
11448 		err = PTR_ERR(pmu);
11449 		goto err_ns;
11450 	}
11451 
11452 	/*
11453 	 * Disallow uncore-cgroup events, they don't make sense as the cgroup will
11454 	 * be different on other CPUs in the uncore mask.
11455 	 */
11456 	if (pmu->task_ctx_nr == perf_invalid_context && cgroup_fd != -1) {
11457 		err = -EINVAL;
11458 		goto err_pmu;
11459 	}
11460 
11461 	if (event->attr.aux_output &&
11462 	    !(pmu->capabilities & PERF_PMU_CAP_AUX_OUTPUT)) {
11463 		err = -EOPNOTSUPP;
11464 		goto err_pmu;
11465 	}
11466 
11467 	if (cgroup_fd != -1) {
11468 		err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
11469 		if (err)
11470 			goto err_pmu;
11471 	}
11472 
11473 	err = exclusive_event_init(event);
11474 	if (err)
11475 		goto err_pmu;
11476 
11477 	if (has_addr_filter(event)) {
11478 		event->addr_filter_ranges = kcalloc(pmu->nr_addr_filters,
11479 						    sizeof(struct perf_addr_filter_range),
11480 						    GFP_KERNEL);
11481 		if (!event->addr_filter_ranges) {
11482 			err = -ENOMEM;
11483 			goto err_per_task;
11484 		}
11485 
11486 		/*
11487 		 * Clone the parent's vma offsets: they are valid until exec()
11488 		 * even if the mm is not shared with the parent.
11489 		 */
11490 		if (event->parent) {
11491 			struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
11492 
11493 			raw_spin_lock_irq(&ifh->lock);
11494 			memcpy(event->addr_filter_ranges,
11495 			       event->parent->addr_filter_ranges,
11496 			       pmu->nr_addr_filters * sizeof(struct perf_addr_filter_range));
11497 			raw_spin_unlock_irq(&ifh->lock);
11498 		}
11499 
11500 		/* force hw sync on the address filters */
11501 		event->addr_filters_gen = 1;
11502 	}
11503 
11504 	if (!event->parent) {
11505 		if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
11506 			err = get_callchain_buffers(attr->sample_max_stack);
11507 			if (err)
11508 				goto err_addr_filters;
11509 		}
11510 	}
11511 
11512 	err = security_perf_event_alloc(event);
11513 	if (err)
11514 		goto err_callchain_buffer;
11515 
11516 	/* symmetric to unaccount_event() in _free_event() */
11517 	account_event(event);
11518 
11519 	return event;
11520 
11521 err_callchain_buffer:
11522 	if (!event->parent) {
11523 		if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
11524 			put_callchain_buffers();
11525 	}
11526 err_addr_filters:
11527 	kfree(event->addr_filter_ranges);
11528 
11529 err_per_task:
11530 	exclusive_event_destroy(event);
11531 
11532 err_pmu:
11533 	if (is_cgroup_event(event))
11534 		perf_detach_cgroup(event);
11535 	if (event->destroy)
11536 		event->destroy(event);
11537 	module_put(pmu->module);
11538 err_ns:
11539 	if (event->ns)
11540 		put_pid_ns(event->ns);
11541 	if (event->hw.target)
11542 		put_task_struct(event->hw.target);
11543 	kfree(event);
11544 
11545 	return ERR_PTR(err);
11546 }
11547 
perf_copy_attr(struct perf_event_attr __user * uattr,struct perf_event_attr * attr)11548 static int perf_copy_attr(struct perf_event_attr __user *uattr,
11549 			  struct perf_event_attr *attr)
11550 {
11551 	u32 size;
11552 	int ret;
11553 
11554 	/* Zero the full structure, so that a short copy will be nice. */
11555 	memset(attr, 0, sizeof(*attr));
11556 
11557 	ret = get_user(size, &uattr->size);
11558 	if (ret)
11559 		return ret;
11560 
11561 	/* ABI compatibility quirk: */
11562 	if (!size)
11563 		size = PERF_ATTR_SIZE_VER0;
11564 	if (size < PERF_ATTR_SIZE_VER0 || size > PAGE_SIZE)
11565 		goto err_size;
11566 
11567 	ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size);
11568 	if (ret) {
11569 		if (ret == -E2BIG)
11570 			goto err_size;
11571 		return ret;
11572 	}
11573 
11574 	attr->size = size;
11575 
11576 	if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3)
11577 		return -EINVAL;
11578 
11579 	if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
11580 		return -EINVAL;
11581 
11582 	if (attr->read_format & ~(PERF_FORMAT_MAX-1))
11583 		return -EINVAL;
11584 
11585 	if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
11586 		u64 mask = attr->branch_sample_type;
11587 
11588 		/* only using defined bits */
11589 		if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
11590 			return -EINVAL;
11591 
11592 		/* at least one branch bit must be set */
11593 		if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
11594 			return -EINVAL;
11595 
11596 		/* propagate priv level, when not set for branch */
11597 		if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
11598 
11599 			/* exclude_kernel checked on syscall entry */
11600 			if (!attr->exclude_kernel)
11601 				mask |= PERF_SAMPLE_BRANCH_KERNEL;
11602 
11603 			if (!attr->exclude_user)
11604 				mask |= PERF_SAMPLE_BRANCH_USER;
11605 
11606 			if (!attr->exclude_hv)
11607 				mask |= PERF_SAMPLE_BRANCH_HV;
11608 			/*
11609 			 * adjust user setting (for HW filter setup)
11610 			 */
11611 			attr->branch_sample_type = mask;
11612 		}
11613 		/* privileged levels capture (kernel, hv): check permissions */
11614 		if (mask & PERF_SAMPLE_BRANCH_PERM_PLM) {
11615 			ret = perf_allow_kernel(attr);
11616 			if (ret)
11617 				return ret;
11618 		}
11619 	}
11620 
11621 	if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
11622 		ret = perf_reg_validate(attr->sample_regs_user);
11623 		if (ret)
11624 			return ret;
11625 	}
11626 
11627 	if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
11628 		if (!arch_perf_have_user_stack_dump())
11629 			return -ENOSYS;
11630 
11631 		/*
11632 		 * We have __u32 type for the size, but so far
11633 		 * we can only use __u16 as maximum due to the
11634 		 * __u16 sample size limit.
11635 		 */
11636 		if (attr->sample_stack_user >= USHRT_MAX)
11637 			return -EINVAL;
11638 		else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
11639 			return -EINVAL;
11640 	}
11641 
11642 	if (!attr->sample_max_stack)
11643 		attr->sample_max_stack = sysctl_perf_event_max_stack;
11644 
11645 	if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
11646 		ret = perf_reg_validate(attr->sample_regs_intr);
11647 
11648 #ifndef CONFIG_CGROUP_PERF
11649 	if (attr->sample_type & PERF_SAMPLE_CGROUP)
11650 		return -EINVAL;
11651 #endif
11652 
11653 out:
11654 	return ret;
11655 
11656 err_size:
11657 	put_user(sizeof(*attr), &uattr->size);
11658 	ret = -E2BIG;
11659 	goto out;
11660 }
11661 
mutex_lock_double(struct mutex * a,struct mutex * b)11662 static void mutex_lock_double(struct mutex *a, struct mutex *b)
11663 {
11664 	if (b < a)
11665 		swap(a, b);
11666 
11667 	mutex_lock(a);
11668 	mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
11669 }
11670 
11671 static int
perf_event_set_output(struct perf_event * event,struct perf_event * output_event)11672 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
11673 {
11674 	struct perf_buffer *rb = NULL;
11675 	int ret = -EINVAL;
11676 
11677 	if (!output_event) {
11678 		mutex_lock(&event->mmap_mutex);
11679 		goto set;
11680 	}
11681 
11682 	/* don't allow circular references */
11683 	if (event == output_event)
11684 		goto out;
11685 
11686 	/*
11687 	 * Don't allow cross-cpu buffers
11688 	 */
11689 	if (output_event->cpu != event->cpu)
11690 		goto out;
11691 
11692 	/*
11693 	 * If its not a per-cpu rb, it must be the same task.
11694 	 */
11695 	if (output_event->cpu == -1 && output_event->hw.target != event->hw.target)
11696 		goto out;
11697 
11698 	/*
11699 	 * Mixing clocks in the same buffer is trouble you don't need.
11700 	 */
11701 	if (output_event->clock != event->clock)
11702 		goto out;
11703 
11704 	/*
11705 	 * Either writing ring buffer from beginning or from end.
11706 	 * Mixing is not allowed.
11707 	 */
11708 	if (is_write_backward(output_event) != is_write_backward(event))
11709 		goto out;
11710 
11711 	/*
11712 	 * If both events generate aux data, they must be on the same PMU
11713 	 */
11714 	if (has_aux(event) && has_aux(output_event) &&
11715 	    event->pmu != output_event->pmu)
11716 		goto out;
11717 
11718 	/*
11719 	 * Hold both mmap_mutex to serialize against perf_mmap_close().  Since
11720 	 * output_event is already on rb->event_list, and the list iteration
11721 	 * restarts after every removal, it is guaranteed this new event is
11722 	 * observed *OR* if output_event is already removed, it's guaranteed we
11723 	 * observe !rb->mmap_count.
11724 	 */
11725 	mutex_lock_double(&event->mmap_mutex, &output_event->mmap_mutex);
11726 set:
11727 	/* Can't redirect output if we've got an active mmap() */
11728 	if (atomic_read(&event->mmap_count))
11729 		goto unlock;
11730 
11731 	if (output_event) {
11732 		/* get the rb we want to redirect to */
11733 		rb = ring_buffer_get(output_event);
11734 		if (!rb)
11735 			goto unlock;
11736 
11737 		/* did we race against perf_mmap_close() */
11738 		if (!atomic_read(&rb->mmap_count)) {
11739 			ring_buffer_put(rb);
11740 			goto unlock;
11741 		}
11742 	}
11743 
11744 	ring_buffer_attach(event, rb);
11745 
11746 	ret = 0;
11747 unlock:
11748 	mutex_unlock(&event->mmap_mutex);
11749 	if (output_event)
11750 		mutex_unlock(&output_event->mmap_mutex);
11751 
11752 out:
11753 	return ret;
11754 }
11755 
perf_event_set_clock(struct perf_event * event,clockid_t clk_id)11756 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
11757 {
11758 	bool nmi_safe = false;
11759 
11760 	switch (clk_id) {
11761 	case CLOCK_MONOTONIC:
11762 		event->clock = &ktime_get_mono_fast_ns;
11763 		nmi_safe = true;
11764 		break;
11765 
11766 	case CLOCK_MONOTONIC_RAW:
11767 		event->clock = &ktime_get_raw_fast_ns;
11768 		nmi_safe = true;
11769 		break;
11770 
11771 	case CLOCK_REALTIME:
11772 		event->clock = &ktime_get_real_ns;
11773 		break;
11774 
11775 	case CLOCK_BOOTTIME:
11776 		event->clock = &ktime_get_boottime_ns;
11777 		break;
11778 
11779 	case CLOCK_TAI:
11780 		event->clock = &ktime_get_clocktai_ns;
11781 		break;
11782 
11783 	default:
11784 		return -EINVAL;
11785 	}
11786 
11787 	if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
11788 		return -EINVAL;
11789 
11790 	return 0;
11791 }
11792 
11793 /*
11794  * Variation on perf_event_ctx_lock_nested(), except we take two context
11795  * mutexes.
11796  */
11797 static struct perf_event_context *
__perf_event_ctx_lock_double(struct perf_event * group_leader,struct perf_event_context * ctx)11798 __perf_event_ctx_lock_double(struct perf_event *group_leader,
11799 			     struct perf_event_context *ctx)
11800 {
11801 	struct perf_event_context *gctx;
11802 
11803 again:
11804 	rcu_read_lock();
11805 	gctx = READ_ONCE(group_leader->ctx);
11806 	if (!refcount_inc_not_zero(&gctx->refcount)) {
11807 		rcu_read_unlock();
11808 		goto again;
11809 	}
11810 	rcu_read_unlock();
11811 
11812 	mutex_lock_double(&gctx->mutex, &ctx->mutex);
11813 
11814 	if (group_leader->ctx != gctx) {
11815 		mutex_unlock(&ctx->mutex);
11816 		mutex_unlock(&gctx->mutex);
11817 		put_ctx(gctx);
11818 		goto again;
11819 	}
11820 
11821 	return gctx;
11822 }
11823 
11824 /**
11825  * sys_perf_event_open - open a performance event, associate it to a task/cpu
11826  *
11827  * @attr_uptr:	event_id type attributes for monitoring/sampling
11828  * @pid:		target pid
11829  * @cpu:		target cpu
11830  * @group_fd:		group leader event fd
11831  */
SYSCALL_DEFINE5(perf_event_open,struct perf_event_attr __user *,attr_uptr,pid_t,pid,int,cpu,int,group_fd,unsigned long,flags)11832 SYSCALL_DEFINE5(perf_event_open,
11833 		struct perf_event_attr __user *, attr_uptr,
11834 		pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
11835 {
11836 	struct perf_event *group_leader = NULL, *output_event = NULL;
11837 	struct perf_event *event, *sibling;
11838 	struct perf_event_attr attr;
11839 	struct perf_event_context *ctx, *gctx;
11840 	struct file *event_file = NULL;
11841 	struct fd group = {NULL, 0};
11842 	struct task_struct *task = NULL;
11843 	struct pmu *pmu;
11844 	int event_fd;
11845 	int move_group = 0;
11846 	int err;
11847 	int f_flags = O_RDWR;
11848 	int cgroup_fd = -1;
11849 
11850 	/* for future expandability... */
11851 	if (flags & ~PERF_FLAG_ALL)
11852 		return -EINVAL;
11853 
11854 	err = perf_copy_attr(attr_uptr, &attr);
11855 	if (err)
11856 		return err;
11857 
11858 	/* Do we allow access to perf_event_open(2) ? */
11859 	err = security_perf_event_open(&attr, PERF_SECURITY_OPEN);
11860 	if (err)
11861 		return err;
11862 
11863 	if (!attr.exclude_kernel) {
11864 		err = perf_allow_kernel(&attr);
11865 		if (err)
11866 			return err;
11867 	}
11868 
11869 	if (attr.namespaces) {
11870 		if (!perfmon_capable())
11871 			return -EACCES;
11872 	}
11873 
11874 	if (attr.freq) {
11875 		if (attr.sample_freq > sysctl_perf_event_sample_rate)
11876 			return -EINVAL;
11877 	} else {
11878 		if (attr.sample_period & (1ULL << 63))
11879 			return -EINVAL;
11880 	}
11881 
11882 	/* Only privileged users can get physical addresses */
11883 	if ((attr.sample_type & PERF_SAMPLE_PHYS_ADDR)) {
11884 		err = perf_allow_kernel(&attr);
11885 		if (err)
11886 			return err;
11887 	}
11888 
11889 	/* REGS_INTR can leak data, lockdown must prevent this */
11890 	if (attr.sample_type & PERF_SAMPLE_REGS_INTR) {
11891 		err = security_locked_down(LOCKDOWN_PERF);
11892 		if (err)
11893 			return err;
11894 	}
11895 
11896 	/*
11897 	 * In cgroup mode, the pid argument is used to pass the fd
11898 	 * opened to the cgroup directory in cgroupfs. The cpu argument
11899 	 * designates the cpu on which to monitor threads from that
11900 	 * cgroup.
11901 	 */
11902 	if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
11903 		return -EINVAL;
11904 
11905 	if (flags & PERF_FLAG_FD_CLOEXEC)
11906 		f_flags |= O_CLOEXEC;
11907 
11908 	event_fd = get_unused_fd_flags(f_flags);
11909 	if (event_fd < 0)
11910 		return event_fd;
11911 
11912 	if (group_fd != -1) {
11913 		err = perf_fget_light(group_fd, &group);
11914 		if (err)
11915 			goto err_fd;
11916 		group_leader = group.file->private_data;
11917 		if (flags & PERF_FLAG_FD_OUTPUT)
11918 			output_event = group_leader;
11919 		if (flags & PERF_FLAG_FD_NO_GROUP)
11920 			group_leader = NULL;
11921 	}
11922 
11923 	if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
11924 		task = find_lively_task_by_vpid(pid);
11925 		if (IS_ERR(task)) {
11926 			err = PTR_ERR(task);
11927 			goto err_group_fd;
11928 		}
11929 	}
11930 
11931 	if (task && group_leader &&
11932 	    group_leader->attr.inherit != attr.inherit) {
11933 		err = -EINVAL;
11934 		goto err_task;
11935 	}
11936 
11937 	if (flags & PERF_FLAG_PID_CGROUP)
11938 		cgroup_fd = pid;
11939 
11940 	event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
11941 				 NULL, NULL, cgroup_fd);
11942 	if (IS_ERR(event)) {
11943 		err = PTR_ERR(event);
11944 		goto err_task;
11945 	}
11946 
11947 	if (is_sampling_event(event)) {
11948 		if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
11949 			err = -EOPNOTSUPP;
11950 			goto err_alloc;
11951 		}
11952 	}
11953 
11954 	/*
11955 	 * Special case software events and allow them to be part of
11956 	 * any hardware group.
11957 	 */
11958 	pmu = event->pmu;
11959 
11960 	if (attr.use_clockid) {
11961 		err = perf_event_set_clock(event, attr.clockid);
11962 		if (err)
11963 			goto err_alloc;
11964 	}
11965 
11966 	if (pmu->task_ctx_nr == perf_sw_context)
11967 		event->event_caps |= PERF_EV_CAP_SOFTWARE;
11968 
11969 	if (group_leader) {
11970 		if (is_software_event(event) &&
11971 		    !in_software_context(group_leader)) {
11972 			/*
11973 			 * If the event is a sw event, but the group_leader
11974 			 * is on hw context.
11975 			 *
11976 			 * Allow the addition of software events to hw
11977 			 * groups, this is safe because software events
11978 			 * never fail to schedule.
11979 			 */
11980 			pmu = group_leader->ctx->pmu;
11981 		} else if (!is_software_event(event) &&
11982 			   is_software_event(group_leader) &&
11983 			   (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
11984 			/*
11985 			 * In case the group is a pure software group, and we
11986 			 * try to add a hardware event, move the whole group to
11987 			 * the hardware context.
11988 			 */
11989 			move_group = 1;
11990 		}
11991 	}
11992 
11993 	/*
11994 	 * Get the target context (task or percpu):
11995 	 */
11996 	ctx = find_get_context(pmu, task, event);
11997 	if (IS_ERR(ctx)) {
11998 		err = PTR_ERR(ctx);
11999 		goto err_alloc;
12000 	}
12001 
12002 	/*
12003 	 * Look up the group leader (we will attach this event to it):
12004 	 */
12005 	if (group_leader) {
12006 		err = -EINVAL;
12007 
12008 		/*
12009 		 * Do not allow a recursive hierarchy (this new sibling
12010 		 * becoming part of another group-sibling):
12011 		 */
12012 		if (group_leader->group_leader != group_leader)
12013 			goto err_context;
12014 
12015 		/* All events in a group should have the same clock */
12016 		if (group_leader->clock != event->clock)
12017 			goto err_context;
12018 
12019 		/*
12020 		 * Make sure we're both events for the same CPU;
12021 		 * grouping events for different CPUs is broken; since
12022 		 * you can never concurrently schedule them anyhow.
12023 		 */
12024 		if (group_leader->cpu != event->cpu)
12025 			goto err_context;
12026 
12027 		/*
12028 		 * Make sure we're both on the same task, or both
12029 		 * per-CPU events.
12030 		 */
12031 		if (group_leader->ctx->task != ctx->task)
12032 			goto err_context;
12033 
12034 		/*
12035 		 * Do not allow to attach to a group in a different task
12036 		 * or CPU context. If we're moving SW events, we'll fix
12037 		 * this up later, so allow that.
12038 		 *
12039 		 * Racy, not holding group_leader->ctx->mutex, see comment with
12040 		 * perf_event_ctx_lock().
12041 		 */
12042 		if (!move_group && group_leader->ctx != ctx)
12043 			goto err_context;
12044 
12045 		/*
12046 		 * Only a group leader can be exclusive or pinned
12047 		 */
12048 		if (attr.exclusive || attr.pinned)
12049 			goto err_context;
12050 	}
12051 
12052 	if (output_event) {
12053 		err = perf_event_set_output(event, output_event);
12054 		if (err)
12055 			goto err_context;
12056 	}
12057 
12058 	event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
12059 					f_flags);
12060 	if (IS_ERR(event_file)) {
12061 		err = PTR_ERR(event_file);
12062 		event_file = NULL;
12063 		goto err_context;
12064 	}
12065 
12066 	if (task) {
12067 		err = down_read_interruptible(&task->signal->exec_update_lock);
12068 		if (err)
12069 			goto err_file;
12070 
12071 		/*
12072 		 * Preserve ptrace permission check for backwards compatibility.
12073 		 *
12074 		 * We must hold exec_update_lock across this and any potential
12075 		 * perf_install_in_context() call for this new event to
12076 		 * serialize against exec() altering our credentials (and the
12077 		 * perf_event_exit_task() that could imply).
12078 		 */
12079 		err = -EACCES;
12080 		if (!perfmon_capable() && !ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS))
12081 			goto err_cred;
12082 	}
12083 
12084 	if (move_group) {
12085 		gctx = __perf_event_ctx_lock_double(group_leader, ctx);
12086 
12087 		if (gctx->task == TASK_TOMBSTONE) {
12088 			err = -ESRCH;
12089 			goto err_locked;
12090 		}
12091 
12092 		/*
12093 		 * Check if we raced against another sys_perf_event_open() call
12094 		 * moving the software group underneath us.
12095 		 */
12096 		if (!(group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
12097 			/*
12098 			 * If someone moved the group out from under us, check
12099 			 * if this new event wound up on the same ctx, if so
12100 			 * its the regular !move_group case, otherwise fail.
12101 			 */
12102 			if (gctx != ctx) {
12103 				err = -EINVAL;
12104 				goto err_locked;
12105 			} else {
12106 				perf_event_ctx_unlock(group_leader, gctx);
12107 				move_group = 0;
12108 				goto not_move_group;
12109 			}
12110 		}
12111 
12112 		/*
12113 		 * Failure to create exclusive events returns -EBUSY.
12114 		 */
12115 		err = -EBUSY;
12116 		if (!exclusive_event_installable(group_leader, ctx))
12117 			goto err_locked;
12118 
12119 		for_each_sibling_event(sibling, group_leader) {
12120 			if (!exclusive_event_installable(sibling, ctx))
12121 				goto err_locked;
12122 		}
12123 	} else {
12124 		mutex_lock(&ctx->mutex);
12125 
12126 		/*
12127 		 * Now that we hold ctx->lock, (re)validate group_leader->ctx == ctx,
12128 		 * see the group_leader && !move_group test earlier.
12129 		 */
12130 		if (group_leader && group_leader->ctx != ctx) {
12131 			err = -EINVAL;
12132 			goto err_locked;
12133 		}
12134 	}
12135 not_move_group:
12136 
12137 	if (ctx->task == TASK_TOMBSTONE) {
12138 		err = -ESRCH;
12139 		goto err_locked;
12140 	}
12141 
12142 	if (!perf_event_validate_size(event)) {
12143 		err = -E2BIG;
12144 		goto err_locked;
12145 	}
12146 
12147 	if (!task) {
12148 		/*
12149 		 * Check if the @cpu we're creating an event for is online.
12150 		 *
12151 		 * We use the perf_cpu_context::ctx::mutex to serialize against
12152 		 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
12153 		 */
12154 		struct perf_cpu_context *cpuctx =
12155 			container_of(ctx, struct perf_cpu_context, ctx);
12156 
12157 		if (!cpuctx->online) {
12158 			err = -ENODEV;
12159 			goto err_locked;
12160 		}
12161 	}
12162 
12163 	if (perf_need_aux_event(event) && !perf_get_aux_event(event, group_leader)) {
12164 		err = -EINVAL;
12165 		goto err_locked;
12166 	}
12167 
12168 	/*
12169 	 * Must be under the same ctx::mutex as perf_install_in_context(),
12170 	 * because we need to serialize with concurrent event creation.
12171 	 */
12172 	if (!exclusive_event_installable(event, ctx)) {
12173 		err = -EBUSY;
12174 		goto err_locked;
12175 	}
12176 
12177 	WARN_ON_ONCE(ctx->parent_ctx);
12178 
12179 	/*
12180 	 * This is the point on no return; we cannot fail hereafter. This is
12181 	 * where we start modifying current state.
12182 	 */
12183 
12184 	if (move_group) {
12185 		/*
12186 		 * See perf_event_ctx_lock() for comments on the details
12187 		 * of swizzling perf_event::ctx.
12188 		 */
12189 		perf_remove_from_context(group_leader, 0);
12190 		put_ctx(gctx);
12191 
12192 		for_each_sibling_event(sibling, group_leader) {
12193 			perf_remove_from_context(sibling, 0);
12194 			put_ctx(gctx);
12195 		}
12196 
12197 		/*
12198 		 * Wait for everybody to stop referencing the events through
12199 		 * the old lists, before installing it on new lists.
12200 		 */
12201 		synchronize_rcu();
12202 
12203 		/*
12204 		 * Install the group siblings before the group leader.
12205 		 *
12206 		 * Because a group leader will try and install the entire group
12207 		 * (through the sibling list, which is still in-tact), we can
12208 		 * end up with siblings installed in the wrong context.
12209 		 *
12210 		 * By installing siblings first we NO-OP because they're not
12211 		 * reachable through the group lists.
12212 		 */
12213 		for_each_sibling_event(sibling, group_leader) {
12214 			perf_event__state_init(sibling);
12215 			perf_install_in_context(ctx, sibling, sibling->cpu);
12216 			get_ctx(ctx);
12217 		}
12218 
12219 		/*
12220 		 * Removing from the context ends up with disabled
12221 		 * event. What we want here is event in the initial
12222 		 * startup state, ready to be add into new context.
12223 		 */
12224 		perf_event__state_init(group_leader);
12225 		perf_install_in_context(ctx, group_leader, group_leader->cpu);
12226 		get_ctx(ctx);
12227 	}
12228 
12229 	/*
12230 	 * Precalculate sample_data sizes; do while holding ctx::mutex such
12231 	 * that we're serialized against further additions and before
12232 	 * perf_install_in_context() which is the point the event is active and
12233 	 * can use these values.
12234 	 */
12235 	perf_event__header_size(event);
12236 	perf_event__id_header_size(event);
12237 
12238 	event->owner = current;
12239 
12240 	perf_install_in_context(ctx, event, event->cpu);
12241 	perf_unpin_context(ctx);
12242 
12243 	if (move_group)
12244 		perf_event_ctx_unlock(group_leader, gctx);
12245 	mutex_unlock(&ctx->mutex);
12246 
12247 	if (task) {
12248 		up_read(&task->signal->exec_update_lock);
12249 		put_task_struct(task);
12250 	}
12251 
12252 	mutex_lock(&current->perf_event_mutex);
12253 	list_add_tail(&event->owner_entry, &current->perf_event_list);
12254 	mutex_unlock(&current->perf_event_mutex);
12255 
12256 	/*
12257 	 * Drop the reference on the group_event after placing the
12258 	 * new event on the sibling_list. This ensures destruction
12259 	 * of the group leader will find the pointer to itself in
12260 	 * perf_group_detach().
12261 	 */
12262 	fdput(group);
12263 	fd_install(event_fd, event_file);
12264 	return event_fd;
12265 
12266 err_locked:
12267 	if (move_group)
12268 		perf_event_ctx_unlock(group_leader, gctx);
12269 	mutex_unlock(&ctx->mutex);
12270 err_cred:
12271 	if (task)
12272 		up_read(&task->signal->exec_update_lock);
12273 err_file:
12274 	fput(event_file);
12275 err_context:
12276 	perf_unpin_context(ctx);
12277 	put_ctx(ctx);
12278 err_alloc:
12279 	/*
12280 	 * If event_file is set, the fput() above will have called ->release()
12281 	 * and that will take care of freeing the event.
12282 	 */
12283 	if (!event_file)
12284 		free_event(event);
12285 err_task:
12286 	if (task)
12287 		put_task_struct(task);
12288 err_group_fd:
12289 	fdput(group);
12290 err_fd:
12291 	put_unused_fd(event_fd);
12292 	return err;
12293 }
12294 
12295 /**
12296  * perf_event_create_kernel_counter
12297  *
12298  * @attr: attributes of the counter to create
12299  * @cpu: cpu in which the counter is bound
12300  * @task: task to profile (NULL for percpu)
12301  */
12302 struct perf_event *
perf_event_create_kernel_counter(struct perf_event_attr * attr,int cpu,struct task_struct * task,perf_overflow_handler_t overflow_handler,void * context)12303 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
12304 				 struct task_struct *task,
12305 				 perf_overflow_handler_t overflow_handler,
12306 				 void *context)
12307 {
12308 	struct perf_event_context *ctx;
12309 	struct perf_event *event;
12310 	int err;
12311 
12312 	/*
12313 	 * Grouping is not supported for kernel events, neither is 'AUX',
12314 	 * make sure the caller's intentions are adjusted.
12315 	 */
12316 	if (attr->aux_output)
12317 		return ERR_PTR(-EINVAL);
12318 
12319 	event = perf_event_alloc(attr, cpu, task, NULL, NULL,
12320 				 overflow_handler, context, -1);
12321 	if (IS_ERR(event)) {
12322 		err = PTR_ERR(event);
12323 		goto err;
12324 	}
12325 
12326 	/* Mark owner so we could distinguish it from user events. */
12327 	event->owner = TASK_TOMBSTONE;
12328 
12329 	/*
12330 	 * Get the target context (task or percpu):
12331 	 */
12332 	ctx = find_get_context(event->pmu, task, event);
12333 	if (IS_ERR(ctx)) {
12334 		err = PTR_ERR(ctx);
12335 		goto err_free;
12336 	}
12337 
12338 	WARN_ON_ONCE(ctx->parent_ctx);
12339 	mutex_lock(&ctx->mutex);
12340 	if (ctx->task == TASK_TOMBSTONE) {
12341 		err = -ESRCH;
12342 		goto err_unlock;
12343 	}
12344 
12345 	if (!task) {
12346 		/*
12347 		 * Check if the @cpu we're creating an event for is online.
12348 		 *
12349 		 * We use the perf_cpu_context::ctx::mutex to serialize against
12350 		 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
12351 		 */
12352 		struct perf_cpu_context *cpuctx =
12353 			container_of(ctx, struct perf_cpu_context, ctx);
12354 		if (!cpuctx->online) {
12355 			err = -ENODEV;
12356 			goto err_unlock;
12357 		}
12358 	}
12359 
12360 	if (!exclusive_event_installable(event, ctx)) {
12361 		err = -EBUSY;
12362 		goto err_unlock;
12363 	}
12364 
12365 	perf_install_in_context(ctx, event, event->cpu);
12366 	perf_unpin_context(ctx);
12367 	mutex_unlock(&ctx->mutex);
12368 
12369 	return event;
12370 
12371 err_unlock:
12372 	mutex_unlock(&ctx->mutex);
12373 	perf_unpin_context(ctx);
12374 	put_ctx(ctx);
12375 err_free:
12376 	free_event(event);
12377 err:
12378 	return ERR_PTR(err);
12379 }
12380 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
12381 
perf_pmu_migrate_context(struct pmu * pmu,int src_cpu,int dst_cpu)12382 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
12383 {
12384 	struct perf_event_context *src_ctx;
12385 	struct perf_event_context *dst_ctx;
12386 	struct perf_event *event, *tmp;
12387 	LIST_HEAD(events);
12388 
12389 	src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
12390 	dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
12391 
12392 	/*
12393 	 * See perf_event_ctx_lock() for comments on the details
12394 	 * of swizzling perf_event::ctx.
12395 	 */
12396 	mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
12397 	list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
12398 				 event_entry) {
12399 		perf_remove_from_context(event, 0);
12400 		unaccount_event_cpu(event, src_cpu);
12401 		put_ctx(src_ctx);
12402 		list_add(&event->migrate_entry, &events);
12403 	}
12404 
12405 	/*
12406 	 * Wait for the events to quiesce before re-instating them.
12407 	 */
12408 	synchronize_rcu();
12409 
12410 	/*
12411 	 * Re-instate events in 2 passes.
12412 	 *
12413 	 * Skip over group leaders and only install siblings on this first
12414 	 * pass, siblings will not get enabled without a leader, however a
12415 	 * leader will enable its siblings, even if those are still on the old
12416 	 * context.
12417 	 */
12418 	list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
12419 		if (event->group_leader == event)
12420 			continue;
12421 
12422 		list_del(&event->migrate_entry);
12423 		if (event->state >= PERF_EVENT_STATE_OFF)
12424 			event->state = PERF_EVENT_STATE_INACTIVE;
12425 		account_event_cpu(event, dst_cpu);
12426 		perf_install_in_context(dst_ctx, event, dst_cpu);
12427 		get_ctx(dst_ctx);
12428 	}
12429 
12430 	/*
12431 	 * Once all the siblings are setup properly, install the group leaders
12432 	 * to make it go.
12433 	 */
12434 	list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
12435 		list_del(&event->migrate_entry);
12436 		if (event->state >= PERF_EVENT_STATE_OFF)
12437 			event->state = PERF_EVENT_STATE_INACTIVE;
12438 		account_event_cpu(event, dst_cpu);
12439 		perf_install_in_context(dst_ctx, event, dst_cpu);
12440 		get_ctx(dst_ctx);
12441 	}
12442 	mutex_unlock(&dst_ctx->mutex);
12443 	mutex_unlock(&src_ctx->mutex);
12444 }
12445 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
12446 
sync_child_event(struct perf_event * child_event,struct task_struct * child)12447 static void sync_child_event(struct perf_event *child_event,
12448 			       struct task_struct *child)
12449 {
12450 	struct perf_event *parent_event = child_event->parent;
12451 	u64 child_val;
12452 
12453 	if (child_event->attr.inherit_stat)
12454 		perf_event_read_event(child_event, child);
12455 
12456 	child_val = perf_event_count(child_event);
12457 
12458 	/*
12459 	 * Add back the child's count to the parent's count:
12460 	 */
12461 	atomic64_add(child_val, &parent_event->child_count);
12462 	atomic64_add(child_event->total_time_enabled,
12463 		     &parent_event->child_total_time_enabled);
12464 	atomic64_add(child_event->total_time_running,
12465 		     &parent_event->child_total_time_running);
12466 }
12467 
12468 static void
perf_event_exit_event(struct perf_event * child_event,struct perf_event_context * child_ctx,struct task_struct * child)12469 perf_event_exit_event(struct perf_event *child_event,
12470 		      struct perf_event_context *child_ctx,
12471 		      struct task_struct *child)
12472 {
12473 	struct perf_event *parent_event = child_event->parent;
12474 
12475 	/*
12476 	 * Do not destroy the 'original' grouping; because of the context
12477 	 * switch optimization the original events could've ended up in a
12478 	 * random child task.
12479 	 *
12480 	 * If we were to destroy the original group, all group related
12481 	 * operations would cease to function properly after this random
12482 	 * child dies.
12483 	 *
12484 	 * Do destroy all inherited groups, we don't care about those
12485 	 * and being thorough is better.
12486 	 */
12487 	raw_spin_lock_irq(&child_ctx->lock);
12488 	WARN_ON_ONCE(child_ctx->is_active);
12489 
12490 	if (parent_event)
12491 		perf_group_detach(child_event);
12492 	list_del_event(child_event, child_ctx);
12493 	perf_event_set_state(child_event, PERF_EVENT_STATE_EXIT); /* is_event_hup() */
12494 	raw_spin_unlock_irq(&child_ctx->lock);
12495 
12496 	/*
12497 	 * Parent events are governed by their filedesc, retain them.
12498 	 */
12499 	if (!parent_event) {
12500 		perf_event_wakeup(child_event);
12501 		return;
12502 	}
12503 	/*
12504 	 * Child events can be cleaned up.
12505 	 */
12506 
12507 	sync_child_event(child_event, child);
12508 
12509 	/*
12510 	 * Remove this event from the parent's list
12511 	 */
12512 	WARN_ON_ONCE(parent_event->ctx->parent_ctx);
12513 	mutex_lock(&parent_event->child_mutex);
12514 	list_del_init(&child_event->child_list);
12515 	mutex_unlock(&parent_event->child_mutex);
12516 
12517 	/*
12518 	 * Kick perf_poll() for is_event_hup().
12519 	 */
12520 	perf_event_wakeup(parent_event);
12521 	free_event(child_event);
12522 	put_event(parent_event);
12523 }
12524 
perf_event_exit_task_context(struct task_struct * child,int ctxn)12525 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
12526 {
12527 	struct perf_event_context *child_ctx, *clone_ctx = NULL;
12528 	struct perf_event *child_event, *next;
12529 
12530 	WARN_ON_ONCE(child != current);
12531 
12532 	child_ctx = perf_pin_task_context(child, ctxn);
12533 	if (!child_ctx)
12534 		return;
12535 
12536 	/*
12537 	 * In order to reduce the amount of tricky in ctx tear-down, we hold
12538 	 * ctx::mutex over the entire thing. This serializes against almost
12539 	 * everything that wants to access the ctx.
12540 	 *
12541 	 * The exception is sys_perf_event_open() /
12542 	 * perf_event_create_kernel_count() which does find_get_context()
12543 	 * without ctx::mutex (it cannot because of the move_group double mutex
12544 	 * lock thing). See the comments in perf_install_in_context().
12545 	 */
12546 	mutex_lock(&child_ctx->mutex);
12547 
12548 	/*
12549 	 * In a single ctx::lock section, de-schedule the events and detach the
12550 	 * context from the task such that we cannot ever get it scheduled back
12551 	 * in.
12552 	 */
12553 	raw_spin_lock_irq(&child_ctx->lock);
12554 	task_ctx_sched_out(__get_cpu_context(child_ctx), child_ctx, EVENT_ALL);
12555 
12556 	/*
12557 	 * Now that the context is inactive, destroy the task <-> ctx relation
12558 	 * and mark the context dead.
12559 	 */
12560 	RCU_INIT_POINTER(child->perf_event_ctxp[ctxn], NULL);
12561 	put_ctx(child_ctx); /* cannot be last */
12562 	WRITE_ONCE(child_ctx->task, TASK_TOMBSTONE);
12563 	put_task_struct(current); /* cannot be last */
12564 
12565 	clone_ctx = unclone_ctx(child_ctx);
12566 	raw_spin_unlock_irq(&child_ctx->lock);
12567 
12568 	if (clone_ctx)
12569 		put_ctx(clone_ctx);
12570 
12571 	/*
12572 	 * Report the task dead after unscheduling the events so that we
12573 	 * won't get any samples after PERF_RECORD_EXIT. We can however still
12574 	 * get a few PERF_RECORD_READ events.
12575 	 */
12576 	perf_event_task(child, child_ctx, 0);
12577 
12578 	list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
12579 		perf_event_exit_event(child_event, child_ctx, child);
12580 
12581 	mutex_unlock(&child_ctx->mutex);
12582 
12583 	put_ctx(child_ctx);
12584 }
12585 
12586 /*
12587  * When a child task exits, feed back event values to parent events.
12588  *
12589  * Can be called with exec_update_lock held when called from
12590  * setup_new_exec().
12591  */
perf_event_exit_task(struct task_struct * child)12592 void perf_event_exit_task(struct task_struct *child)
12593 {
12594 	struct perf_event *event, *tmp;
12595 	int ctxn;
12596 
12597 	mutex_lock(&child->perf_event_mutex);
12598 	list_for_each_entry_safe(event, tmp, &child->perf_event_list,
12599 				 owner_entry) {
12600 		list_del_init(&event->owner_entry);
12601 
12602 		/*
12603 		 * Ensure the list deletion is visible before we clear
12604 		 * the owner, closes a race against perf_release() where
12605 		 * we need to serialize on the owner->perf_event_mutex.
12606 		 */
12607 		smp_store_release(&event->owner, NULL);
12608 	}
12609 	mutex_unlock(&child->perf_event_mutex);
12610 
12611 	for_each_task_context_nr(ctxn)
12612 		perf_event_exit_task_context(child, ctxn);
12613 
12614 	/*
12615 	 * The perf_event_exit_task_context calls perf_event_task
12616 	 * with child's task_ctx, which generates EXIT events for
12617 	 * child contexts and sets child->perf_event_ctxp[] to NULL.
12618 	 * At this point we need to send EXIT events to cpu contexts.
12619 	 */
12620 	perf_event_task(child, NULL, 0);
12621 }
12622 
perf_free_event(struct perf_event * event,struct perf_event_context * ctx)12623 static void perf_free_event(struct perf_event *event,
12624 			    struct perf_event_context *ctx)
12625 {
12626 	struct perf_event *parent = event->parent;
12627 
12628 	if (WARN_ON_ONCE(!parent))
12629 		return;
12630 
12631 	mutex_lock(&parent->child_mutex);
12632 	list_del_init(&event->child_list);
12633 	mutex_unlock(&parent->child_mutex);
12634 
12635 	put_event(parent);
12636 
12637 	raw_spin_lock_irq(&ctx->lock);
12638 	perf_group_detach(event);
12639 	list_del_event(event, ctx);
12640 	raw_spin_unlock_irq(&ctx->lock);
12641 	free_event(event);
12642 }
12643 
12644 /*
12645  * Free a context as created by inheritance by perf_event_init_task() below,
12646  * used by fork() in case of fail.
12647  *
12648  * Even though the task has never lived, the context and events have been
12649  * exposed through the child_list, so we must take care tearing it all down.
12650  */
perf_event_free_task(struct task_struct * task)12651 void perf_event_free_task(struct task_struct *task)
12652 {
12653 	struct perf_event_context *ctx;
12654 	struct perf_event *event, *tmp;
12655 	int ctxn;
12656 
12657 	for_each_task_context_nr(ctxn) {
12658 		ctx = task->perf_event_ctxp[ctxn];
12659 		if (!ctx)
12660 			continue;
12661 
12662 		mutex_lock(&ctx->mutex);
12663 		raw_spin_lock_irq(&ctx->lock);
12664 		/*
12665 		 * Destroy the task <-> ctx relation and mark the context dead.
12666 		 *
12667 		 * This is important because even though the task hasn't been
12668 		 * exposed yet the context has been (through child_list).
12669 		 */
12670 		RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], NULL);
12671 		WRITE_ONCE(ctx->task, TASK_TOMBSTONE);
12672 		put_task_struct(task); /* cannot be last */
12673 		raw_spin_unlock_irq(&ctx->lock);
12674 
12675 		list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry)
12676 			perf_free_event(event, ctx);
12677 
12678 		mutex_unlock(&ctx->mutex);
12679 
12680 		/*
12681 		 * perf_event_release_kernel() could've stolen some of our
12682 		 * child events and still have them on its free_list. In that
12683 		 * case we must wait for these events to have been freed (in
12684 		 * particular all their references to this task must've been
12685 		 * dropped).
12686 		 *
12687 		 * Without this copy_process() will unconditionally free this
12688 		 * task (irrespective of its reference count) and
12689 		 * _free_event()'s put_task_struct(event->hw.target) will be a
12690 		 * use-after-free.
12691 		 *
12692 		 * Wait for all events to drop their context reference.
12693 		 */
12694 		wait_var_event(&ctx->refcount, refcount_read(&ctx->refcount) == 1);
12695 		put_ctx(ctx); /* must be last */
12696 	}
12697 }
12698 
perf_event_delayed_put(struct task_struct * task)12699 void perf_event_delayed_put(struct task_struct *task)
12700 {
12701 	int ctxn;
12702 
12703 	for_each_task_context_nr(ctxn)
12704 		WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
12705 }
12706 
perf_event_get(unsigned int fd)12707 struct file *perf_event_get(unsigned int fd)
12708 {
12709 	struct file *file = fget(fd);
12710 	if (!file)
12711 		return ERR_PTR(-EBADF);
12712 
12713 	if (file->f_op != &perf_fops) {
12714 		fput(file);
12715 		return ERR_PTR(-EBADF);
12716 	}
12717 
12718 	return file;
12719 }
12720 
perf_get_event(struct file * file)12721 const struct perf_event *perf_get_event(struct file *file)
12722 {
12723 	if (file->f_op != &perf_fops)
12724 		return ERR_PTR(-EINVAL);
12725 
12726 	return file->private_data;
12727 }
12728 
perf_event_attrs(struct perf_event * event)12729 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
12730 {
12731 	if (!event)
12732 		return ERR_PTR(-EINVAL);
12733 
12734 	return &event->attr;
12735 }
12736 
12737 /*
12738  * Inherit an event from parent task to child task.
12739  *
12740  * Returns:
12741  *  - valid pointer on success
12742  *  - NULL for orphaned events
12743  *  - IS_ERR() on error
12744  */
12745 static struct perf_event *
inherit_event(struct perf_event * parent_event,struct task_struct * parent,struct perf_event_context * parent_ctx,struct task_struct * child,struct perf_event * group_leader,struct perf_event_context * child_ctx)12746 inherit_event(struct perf_event *parent_event,
12747 	      struct task_struct *parent,
12748 	      struct perf_event_context *parent_ctx,
12749 	      struct task_struct *child,
12750 	      struct perf_event *group_leader,
12751 	      struct perf_event_context *child_ctx)
12752 {
12753 	enum perf_event_state parent_state = parent_event->state;
12754 	struct perf_event *child_event;
12755 	unsigned long flags;
12756 
12757 	/*
12758 	 * Instead of creating recursive hierarchies of events,
12759 	 * we link inherited events back to the original parent,
12760 	 * which has a filp for sure, which we use as the reference
12761 	 * count:
12762 	 */
12763 	if (parent_event->parent)
12764 		parent_event = parent_event->parent;
12765 
12766 	child_event = perf_event_alloc(&parent_event->attr,
12767 					   parent_event->cpu,
12768 					   child,
12769 					   group_leader, parent_event,
12770 					   NULL, NULL, -1);
12771 	if (IS_ERR(child_event))
12772 		return child_event;
12773 
12774 
12775 	if ((child_event->attach_state & PERF_ATTACH_TASK_DATA) &&
12776 	    !child_ctx->task_ctx_data) {
12777 		struct pmu *pmu = child_event->pmu;
12778 
12779 		child_ctx->task_ctx_data = alloc_task_ctx_data(pmu);
12780 		if (!child_ctx->task_ctx_data) {
12781 			free_event(child_event);
12782 			return ERR_PTR(-ENOMEM);
12783 		}
12784 	}
12785 
12786 	/*
12787 	 * is_orphaned_event() and list_add_tail(&parent_event->child_list)
12788 	 * must be under the same lock in order to serialize against
12789 	 * perf_event_release_kernel(), such that either we must observe
12790 	 * is_orphaned_event() or they will observe us on the child_list.
12791 	 */
12792 	mutex_lock(&parent_event->child_mutex);
12793 	if (is_orphaned_event(parent_event) ||
12794 	    !atomic_long_inc_not_zero(&parent_event->refcount)) {
12795 		mutex_unlock(&parent_event->child_mutex);
12796 		/* task_ctx_data is freed with child_ctx */
12797 		free_event(child_event);
12798 		return NULL;
12799 	}
12800 
12801 	get_ctx(child_ctx);
12802 
12803 	/*
12804 	 * Make the child state follow the state of the parent event,
12805 	 * not its attr.disabled bit.  We hold the parent's mutex,
12806 	 * so we won't race with perf_event_{en, dis}able_family.
12807 	 */
12808 	if (parent_state >= PERF_EVENT_STATE_INACTIVE)
12809 		child_event->state = PERF_EVENT_STATE_INACTIVE;
12810 	else
12811 		child_event->state = PERF_EVENT_STATE_OFF;
12812 
12813 	if (parent_event->attr.freq) {
12814 		u64 sample_period = parent_event->hw.sample_period;
12815 		struct hw_perf_event *hwc = &child_event->hw;
12816 
12817 		hwc->sample_period = sample_period;
12818 		hwc->last_period   = sample_period;
12819 
12820 		local64_set(&hwc->period_left, sample_period);
12821 	}
12822 
12823 	child_event->ctx = child_ctx;
12824 	child_event->overflow_handler = parent_event->overflow_handler;
12825 	child_event->overflow_handler_context
12826 		= parent_event->overflow_handler_context;
12827 
12828 	/*
12829 	 * Precalculate sample_data sizes
12830 	 */
12831 	perf_event__header_size(child_event);
12832 	perf_event__id_header_size(child_event);
12833 
12834 	/*
12835 	 * Link it up in the child's context:
12836 	 */
12837 	raw_spin_lock_irqsave(&child_ctx->lock, flags);
12838 	add_event_to_ctx(child_event, child_ctx);
12839 	raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
12840 
12841 	/*
12842 	 * Link this into the parent event's child list
12843 	 */
12844 	list_add_tail(&child_event->child_list, &parent_event->child_list);
12845 	mutex_unlock(&parent_event->child_mutex);
12846 
12847 	return child_event;
12848 }
12849 
12850 /*
12851  * Inherits an event group.
12852  *
12853  * This will quietly suppress orphaned events; !inherit_event() is not an error.
12854  * This matches with perf_event_release_kernel() removing all child events.
12855  *
12856  * Returns:
12857  *  - 0 on success
12858  *  - <0 on error
12859  */
inherit_group(struct perf_event * parent_event,struct task_struct * parent,struct perf_event_context * parent_ctx,struct task_struct * child,struct perf_event_context * child_ctx)12860 static int inherit_group(struct perf_event *parent_event,
12861 	      struct task_struct *parent,
12862 	      struct perf_event_context *parent_ctx,
12863 	      struct task_struct *child,
12864 	      struct perf_event_context *child_ctx)
12865 {
12866 	struct perf_event *leader;
12867 	struct perf_event *sub;
12868 	struct perf_event *child_ctr;
12869 
12870 	leader = inherit_event(parent_event, parent, parent_ctx,
12871 				 child, NULL, child_ctx);
12872 	if (IS_ERR(leader))
12873 		return PTR_ERR(leader);
12874 	/*
12875 	 * @leader can be NULL here because of is_orphaned_event(). In this
12876 	 * case inherit_event() will create individual events, similar to what
12877 	 * perf_group_detach() would do anyway.
12878 	 */
12879 	for_each_sibling_event(sub, parent_event) {
12880 		child_ctr = inherit_event(sub, parent, parent_ctx,
12881 					    child, leader, child_ctx);
12882 		if (IS_ERR(child_ctr))
12883 			return PTR_ERR(child_ctr);
12884 
12885 		if (sub->aux_event == parent_event && child_ctr &&
12886 		    !perf_get_aux_event(child_ctr, leader))
12887 			return -EINVAL;
12888 	}
12889 	if (leader)
12890 		leader->group_generation = parent_event->group_generation;
12891 	return 0;
12892 }
12893 
12894 /*
12895  * Creates the child task context and tries to inherit the event-group.
12896  *
12897  * Clears @inherited_all on !attr.inherited or error. Note that we'll leave
12898  * inherited_all set when we 'fail' to inherit an orphaned event; this is
12899  * consistent with perf_event_release_kernel() removing all child events.
12900  *
12901  * Returns:
12902  *  - 0 on success
12903  *  - <0 on error
12904  */
12905 static int
inherit_task_group(struct perf_event * event,struct task_struct * parent,struct perf_event_context * parent_ctx,struct task_struct * child,int ctxn,int * inherited_all)12906 inherit_task_group(struct perf_event *event, struct task_struct *parent,
12907 		   struct perf_event_context *parent_ctx,
12908 		   struct task_struct *child, int ctxn,
12909 		   int *inherited_all)
12910 {
12911 	int ret;
12912 	struct perf_event_context *child_ctx;
12913 
12914 	if (!event->attr.inherit) {
12915 		*inherited_all = 0;
12916 		return 0;
12917 	}
12918 
12919 	child_ctx = child->perf_event_ctxp[ctxn];
12920 	if (!child_ctx) {
12921 		/*
12922 		 * This is executed from the parent task context, so
12923 		 * inherit events that have been marked for cloning.
12924 		 * First allocate and initialize a context for the
12925 		 * child.
12926 		 */
12927 		child_ctx = alloc_perf_context(parent_ctx->pmu, child);
12928 		if (!child_ctx)
12929 			return -ENOMEM;
12930 
12931 		child->perf_event_ctxp[ctxn] = child_ctx;
12932 	}
12933 
12934 	ret = inherit_group(event, parent, parent_ctx,
12935 			    child, child_ctx);
12936 
12937 	if (ret)
12938 		*inherited_all = 0;
12939 
12940 	return ret;
12941 }
12942 
12943 /*
12944  * Initialize the perf_event context in task_struct
12945  */
perf_event_init_context(struct task_struct * child,int ctxn)12946 static int perf_event_init_context(struct task_struct *child, int ctxn)
12947 {
12948 	struct perf_event_context *child_ctx, *parent_ctx;
12949 	struct perf_event_context *cloned_ctx;
12950 	struct perf_event *event;
12951 	struct task_struct *parent = current;
12952 	int inherited_all = 1;
12953 	unsigned long flags;
12954 	int ret = 0;
12955 
12956 	if (likely(!parent->perf_event_ctxp[ctxn]))
12957 		return 0;
12958 
12959 	/*
12960 	 * If the parent's context is a clone, pin it so it won't get
12961 	 * swapped under us.
12962 	 */
12963 	parent_ctx = perf_pin_task_context(parent, ctxn);
12964 	if (!parent_ctx)
12965 		return 0;
12966 
12967 	/*
12968 	 * No need to check if parent_ctx != NULL here; since we saw
12969 	 * it non-NULL earlier, the only reason for it to become NULL
12970 	 * is if we exit, and since we're currently in the middle of
12971 	 * a fork we can't be exiting at the same time.
12972 	 */
12973 
12974 	/*
12975 	 * Lock the parent list. No need to lock the child - not PID
12976 	 * hashed yet and not running, so nobody can access it.
12977 	 */
12978 	mutex_lock(&parent_ctx->mutex);
12979 
12980 	/*
12981 	 * We dont have to disable NMIs - we are only looking at
12982 	 * the list, not manipulating it:
12983 	 */
12984 	perf_event_groups_for_each(event, &parent_ctx->pinned_groups) {
12985 		ret = inherit_task_group(event, parent, parent_ctx,
12986 					 child, ctxn, &inherited_all);
12987 		if (ret)
12988 			goto out_unlock;
12989 	}
12990 
12991 	/*
12992 	 * We can't hold ctx->lock when iterating the ->flexible_group list due
12993 	 * to allocations, but we need to prevent rotation because
12994 	 * rotate_ctx() will change the list from interrupt context.
12995 	 */
12996 	raw_spin_lock_irqsave(&parent_ctx->lock, flags);
12997 	parent_ctx->rotate_disable = 1;
12998 	raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
12999 
13000 	perf_event_groups_for_each(event, &parent_ctx->flexible_groups) {
13001 		ret = inherit_task_group(event, parent, parent_ctx,
13002 					 child, ctxn, &inherited_all);
13003 		if (ret)
13004 			goto out_unlock;
13005 	}
13006 
13007 	raw_spin_lock_irqsave(&parent_ctx->lock, flags);
13008 	parent_ctx->rotate_disable = 0;
13009 
13010 	child_ctx = child->perf_event_ctxp[ctxn];
13011 
13012 	if (child_ctx && inherited_all) {
13013 		/*
13014 		 * Mark the child context as a clone of the parent
13015 		 * context, or of whatever the parent is a clone of.
13016 		 *
13017 		 * Note that if the parent is a clone, the holding of
13018 		 * parent_ctx->lock avoids it from being uncloned.
13019 		 */
13020 		cloned_ctx = parent_ctx->parent_ctx;
13021 		if (cloned_ctx) {
13022 			child_ctx->parent_ctx = cloned_ctx;
13023 			child_ctx->parent_gen = parent_ctx->parent_gen;
13024 		} else {
13025 			child_ctx->parent_ctx = parent_ctx;
13026 			child_ctx->parent_gen = parent_ctx->generation;
13027 		}
13028 		get_ctx(child_ctx->parent_ctx);
13029 	}
13030 
13031 	raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
13032 out_unlock:
13033 	mutex_unlock(&parent_ctx->mutex);
13034 
13035 	perf_unpin_context(parent_ctx);
13036 	put_ctx(parent_ctx);
13037 
13038 	return ret;
13039 }
13040 
13041 /*
13042  * Initialize the perf_event context in task_struct
13043  */
perf_event_init_task(struct task_struct * child)13044 int perf_event_init_task(struct task_struct *child)
13045 {
13046 	int ctxn, ret;
13047 
13048 	memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
13049 	mutex_init(&child->perf_event_mutex);
13050 	INIT_LIST_HEAD(&child->perf_event_list);
13051 
13052 	for_each_task_context_nr(ctxn) {
13053 		ret = perf_event_init_context(child, ctxn);
13054 		if (ret) {
13055 			perf_event_free_task(child);
13056 			return ret;
13057 		}
13058 	}
13059 
13060 	return 0;
13061 }
13062 
perf_event_init_all_cpus(void)13063 static void __init perf_event_init_all_cpus(void)
13064 {
13065 	struct swevent_htable *swhash;
13066 	int cpu;
13067 
13068 	zalloc_cpumask_var(&perf_online_mask, GFP_KERNEL);
13069 
13070 	for_each_possible_cpu(cpu) {
13071 		swhash = &per_cpu(swevent_htable, cpu);
13072 		mutex_init(&swhash->hlist_mutex);
13073 		INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
13074 
13075 		INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu));
13076 		raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu));
13077 
13078 #ifdef CONFIG_CGROUP_PERF
13079 		INIT_LIST_HEAD(&per_cpu(cgrp_cpuctx_list, cpu));
13080 #endif
13081 		INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu));
13082 	}
13083 }
13084 
perf_swevent_init_cpu(unsigned int cpu)13085 static void perf_swevent_init_cpu(unsigned int cpu)
13086 {
13087 	struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
13088 
13089 	mutex_lock(&swhash->hlist_mutex);
13090 	if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
13091 		struct swevent_hlist *hlist;
13092 
13093 		hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
13094 		WARN_ON(!hlist);
13095 		rcu_assign_pointer(swhash->swevent_hlist, hlist);
13096 	}
13097 	mutex_unlock(&swhash->hlist_mutex);
13098 }
13099 
13100 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
__perf_event_exit_context(void * __info)13101 static void __perf_event_exit_context(void *__info)
13102 {
13103 	struct perf_event_context *ctx = __info;
13104 	struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
13105 	struct perf_event *event;
13106 
13107 	raw_spin_lock(&ctx->lock);
13108 	ctx_sched_out(ctx, cpuctx, EVENT_TIME);
13109 	list_for_each_entry(event, &ctx->event_list, event_entry)
13110 		__perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
13111 	raw_spin_unlock(&ctx->lock);
13112 }
13113 
perf_event_exit_cpu_context(int cpu)13114 static void perf_event_exit_cpu_context(int cpu)
13115 {
13116 	struct perf_cpu_context *cpuctx;
13117 	struct perf_event_context *ctx;
13118 	struct pmu *pmu;
13119 
13120 	mutex_lock(&pmus_lock);
13121 	list_for_each_entry(pmu, &pmus, entry) {
13122 		cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
13123 		ctx = &cpuctx->ctx;
13124 
13125 		mutex_lock(&ctx->mutex);
13126 		smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
13127 		cpuctx->online = 0;
13128 		mutex_unlock(&ctx->mutex);
13129 	}
13130 	cpumask_clear_cpu(cpu, perf_online_mask);
13131 	mutex_unlock(&pmus_lock);
13132 }
13133 #else
13134 
perf_event_exit_cpu_context(int cpu)13135 static void perf_event_exit_cpu_context(int cpu) { }
13136 
13137 #endif
13138 
perf_event_init_cpu(unsigned int cpu)13139 int perf_event_init_cpu(unsigned int cpu)
13140 {
13141 	struct perf_cpu_context *cpuctx;
13142 	struct perf_event_context *ctx;
13143 	struct pmu *pmu;
13144 
13145 	perf_swevent_init_cpu(cpu);
13146 
13147 	mutex_lock(&pmus_lock);
13148 	cpumask_set_cpu(cpu, perf_online_mask);
13149 	list_for_each_entry(pmu, &pmus, entry) {
13150 		cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
13151 		ctx = &cpuctx->ctx;
13152 
13153 		mutex_lock(&ctx->mutex);
13154 		cpuctx->online = 1;
13155 		mutex_unlock(&ctx->mutex);
13156 	}
13157 	mutex_unlock(&pmus_lock);
13158 
13159 	return 0;
13160 }
13161 
perf_event_exit_cpu(unsigned int cpu)13162 int perf_event_exit_cpu(unsigned int cpu)
13163 {
13164 	perf_event_exit_cpu_context(cpu);
13165 	return 0;
13166 }
13167 
13168 static int
perf_reboot(struct notifier_block * notifier,unsigned long val,void * v)13169 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
13170 {
13171 	int cpu;
13172 
13173 	for_each_online_cpu(cpu)
13174 		perf_event_exit_cpu(cpu);
13175 
13176 	return NOTIFY_OK;
13177 }
13178 
13179 /*
13180  * Run the perf reboot notifier at the very last possible moment so that
13181  * the generic watchdog code runs as long as possible.
13182  */
13183 static struct notifier_block perf_reboot_notifier = {
13184 	.notifier_call = perf_reboot,
13185 	.priority = INT_MIN,
13186 };
13187 
perf_event_init(void)13188 void __init perf_event_init(void)
13189 {
13190 	int ret;
13191 
13192 	idr_init(&pmu_idr);
13193 
13194 	perf_event_init_all_cpus();
13195 	init_srcu_struct(&pmus_srcu);
13196 	perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
13197 	perf_pmu_register(&perf_cpu_clock, NULL, -1);
13198 	perf_pmu_register(&perf_task_clock, NULL, -1);
13199 	perf_tp_register();
13200 	perf_event_init_cpu(smp_processor_id());
13201 	register_reboot_notifier(&perf_reboot_notifier);
13202 
13203 	ret = init_hw_breakpoint();
13204 	WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
13205 
13206 	/*
13207 	 * Build time assertion that we keep the data_head at the intended
13208 	 * location.  IOW, validation we got the __reserved[] size right.
13209 	 */
13210 	BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
13211 		     != 1024);
13212 }
13213 
perf_event_sysfs_show(struct device * dev,struct device_attribute * attr,char * page)13214 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
13215 			      char *page)
13216 {
13217 	struct perf_pmu_events_attr *pmu_attr =
13218 		container_of(attr, struct perf_pmu_events_attr, attr);
13219 
13220 	if (pmu_attr->event_str)
13221 		return sprintf(page, "%s\n", pmu_attr->event_str);
13222 
13223 	return 0;
13224 }
13225 EXPORT_SYMBOL_GPL(perf_event_sysfs_show);
13226 
perf_event_sysfs_init(void)13227 static int __init perf_event_sysfs_init(void)
13228 {
13229 	struct pmu *pmu;
13230 	int ret;
13231 
13232 	mutex_lock(&pmus_lock);
13233 
13234 	ret = bus_register(&pmu_bus);
13235 	if (ret)
13236 		goto unlock;
13237 
13238 	list_for_each_entry(pmu, &pmus, entry) {
13239 		if (!pmu->name || pmu->type < 0)
13240 			continue;
13241 
13242 		ret = pmu_dev_alloc(pmu);
13243 		WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
13244 	}
13245 	pmu_bus_running = 1;
13246 	ret = 0;
13247 
13248 unlock:
13249 	mutex_unlock(&pmus_lock);
13250 
13251 	return ret;
13252 }
13253 device_initcall(perf_event_sysfs_init);
13254 
13255 #ifdef CONFIG_CGROUP_PERF
13256 static struct cgroup_subsys_state *
perf_cgroup_css_alloc(struct cgroup_subsys_state * parent_css)13257 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
13258 {
13259 	struct perf_cgroup *jc;
13260 
13261 	jc = kzalloc(sizeof(*jc), GFP_KERNEL);
13262 	if (!jc)
13263 		return ERR_PTR(-ENOMEM);
13264 
13265 	jc->info = alloc_percpu(struct perf_cgroup_info);
13266 	if (!jc->info) {
13267 		kfree(jc);
13268 		return ERR_PTR(-ENOMEM);
13269 	}
13270 
13271 	return &jc->css;
13272 }
13273 
perf_cgroup_css_free(struct cgroup_subsys_state * css)13274 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
13275 {
13276 	struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
13277 
13278 	free_percpu(jc->info);
13279 	kfree(jc);
13280 }
13281 
perf_cgroup_css_online(struct cgroup_subsys_state * css)13282 static int perf_cgroup_css_online(struct cgroup_subsys_state *css)
13283 {
13284 	perf_event_cgroup(css->cgroup);
13285 	return 0;
13286 }
13287 
__perf_cgroup_move(void * info)13288 static int __perf_cgroup_move(void *info)
13289 {
13290 	struct task_struct *task = info;
13291 	rcu_read_lock();
13292 	perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
13293 	rcu_read_unlock();
13294 	return 0;
13295 }
13296 
perf_cgroup_attach(struct cgroup_taskset * tset)13297 static void perf_cgroup_attach(struct cgroup_taskset *tset)
13298 {
13299 	struct task_struct *task;
13300 	struct cgroup_subsys_state *css;
13301 
13302 	cgroup_taskset_for_each(task, css, tset)
13303 		task_function_call(task, __perf_cgroup_move, task);
13304 }
13305 
13306 struct cgroup_subsys perf_event_cgrp_subsys = {
13307 	.css_alloc	= perf_cgroup_css_alloc,
13308 	.css_free	= perf_cgroup_css_free,
13309 	.css_online	= perf_cgroup_css_online,
13310 	.attach		= perf_cgroup_attach,
13311 	/*
13312 	 * Implicitly enable on dfl hierarchy so that perf events can
13313 	 * always be filtered by cgroup2 path as long as perf_event
13314 	 * controller is not mounted on a legacy hierarchy.
13315 	 */
13316 	.implicit_on_dfl = true,
13317 	.threaded	= true,
13318 };
13319 #endif /* CONFIG_CGROUP_PERF */
13320