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