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