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