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