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