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