• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Performance events core code:
3  *
4  *  Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
5  *  Copyright (C) 2008-2011 Red Hat, Inc., Ingo Molnar
6  *  Copyright (C) 2008-2011 Red Hat, Inc., Peter Zijlstra
7  *  Copyright  ©  2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
8  *
9  * For licensing details see kernel-base/COPYING
10  */
11 
12 #include <linux/fs.h>
13 #include <linux/mm.h>
14 #include <linux/cpu.h>
15 #include <linux/smp.h>
16 #include <linux/idr.h>
17 #include <linux/file.h>
18 #include <linux/poll.h>
19 #include <linux/slab.h>
20 #include <linux/hash.h>
21 #include <linux/tick.h>
22 #include <linux/sysfs.h>
23 #include <linux/dcache.h>
24 #include <linux/percpu.h>
25 #include <linux/ptrace.h>
26 #include <linux/reboot.h>
27 #include <linux/vmstat.h>
28 #include <linux/device.h>
29 #include <linux/export.h>
30 #include <linux/vmalloc.h>
31 #include <linux/hardirq.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 
48 #include "internal.h"
49 
50 #include <asm/irq_regs.h>
51 
52 static struct workqueue_struct *perf_wq;
53 
54 typedef int (*remote_function_f)(void *);
55 
56 struct remote_function_call {
57 	struct task_struct	*p;
58 	remote_function_f	func;
59 	void			*info;
60 	int			ret;
61 };
62 
remote_function(void * data)63 static void remote_function(void *data)
64 {
65 	struct remote_function_call *tfc = data;
66 	struct task_struct *p = tfc->p;
67 
68 	if (p) {
69 		tfc->ret = -EAGAIN;
70 		if (task_cpu(p) != smp_processor_id() || !task_curr(p))
71 			return;
72 	}
73 
74 	tfc->ret = tfc->func(tfc->info);
75 }
76 
77 /**
78  * task_function_call - call a function on the cpu on which a task runs
79  * @p:		the task to evaluate
80  * @func:	the function to be called
81  * @info:	the function call argument
82  *
83  * Calls the function @func when the task is currently running. This might
84  * be on the current CPU, which just calls the function directly
85  *
86  * returns: @func return value, or
87  *	    -ESRCH  - when the process isn't running
88  *	    -EAGAIN - when the process moved away
89  */
90 static int
task_function_call(struct task_struct * p,remote_function_f func,void * info)91 task_function_call(struct task_struct *p, remote_function_f func, void *info)
92 {
93 	struct remote_function_call data = {
94 		.p	= p,
95 		.func	= func,
96 		.info	= info,
97 		.ret	= -ESRCH, /* No such (running) process */
98 	};
99 
100 	if (task_curr(p))
101 		smp_call_function_single(task_cpu(p), remote_function, &data, 1);
102 
103 	return data.ret;
104 }
105 
106 /**
107  * cpu_function_call - call a function on the cpu
108  * @func:	the function to be called
109  * @info:	the function call argument
110  *
111  * Calls the function @func on the remote cpu.
112  *
113  * returns: @func return value or -ENXIO when the cpu is offline
114  */
cpu_function_call(int cpu,remote_function_f func,void * info)115 static int cpu_function_call(int cpu, remote_function_f func, void *info)
116 {
117 	struct remote_function_call data = {
118 		.p	= NULL,
119 		.func	= func,
120 		.info	= info,
121 		.ret	= -ENXIO, /* No such CPU */
122 	};
123 
124 	smp_call_function_single(cpu, remote_function, &data, 1);
125 
126 	return data.ret;
127 }
128 
129 #define EVENT_OWNER_KERNEL ((void *) -1)
130 
is_kernel_event(struct perf_event * event)131 static bool is_kernel_event(struct perf_event *event)
132 {
133 	return event->owner == EVENT_OWNER_KERNEL;
134 }
135 
136 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
137 		       PERF_FLAG_FD_OUTPUT  |\
138 		       PERF_FLAG_PID_CGROUP |\
139 		       PERF_FLAG_FD_CLOEXEC)
140 
141 /*
142  * branch priv levels that need permission checks
143  */
144 #define PERF_SAMPLE_BRANCH_PERM_PLM \
145 	(PERF_SAMPLE_BRANCH_KERNEL |\
146 	 PERF_SAMPLE_BRANCH_HV)
147 
148 enum event_type_t {
149 	EVENT_FLEXIBLE = 0x1,
150 	EVENT_PINNED = 0x2,
151 	EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
152 };
153 
154 /*
155  * perf_sched_events : >0 events exist
156  * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
157  */
158 struct static_key_deferred perf_sched_events __read_mostly;
159 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
160 static DEFINE_PER_CPU(int, perf_sched_cb_usages);
161 
162 static atomic_t nr_mmap_events __read_mostly;
163 static atomic_t nr_comm_events __read_mostly;
164 static atomic_t nr_task_events __read_mostly;
165 static atomic_t nr_freq_events __read_mostly;
166 static atomic_t nr_switch_events __read_mostly;
167 
168 static LIST_HEAD(pmus);
169 static DEFINE_MUTEX(pmus_lock);
170 static struct srcu_struct pmus_srcu;
171 
172 /*
173  * perf event paranoia level:
174  *  -1 - not paranoid at all
175  *   0 - disallow raw tracepoint access for unpriv
176  *   1 - disallow cpu events for unpriv
177  *   2 - disallow kernel profiling for unpriv
178  *   3 - disallow all unpriv perf event use
179  */
180 #ifdef CONFIG_SECURITY_PERF_EVENTS_RESTRICT
181 int sysctl_perf_event_paranoid __read_mostly = 3;
182 #else
183 int sysctl_perf_event_paranoid __read_mostly = 1;
184 #endif
185 
186 /* Minimum for 512 kiB + 1 user control page */
187 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
188 
189 /*
190  * max perf event sample rate
191  */
192 #define DEFAULT_MAX_SAMPLE_RATE		100000
193 #define DEFAULT_SAMPLE_PERIOD_NS	(NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
194 #define DEFAULT_CPU_TIME_MAX_PERCENT	25
195 
196 int sysctl_perf_event_sample_rate __read_mostly	= DEFAULT_MAX_SAMPLE_RATE;
197 
198 static int max_samples_per_tick __read_mostly	= DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
199 static int perf_sample_period_ns __read_mostly	= DEFAULT_SAMPLE_PERIOD_NS;
200 
201 static int perf_sample_allowed_ns __read_mostly =
202 	DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
203 
update_perf_cpu_limits(void)204 static void update_perf_cpu_limits(void)
205 {
206 	u64 tmp = perf_sample_period_ns;
207 
208 	tmp *= sysctl_perf_cpu_time_max_percent;
209 	do_div(tmp, 100);
210 	ACCESS_ONCE(perf_sample_allowed_ns) = tmp;
211 }
212 
213 static int perf_rotate_context(struct perf_cpu_context *cpuctx);
214 
perf_proc_update_handler(struct ctl_table * table,int write,void __user * buffer,size_t * lenp,loff_t * ppos)215 int perf_proc_update_handler(struct ctl_table *table, int write,
216 		void __user *buffer, size_t *lenp,
217 		loff_t *ppos)
218 {
219 	int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
220 
221 	if (ret || !write)
222 		return ret;
223 
224 	max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
225 	perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
226 	update_perf_cpu_limits();
227 
228 	return 0;
229 }
230 
231 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
232 
perf_cpu_time_max_percent_handler(struct ctl_table * table,int write,void __user * buffer,size_t * lenp,loff_t * ppos)233 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
234 				void __user *buffer, size_t *lenp,
235 				loff_t *ppos)
236 {
237 	int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
238 
239 	if (ret || !write)
240 		return ret;
241 
242 	update_perf_cpu_limits();
243 
244 	return 0;
245 }
246 
247 /*
248  * perf samples are done in some very critical code paths (NMIs).
249  * If they take too much CPU time, the system can lock up and not
250  * get any real work done.  This will drop the sample rate when
251  * we detect that events are taking too long.
252  */
253 #define NR_ACCUMULATED_SAMPLES 128
254 static DEFINE_PER_CPU(u64, running_sample_length);
255 
perf_duration_warn(struct irq_work * w)256 static void perf_duration_warn(struct irq_work *w)
257 {
258 	u64 allowed_ns = ACCESS_ONCE(perf_sample_allowed_ns);
259 	u64 avg_local_sample_len;
260 	u64 local_samples_len;
261 
262 	local_samples_len = __this_cpu_read(running_sample_length);
263 	avg_local_sample_len = local_samples_len/NR_ACCUMULATED_SAMPLES;
264 
265 	printk_ratelimited(KERN_WARNING
266 			"perf interrupt took too long (%lld > %lld), lowering "
267 			"kernel.perf_event_max_sample_rate to %d\n",
268 			avg_local_sample_len, allowed_ns >> 1,
269 			sysctl_perf_event_sample_rate);
270 }
271 
272 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
273 
perf_sample_event_took(u64 sample_len_ns)274 void perf_sample_event_took(u64 sample_len_ns)
275 {
276 	u64 allowed_ns = ACCESS_ONCE(perf_sample_allowed_ns);
277 	u64 avg_local_sample_len;
278 	u64 local_samples_len;
279 
280 	if (allowed_ns == 0)
281 		return;
282 
283 	/* decay the counter by 1 average sample */
284 	local_samples_len = __this_cpu_read(running_sample_length);
285 	local_samples_len -= local_samples_len/NR_ACCUMULATED_SAMPLES;
286 	local_samples_len += sample_len_ns;
287 	__this_cpu_write(running_sample_length, local_samples_len);
288 
289 	/*
290 	 * note: this will be biased artifically low until we have
291 	 * seen NR_ACCUMULATED_SAMPLES.  Doing it this way keeps us
292 	 * from having to maintain a count.
293 	 */
294 	avg_local_sample_len = local_samples_len/NR_ACCUMULATED_SAMPLES;
295 
296 	if (avg_local_sample_len <= allowed_ns)
297 		return;
298 
299 	if (max_samples_per_tick <= 1)
300 		return;
301 
302 	max_samples_per_tick = DIV_ROUND_UP(max_samples_per_tick, 2);
303 	sysctl_perf_event_sample_rate = max_samples_per_tick * HZ;
304 	perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
305 
306 	update_perf_cpu_limits();
307 
308 	if (!irq_work_queue(&perf_duration_work)) {
309 		early_printk("perf interrupt took too long (%lld > %lld), lowering "
310 			     "kernel.perf_event_max_sample_rate to %d\n",
311 			     avg_local_sample_len, allowed_ns >> 1,
312 			     sysctl_perf_event_sample_rate);
313 	}
314 }
315 
316 static atomic64_t perf_event_id;
317 
318 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
319 			      enum event_type_t event_type);
320 
321 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
322 			     enum event_type_t event_type,
323 			     struct task_struct *task);
324 
325 static void update_context_time(struct perf_event_context *ctx);
326 static u64 perf_event_time(struct perf_event *event);
327 
perf_event_print_debug(void)328 void __weak perf_event_print_debug(void)	{ }
329 
perf_pmu_name(void)330 extern __weak const char *perf_pmu_name(void)
331 {
332 	return "pmu";
333 }
334 
perf_clock(void)335 static inline u64 perf_clock(void)
336 {
337 	return local_clock();
338 }
339 
perf_event_clock(struct perf_event * event)340 static inline u64 perf_event_clock(struct perf_event *event)
341 {
342 	return event->clock();
343 }
344 
345 static inline struct perf_cpu_context *
__get_cpu_context(struct perf_event_context * ctx)346 __get_cpu_context(struct perf_event_context *ctx)
347 {
348 	return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
349 }
350 
perf_ctx_lock(struct perf_cpu_context * cpuctx,struct perf_event_context * ctx)351 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
352 			  struct perf_event_context *ctx)
353 {
354 	raw_spin_lock(&cpuctx->ctx.lock);
355 	if (ctx)
356 		raw_spin_lock(&ctx->lock);
357 }
358 
perf_ctx_unlock(struct perf_cpu_context * cpuctx,struct perf_event_context * ctx)359 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
360 			    struct perf_event_context *ctx)
361 {
362 	if (ctx)
363 		raw_spin_unlock(&ctx->lock);
364 	raw_spin_unlock(&cpuctx->ctx.lock);
365 }
366 
367 #ifdef CONFIG_CGROUP_PERF
368 
369 static inline bool
perf_cgroup_match(struct perf_event * event)370 perf_cgroup_match(struct perf_event *event)
371 {
372 	struct perf_event_context *ctx = event->ctx;
373 	struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
374 
375 	/* @event doesn't care about cgroup */
376 	if (!event->cgrp)
377 		return true;
378 
379 	/* wants specific cgroup scope but @cpuctx isn't associated with any */
380 	if (!cpuctx->cgrp)
381 		return false;
382 
383 	/*
384 	 * Cgroup scoping is recursive.  An event enabled for a cgroup is
385 	 * also enabled for all its descendant cgroups.  If @cpuctx's
386 	 * cgroup is a descendant of @event's (the test covers identity
387 	 * case), it's a match.
388 	 */
389 	return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
390 				    event->cgrp->css.cgroup);
391 }
392 
perf_detach_cgroup(struct perf_event * event)393 static inline void perf_detach_cgroup(struct perf_event *event)
394 {
395 	css_put(&event->cgrp->css);
396 	event->cgrp = NULL;
397 }
398 
is_cgroup_event(struct perf_event * event)399 static inline int is_cgroup_event(struct perf_event *event)
400 {
401 	return event->cgrp != NULL;
402 }
403 
perf_cgroup_event_time(struct perf_event * event)404 static inline u64 perf_cgroup_event_time(struct perf_event *event)
405 {
406 	struct perf_cgroup_info *t;
407 
408 	t = per_cpu_ptr(event->cgrp->info, event->cpu);
409 	return t->time;
410 }
411 
__update_cgrp_time(struct perf_cgroup * cgrp)412 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
413 {
414 	struct perf_cgroup_info *info;
415 	u64 now;
416 
417 	now = perf_clock();
418 
419 	info = this_cpu_ptr(cgrp->info);
420 
421 	info->time += now - info->timestamp;
422 	info->timestamp = now;
423 }
424 
update_cgrp_time_from_cpuctx(struct perf_cpu_context * cpuctx)425 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
426 {
427 	struct perf_cgroup *cgrp = cpuctx->cgrp;
428 	struct cgroup_subsys_state *css;
429 
430 	if (cgrp) {
431 		for (css = &cgrp->css; css; css = css->parent) {
432 			cgrp = container_of(css, struct perf_cgroup, css);
433 			__update_cgrp_time(cgrp);
434 		}
435 	}
436 }
437 
update_cgrp_time_from_event(struct perf_event * event)438 static inline void update_cgrp_time_from_event(struct perf_event *event)
439 {
440 	struct perf_cgroup *cgrp;
441 
442 	/*
443 	 * ensure we access cgroup data only when needed and
444 	 * when we know the cgroup is pinned (css_get)
445 	 */
446 	if (!is_cgroup_event(event))
447 		return;
448 
449 	cgrp = perf_cgroup_from_task(current, event->ctx);
450 	/*
451 	 * Do not update time when cgroup is not active
452 	 */
453 	if (cgrp == event->cgrp)
454 		__update_cgrp_time(event->cgrp);
455 }
456 
457 static inline void
perf_cgroup_set_timestamp(struct task_struct * task,struct perf_event_context * ctx)458 perf_cgroup_set_timestamp(struct task_struct *task,
459 			  struct perf_event_context *ctx)
460 {
461 	struct perf_cgroup *cgrp;
462 	struct perf_cgroup_info *info;
463 	struct cgroup_subsys_state *css;
464 
465 	/*
466 	 * ctx->lock held by caller
467 	 * ensure we do not access cgroup data
468 	 * unless we have the cgroup pinned (css_get)
469 	 */
470 	if (!task || !ctx->nr_cgroups)
471 		return;
472 
473 	cgrp = perf_cgroup_from_task(task, ctx);
474 
475 	for (css = &cgrp->css; css; css = css->parent) {
476 		cgrp = container_of(css, struct perf_cgroup, css);
477 		info = this_cpu_ptr(cgrp->info);
478 		info->timestamp = ctx->timestamp;
479 	}
480 }
481 
482 #define PERF_CGROUP_SWOUT	0x1 /* cgroup switch out every event */
483 #define PERF_CGROUP_SWIN	0x2 /* cgroup switch in events based on task */
484 
485 /*
486  * reschedule events based on the cgroup constraint of task.
487  *
488  * mode SWOUT : schedule out everything
489  * mode SWIN : schedule in based on cgroup for next
490  */
perf_cgroup_switch(struct task_struct * task,int mode)491 static void perf_cgroup_switch(struct task_struct *task, int mode)
492 {
493 	struct perf_cpu_context *cpuctx;
494 	struct pmu *pmu;
495 	unsigned long flags;
496 
497 	/*
498 	 * disable interrupts to avoid geting nr_cgroup
499 	 * changes via __perf_event_disable(). Also
500 	 * avoids preemption.
501 	 */
502 	local_irq_save(flags);
503 
504 	/*
505 	 * we reschedule only in the presence of cgroup
506 	 * constrained events.
507 	 */
508 
509 	list_for_each_entry_rcu(pmu, &pmus, entry) {
510 		cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
511 		if (cpuctx->unique_pmu != pmu)
512 			continue; /* ensure we process each cpuctx once */
513 
514 		/*
515 		 * perf_cgroup_events says at least one
516 		 * context on this CPU has cgroup events.
517 		 *
518 		 * ctx->nr_cgroups reports the number of cgroup
519 		 * events for a context.
520 		 */
521 		if (cpuctx->ctx.nr_cgroups > 0) {
522 			perf_ctx_lock(cpuctx, cpuctx->task_ctx);
523 			perf_pmu_disable(cpuctx->ctx.pmu);
524 
525 			if (mode & PERF_CGROUP_SWOUT) {
526 				cpu_ctx_sched_out(cpuctx, EVENT_ALL);
527 				/*
528 				 * must not be done before ctxswout due
529 				 * to event_filter_match() in event_sched_out()
530 				 */
531 				cpuctx->cgrp = NULL;
532 			}
533 
534 			if (mode & PERF_CGROUP_SWIN) {
535 				WARN_ON_ONCE(cpuctx->cgrp);
536 				/*
537 				 * set cgrp before ctxsw in to allow
538 				 * event_filter_match() to not have to pass
539 				 * task around
540 				 * we pass the cpuctx->ctx to perf_cgroup_from_task()
541 				 * because cgorup events are only per-cpu
542 				 */
543 				cpuctx->cgrp = perf_cgroup_from_task(task, &cpuctx->ctx);
544 				cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
545 			}
546 			perf_pmu_enable(cpuctx->ctx.pmu);
547 			perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
548 		}
549 	}
550 
551 	local_irq_restore(flags);
552 }
553 
perf_cgroup_sched_out(struct task_struct * task,struct task_struct * next)554 static inline void perf_cgroup_sched_out(struct task_struct *task,
555 					 struct task_struct *next)
556 {
557 	struct perf_cgroup *cgrp1;
558 	struct perf_cgroup *cgrp2 = NULL;
559 
560 	rcu_read_lock();
561 	/*
562 	 * we come here when we know perf_cgroup_events > 0
563 	 * we do not need to pass the ctx here because we know
564 	 * we are holding the rcu lock
565 	 */
566 	cgrp1 = perf_cgroup_from_task(task, NULL);
567 
568 	/*
569 	 * next is NULL when called from perf_event_enable_on_exec()
570 	 * that will systematically cause a cgroup_switch()
571 	 */
572 	if (next)
573 		cgrp2 = perf_cgroup_from_task(next, NULL);
574 
575 	/*
576 	 * only schedule out current cgroup events if we know
577 	 * that we are switching to a different cgroup. Otherwise,
578 	 * do no touch the cgroup events.
579 	 */
580 	if (cgrp1 != cgrp2)
581 		perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
582 
583 	rcu_read_unlock();
584 }
585 
perf_cgroup_sched_in(struct task_struct * prev,struct task_struct * task)586 static inline void perf_cgroup_sched_in(struct task_struct *prev,
587 					struct task_struct *task)
588 {
589 	struct perf_cgroup *cgrp1;
590 	struct perf_cgroup *cgrp2 = NULL;
591 
592 	rcu_read_lock();
593 	/*
594 	 * we come here when we know perf_cgroup_events > 0
595 	 * we do not need to pass the ctx here because we know
596 	 * we are holding the rcu lock
597 	 */
598 	cgrp1 = perf_cgroup_from_task(task, NULL);
599 
600 	/* prev can never be NULL */
601 	cgrp2 = perf_cgroup_from_task(prev, NULL);
602 
603 	/*
604 	 * only need to schedule in cgroup events if we are changing
605 	 * cgroup during ctxsw. Cgroup events were not scheduled
606 	 * out of ctxsw out if that was not the case.
607 	 */
608 	if (cgrp1 != cgrp2)
609 		perf_cgroup_switch(task, PERF_CGROUP_SWIN);
610 
611 	rcu_read_unlock();
612 }
613 
perf_cgroup_connect(int fd,struct perf_event * event,struct perf_event_attr * attr,struct perf_event * group_leader)614 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
615 				      struct perf_event_attr *attr,
616 				      struct perf_event *group_leader)
617 {
618 	struct perf_cgroup *cgrp;
619 	struct cgroup_subsys_state *css;
620 	struct fd f = fdget(fd);
621 	int ret = 0;
622 
623 	if (!f.file)
624 		return -EBADF;
625 
626 	css = css_tryget_online_from_dir(f.file->f_path.dentry,
627 					 &perf_event_cgrp_subsys);
628 	if (IS_ERR(css)) {
629 		ret = PTR_ERR(css);
630 		goto out;
631 	}
632 
633 	cgrp = container_of(css, struct perf_cgroup, css);
634 	event->cgrp = cgrp;
635 
636 	/*
637 	 * all events in a group must monitor
638 	 * the same cgroup because a task belongs
639 	 * to only one perf cgroup at a time
640 	 */
641 	if (group_leader && group_leader->cgrp != cgrp) {
642 		perf_detach_cgroup(event);
643 		ret = -EINVAL;
644 	}
645 out:
646 	fdput(f);
647 	return ret;
648 }
649 
650 static inline void
perf_cgroup_set_shadow_time(struct perf_event * event,u64 now)651 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
652 {
653 	struct perf_cgroup_info *t;
654 	t = per_cpu_ptr(event->cgrp->info, event->cpu);
655 	event->shadow_ctx_time = now - t->timestamp;
656 }
657 
658 static inline void
perf_cgroup_defer_enabled(struct perf_event * event)659 perf_cgroup_defer_enabled(struct perf_event *event)
660 {
661 	/*
662 	 * when the current task's perf cgroup does not match
663 	 * the event's, we need to remember to call the
664 	 * perf_mark_enable() function the first time a task with
665 	 * a matching perf cgroup is scheduled in.
666 	 */
667 	if (is_cgroup_event(event) && !perf_cgroup_match(event))
668 		event->cgrp_defer_enabled = 1;
669 }
670 
671 static inline void
perf_cgroup_mark_enabled(struct perf_event * event,struct perf_event_context * ctx)672 perf_cgroup_mark_enabled(struct perf_event *event,
673 			 struct perf_event_context *ctx)
674 {
675 	struct perf_event *sub;
676 	u64 tstamp = perf_event_time(event);
677 
678 	if (!event->cgrp_defer_enabled)
679 		return;
680 
681 	event->cgrp_defer_enabled = 0;
682 
683 	event->tstamp_enabled = tstamp - event->total_time_enabled;
684 	list_for_each_entry(sub, &event->sibling_list, group_entry) {
685 		if (sub->state >= PERF_EVENT_STATE_INACTIVE) {
686 			sub->tstamp_enabled = tstamp - sub->total_time_enabled;
687 			sub->cgrp_defer_enabled = 0;
688 		}
689 	}
690 }
691 #else /* !CONFIG_CGROUP_PERF */
692 
693 static inline bool
perf_cgroup_match(struct perf_event * event)694 perf_cgroup_match(struct perf_event *event)
695 {
696 	return true;
697 }
698 
perf_detach_cgroup(struct perf_event * event)699 static inline void perf_detach_cgroup(struct perf_event *event)
700 {}
701 
is_cgroup_event(struct perf_event * event)702 static inline int is_cgroup_event(struct perf_event *event)
703 {
704 	return 0;
705 }
706 
perf_cgroup_event_cgrp_time(struct perf_event * event)707 static inline u64 perf_cgroup_event_cgrp_time(struct perf_event *event)
708 {
709 	return 0;
710 }
711 
update_cgrp_time_from_event(struct perf_event * event)712 static inline void update_cgrp_time_from_event(struct perf_event *event)
713 {
714 }
715 
update_cgrp_time_from_cpuctx(struct perf_cpu_context * cpuctx)716 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
717 {
718 }
719 
perf_cgroup_sched_out(struct task_struct * task,struct task_struct * next)720 static inline void perf_cgroup_sched_out(struct task_struct *task,
721 					 struct task_struct *next)
722 {
723 }
724 
perf_cgroup_sched_in(struct task_struct * prev,struct task_struct * task)725 static inline void perf_cgroup_sched_in(struct task_struct *prev,
726 					struct task_struct *task)
727 {
728 }
729 
perf_cgroup_connect(pid_t pid,struct perf_event * event,struct perf_event_attr * attr,struct perf_event * group_leader)730 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
731 				      struct perf_event_attr *attr,
732 				      struct perf_event *group_leader)
733 {
734 	return -EINVAL;
735 }
736 
737 static inline void
perf_cgroup_set_timestamp(struct task_struct * task,struct perf_event_context * ctx)738 perf_cgroup_set_timestamp(struct task_struct *task,
739 			  struct perf_event_context *ctx)
740 {
741 }
742 
743 void
perf_cgroup_switch(struct task_struct * task,struct task_struct * next)744 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
745 {
746 }
747 
748 static inline void
perf_cgroup_set_shadow_time(struct perf_event * event,u64 now)749 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
750 {
751 }
752 
perf_cgroup_event_time(struct perf_event * event)753 static inline u64 perf_cgroup_event_time(struct perf_event *event)
754 {
755 	return 0;
756 }
757 
758 static inline void
perf_cgroup_defer_enabled(struct perf_event * event)759 perf_cgroup_defer_enabled(struct perf_event *event)
760 {
761 }
762 
763 static inline void
perf_cgroup_mark_enabled(struct perf_event * event,struct perf_event_context * ctx)764 perf_cgroup_mark_enabled(struct perf_event *event,
765 			 struct perf_event_context *ctx)
766 {
767 }
768 #endif
769 
770 /*
771  * set default to be dependent on timer tick just
772  * like original code
773  */
774 #define PERF_CPU_HRTIMER (1000 / HZ)
775 /*
776  * function must be called with interrupts disbled
777  */
perf_mux_hrtimer_handler(struct hrtimer * hr)778 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
779 {
780 	struct perf_cpu_context *cpuctx;
781 	int rotations = 0;
782 
783 	WARN_ON(!irqs_disabled());
784 
785 	cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
786 	rotations = perf_rotate_context(cpuctx);
787 
788 	raw_spin_lock(&cpuctx->hrtimer_lock);
789 	if (rotations)
790 		hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
791 	else
792 		cpuctx->hrtimer_active = 0;
793 	raw_spin_unlock(&cpuctx->hrtimer_lock);
794 
795 	return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
796 }
797 
__perf_mux_hrtimer_init(struct perf_cpu_context * cpuctx,int cpu)798 static void __perf_mux_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
799 {
800 	struct hrtimer *timer = &cpuctx->hrtimer;
801 	struct pmu *pmu = cpuctx->ctx.pmu;
802 	u64 interval;
803 
804 	/* no multiplexing needed for SW PMU */
805 	if (pmu->task_ctx_nr == perf_sw_context)
806 		return;
807 
808 	/*
809 	 * check default is sane, if not set then force to
810 	 * default interval (1/tick)
811 	 */
812 	interval = pmu->hrtimer_interval_ms;
813 	if (interval < 1)
814 		interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
815 
816 	cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
817 
818 	raw_spin_lock_init(&cpuctx->hrtimer_lock);
819 	hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
820 	timer->function = perf_mux_hrtimer_handler;
821 }
822 
perf_mux_hrtimer_restart(struct perf_cpu_context * cpuctx)823 static int perf_mux_hrtimer_restart(struct perf_cpu_context *cpuctx)
824 {
825 	struct hrtimer *timer = &cpuctx->hrtimer;
826 	struct pmu *pmu = cpuctx->ctx.pmu;
827 	unsigned long flags;
828 
829 	/* not for SW PMU */
830 	if (pmu->task_ctx_nr == perf_sw_context)
831 		return 0;
832 
833 	raw_spin_lock_irqsave(&cpuctx->hrtimer_lock, flags);
834 	if (!cpuctx->hrtimer_active) {
835 		cpuctx->hrtimer_active = 1;
836 		hrtimer_forward_now(timer, cpuctx->hrtimer_interval);
837 		hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
838 	}
839 	raw_spin_unlock_irqrestore(&cpuctx->hrtimer_lock, flags);
840 
841 	return 0;
842 }
843 
perf_pmu_disable(struct pmu * pmu)844 void perf_pmu_disable(struct pmu *pmu)
845 {
846 	int *count = this_cpu_ptr(pmu->pmu_disable_count);
847 	if (!(*count)++)
848 		pmu->pmu_disable(pmu);
849 }
850 
perf_pmu_enable(struct pmu * pmu)851 void perf_pmu_enable(struct pmu *pmu)
852 {
853 	int *count = this_cpu_ptr(pmu->pmu_disable_count);
854 	if (!--(*count))
855 		pmu->pmu_enable(pmu);
856 }
857 
858 static DEFINE_PER_CPU(struct list_head, active_ctx_list);
859 
860 /*
861  * perf_event_ctx_activate(), perf_event_ctx_deactivate(), and
862  * perf_event_task_tick() are fully serialized because they're strictly cpu
863  * affine and perf_event_ctx{activate,deactivate} are called with IRQs
864  * disabled, while perf_event_task_tick is called from IRQ context.
865  */
perf_event_ctx_activate(struct perf_event_context * ctx)866 static void perf_event_ctx_activate(struct perf_event_context *ctx)
867 {
868 	struct list_head *head = this_cpu_ptr(&active_ctx_list);
869 
870 	WARN_ON(!irqs_disabled());
871 
872 	WARN_ON(!list_empty(&ctx->active_ctx_list));
873 
874 	list_add(&ctx->active_ctx_list, head);
875 }
876 
perf_event_ctx_deactivate(struct perf_event_context * ctx)877 static void perf_event_ctx_deactivate(struct perf_event_context *ctx)
878 {
879 	WARN_ON(!irqs_disabled());
880 
881 	WARN_ON(list_empty(&ctx->active_ctx_list));
882 
883 	list_del_init(&ctx->active_ctx_list);
884 }
885 
get_ctx(struct perf_event_context * ctx)886 static void get_ctx(struct perf_event_context *ctx)
887 {
888 	WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
889 }
890 
free_ctx(struct rcu_head * head)891 static void free_ctx(struct rcu_head *head)
892 {
893 	struct perf_event_context *ctx;
894 
895 	ctx = container_of(head, struct perf_event_context, rcu_head);
896 	kfree(ctx->task_ctx_data);
897 	kfree(ctx);
898 }
899 
put_ctx(struct perf_event_context * ctx)900 static void put_ctx(struct perf_event_context *ctx)
901 {
902 	if (atomic_dec_and_test(&ctx->refcount)) {
903 		if (ctx->parent_ctx)
904 			put_ctx(ctx->parent_ctx);
905 		if (ctx->task)
906 			put_task_struct(ctx->task);
907 		call_rcu(&ctx->rcu_head, free_ctx);
908 	}
909 }
910 
911 /*
912  * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
913  * perf_pmu_migrate_context() we need some magic.
914  *
915  * Those places that change perf_event::ctx will hold both
916  * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
917  *
918  * Lock ordering is by mutex address. There are two other sites where
919  * perf_event_context::mutex nests and those are:
920  *
921  *  - perf_event_exit_task_context()	[ child , 0 ]
922  *      __perf_event_exit_task()
923  *        sync_child_event()
924  *          put_event()			[ parent, 1 ]
925  *
926  *  - perf_event_init_context()		[ parent, 0 ]
927  *      inherit_task_group()
928  *        inherit_group()
929  *          inherit_event()
930  *            perf_event_alloc()
931  *              perf_init_event()
932  *                perf_try_init_event()	[ child , 1 ]
933  *
934  * While it appears there is an obvious deadlock here -- the parent and child
935  * nesting levels are inverted between the two. This is in fact safe because
936  * life-time rules separate them. That is an exiting task cannot fork, and a
937  * spawning task cannot (yet) exit.
938  *
939  * But remember that that these are parent<->child context relations, and
940  * migration does not affect children, therefore these two orderings should not
941  * interact.
942  *
943  * The change in perf_event::ctx does not affect children (as claimed above)
944  * because the sys_perf_event_open() case will install a new event and break
945  * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
946  * concerned with cpuctx and that doesn't have children.
947  *
948  * The places that change perf_event::ctx will issue:
949  *
950  *   perf_remove_from_context();
951  *   synchronize_rcu();
952  *   perf_install_in_context();
953  *
954  * to affect the change. The remove_from_context() + synchronize_rcu() should
955  * quiesce the event, after which we can install it in the new location. This
956  * means that only external vectors (perf_fops, prctl) can perturb the event
957  * while in transit. Therefore all such accessors should also acquire
958  * perf_event_context::mutex to serialize against this.
959  *
960  * However; because event->ctx can change while we're waiting to acquire
961  * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
962  * function.
963  *
964  * Lock order:
965  *    cred_guard_mutex
966  *	task_struct::perf_event_mutex
967  *	  perf_event_context::mutex
968  *	    perf_event_context::lock
969  *	    perf_event::child_mutex;
970  *	    perf_event::mmap_mutex
971  *	    mmap_sem
972  */
973 static struct perf_event_context *
perf_event_ctx_lock_nested(struct perf_event * event,int nesting)974 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
975 {
976 	struct perf_event_context *ctx;
977 
978 again:
979 	rcu_read_lock();
980 	ctx = ACCESS_ONCE(event->ctx);
981 	if (!atomic_inc_not_zero(&ctx->refcount)) {
982 		rcu_read_unlock();
983 		goto again;
984 	}
985 	rcu_read_unlock();
986 
987 	mutex_lock_nested(&ctx->mutex, nesting);
988 	if (event->ctx != ctx) {
989 		mutex_unlock(&ctx->mutex);
990 		put_ctx(ctx);
991 		goto again;
992 	}
993 
994 	return ctx;
995 }
996 
997 static inline struct perf_event_context *
perf_event_ctx_lock(struct perf_event * event)998 perf_event_ctx_lock(struct perf_event *event)
999 {
1000 	return perf_event_ctx_lock_nested(event, 0);
1001 }
1002 
perf_event_ctx_unlock(struct perf_event * event,struct perf_event_context * ctx)1003 static void perf_event_ctx_unlock(struct perf_event *event,
1004 				  struct perf_event_context *ctx)
1005 {
1006 	mutex_unlock(&ctx->mutex);
1007 	put_ctx(ctx);
1008 }
1009 
1010 /*
1011  * This must be done under the ctx->lock, such as to serialize against
1012  * context_equiv(), therefore we cannot call put_ctx() since that might end up
1013  * calling scheduler related locks and ctx->lock nests inside those.
1014  */
1015 static __must_check struct perf_event_context *
unclone_ctx(struct perf_event_context * ctx)1016 unclone_ctx(struct perf_event_context *ctx)
1017 {
1018 	struct perf_event_context *parent_ctx = ctx->parent_ctx;
1019 
1020 	lockdep_assert_held(&ctx->lock);
1021 
1022 	if (parent_ctx)
1023 		ctx->parent_ctx = NULL;
1024 	ctx->generation++;
1025 
1026 	return parent_ctx;
1027 }
1028 
perf_event_pid(struct perf_event * event,struct task_struct * p)1029 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1030 {
1031 	/*
1032 	 * only top level events have the pid namespace they were created in
1033 	 */
1034 	if (event->parent)
1035 		event = event->parent;
1036 
1037 	return task_tgid_nr_ns(p, event->ns);
1038 }
1039 
perf_event_tid(struct perf_event * event,struct task_struct * p)1040 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1041 {
1042 	/*
1043 	 * only top level events have the pid namespace they were created in
1044 	 */
1045 	if (event->parent)
1046 		event = event->parent;
1047 
1048 	return task_pid_nr_ns(p, event->ns);
1049 }
1050 
1051 /*
1052  * If we inherit events we want to return the parent event id
1053  * to userspace.
1054  */
primary_event_id(struct perf_event * event)1055 static u64 primary_event_id(struct perf_event *event)
1056 {
1057 	u64 id = event->id;
1058 
1059 	if (event->parent)
1060 		id = event->parent->id;
1061 
1062 	return id;
1063 }
1064 
1065 /*
1066  * Get the perf_event_context for a task and lock it.
1067  * This has to cope with with the fact that until it is locked,
1068  * the context could get moved to another task.
1069  */
1070 static struct perf_event_context *
perf_lock_task_context(struct task_struct * task,int ctxn,unsigned long * flags)1071 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
1072 {
1073 	struct perf_event_context *ctx;
1074 
1075 retry:
1076 	/*
1077 	 * One of the few rules of preemptible RCU is that one cannot do
1078 	 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1079 	 * part of the read side critical section was irqs-enabled -- see
1080 	 * rcu_read_unlock_special().
1081 	 *
1082 	 * Since ctx->lock nests under rq->lock we must ensure the entire read
1083 	 * side critical section has interrupts disabled.
1084 	 */
1085 	local_irq_save(*flags);
1086 	rcu_read_lock();
1087 	ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
1088 	if (ctx) {
1089 		/*
1090 		 * If this context is a clone of another, it might
1091 		 * get swapped for another underneath us by
1092 		 * perf_event_task_sched_out, though the
1093 		 * rcu_read_lock() protects us from any context
1094 		 * getting freed.  Lock the context and check if it
1095 		 * got swapped before we could get the lock, and retry
1096 		 * if so.  If we locked the right context, then it
1097 		 * can't get swapped on us any more.
1098 		 */
1099 		raw_spin_lock(&ctx->lock);
1100 		if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
1101 			raw_spin_unlock(&ctx->lock);
1102 			rcu_read_unlock();
1103 			local_irq_restore(*flags);
1104 			goto retry;
1105 		}
1106 
1107 		if (!atomic_inc_not_zero(&ctx->refcount)) {
1108 			raw_spin_unlock(&ctx->lock);
1109 			ctx = NULL;
1110 		}
1111 	}
1112 	rcu_read_unlock();
1113 	if (!ctx)
1114 		local_irq_restore(*flags);
1115 	return ctx;
1116 }
1117 
1118 /*
1119  * Get the context for a task and increment its pin_count so it
1120  * can't get swapped to another task.  This also increments its
1121  * reference count so that the context can't get freed.
1122  */
1123 static struct perf_event_context *
perf_pin_task_context(struct task_struct * task,int ctxn)1124 perf_pin_task_context(struct task_struct *task, int ctxn)
1125 {
1126 	struct perf_event_context *ctx;
1127 	unsigned long flags;
1128 
1129 	ctx = perf_lock_task_context(task, ctxn, &flags);
1130 	if (ctx) {
1131 		++ctx->pin_count;
1132 		raw_spin_unlock_irqrestore(&ctx->lock, flags);
1133 	}
1134 	return ctx;
1135 }
1136 
perf_unpin_context(struct perf_event_context * ctx)1137 static void perf_unpin_context(struct perf_event_context *ctx)
1138 {
1139 	unsigned long flags;
1140 
1141 	raw_spin_lock_irqsave(&ctx->lock, flags);
1142 	--ctx->pin_count;
1143 	raw_spin_unlock_irqrestore(&ctx->lock, flags);
1144 }
1145 
1146 /*
1147  * Update the record of the current time in a context.
1148  */
update_context_time(struct perf_event_context * ctx)1149 static void update_context_time(struct perf_event_context *ctx)
1150 {
1151 	u64 now = perf_clock();
1152 
1153 	ctx->time += now - ctx->timestamp;
1154 	ctx->timestamp = now;
1155 }
1156 
perf_event_time(struct perf_event * event)1157 static u64 perf_event_time(struct perf_event *event)
1158 {
1159 	struct perf_event_context *ctx = event->ctx;
1160 
1161 	if (is_cgroup_event(event))
1162 		return perf_cgroup_event_time(event);
1163 
1164 	return ctx ? ctx->time : 0;
1165 }
1166 
1167 /*
1168  * Update the total_time_enabled and total_time_running fields for a event.
1169  * The caller of this function needs to hold the ctx->lock.
1170  */
update_event_times(struct perf_event * event)1171 static void update_event_times(struct perf_event *event)
1172 {
1173 	struct perf_event_context *ctx = event->ctx;
1174 	u64 run_end;
1175 
1176 	if (event->state < PERF_EVENT_STATE_INACTIVE ||
1177 	    event->group_leader->state < PERF_EVENT_STATE_INACTIVE)
1178 		return;
1179 	/*
1180 	 * in cgroup mode, time_enabled represents
1181 	 * the time the event was enabled AND active
1182 	 * tasks were in the monitored cgroup. This is
1183 	 * independent of the activity of the context as
1184 	 * there may be a mix of cgroup and non-cgroup events.
1185 	 *
1186 	 * That is why we treat cgroup events differently
1187 	 * here.
1188 	 */
1189 	if (is_cgroup_event(event))
1190 		run_end = perf_cgroup_event_time(event);
1191 	else if (ctx->is_active)
1192 		run_end = ctx->time;
1193 	else
1194 		run_end = event->tstamp_stopped;
1195 
1196 	event->total_time_enabled = run_end - event->tstamp_enabled;
1197 
1198 	if (event->state == PERF_EVENT_STATE_INACTIVE)
1199 		run_end = event->tstamp_stopped;
1200 	else
1201 		run_end = perf_event_time(event);
1202 
1203 	event->total_time_running = run_end - event->tstamp_running;
1204 
1205 }
1206 
1207 /*
1208  * Update total_time_enabled and total_time_running for all events in a group.
1209  */
update_group_times(struct perf_event * leader)1210 static void update_group_times(struct perf_event *leader)
1211 {
1212 	struct perf_event *event;
1213 
1214 	update_event_times(leader);
1215 	list_for_each_entry(event, &leader->sibling_list, group_entry)
1216 		update_event_times(event);
1217 }
1218 
1219 static struct list_head *
ctx_group_list(struct perf_event * event,struct perf_event_context * ctx)1220 ctx_group_list(struct perf_event *event, struct perf_event_context *ctx)
1221 {
1222 	if (event->attr.pinned)
1223 		return &ctx->pinned_groups;
1224 	else
1225 		return &ctx->flexible_groups;
1226 }
1227 
1228 /*
1229  * Add a event from the lists for its context.
1230  * Must be called with ctx->mutex and ctx->lock held.
1231  */
1232 static void
list_add_event(struct perf_event * event,struct perf_event_context * ctx)1233 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1234 {
1235 	WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1236 	event->attach_state |= PERF_ATTACH_CONTEXT;
1237 
1238 	/*
1239 	 * If we're a stand alone event or group leader, we go to the context
1240 	 * list, group events are kept attached to the group so that
1241 	 * perf_group_detach can, at all times, locate all siblings.
1242 	 */
1243 	if (event->group_leader == event) {
1244 		struct list_head *list;
1245 
1246 		if (is_software_event(event))
1247 			event->group_flags |= PERF_GROUP_SOFTWARE;
1248 
1249 		list = ctx_group_list(event, ctx);
1250 		list_add_tail(&event->group_entry, list);
1251 	}
1252 
1253 	if (is_cgroup_event(event))
1254 		ctx->nr_cgroups++;
1255 
1256 	list_add_rcu(&event->event_entry, &ctx->event_list);
1257 	ctx->nr_events++;
1258 	if (event->attr.inherit_stat)
1259 		ctx->nr_stat++;
1260 
1261 	ctx->generation++;
1262 }
1263 
1264 /*
1265  * Initialize event state based on the perf_event_attr::disabled.
1266  */
perf_event__state_init(struct perf_event * event)1267 static inline void perf_event__state_init(struct perf_event *event)
1268 {
1269 	event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1270 					      PERF_EVENT_STATE_INACTIVE;
1271 }
1272 
__perf_event_read_size(struct perf_event * event,int nr_siblings)1273 static void __perf_event_read_size(struct perf_event *event, int nr_siblings)
1274 {
1275 	int entry = sizeof(u64); /* value */
1276 	int size = 0;
1277 	int nr = 1;
1278 
1279 	if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1280 		size += sizeof(u64);
1281 
1282 	if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1283 		size += sizeof(u64);
1284 
1285 	if (event->attr.read_format & PERF_FORMAT_ID)
1286 		entry += sizeof(u64);
1287 
1288 	if (event->attr.read_format & PERF_FORMAT_GROUP) {
1289 		nr += nr_siblings;
1290 		size += sizeof(u64);
1291 	}
1292 
1293 	size += entry * nr;
1294 	event->read_size = size;
1295 }
1296 
__perf_event_header_size(struct perf_event * event,u64 sample_type)1297 static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
1298 {
1299 	struct perf_sample_data *data;
1300 	u16 size = 0;
1301 
1302 	if (sample_type & PERF_SAMPLE_IP)
1303 		size += sizeof(data->ip);
1304 
1305 	if (sample_type & PERF_SAMPLE_ADDR)
1306 		size += sizeof(data->addr);
1307 
1308 	if (sample_type & PERF_SAMPLE_PERIOD)
1309 		size += sizeof(data->period);
1310 
1311 	if (sample_type & PERF_SAMPLE_WEIGHT)
1312 		size += sizeof(data->weight);
1313 
1314 	if (sample_type & PERF_SAMPLE_READ)
1315 		size += event->read_size;
1316 
1317 	if (sample_type & PERF_SAMPLE_DATA_SRC)
1318 		size += sizeof(data->data_src.val);
1319 
1320 	if (sample_type & PERF_SAMPLE_TRANSACTION)
1321 		size += sizeof(data->txn);
1322 
1323 	event->header_size = size;
1324 }
1325 
1326 /*
1327  * Called at perf_event creation and when events are attached/detached from a
1328  * group.
1329  */
perf_event__header_size(struct perf_event * event)1330 static void perf_event__header_size(struct perf_event *event)
1331 {
1332 	__perf_event_read_size(event,
1333 			       event->group_leader->nr_siblings);
1334 	__perf_event_header_size(event, event->attr.sample_type);
1335 }
1336 
perf_event__id_header_size(struct perf_event * event)1337 static void perf_event__id_header_size(struct perf_event *event)
1338 {
1339 	struct perf_sample_data *data;
1340 	u64 sample_type = event->attr.sample_type;
1341 	u16 size = 0;
1342 
1343 	if (sample_type & PERF_SAMPLE_TID)
1344 		size += sizeof(data->tid_entry);
1345 
1346 	if (sample_type & PERF_SAMPLE_TIME)
1347 		size += sizeof(data->time);
1348 
1349 	if (sample_type & PERF_SAMPLE_IDENTIFIER)
1350 		size += sizeof(data->id);
1351 
1352 	if (sample_type & PERF_SAMPLE_ID)
1353 		size += sizeof(data->id);
1354 
1355 	if (sample_type & PERF_SAMPLE_STREAM_ID)
1356 		size += sizeof(data->stream_id);
1357 
1358 	if (sample_type & PERF_SAMPLE_CPU)
1359 		size += sizeof(data->cpu_entry);
1360 
1361 	event->id_header_size = size;
1362 }
1363 
perf_event_validate_size(struct perf_event * event)1364 static bool perf_event_validate_size(struct perf_event *event)
1365 {
1366 	/*
1367 	 * The values computed here will be over-written when we actually
1368 	 * attach the event.
1369 	 */
1370 	__perf_event_read_size(event, event->group_leader->nr_siblings + 1);
1371 	__perf_event_header_size(event, event->attr.sample_type & ~PERF_SAMPLE_READ);
1372 	perf_event__id_header_size(event);
1373 
1374 	/*
1375 	 * Sum the lot; should not exceed the 64k limit we have on records.
1376 	 * Conservative limit to allow for callchains and other variable fields.
1377 	 */
1378 	if (event->read_size + event->header_size +
1379 	    event->id_header_size + sizeof(struct perf_event_header) >= 16*1024)
1380 		return false;
1381 
1382 	return true;
1383 }
1384 
perf_group_attach(struct perf_event * event)1385 static void perf_group_attach(struct perf_event *event)
1386 {
1387 	struct perf_event *group_leader = event->group_leader, *pos;
1388 
1389 	/*
1390 	 * We can have double attach due to group movement in perf_event_open.
1391 	 */
1392 	if (event->attach_state & PERF_ATTACH_GROUP)
1393 		return;
1394 
1395 	event->attach_state |= PERF_ATTACH_GROUP;
1396 
1397 	if (group_leader == event)
1398 		return;
1399 
1400 	WARN_ON_ONCE(group_leader->ctx != event->ctx);
1401 
1402 	if (group_leader->group_flags & PERF_GROUP_SOFTWARE &&
1403 			!is_software_event(event))
1404 		group_leader->group_flags &= ~PERF_GROUP_SOFTWARE;
1405 
1406 	list_add_tail(&event->group_entry, &group_leader->sibling_list);
1407 	group_leader->nr_siblings++;
1408 
1409 	perf_event__header_size(group_leader);
1410 
1411 	list_for_each_entry(pos, &group_leader->sibling_list, group_entry)
1412 		perf_event__header_size(pos);
1413 }
1414 
1415 /*
1416  * Remove a event from the lists for its context.
1417  * Must be called with ctx->mutex and ctx->lock held.
1418  */
1419 static void
list_del_event(struct perf_event * event,struct perf_event_context * ctx)1420 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1421 {
1422 	struct perf_cpu_context *cpuctx;
1423 
1424 	WARN_ON_ONCE(event->ctx != ctx);
1425 	lockdep_assert_held(&ctx->lock);
1426 
1427 	/*
1428 	 * We can have double detach due to exit/hot-unplug + close.
1429 	 */
1430 	if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1431 		return;
1432 
1433 	event->attach_state &= ~PERF_ATTACH_CONTEXT;
1434 
1435 	if (is_cgroup_event(event)) {
1436 		ctx->nr_cgroups--;
1437 		cpuctx = __get_cpu_context(ctx);
1438 		/*
1439 		 * if there are no more cgroup events
1440 		 * then cler cgrp to avoid stale pointer
1441 		 * in update_cgrp_time_from_cpuctx()
1442 		 */
1443 		if (!ctx->nr_cgroups)
1444 			cpuctx->cgrp = NULL;
1445 	}
1446 
1447 	ctx->nr_events--;
1448 	if (event->attr.inherit_stat)
1449 		ctx->nr_stat--;
1450 
1451 	list_del_rcu(&event->event_entry);
1452 
1453 	if (event->group_leader == event)
1454 		list_del_init(&event->group_entry);
1455 
1456 	update_group_times(event);
1457 
1458 	/*
1459 	 * If event was in error state, then keep it
1460 	 * that way, otherwise bogus counts will be
1461 	 * returned on read(). The only way to get out
1462 	 * of error state is by explicit re-enabling
1463 	 * of the event
1464 	 */
1465 	if (event->state > PERF_EVENT_STATE_OFF)
1466 		event->state = PERF_EVENT_STATE_OFF;
1467 
1468 	ctx->generation++;
1469 }
1470 
perf_group_detach(struct perf_event * event)1471 static void perf_group_detach(struct perf_event *event)
1472 {
1473 	struct perf_event *sibling, *tmp;
1474 	struct list_head *list = NULL;
1475 
1476 	/*
1477 	 * We can have double detach due to exit/hot-unplug + close.
1478 	 */
1479 	if (!(event->attach_state & PERF_ATTACH_GROUP))
1480 		return;
1481 
1482 	event->attach_state &= ~PERF_ATTACH_GROUP;
1483 
1484 	/*
1485 	 * If this is a sibling, remove it from its group.
1486 	 */
1487 	if (event->group_leader != event) {
1488 		list_del_init(&event->group_entry);
1489 		event->group_leader->nr_siblings--;
1490 		goto out;
1491 	}
1492 
1493 	if (!list_empty(&event->group_entry))
1494 		list = &event->group_entry;
1495 
1496 	/*
1497 	 * If this was a group event with sibling events then
1498 	 * upgrade the siblings to singleton events by adding them
1499 	 * to whatever list we are on.
1500 	 */
1501 	list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) {
1502 		if (list)
1503 			list_move_tail(&sibling->group_entry, list);
1504 		sibling->group_leader = sibling;
1505 
1506 		/* Inherit group flags from the previous leader */
1507 		sibling->group_flags = event->group_flags;
1508 
1509 		WARN_ON_ONCE(sibling->ctx != event->ctx);
1510 	}
1511 
1512 out:
1513 	perf_event__header_size(event->group_leader);
1514 
1515 	list_for_each_entry(tmp, &event->group_leader->sibling_list, group_entry)
1516 		perf_event__header_size(tmp);
1517 }
1518 
1519 /*
1520  * User event without the task.
1521  */
is_orphaned_event(struct perf_event * event)1522 static bool is_orphaned_event(struct perf_event *event)
1523 {
1524 	return event && !is_kernel_event(event) && !event->owner;
1525 }
1526 
1527 /*
1528  * Event has a parent but parent's task finished and it's
1529  * alive only because of children holding refference.
1530  */
is_orphaned_child(struct perf_event * event)1531 static bool is_orphaned_child(struct perf_event *event)
1532 {
1533 	return is_orphaned_event(event->parent);
1534 }
1535 
1536 static void orphans_remove_work(struct work_struct *work);
1537 
schedule_orphans_remove(struct perf_event_context * ctx)1538 static void schedule_orphans_remove(struct perf_event_context *ctx)
1539 {
1540 	if (!ctx->task || ctx->orphans_remove_sched || !perf_wq)
1541 		return;
1542 
1543 	if (queue_delayed_work(perf_wq, &ctx->orphans_remove, 1)) {
1544 		get_ctx(ctx);
1545 		ctx->orphans_remove_sched = true;
1546 	}
1547 }
1548 
perf_workqueue_init(void)1549 static int __init perf_workqueue_init(void)
1550 {
1551 	perf_wq = create_singlethread_workqueue("perf");
1552 	WARN(!perf_wq, "failed to create perf workqueue\n");
1553 	return perf_wq ? 0 : -1;
1554 }
1555 
1556 core_initcall(perf_workqueue_init);
1557 
__pmu_filter_match(struct perf_event * event)1558 static inline int __pmu_filter_match(struct perf_event *event)
1559 {
1560 	struct pmu *pmu = event->pmu;
1561 	return pmu->filter_match ? pmu->filter_match(event) : 1;
1562 }
1563 
1564 /*
1565  * Check whether we should attempt to schedule an event group based on
1566  * PMU-specific filtering. An event group can consist of HW and SW events,
1567  * potentially with a SW leader, so we must check all the filters, to
1568  * determine whether a group is schedulable:
1569  */
pmu_filter_match(struct perf_event * event)1570 static inline int pmu_filter_match(struct perf_event *event)
1571 {
1572 	struct perf_event *child;
1573 
1574 	if (!__pmu_filter_match(event))
1575 		return 0;
1576 
1577 	list_for_each_entry(child, &event->sibling_list, group_entry) {
1578 		if (!__pmu_filter_match(child))
1579 			return 0;
1580 	}
1581 
1582 	return 1;
1583 }
1584 
1585 static inline int
event_filter_match(struct perf_event * event)1586 event_filter_match(struct perf_event *event)
1587 {
1588 	return (event->cpu == -1 || event->cpu == smp_processor_id())
1589 	    && perf_cgroup_match(event) && pmu_filter_match(event);
1590 }
1591 
1592 static void
event_sched_out(struct perf_event * event,struct perf_cpu_context * cpuctx,struct perf_event_context * ctx)1593 event_sched_out(struct perf_event *event,
1594 		  struct perf_cpu_context *cpuctx,
1595 		  struct perf_event_context *ctx)
1596 {
1597 	u64 tstamp = perf_event_time(event);
1598 	u64 delta;
1599 
1600 	WARN_ON_ONCE(event->ctx != ctx);
1601 	lockdep_assert_held(&ctx->lock);
1602 
1603 	/*
1604 	 * An event which could not be activated because of
1605 	 * filter mismatch still needs to have its timings
1606 	 * maintained, otherwise bogus information is return
1607 	 * via read() for time_enabled, time_running:
1608 	 */
1609 	if (event->state == PERF_EVENT_STATE_INACTIVE
1610 	    && !event_filter_match(event)) {
1611 		delta = tstamp - event->tstamp_stopped;
1612 		event->tstamp_running += delta;
1613 		event->tstamp_stopped = tstamp;
1614 	}
1615 
1616 	if (event->state != PERF_EVENT_STATE_ACTIVE)
1617 		return;
1618 
1619 	perf_pmu_disable(event->pmu);
1620 
1621 	event->tstamp_stopped = tstamp;
1622 	event->pmu->del(event, 0);
1623 	event->oncpu = -1;
1624 	event->state = PERF_EVENT_STATE_INACTIVE;
1625 	if (event->pending_disable) {
1626 		event->pending_disable = 0;
1627 		event->state = PERF_EVENT_STATE_OFF;
1628 	}
1629 
1630 	if (!is_software_event(event))
1631 		cpuctx->active_oncpu--;
1632 	if (!--ctx->nr_active)
1633 		perf_event_ctx_deactivate(ctx);
1634 	if (event->attr.freq && event->attr.sample_freq)
1635 		ctx->nr_freq--;
1636 	if (event->attr.exclusive || !cpuctx->active_oncpu)
1637 		cpuctx->exclusive = 0;
1638 
1639 	if (is_orphaned_child(event))
1640 		schedule_orphans_remove(ctx);
1641 
1642 	perf_pmu_enable(event->pmu);
1643 }
1644 
1645 static void
group_sched_out(struct perf_event * group_event,struct perf_cpu_context * cpuctx,struct perf_event_context * ctx)1646 group_sched_out(struct perf_event *group_event,
1647 		struct perf_cpu_context *cpuctx,
1648 		struct perf_event_context *ctx)
1649 {
1650 	struct perf_event *event;
1651 	int state = group_event->state;
1652 
1653 	event_sched_out(group_event, cpuctx, ctx);
1654 
1655 	/*
1656 	 * Schedule out siblings (if any):
1657 	 */
1658 	list_for_each_entry(event, &group_event->sibling_list, group_entry)
1659 		event_sched_out(event, cpuctx, ctx);
1660 
1661 	if (state == PERF_EVENT_STATE_ACTIVE && group_event->attr.exclusive)
1662 		cpuctx->exclusive = 0;
1663 }
1664 
1665 struct remove_event {
1666 	struct perf_event *event;
1667 	bool detach_group;
1668 };
1669 
1670 /*
1671  * Cross CPU call to remove a performance event
1672  *
1673  * We disable the event on the hardware level first. After that we
1674  * remove it from the context list.
1675  */
__perf_remove_from_context(void * info)1676 static int __perf_remove_from_context(void *info)
1677 {
1678 	struct remove_event *re = info;
1679 	struct perf_event *event = re->event;
1680 	struct perf_event_context *ctx = event->ctx;
1681 	struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1682 
1683 	raw_spin_lock(&ctx->lock);
1684 	event_sched_out(event, cpuctx, ctx);
1685 	if (re->detach_group)
1686 		perf_group_detach(event);
1687 	list_del_event(event, ctx);
1688 	if (!ctx->nr_events && cpuctx->task_ctx == ctx) {
1689 		ctx->is_active = 0;
1690 		cpuctx->task_ctx = NULL;
1691 	}
1692 	raw_spin_unlock(&ctx->lock);
1693 
1694 	return 0;
1695 }
1696 
1697 
1698 /*
1699  * Remove the event from a task's (or a CPU's) list of events.
1700  *
1701  * CPU events are removed with a smp call. For task events we only
1702  * call when the task is on a CPU.
1703  *
1704  * If event->ctx is a cloned context, callers must make sure that
1705  * every task struct that event->ctx->task could possibly point to
1706  * remains valid.  This is OK when called from perf_release since
1707  * that only calls us on the top-level context, which can't be a clone.
1708  * When called from perf_event_exit_task, it's OK because the
1709  * context has been detached from its task.
1710  */
perf_remove_from_context(struct perf_event * event,bool detach_group)1711 static void perf_remove_from_context(struct perf_event *event, bool detach_group)
1712 {
1713 	struct perf_event_context *ctx = event->ctx;
1714 	struct task_struct *task = ctx->task;
1715 	struct remove_event re = {
1716 		.event = event,
1717 		.detach_group = detach_group,
1718 	};
1719 
1720 	lockdep_assert_held(&ctx->mutex);
1721 
1722 	if (!task) {
1723 		/*
1724 		 * Per cpu events are removed via an smp call. The removal can
1725 		 * fail if the CPU is currently offline, but in that case we
1726 		 * already called __perf_remove_from_context from
1727 		 * perf_event_exit_cpu.
1728 		 */
1729 		cpu_function_call(event->cpu, __perf_remove_from_context, &re);
1730 		return;
1731 	}
1732 
1733 retry:
1734 	if (!task_function_call(task, __perf_remove_from_context, &re))
1735 		return;
1736 
1737 	raw_spin_lock_irq(&ctx->lock);
1738 	/*
1739 	 * If we failed to find a running task, but find the context active now
1740 	 * that we've acquired the ctx->lock, retry.
1741 	 */
1742 	if (ctx->is_active) {
1743 		raw_spin_unlock_irq(&ctx->lock);
1744 		/*
1745 		 * Reload the task pointer, it might have been changed by
1746 		 * a concurrent perf_event_context_sched_out().
1747 		 */
1748 		task = ctx->task;
1749 		goto retry;
1750 	}
1751 
1752 	/*
1753 	 * Since the task isn't running, its safe to remove the event, us
1754 	 * holding the ctx->lock ensures the task won't get scheduled in.
1755 	 */
1756 	if (detach_group)
1757 		perf_group_detach(event);
1758 	list_del_event(event, ctx);
1759 	raw_spin_unlock_irq(&ctx->lock);
1760 }
1761 
1762 /*
1763  * Cross CPU call to disable a performance event
1764  */
__perf_event_disable(void * info)1765 int __perf_event_disable(void *info)
1766 {
1767 	struct perf_event *event = info;
1768 	struct perf_event_context *ctx = event->ctx;
1769 	struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1770 
1771 	/*
1772 	 * If this is a per-task event, need to check whether this
1773 	 * event's task is the current task on this cpu.
1774 	 *
1775 	 * Can trigger due to concurrent perf_event_context_sched_out()
1776 	 * flipping contexts around.
1777 	 */
1778 	if (ctx->task && cpuctx->task_ctx != ctx)
1779 		return -EINVAL;
1780 
1781 	raw_spin_lock(&ctx->lock);
1782 
1783 	/*
1784 	 * If the event is on, turn it off.
1785 	 * If it is in error state, leave it in error state.
1786 	 */
1787 	if (event->state >= PERF_EVENT_STATE_INACTIVE) {
1788 		update_context_time(ctx);
1789 		update_cgrp_time_from_event(event);
1790 		update_group_times(event);
1791 		if (event == event->group_leader)
1792 			group_sched_out(event, cpuctx, ctx);
1793 		else
1794 			event_sched_out(event, cpuctx, ctx);
1795 		event->state = PERF_EVENT_STATE_OFF;
1796 	}
1797 
1798 	raw_spin_unlock(&ctx->lock);
1799 
1800 	return 0;
1801 }
1802 
1803 /*
1804  * Disable a event.
1805  *
1806  * If event->ctx is a cloned context, callers must make sure that
1807  * every task struct that event->ctx->task could possibly point to
1808  * remains valid.  This condition is satisifed when called through
1809  * perf_event_for_each_child or perf_event_for_each because they
1810  * hold the top-level event's child_mutex, so any descendant that
1811  * goes to exit will block in sync_child_event.
1812  * When called from perf_pending_event it's OK because event->ctx
1813  * is the current context on this CPU and preemption is disabled,
1814  * hence we can't get into perf_event_task_sched_out for this context.
1815  */
_perf_event_disable(struct perf_event * event)1816 static void _perf_event_disable(struct perf_event *event)
1817 {
1818 	struct perf_event_context *ctx = event->ctx;
1819 	struct task_struct *task = ctx->task;
1820 
1821 	if (!task) {
1822 		/*
1823 		 * Disable the event on the cpu that it's on
1824 		 */
1825 		cpu_function_call(event->cpu, __perf_event_disable, event);
1826 		return;
1827 	}
1828 
1829 retry:
1830 	if (!task_function_call(task, __perf_event_disable, event))
1831 		return;
1832 
1833 	raw_spin_lock_irq(&ctx->lock);
1834 	/*
1835 	 * If the event is still active, we need to retry the cross-call.
1836 	 */
1837 	if (event->state == PERF_EVENT_STATE_ACTIVE) {
1838 		raw_spin_unlock_irq(&ctx->lock);
1839 		/*
1840 		 * Reload the task pointer, it might have been changed by
1841 		 * a concurrent perf_event_context_sched_out().
1842 		 */
1843 		task = ctx->task;
1844 		goto retry;
1845 	}
1846 
1847 	/*
1848 	 * Since we have the lock this context can't be scheduled
1849 	 * in, so we can change the state safely.
1850 	 */
1851 	if (event->state == PERF_EVENT_STATE_INACTIVE) {
1852 		update_group_times(event);
1853 		event->state = PERF_EVENT_STATE_OFF;
1854 	}
1855 	raw_spin_unlock_irq(&ctx->lock);
1856 }
1857 
1858 /*
1859  * Strictly speaking kernel users cannot create groups and therefore this
1860  * interface does not need the perf_event_ctx_lock() magic.
1861  */
perf_event_disable(struct perf_event * event)1862 void perf_event_disable(struct perf_event *event)
1863 {
1864 	struct perf_event_context *ctx;
1865 
1866 	ctx = perf_event_ctx_lock(event);
1867 	_perf_event_disable(event);
1868 	perf_event_ctx_unlock(event, ctx);
1869 }
1870 EXPORT_SYMBOL_GPL(perf_event_disable);
1871 
perf_set_shadow_time(struct perf_event * event,struct perf_event_context * ctx,u64 tstamp)1872 static void perf_set_shadow_time(struct perf_event *event,
1873 				 struct perf_event_context *ctx,
1874 				 u64 tstamp)
1875 {
1876 	/*
1877 	 * use the correct time source for the time snapshot
1878 	 *
1879 	 * We could get by without this by leveraging the
1880 	 * fact that to get to this function, the caller
1881 	 * has most likely already called update_context_time()
1882 	 * and update_cgrp_time_xx() and thus both timestamp
1883 	 * are identical (or very close). Given that tstamp is,
1884 	 * already adjusted for cgroup, we could say that:
1885 	 *    tstamp - ctx->timestamp
1886 	 * is equivalent to
1887 	 *    tstamp - cgrp->timestamp.
1888 	 *
1889 	 * Then, in perf_output_read(), the calculation would
1890 	 * work with no changes because:
1891 	 * - event is guaranteed scheduled in
1892 	 * - no scheduled out in between
1893 	 * - thus the timestamp would be the same
1894 	 *
1895 	 * But this is a bit hairy.
1896 	 *
1897 	 * So instead, we have an explicit cgroup call to remain
1898 	 * within the time time source all along. We believe it
1899 	 * is cleaner and simpler to understand.
1900 	 */
1901 	if (is_cgroup_event(event))
1902 		perf_cgroup_set_shadow_time(event, tstamp);
1903 	else
1904 		event->shadow_ctx_time = tstamp - ctx->timestamp;
1905 }
1906 
1907 #define MAX_INTERRUPTS (~0ULL)
1908 
1909 static void perf_log_throttle(struct perf_event *event, int enable);
1910 static void perf_log_itrace_start(struct perf_event *event);
1911 
1912 static int
event_sched_in(struct perf_event * event,struct perf_cpu_context * cpuctx,struct perf_event_context * ctx)1913 event_sched_in(struct perf_event *event,
1914 		 struct perf_cpu_context *cpuctx,
1915 		 struct perf_event_context *ctx)
1916 {
1917 	u64 tstamp = perf_event_time(event);
1918 	int ret = 0;
1919 
1920 	lockdep_assert_held(&ctx->lock);
1921 
1922 	if (event->state <= PERF_EVENT_STATE_OFF)
1923 		return 0;
1924 
1925 	event->state = PERF_EVENT_STATE_ACTIVE;
1926 	event->oncpu = smp_processor_id();
1927 
1928 	/*
1929 	 * Unthrottle events, since we scheduled we might have missed several
1930 	 * ticks already, also for a heavily scheduling task there is little
1931 	 * guarantee it'll get a tick in a timely manner.
1932 	 */
1933 	if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
1934 		perf_log_throttle(event, 1);
1935 		event->hw.interrupts = 0;
1936 	}
1937 
1938 	/*
1939 	 * The new state must be visible before we turn it on in the hardware:
1940 	 */
1941 	smp_wmb();
1942 
1943 	perf_pmu_disable(event->pmu);
1944 
1945 	perf_set_shadow_time(event, ctx, tstamp);
1946 
1947 	perf_log_itrace_start(event);
1948 
1949 	if (event->pmu->add(event, PERF_EF_START)) {
1950 		event->state = PERF_EVENT_STATE_INACTIVE;
1951 		event->oncpu = -1;
1952 		ret = -EAGAIN;
1953 		goto out;
1954 	}
1955 
1956 	event->tstamp_running += tstamp - event->tstamp_stopped;
1957 
1958 	if (!is_software_event(event))
1959 		cpuctx->active_oncpu++;
1960 	if (!ctx->nr_active++)
1961 		perf_event_ctx_activate(ctx);
1962 	if (event->attr.freq && event->attr.sample_freq)
1963 		ctx->nr_freq++;
1964 
1965 	if (event->attr.exclusive)
1966 		cpuctx->exclusive = 1;
1967 
1968 	if (is_orphaned_child(event))
1969 		schedule_orphans_remove(ctx);
1970 
1971 out:
1972 	perf_pmu_enable(event->pmu);
1973 
1974 	return ret;
1975 }
1976 
1977 static int
group_sched_in(struct perf_event * group_event,struct perf_cpu_context * cpuctx,struct perf_event_context * ctx)1978 group_sched_in(struct perf_event *group_event,
1979 	       struct perf_cpu_context *cpuctx,
1980 	       struct perf_event_context *ctx)
1981 {
1982 	struct perf_event *event, *partial_group = NULL;
1983 	struct pmu *pmu = ctx->pmu;
1984 	u64 now = ctx->time;
1985 	bool simulate = false;
1986 
1987 	if (group_event->state == PERF_EVENT_STATE_OFF)
1988 		return 0;
1989 
1990 	pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
1991 
1992 	if (event_sched_in(group_event, cpuctx, ctx)) {
1993 		pmu->cancel_txn(pmu);
1994 		perf_mux_hrtimer_restart(cpuctx);
1995 		return -EAGAIN;
1996 	}
1997 
1998 	/*
1999 	 * Schedule in siblings as one group (if any):
2000 	 */
2001 	list_for_each_entry(event, &group_event->sibling_list, group_entry) {
2002 		if (event_sched_in(event, cpuctx, ctx)) {
2003 			partial_group = event;
2004 			goto group_error;
2005 		}
2006 	}
2007 
2008 	if (!pmu->commit_txn(pmu))
2009 		return 0;
2010 
2011 group_error:
2012 	/*
2013 	 * Groups can be scheduled in as one unit only, so undo any
2014 	 * partial group before returning:
2015 	 * The events up to the failed event are scheduled out normally,
2016 	 * tstamp_stopped will be updated.
2017 	 *
2018 	 * The failed events and the remaining siblings need to have
2019 	 * their timings updated as if they had gone thru event_sched_in()
2020 	 * and event_sched_out(). This is required to get consistent timings
2021 	 * across the group. This also takes care of the case where the group
2022 	 * could never be scheduled by ensuring tstamp_stopped is set to mark
2023 	 * the time the event was actually stopped, such that time delta
2024 	 * calculation in update_event_times() is correct.
2025 	 */
2026 	list_for_each_entry(event, &group_event->sibling_list, group_entry) {
2027 		if (event == partial_group)
2028 			simulate = true;
2029 
2030 		if (simulate) {
2031 			event->tstamp_running += now - event->tstamp_stopped;
2032 			event->tstamp_stopped = now;
2033 		} else {
2034 			event_sched_out(event, cpuctx, ctx);
2035 		}
2036 	}
2037 	event_sched_out(group_event, cpuctx, ctx);
2038 
2039 	pmu->cancel_txn(pmu);
2040 
2041 	perf_mux_hrtimer_restart(cpuctx);
2042 
2043 	return -EAGAIN;
2044 }
2045 
2046 /*
2047  * Work out whether we can put this event group on the CPU now.
2048  */
group_can_go_on(struct perf_event * event,struct perf_cpu_context * cpuctx,int can_add_hw)2049 static int group_can_go_on(struct perf_event *event,
2050 			   struct perf_cpu_context *cpuctx,
2051 			   int can_add_hw)
2052 {
2053 	/*
2054 	 * Groups consisting entirely of software events can always go on.
2055 	 */
2056 	if (event->group_flags & PERF_GROUP_SOFTWARE)
2057 		return 1;
2058 	/*
2059 	 * If an exclusive group is already on, no other hardware
2060 	 * events can go on.
2061 	 */
2062 	if (cpuctx->exclusive)
2063 		return 0;
2064 	/*
2065 	 * If this group is exclusive and there are already
2066 	 * events on the CPU, it can't go on.
2067 	 */
2068 	if (event->attr.exclusive && cpuctx->active_oncpu)
2069 		return 0;
2070 	/*
2071 	 * Otherwise, try to add it if all previous groups were able
2072 	 * to go on.
2073 	 */
2074 	return can_add_hw;
2075 }
2076 
add_event_to_ctx(struct perf_event * event,struct perf_event_context * ctx)2077 static void add_event_to_ctx(struct perf_event *event,
2078 			       struct perf_event_context *ctx)
2079 {
2080 	u64 tstamp = perf_event_time(event);
2081 
2082 	list_add_event(event, ctx);
2083 	perf_group_attach(event);
2084 	event->tstamp_enabled = tstamp;
2085 	event->tstamp_running = tstamp;
2086 	event->tstamp_stopped = tstamp;
2087 }
2088 
2089 static void task_ctx_sched_out(struct perf_event_context *ctx);
2090 static void
2091 ctx_sched_in(struct perf_event_context *ctx,
2092 	     struct perf_cpu_context *cpuctx,
2093 	     enum event_type_t event_type,
2094 	     struct task_struct *task);
2095 
perf_event_sched_in(struct perf_cpu_context * cpuctx,struct perf_event_context * ctx,struct task_struct * task)2096 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2097 				struct perf_event_context *ctx,
2098 				struct task_struct *task)
2099 {
2100 	cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
2101 	if (ctx)
2102 		ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
2103 	cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
2104 	if (ctx)
2105 		ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
2106 }
2107 
2108 /*
2109  * Cross CPU call to install and enable a performance event
2110  *
2111  * Must be called with ctx->mutex held
2112  */
__perf_install_in_context(void * info)2113 static int  __perf_install_in_context(void *info)
2114 {
2115 	struct perf_event *event = info;
2116 	struct perf_event_context *ctx = event->ctx;
2117 	struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2118 	struct perf_event_context *task_ctx = cpuctx->task_ctx;
2119 	struct task_struct *task = current;
2120 
2121 	perf_ctx_lock(cpuctx, task_ctx);
2122 	perf_pmu_disable(cpuctx->ctx.pmu);
2123 
2124 	/*
2125 	 * If there was an active task_ctx schedule it out.
2126 	 */
2127 	if (task_ctx)
2128 		task_ctx_sched_out(task_ctx);
2129 
2130 	/*
2131 	 * If the context we're installing events in is not the
2132 	 * active task_ctx, flip them.
2133 	 */
2134 	if (ctx->task && task_ctx != ctx) {
2135 		if (task_ctx)
2136 			raw_spin_unlock(&task_ctx->lock);
2137 		raw_spin_lock(&ctx->lock);
2138 		task_ctx = ctx;
2139 	}
2140 
2141 	if (task_ctx) {
2142 		cpuctx->task_ctx = task_ctx;
2143 		task = task_ctx->task;
2144 	}
2145 
2146 	cpu_ctx_sched_out(cpuctx, EVENT_ALL);
2147 
2148 	update_context_time(ctx);
2149 	/*
2150 	 * update cgrp time only if current cgrp
2151 	 * matches event->cgrp. Must be done before
2152 	 * calling add_event_to_ctx()
2153 	 */
2154 	update_cgrp_time_from_event(event);
2155 
2156 	add_event_to_ctx(event, ctx);
2157 
2158 	/*
2159 	 * Schedule everything back in
2160 	 */
2161 	perf_event_sched_in(cpuctx, task_ctx, task);
2162 
2163 	perf_pmu_enable(cpuctx->ctx.pmu);
2164 	perf_ctx_unlock(cpuctx, task_ctx);
2165 
2166 	return 0;
2167 }
2168 
2169 /*
2170  * Attach a performance event to a context
2171  *
2172  * First we add the event to the list with the hardware enable bit
2173  * in event->hw_config cleared.
2174  *
2175  * If the event is attached to a task which is on a CPU we use a smp
2176  * call to enable it in the task context. The task might have been
2177  * scheduled away, but we check this in the smp call again.
2178  */
2179 static void
perf_install_in_context(struct perf_event_context * ctx,struct perf_event * event,int cpu)2180 perf_install_in_context(struct perf_event_context *ctx,
2181 			struct perf_event *event,
2182 			int cpu)
2183 {
2184 	struct task_struct *task = ctx->task;
2185 
2186 	lockdep_assert_held(&ctx->mutex);
2187 
2188 	event->ctx = ctx;
2189 	if (event->cpu != -1)
2190 		event->cpu = cpu;
2191 
2192 	if (!task) {
2193 		/*
2194 		 * Per cpu events are installed via an smp call and
2195 		 * the install is always successful.
2196 		 */
2197 		cpu_function_call(cpu, __perf_install_in_context, event);
2198 		return;
2199 	}
2200 
2201 retry:
2202 	if (!task_function_call(task, __perf_install_in_context, event))
2203 		return;
2204 
2205 	raw_spin_lock_irq(&ctx->lock);
2206 	/*
2207 	 * If we failed to find a running task, but find the context active now
2208 	 * that we've acquired the ctx->lock, retry.
2209 	 */
2210 	if (ctx->is_active) {
2211 		raw_spin_unlock_irq(&ctx->lock);
2212 		/*
2213 		 * Reload the task pointer, it might have been changed by
2214 		 * a concurrent perf_event_context_sched_out().
2215 		 */
2216 		task = ctx->task;
2217 		goto retry;
2218 	}
2219 
2220 	/*
2221 	 * Since the task isn't running, its safe to add the event, us holding
2222 	 * the ctx->lock ensures the task won't get scheduled in.
2223 	 */
2224 	add_event_to_ctx(event, ctx);
2225 	raw_spin_unlock_irq(&ctx->lock);
2226 }
2227 
2228 /*
2229  * Put a event into inactive state and update time fields.
2230  * Enabling the leader of a group effectively enables all
2231  * the group members that aren't explicitly disabled, so we
2232  * have to update their ->tstamp_enabled also.
2233  * Note: this works for group members as well as group leaders
2234  * since the non-leader members' sibling_lists will be empty.
2235  */
__perf_event_mark_enabled(struct perf_event * event)2236 static void __perf_event_mark_enabled(struct perf_event *event)
2237 {
2238 	struct perf_event *sub;
2239 	u64 tstamp = perf_event_time(event);
2240 
2241 	event->state = PERF_EVENT_STATE_INACTIVE;
2242 	event->tstamp_enabled = tstamp - event->total_time_enabled;
2243 	list_for_each_entry(sub, &event->sibling_list, group_entry) {
2244 		if (sub->state >= PERF_EVENT_STATE_INACTIVE)
2245 			sub->tstamp_enabled = tstamp - sub->total_time_enabled;
2246 	}
2247 }
2248 
2249 /*
2250  * Cross CPU call to enable a performance event
2251  */
__perf_event_enable(void * info)2252 static int __perf_event_enable(void *info)
2253 {
2254 	struct perf_event *event = info;
2255 	struct perf_event_context *ctx = event->ctx;
2256 	struct perf_event *leader = event->group_leader;
2257 	struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2258 	int err;
2259 
2260 	/*
2261 	 * There's a time window between 'ctx->is_active' check
2262 	 * in perf_event_enable function and this place having:
2263 	 *   - IRQs on
2264 	 *   - ctx->lock unlocked
2265 	 *
2266 	 * where the task could be killed and 'ctx' deactivated
2267 	 * by perf_event_exit_task.
2268 	 */
2269 	if (!ctx->is_active)
2270 		return -EINVAL;
2271 
2272 	raw_spin_lock(&ctx->lock);
2273 	update_context_time(ctx);
2274 
2275 	if (event->state >= PERF_EVENT_STATE_INACTIVE)
2276 		goto unlock;
2277 
2278 	/*
2279 	 * set current task's cgroup time reference point
2280 	 */
2281 	perf_cgroup_set_timestamp(current, ctx);
2282 
2283 	__perf_event_mark_enabled(event);
2284 
2285 	if (!event_filter_match(event)) {
2286 		if (is_cgroup_event(event))
2287 			perf_cgroup_defer_enabled(event);
2288 		goto unlock;
2289 	}
2290 
2291 	/*
2292 	 * If the event is in a group and isn't the group leader,
2293 	 * then don't put it on unless the group is on.
2294 	 */
2295 	if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
2296 		goto unlock;
2297 
2298 	if (!group_can_go_on(event, cpuctx, 1)) {
2299 		err = -EEXIST;
2300 	} else {
2301 		if (event == leader)
2302 			err = group_sched_in(event, cpuctx, ctx);
2303 		else
2304 			err = event_sched_in(event, cpuctx, ctx);
2305 	}
2306 
2307 	if (err) {
2308 		/*
2309 		 * If this event can't go on and it's part of a
2310 		 * group, then the whole group has to come off.
2311 		 */
2312 		if (leader != event) {
2313 			group_sched_out(leader, cpuctx, ctx);
2314 			perf_mux_hrtimer_restart(cpuctx);
2315 		}
2316 		if (leader->attr.pinned) {
2317 			update_group_times(leader);
2318 			leader->state = PERF_EVENT_STATE_ERROR;
2319 		}
2320 	}
2321 
2322 unlock:
2323 	raw_spin_unlock(&ctx->lock);
2324 
2325 	return 0;
2326 }
2327 
2328 /*
2329  * Enable a event.
2330  *
2331  * If event->ctx is a cloned context, callers must make sure that
2332  * every task struct that event->ctx->task could possibly point to
2333  * remains valid.  This condition is satisfied when called through
2334  * perf_event_for_each_child or perf_event_for_each as described
2335  * for perf_event_disable.
2336  */
_perf_event_enable(struct perf_event * event)2337 static void _perf_event_enable(struct perf_event *event)
2338 {
2339 	struct perf_event_context *ctx = event->ctx;
2340 	struct task_struct *task = ctx->task;
2341 
2342 	if (!task) {
2343 		/*
2344 		 * Enable the event on the cpu that it's on
2345 		 */
2346 		cpu_function_call(event->cpu, __perf_event_enable, event);
2347 		return;
2348 	}
2349 
2350 	raw_spin_lock_irq(&ctx->lock);
2351 	if (event->state >= PERF_EVENT_STATE_INACTIVE)
2352 		goto out;
2353 
2354 	/*
2355 	 * If the event is in error state, clear that first.
2356 	 * That way, if we see the event in error state below, we
2357 	 * know that it has gone back into error state, as distinct
2358 	 * from the task having been scheduled away before the
2359 	 * cross-call arrived.
2360 	 */
2361 	if (event->state == PERF_EVENT_STATE_ERROR)
2362 		event->state = PERF_EVENT_STATE_OFF;
2363 
2364 retry:
2365 	if (!ctx->is_active) {
2366 		__perf_event_mark_enabled(event);
2367 		goto out;
2368 	}
2369 
2370 	raw_spin_unlock_irq(&ctx->lock);
2371 
2372 	if (!task_function_call(task, __perf_event_enable, event))
2373 		return;
2374 
2375 	raw_spin_lock_irq(&ctx->lock);
2376 
2377 	/*
2378 	 * If the context is active and the event is still off,
2379 	 * we need to retry the cross-call.
2380 	 */
2381 	if (ctx->is_active && event->state == PERF_EVENT_STATE_OFF) {
2382 		/*
2383 		 * task could have been flipped by a concurrent
2384 		 * perf_event_context_sched_out()
2385 		 */
2386 		task = ctx->task;
2387 		goto retry;
2388 	}
2389 
2390 out:
2391 	raw_spin_unlock_irq(&ctx->lock);
2392 }
2393 
2394 /*
2395  * See perf_event_disable();
2396  */
perf_event_enable(struct perf_event * event)2397 void perf_event_enable(struct perf_event *event)
2398 {
2399 	struct perf_event_context *ctx;
2400 
2401 	ctx = perf_event_ctx_lock(event);
2402 	_perf_event_enable(event);
2403 	perf_event_ctx_unlock(event, ctx);
2404 }
2405 EXPORT_SYMBOL_GPL(perf_event_enable);
2406 
_perf_event_refresh(struct perf_event * event,int refresh)2407 static int _perf_event_refresh(struct perf_event *event, int refresh)
2408 {
2409 	/*
2410 	 * not supported on inherited events
2411 	 */
2412 	if (event->attr.inherit || !is_sampling_event(event))
2413 		return -EINVAL;
2414 
2415 	atomic_add(refresh, &event->event_limit);
2416 	_perf_event_enable(event);
2417 
2418 	return 0;
2419 }
2420 
2421 /*
2422  * See perf_event_disable()
2423  */
perf_event_refresh(struct perf_event * event,int refresh)2424 int perf_event_refresh(struct perf_event *event, int refresh)
2425 {
2426 	struct perf_event_context *ctx;
2427 	int ret;
2428 
2429 	ctx = perf_event_ctx_lock(event);
2430 	ret = _perf_event_refresh(event, refresh);
2431 	perf_event_ctx_unlock(event, ctx);
2432 
2433 	return ret;
2434 }
2435 EXPORT_SYMBOL_GPL(perf_event_refresh);
2436 
ctx_sched_out(struct perf_event_context * ctx,struct perf_cpu_context * cpuctx,enum event_type_t event_type)2437 static void ctx_sched_out(struct perf_event_context *ctx,
2438 			  struct perf_cpu_context *cpuctx,
2439 			  enum event_type_t event_type)
2440 {
2441 	struct perf_event *event;
2442 	int is_active = ctx->is_active;
2443 
2444 	ctx->is_active &= ~event_type;
2445 	if (likely(!ctx->nr_events))
2446 		return;
2447 
2448 	update_context_time(ctx);
2449 	update_cgrp_time_from_cpuctx(cpuctx);
2450 	if (!ctx->nr_active)
2451 		return;
2452 
2453 	perf_pmu_disable(ctx->pmu);
2454 	if ((is_active & EVENT_PINNED) && (event_type & EVENT_PINNED)) {
2455 		list_for_each_entry(event, &ctx->pinned_groups, group_entry)
2456 			group_sched_out(event, cpuctx, ctx);
2457 	}
2458 
2459 	if ((is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE)) {
2460 		list_for_each_entry(event, &ctx->flexible_groups, group_entry)
2461 			group_sched_out(event, cpuctx, ctx);
2462 	}
2463 	perf_pmu_enable(ctx->pmu);
2464 }
2465 
2466 /*
2467  * Test whether two contexts are equivalent, i.e. whether they have both been
2468  * cloned from the same version of the same context.
2469  *
2470  * Equivalence is measured using a generation number in the context that is
2471  * incremented on each modification to it; see unclone_ctx(), list_add_event()
2472  * and list_del_event().
2473  */
context_equiv(struct perf_event_context * ctx1,struct perf_event_context * ctx2)2474 static int context_equiv(struct perf_event_context *ctx1,
2475 			 struct perf_event_context *ctx2)
2476 {
2477 	lockdep_assert_held(&ctx1->lock);
2478 	lockdep_assert_held(&ctx2->lock);
2479 
2480 	/* Pinning disables the swap optimization */
2481 	if (ctx1->pin_count || ctx2->pin_count)
2482 		return 0;
2483 
2484 	/* If ctx1 is the parent of ctx2 */
2485 	if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
2486 		return 1;
2487 
2488 	/* If ctx2 is the parent of ctx1 */
2489 	if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
2490 		return 1;
2491 
2492 	/*
2493 	 * If ctx1 and ctx2 have the same parent; we flatten the parent
2494 	 * hierarchy, see perf_event_init_context().
2495 	 */
2496 	if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
2497 			ctx1->parent_gen == ctx2->parent_gen)
2498 		return 1;
2499 
2500 	/* Unmatched */
2501 	return 0;
2502 }
2503 
__perf_event_sync_stat(struct perf_event * event,struct perf_event * next_event)2504 static void __perf_event_sync_stat(struct perf_event *event,
2505 				     struct perf_event *next_event)
2506 {
2507 	u64 value;
2508 
2509 	if (!event->attr.inherit_stat)
2510 		return;
2511 
2512 	/*
2513 	 * Update the event value, we cannot use perf_event_read()
2514 	 * because we're in the middle of a context switch and have IRQs
2515 	 * disabled, which upsets smp_call_function_single(), however
2516 	 * we know the event must be on the current CPU, therefore we
2517 	 * don't need to use it.
2518 	 */
2519 	switch (event->state) {
2520 	case PERF_EVENT_STATE_ACTIVE:
2521 		event->pmu->read(event);
2522 		/* fall-through */
2523 
2524 	case PERF_EVENT_STATE_INACTIVE:
2525 		update_event_times(event);
2526 		break;
2527 
2528 	default:
2529 		break;
2530 	}
2531 
2532 	/*
2533 	 * In order to keep per-task stats reliable we need to flip the event
2534 	 * values when we flip the contexts.
2535 	 */
2536 	value = local64_read(&next_event->count);
2537 	value = local64_xchg(&event->count, value);
2538 	local64_set(&next_event->count, value);
2539 
2540 	swap(event->total_time_enabled, next_event->total_time_enabled);
2541 	swap(event->total_time_running, next_event->total_time_running);
2542 
2543 	/*
2544 	 * Since we swizzled the values, update the user visible data too.
2545 	 */
2546 	perf_event_update_userpage(event);
2547 	perf_event_update_userpage(next_event);
2548 }
2549 
perf_event_sync_stat(struct perf_event_context * ctx,struct perf_event_context * next_ctx)2550 static void perf_event_sync_stat(struct perf_event_context *ctx,
2551 				   struct perf_event_context *next_ctx)
2552 {
2553 	struct perf_event *event, *next_event;
2554 
2555 	if (!ctx->nr_stat)
2556 		return;
2557 
2558 	update_context_time(ctx);
2559 
2560 	event = list_first_entry(&ctx->event_list,
2561 				   struct perf_event, event_entry);
2562 
2563 	next_event = list_first_entry(&next_ctx->event_list,
2564 					struct perf_event, event_entry);
2565 
2566 	while (&event->event_entry != &ctx->event_list &&
2567 	       &next_event->event_entry != &next_ctx->event_list) {
2568 
2569 		__perf_event_sync_stat(event, next_event);
2570 
2571 		event = list_next_entry(event, event_entry);
2572 		next_event = list_next_entry(next_event, event_entry);
2573 	}
2574 }
2575 
perf_event_context_sched_out(struct task_struct * task,int ctxn,struct task_struct * next)2576 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
2577 					 struct task_struct *next)
2578 {
2579 	struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
2580 	struct perf_event_context *next_ctx;
2581 	struct perf_event_context *parent, *next_parent;
2582 	struct perf_cpu_context *cpuctx;
2583 	int do_switch = 1;
2584 
2585 	if (likely(!ctx))
2586 		return;
2587 
2588 	cpuctx = __get_cpu_context(ctx);
2589 	if (!cpuctx->task_ctx)
2590 		return;
2591 
2592 	rcu_read_lock();
2593 	next_ctx = next->perf_event_ctxp[ctxn];
2594 	if (!next_ctx)
2595 		goto unlock;
2596 
2597 	parent = rcu_dereference(ctx->parent_ctx);
2598 	next_parent = rcu_dereference(next_ctx->parent_ctx);
2599 
2600 	/* If neither context have a parent context; they cannot be clones. */
2601 	if (!parent && !next_parent)
2602 		goto unlock;
2603 
2604 	if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
2605 		/*
2606 		 * Looks like the two contexts are clones, so we might be
2607 		 * able to optimize the context switch.  We lock both
2608 		 * contexts and check that they are clones under the
2609 		 * lock (including re-checking that neither has been
2610 		 * uncloned in the meantime).  It doesn't matter which
2611 		 * order we take the locks because no other cpu could
2612 		 * be trying to lock both of these tasks.
2613 		 */
2614 		raw_spin_lock(&ctx->lock);
2615 		raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
2616 		if (context_equiv(ctx, next_ctx)) {
2617 			/*
2618 			 * XXX do we need a memory barrier of sorts
2619 			 * wrt to rcu_dereference() of perf_event_ctxp
2620 			 */
2621 			task->perf_event_ctxp[ctxn] = next_ctx;
2622 			next->perf_event_ctxp[ctxn] = ctx;
2623 			ctx->task = next;
2624 			next_ctx->task = task;
2625 
2626 			swap(ctx->task_ctx_data, next_ctx->task_ctx_data);
2627 
2628 			do_switch = 0;
2629 
2630 			perf_event_sync_stat(ctx, next_ctx);
2631 		}
2632 		raw_spin_unlock(&next_ctx->lock);
2633 		raw_spin_unlock(&ctx->lock);
2634 	}
2635 unlock:
2636 	rcu_read_unlock();
2637 
2638 	if (do_switch) {
2639 		raw_spin_lock(&ctx->lock);
2640 		ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2641 		cpuctx->task_ctx = NULL;
2642 		raw_spin_unlock(&ctx->lock);
2643 	}
2644 }
2645 
perf_sched_cb_dec(struct pmu * pmu)2646 void perf_sched_cb_dec(struct pmu *pmu)
2647 {
2648 	this_cpu_dec(perf_sched_cb_usages);
2649 }
2650 
perf_sched_cb_inc(struct pmu * pmu)2651 void perf_sched_cb_inc(struct pmu *pmu)
2652 {
2653 	this_cpu_inc(perf_sched_cb_usages);
2654 }
2655 
2656 /*
2657  * This function provides the context switch callback to the lower code
2658  * layer. It is invoked ONLY when the context switch callback is enabled.
2659  */
perf_pmu_sched_task(struct task_struct * prev,struct task_struct * next,bool sched_in)2660 static void perf_pmu_sched_task(struct task_struct *prev,
2661 				struct task_struct *next,
2662 				bool sched_in)
2663 {
2664 	struct perf_cpu_context *cpuctx;
2665 	struct pmu *pmu;
2666 	unsigned long flags;
2667 
2668 	if (prev == next)
2669 		return;
2670 
2671 	local_irq_save(flags);
2672 
2673 	rcu_read_lock();
2674 
2675 	list_for_each_entry_rcu(pmu, &pmus, entry) {
2676 		if (pmu->sched_task) {
2677 			cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2678 
2679 			perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2680 
2681 			perf_pmu_disable(pmu);
2682 
2683 			pmu->sched_task(cpuctx->task_ctx, sched_in);
2684 
2685 			perf_pmu_enable(pmu);
2686 
2687 			perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2688 		}
2689 	}
2690 
2691 	rcu_read_unlock();
2692 
2693 	local_irq_restore(flags);
2694 }
2695 
2696 static void perf_event_switch(struct task_struct *task,
2697 			      struct task_struct *next_prev, bool sched_in);
2698 
2699 #define for_each_task_context_nr(ctxn)					\
2700 	for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
2701 
2702 /*
2703  * Called from scheduler to remove the events of the current task,
2704  * with interrupts disabled.
2705  *
2706  * We stop each event and update the event value in event->count.
2707  *
2708  * This does not protect us against NMI, but disable()
2709  * sets the disabled bit in the control field of event _before_
2710  * accessing the event control register. If a NMI hits, then it will
2711  * not restart the event.
2712  */
__perf_event_task_sched_out(struct task_struct * task,struct task_struct * next)2713 void __perf_event_task_sched_out(struct task_struct *task,
2714 				 struct task_struct *next)
2715 {
2716 	int ctxn;
2717 
2718 	if (__this_cpu_read(perf_sched_cb_usages))
2719 		perf_pmu_sched_task(task, next, false);
2720 
2721 	if (atomic_read(&nr_switch_events))
2722 		perf_event_switch(task, next, false);
2723 
2724 	for_each_task_context_nr(ctxn)
2725 		perf_event_context_sched_out(task, ctxn, next);
2726 
2727 	/*
2728 	 * if cgroup events exist on this CPU, then we need
2729 	 * to check if we have to switch out PMU state.
2730 	 * cgroup event are system-wide mode only
2731 	 */
2732 	if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
2733 		perf_cgroup_sched_out(task, next);
2734 }
2735 
task_ctx_sched_out(struct perf_event_context * ctx)2736 static void task_ctx_sched_out(struct perf_event_context *ctx)
2737 {
2738 	struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2739 
2740 	if (!cpuctx->task_ctx)
2741 		return;
2742 
2743 	if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2744 		return;
2745 
2746 	ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2747 	cpuctx->task_ctx = NULL;
2748 }
2749 
2750 /*
2751  * Called with IRQs disabled
2752  */
cpu_ctx_sched_out(struct perf_cpu_context * cpuctx,enum event_type_t event_type)2753 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
2754 			      enum event_type_t event_type)
2755 {
2756 	ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
2757 }
2758 
2759 static void
ctx_pinned_sched_in(struct perf_event_context * ctx,struct perf_cpu_context * cpuctx)2760 ctx_pinned_sched_in(struct perf_event_context *ctx,
2761 		    struct perf_cpu_context *cpuctx)
2762 {
2763 	struct perf_event *event;
2764 
2765 	list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
2766 		if (event->state <= PERF_EVENT_STATE_OFF)
2767 			continue;
2768 		if (!event_filter_match(event))
2769 			continue;
2770 
2771 		/* may need to reset tstamp_enabled */
2772 		if (is_cgroup_event(event))
2773 			perf_cgroup_mark_enabled(event, ctx);
2774 
2775 		if (group_can_go_on(event, cpuctx, 1))
2776 			group_sched_in(event, cpuctx, ctx);
2777 
2778 		/*
2779 		 * If this pinned group hasn't been scheduled,
2780 		 * put it in error state.
2781 		 */
2782 		if (event->state == PERF_EVENT_STATE_INACTIVE) {
2783 			update_group_times(event);
2784 			event->state = PERF_EVENT_STATE_ERROR;
2785 		}
2786 	}
2787 }
2788 
2789 static void
ctx_flexible_sched_in(struct perf_event_context * ctx,struct perf_cpu_context * cpuctx)2790 ctx_flexible_sched_in(struct perf_event_context *ctx,
2791 		      struct perf_cpu_context *cpuctx)
2792 {
2793 	struct perf_event *event;
2794 	int can_add_hw = 1;
2795 
2796 	list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
2797 		/* Ignore events in OFF or ERROR state */
2798 		if (event->state <= PERF_EVENT_STATE_OFF)
2799 			continue;
2800 		/*
2801 		 * Listen to the 'cpu' scheduling filter constraint
2802 		 * of events:
2803 		 */
2804 		if (!event_filter_match(event))
2805 			continue;
2806 
2807 		/* may need to reset tstamp_enabled */
2808 		if (is_cgroup_event(event))
2809 			perf_cgroup_mark_enabled(event, ctx);
2810 
2811 		if (group_can_go_on(event, cpuctx, can_add_hw)) {
2812 			if (group_sched_in(event, cpuctx, ctx))
2813 				can_add_hw = 0;
2814 		}
2815 	}
2816 }
2817 
2818 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)2819 ctx_sched_in(struct perf_event_context *ctx,
2820 	     struct perf_cpu_context *cpuctx,
2821 	     enum event_type_t event_type,
2822 	     struct task_struct *task)
2823 {
2824 	u64 now;
2825 	int is_active = ctx->is_active;
2826 
2827 	ctx->is_active |= event_type;
2828 	if (likely(!ctx->nr_events))
2829 		return;
2830 
2831 	now = perf_clock();
2832 	ctx->timestamp = now;
2833 	perf_cgroup_set_timestamp(task, ctx);
2834 	/*
2835 	 * First go through the list and put on any pinned groups
2836 	 * in order to give them the best chance of going on.
2837 	 */
2838 	if (!(is_active & EVENT_PINNED) && (event_type & EVENT_PINNED))
2839 		ctx_pinned_sched_in(ctx, cpuctx);
2840 
2841 	/* Then walk through the lower prio flexible groups */
2842 	if (!(is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE))
2843 		ctx_flexible_sched_in(ctx, cpuctx);
2844 }
2845 
cpu_ctx_sched_in(struct perf_cpu_context * cpuctx,enum event_type_t event_type,struct task_struct * task)2846 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
2847 			     enum event_type_t event_type,
2848 			     struct task_struct *task)
2849 {
2850 	struct perf_event_context *ctx = &cpuctx->ctx;
2851 
2852 	ctx_sched_in(ctx, cpuctx, event_type, task);
2853 }
2854 
perf_event_context_sched_in(struct perf_event_context * ctx,struct task_struct * task)2855 static void perf_event_context_sched_in(struct perf_event_context *ctx,
2856 					struct task_struct *task)
2857 {
2858 	struct perf_cpu_context *cpuctx;
2859 
2860 	cpuctx = __get_cpu_context(ctx);
2861 	if (cpuctx->task_ctx == ctx)
2862 		return;
2863 
2864 	perf_ctx_lock(cpuctx, ctx);
2865 	perf_pmu_disable(ctx->pmu);
2866 	/*
2867 	 * We want to keep the following priority order:
2868 	 * cpu pinned (that don't need to move), task pinned,
2869 	 * cpu flexible, task flexible.
2870 	 */
2871 	cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2872 
2873 	if (ctx->nr_events)
2874 		cpuctx->task_ctx = ctx;
2875 
2876 	perf_event_sched_in(cpuctx, cpuctx->task_ctx, task);
2877 
2878 	perf_pmu_enable(ctx->pmu);
2879 	perf_ctx_unlock(cpuctx, ctx);
2880 }
2881 
2882 /*
2883  * Called from scheduler to add the events of the current task
2884  * with interrupts disabled.
2885  *
2886  * We restore the event value and then enable it.
2887  *
2888  * This does not protect us against NMI, but enable()
2889  * sets the enabled bit in the control field of event _before_
2890  * accessing the event control register. If a NMI hits, then it will
2891  * keep the event running.
2892  */
__perf_event_task_sched_in(struct task_struct * prev,struct task_struct * task)2893 void __perf_event_task_sched_in(struct task_struct *prev,
2894 				struct task_struct *task)
2895 {
2896 	struct perf_event_context *ctx;
2897 	int ctxn;
2898 
2899 	for_each_task_context_nr(ctxn) {
2900 		ctx = task->perf_event_ctxp[ctxn];
2901 		if (likely(!ctx))
2902 			continue;
2903 
2904 		perf_event_context_sched_in(ctx, task);
2905 	}
2906 	/*
2907 	 * if cgroup events exist on this CPU, then we need
2908 	 * to check if we have to switch in PMU state.
2909 	 * cgroup event are system-wide mode only
2910 	 */
2911 	if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
2912 		perf_cgroup_sched_in(prev, task);
2913 
2914 	if (atomic_read(&nr_switch_events))
2915 		perf_event_switch(task, prev, true);
2916 
2917 	if (__this_cpu_read(perf_sched_cb_usages))
2918 		perf_pmu_sched_task(prev, task, true);
2919 }
2920 
perf_calculate_period(struct perf_event * event,u64 nsec,u64 count)2921 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
2922 {
2923 	u64 frequency = event->attr.sample_freq;
2924 	u64 sec = NSEC_PER_SEC;
2925 	u64 divisor, dividend;
2926 
2927 	int count_fls, nsec_fls, frequency_fls, sec_fls;
2928 
2929 	count_fls = fls64(count);
2930 	nsec_fls = fls64(nsec);
2931 	frequency_fls = fls64(frequency);
2932 	sec_fls = 30;
2933 
2934 	/*
2935 	 * We got @count in @nsec, with a target of sample_freq HZ
2936 	 * the target period becomes:
2937 	 *
2938 	 *             @count * 10^9
2939 	 * period = -------------------
2940 	 *          @nsec * sample_freq
2941 	 *
2942 	 */
2943 
2944 	/*
2945 	 * Reduce accuracy by one bit such that @a and @b converge
2946 	 * to a similar magnitude.
2947 	 */
2948 #define REDUCE_FLS(a, b)		\
2949 do {					\
2950 	if (a##_fls > b##_fls) {	\
2951 		a >>= 1;		\
2952 		a##_fls--;		\
2953 	} else {			\
2954 		b >>= 1;		\
2955 		b##_fls--;		\
2956 	}				\
2957 } while (0)
2958 
2959 	/*
2960 	 * Reduce accuracy until either term fits in a u64, then proceed with
2961 	 * the other, so that finally we can do a u64/u64 division.
2962 	 */
2963 	while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
2964 		REDUCE_FLS(nsec, frequency);
2965 		REDUCE_FLS(sec, count);
2966 	}
2967 
2968 	if (count_fls + sec_fls > 64) {
2969 		divisor = nsec * frequency;
2970 
2971 		while (count_fls + sec_fls > 64) {
2972 			REDUCE_FLS(count, sec);
2973 			divisor >>= 1;
2974 		}
2975 
2976 		dividend = count * sec;
2977 	} else {
2978 		dividend = count * sec;
2979 
2980 		while (nsec_fls + frequency_fls > 64) {
2981 			REDUCE_FLS(nsec, frequency);
2982 			dividend >>= 1;
2983 		}
2984 
2985 		divisor = nsec * frequency;
2986 	}
2987 
2988 	if (!divisor)
2989 		return dividend;
2990 
2991 	return div64_u64(dividend, divisor);
2992 }
2993 
2994 static DEFINE_PER_CPU(int, perf_throttled_count);
2995 static DEFINE_PER_CPU(u64, perf_throttled_seq);
2996 
perf_adjust_period(struct perf_event * event,u64 nsec,u64 count,bool disable)2997 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
2998 {
2999 	struct hw_perf_event *hwc = &event->hw;
3000 	s64 period, sample_period;
3001 	s64 delta;
3002 
3003 	period = perf_calculate_period(event, nsec, count);
3004 
3005 	delta = (s64)(period - hwc->sample_period);
3006 	delta = (delta + 7) / 8; /* low pass filter */
3007 
3008 	sample_period = hwc->sample_period + delta;
3009 
3010 	if (!sample_period)
3011 		sample_period = 1;
3012 
3013 	hwc->sample_period = sample_period;
3014 
3015 	if (local64_read(&hwc->period_left) > 8*sample_period) {
3016 		if (disable)
3017 			event->pmu->stop(event, PERF_EF_UPDATE);
3018 
3019 		local64_set(&hwc->period_left, 0);
3020 
3021 		if (disable)
3022 			event->pmu->start(event, PERF_EF_RELOAD);
3023 	}
3024 }
3025 
3026 /*
3027  * combine freq adjustment with unthrottling to avoid two passes over the
3028  * events. At the same time, make sure, having freq events does not change
3029  * the rate of unthrottling as that would introduce bias.
3030  */
perf_adjust_freq_unthr_context(struct perf_event_context * ctx,int needs_unthr)3031 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
3032 					   int needs_unthr)
3033 {
3034 	struct perf_event *event;
3035 	struct hw_perf_event *hwc;
3036 	u64 now, period = TICK_NSEC;
3037 	s64 delta;
3038 
3039 	/*
3040 	 * only need to iterate over all events iff:
3041 	 * - context have events in frequency mode (needs freq adjust)
3042 	 * - there are events to unthrottle on this cpu
3043 	 */
3044 	if (!(ctx->nr_freq || needs_unthr))
3045 		return;
3046 
3047 	raw_spin_lock(&ctx->lock);
3048 	perf_pmu_disable(ctx->pmu);
3049 
3050 	list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
3051 		if (event->state != PERF_EVENT_STATE_ACTIVE)
3052 			continue;
3053 
3054 		if (!event_filter_match(event))
3055 			continue;
3056 
3057 		perf_pmu_disable(event->pmu);
3058 
3059 		hwc = &event->hw;
3060 
3061 		if (hwc->interrupts == MAX_INTERRUPTS) {
3062 			hwc->interrupts = 0;
3063 			perf_log_throttle(event, 1);
3064 			event->pmu->start(event, 0);
3065 		}
3066 
3067 		if (!event->attr.freq || !event->attr.sample_freq)
3068 			goto next;
3069 
3070 		/*
3071 		 * stop the event and update event->count
3072 		 */
3073 		event->pmu->stop(event, PERF_EF_UPDATE);
3074 
3075 		now = local64_read(&event->count);
3076 		delta = now - hwc->freq_count_stamp;
3077 		hwc->freq_count_stamp = now;
3078 
3079 		/*
3080 		 * restart the event
3081 		 * reload only if value has changed
3082 		 * we have stopped the event so tell that
3083 		 * to perf_adjust_period() to avoid stopping it
3084 		 * twice.
3085 		 */
3086 		if (delta > 0)
3087 			perf_adjust_period(event, period, delta, false);
3088 
3089 		event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
3090 	next:
3091 		perf_pmu_enable(event->pmu);
3092 	}
3093 
3094 	perf_pmu_enable(ctx->pmu);
3095 	raw_spin_unlock(&ctx->lock);
3096 }
3097 
3098 /*
3099  * Round-robin a context's events:
3100  */
rotate_ctx(struct perf_event_context * ctx)3101 static void rotate_ctx(struct perf_event_context *ctx)
3102 {
3103 	/*
3104 	 * Rotate the first entry last of non-pinned groups. Rotation might be
3105 	 * disabled by the inheritance code.
3106 	 */
3107 	if (!ctx->rotate_disable)
3108 		list_rotate_left(&ctx->flexible_groups);
3109 }
3110 
perf_rotate_context(struct perf_cpu_context * cpuctx)3111 static int perf_rotate_context(struct perf_cpu_context *cpuctx)
3112 {
3113 	struct perf_event_context *ctx = NULL;
3114 	int rotate = 0;
3115 
3116 	if (cpuctx->ctx.nr_events) {
3117 		if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
3118 			rotate = 1;
3119 	}
3120 
3121 	ctx = cpuctx->task_ctx;
3122 	if (ctx && ctx->nr_events) {
3123 		if (ctx->nr_events != ctx->nr_active)
3124 			rotate = 1;
3125 	}
3126 
3127 	if (!rotate)
3128 		goto done;
3129 
3130 	perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3131 	perf_pmu_disable(cpuctx->ctx.pmu);
3132 
3133 	cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3134 	if (ctx)
3135 		ctx_sched_out(ctx, cpuctx, EVENT_FLEXIBLE);
3136 
3137 	rotate_ctx(&cpuctx->ctx);
3138 	if (ctx)
3139 		rotate_ctx(ctx);
3140 
3141 	perf_event_sched_in(cpuctx, ctx, current);
3142 
3143 	perf_pmu_enable(cpuctx->ctx.pmu);
3144 	perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3145 done:
3146 
3147 	return rotate;
3148 }
3149 
3150 #ifdef CONFIG_NO_HZ_FULL
perf_event_can_stop_tick(void)3151 bool perf_event_can_stop_tick(void)
3152 {
3153 	if (atomic_read(&nr_freq_events) ||
3154 	    __this_cpu_read(perf_throttled_count))
3155 		return false;
3156 	else
3157 		return true;
3158 }
3159 #endif
3160 
perf_event_task_tick(void)3161 void perf_event_task_tick(void)
3162 {
3163 	struct list_head *head = this_cpu_ptr(&active_ctx_list);
3164 	struct perf_event_context *ctx, *tmp;
3165 	int throttled;
3166 
3167 	WARN_ON(!irqs_disabled());
3168 
3169 	__this_cpu_inc(perf_throttled_seq);
3170 	throttled = __this_cpu_xchg(perf_throttled_count, 0);
3171 
3172 	list_for_each_entry_safe(ctx, tmp, head, active_ctx_list)
3173 		perf_adjust_freq_unthr_context(ctx, throttled);
3174 }
3175 
event_enable_on_exec(struct perf_event * event,struct perf_event_context * ctx)3176 static int event_enable_on_exec(struct perf_event *event,
3177 				struct perf_event_context *ctx)
3178 {
3179 	if (!event->attr.enable_on_exec)
3180 		return 0;
3181 
3182 	event->attr.enable_on_exec = 0;
3183 	if (event->state >= PERF_EVENT_STATE_INACTIVE)
3184 		return 0;
3185 
3186 	__perf_event_mark_enabled(event);
3187 
3188 	return 1;
3189 }
3190 
3191 /*
3192  * Enable all of a task's events that have been marked enable-on-exec.
3193  * This expects task == current.
3194  */
perf_event_enable_on_exec(int ctxn)3195 static void perf_event_enable_on_exec(int ctxn)
3196 {
3197 	struct perf_event_context *ctx, *clone_ctx = NULL;
3198 	struct perf_event *event;
3199 	unsigned long flags;
3200 	int enabled = 0;
3201 	int ret;
3202 
3203 	local_irq_save(flags);
3204 	ctx = current->perf_event_ctxp[ctxn];
3205 	if (!ctx || !ctx->nr_events)
3206 		goto out;
3207 
3208 	/*
3209 	 * We must ctxsw out cgroup events to avoid conflict
3210 	 * when invoking perf_task_event_sched_in() later on
3211 	 * in this function. Otherwise we end up trying to
3212 	 * ctxswin cgroup events which are already scheduled
3213 	 * in.
3214 	 */
3215 	perf_cgroup_sched_out(current, NULL);
3216 
3217 	raw_spin_lock(&ctx->lock);
3218 	task_ctx_sched_out(ctx);
3219 
3220 	list_for_each_entry(event, &ctx->event_list, event_entry) {
3221 		ret = event_enable_on_exec(event, ctx);
3222 		if (ret)
3223 			enabled = 1;
3224 	}
3225 
3226 	/*
3227 	 * Unclone this context if we enabled any event.
3228 	 */
3229 	if (enabled)
3230 		clone_ctx = unclone_ctx(ctx);
3231 
3232 	raw_spin_unlock(&ctx->lock);
3233 
3234 	/*
3235 	 * Also calls ctxswin for cgroup events, if any:
3236 	 */
3237 	perf_event_context_sched_in(ctx, ctx->task);
3238 out:
3239 	local_irq_restore(flags);
3240 
3241 	if (clone_ctx)
3242 		put_ctx(clone_ctx);
3243 }
3244 
perf_event_exec(void)3245 void perf_event_exec(void)
3246 {
3247 	int ctxn;
3248 
3249 	rcu_read_lock();
3250 	for_each_task_context_nr(ctxn)
3251 		perf_event_enable_on_exec(ctxn);
3252 	rcu_read_unlock();
3253 }
3254 
3255 struct perf_read_data {
3256 	struct perf_event *event;
3257 	bool group;
3258 	int ret;
3259 };
3260 
3261 /*
3262  * Cross CPU call to read the hardware event
3263  */
__perf_event_read(void * info)3264 static void __perf_event_read(void *info)
3265 {
3266 	struct perf_read_data *data = info;
3267 	struct perf_event *sub, *event = data->event;
3268 	struct perf_event_context *ctx = event->ctx;
3269 	struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3270 	struct pmu *pmu = event->pmu;
3271 
3272 	/*
3273 	 * If this is a task context, we need to check whether it is
3274 	 * the current task context of this cpu.  If not it has been
3275 	 * scheduled out before the smp call arrived.  In that case
3276 	 * event->count would have been updated to a recent sample
3277 	 * when the event was scheduled out.
3278 	 */
3279 	if (ctx->task && cpuctx->task_ctx != ctx)
3280 		return;
3281 
3282 	raw_spin_lock(&ctx->lock);
3283 	if (ctx->is_active) {
3284 		update_context_time(ctx);
3285 		update_cgrp_time_from_event(event);
3286 	}
3287 
3288 	update_event_times(event);
3289 	if (event->state != PERF_EVENT_STATE_ACTIVE)
3290 		goto unlock;
3291 
3292 	if (!data->group) {
3293 		pmu->read(event);
3294 		data->ret = 0;
3295 		goto unlock;
3296 	}
3297 
3298 	pmu->start_txn(pmu, PERF_PMU_TXN_READ);
3299 
3300 	pmu->read(event);
3301 
3302 	list_for_each_entry(sub, &event->sibling_list, group_entry) {
3303 		update_event_times(sub);
3304 		if (sub->state == PERF_EVENT_STATE_ACTIVE) {
3305 			/*
3306 			 * Use sibling's PMU rather than @event's since
3307 			 * sibling could be on different (eg: software) PMU.
3308 			 */
3309 			sub->pmu->read(sub);
3310 		}
3311 	}
3312 
3313 	data->ret = pmu->commit_txn(pmu);
3314 
3315 unlock:
3316 	raw_spin_unlock(&ctx->lock);
3317 }
3318 
perf_event_count(struct perf_event * event)3319 static inline u64 perf_event_count(struct perf_event *event)
3320 {
3321 	if (event->pmu->count)
3322 		return event->pmu->count(event);
3323 
3324 	return __perf_event_count(event);
3325 }
3326 
3327 /*
3328  * NMI-safe method to read a local event, that is an event that
3329  * is:
3330  *   - either for the current task, or for this CPU
3331  *   - does not have inherit set, for inherited task events
3332  *     will not be local and we cannot read them atomically
3333  *   - must not have a pmu::count method
3334  */
perf_event_read_local(struct perf_event * event)3335 u64 perf_event_read_local(struct perf_event *event)
3336 {
3337 	unsigned long flags;
3338 	u64 val;
3339 
3340 	/*
3341 	 * Disabling interrupts avoids all counter scheduling (context
3342 	 * switches, timer based rotation and IPIs).
3343 	 */
3344 	local_irq_save(flags);
3345 
3346 	/* If this is a per-task event, it must be for current */
3347 	WARN_ON_ONCE((event->attach_state & PERF_ATTACH_TASK) &&
3348 		     event->hw.target != current);
3349 
3350 	/* If this is a per-CPU event, it must be for this CPU */
3351 	WARN_ON_ONCE(!(event->attach_state & PERF_ATTACH_TASK) &&
3352 		     event->cpu != smp_processor_id());
3353 
3354 	/*
3355 	 * It must not be an event with inherit set, we cannot read
3356 	 * all child counters from atomic context.
3357 	 */
3358 	WARN_ON_ONCE(event->attr.inherit);
3359 
3360 	/*
3361 	 * It must not have a pmu::count method, those are not
3362 	 * NMI safe.
3363 	 */
3364 	WARN_ON_ONCE(event->pmu->count);
3365 
3366 	/*
3367 	 * If the event is currently on this CPU, its either a per-task event,
3368 	 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
3369 	 * oncpu == -1).
3370 	 */
3371 	if (event->oncpu == smp_processor_id())
3372 		event->pmu->read(event);
3373 
3374 	val = local64_read(&event->count);
3375 	local_irq_restore(flags);
3376 
3377 	return val;
3378 }
3379 
perf_event_read(struct perf_event * event,bool group)3380 static int perf_event_read(struct perf_event *event, bool group)
3381 {
3382 	int ret = 0;
3383 
3384 	/*
3385 	 * If event is enabled and currently active on a CPU, update the
3386 	 * value in the event structure:
3387 	 */
3388 	if (event->state == PERF_EVENT_STATE_ACTIVE) {
3389 		struct perf_read_data data = {
3390 			.event = event,
3391 			.group = group,
3392 			.ret = 0,
3393 		};
3394 		smp_call_function_single(event->oncpu,
3395 					 __perf_event_read, &data, 1);
3396 		ret = data.ret;
3397 	} else if (event->state == PERF_EVENT_STATE_INACTIVE) {
3398 		struct perf_event_context *ctx = event->ctx;
3399 		unsigned long flags;
3400 
3401 		raw_spin_lock_irqsave(&ctx->lock, flags);
3402 		/*
3403 		 * may read while context is not active
3404 		 * (e.g., thread is blocked), in that case
3405 		 * we cannot update context time
3406 		 */
3407 		if (ctx->is_active) {
3408 			update_context_time(ctx);
3409 			update_cgrp_time_from_event(event);
3410 		}
3411 		if (group)
3412 			update_group_times(event);
3413 		else
3414 			update_event_times(event);
3415 		raw_spin_unlock_irqrestore(&ctx->lock, flags);
3416 	}
3417 
3418 	return ret;
3419 }
3420 
3421 /*
3422  * Initialize the perf_event context in a task_struct:
3423  */
__perf_event_init_context(struct perf_event_context * ctx)3424 static void __perf_event_init_context(struct perf_event_context *ctx)
3425 {
3426 	raw_spin_lock_init(&ctx->lock);
3427 	mutex_init(&ctx->mutex);
3428 	INIT_LIST_HEAD(&ctx->active_ctx_list);
3429 	INIT_LIST_HEAD(&ctx->pinned_groups);
3430 	INIT_LIST_HEAD(&ctx->flexible_groups);
3431 	INIT_LIST_HEAD(&ctx->event_list);
3432 	atomic_set(&ctx->refcount, 1);
3433 	INIT_DELAYED_WORK(&ctx->orphans_remove, orphans_remove_work);
3434 }
3435 
3436 static struct perf_event_context *
alloc_perf_context(struct pmu * pmu,struct task_struct * task)3437 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
3438 {
3439 	struct perf_event_context *ctx;
3440 
3441 	ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
3442 	if (!ctx)
3443 		return NULL;
3444 
3445 	__perf_event_init_context(ctx);
3446 	if (task) {
3447 		ctx->task = task;
3448 		get_task_struct(task);
3449 	}
3450 	ctx->pmu = pmu;
3451 
3452 	return ctx;
3453 }
3454 
3455 static struct task_struct *
find_lively_task_by_vpid(pid_t vpid)3456 find_lively_task_by_vpid(pid_t vpid)
3457 {
3458 	struct task_struct *task;
3459 
3460 	rcu_read_lock();
3461 	if (!vpid)
3462 		task = current;
3463 	else
3464 		task = find_task_by_vpid(vpid);
3465 	if (task)
3466 		get_task_struct(task);
3467 	rcu_read_unlock();
3468 
3469 	if (!task)
3470 		return ERR_PTR(-ESRCH);
3471 
3472 	return task;
3473 }
3474 
3475 /*
3476  * Returns a matching context with refcount and pincount.
3477  */
3478 static struct perf_event_context *
find_get_context(struct pmu * pmu,struct task_struct * task,struct perf_event * event)3479 find_get_context(struct pmu *pmu, struct task_struct *task,
3480 		struct perf_event *event)
3481 {
3482 	struct perf_event_context *ctx, *clone_ctx = NULL;
3483 	struct perf_cpu_context *cpuctx;
3484 	void *task_ctx_data = NULL;
3485 	unsigned long flags;
3486 	int ctxn, err;
3487 	int cpu = event->cpu;
3488 
3489 	if (!task) {
3490 		/* Must be root to operate on a CPU event: */
3491 		if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
3492 			return ERR_PTR(-EACCES);
3493 
3494 		/*
3495 		 * We could be clever and allow to attach a event to an
3496 		 * offline CPU and activate it when the CPU comes up, but
3497 		 * that's for later.
3498 		 */
3499 		if (!cpu_online(cpu))
3500 			return ERR_PTR(-ENODEV);
3501 
3502 		cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
3503 		ctx = &cpuctx->ctx;
3504 		get_ctx(ctx);
3505 		raw_spin_lock_irqsave(&ctx->lock, flags);
3506 		++ctx->pin_count;
3507 		raw_spin_unlock_irqrestore(&ctx->lock, flags);
3508 
3509 		return ctx;
3510 	}
3511 
3512 	err = -EINVAL;
3513 	ctxn = pmu->task_ctx_nr;
3514 	if (ctxn < 0)
3515 		goto errout;
3516 
3517 	if (event->attach_state & PERF_ATTACH_TASK_DATA) {
3518 		task_ctx_data = kzalloc(pmu->task_ctx_size, GFP_KERNEL);
3519 		if (!task_ctx_data) {
3520 			err = -ENOMEM;
3521 			goto errout;
3522 		}
3523 	}
3524 
3525 retry:
3526 	ctx = perf_lock_task_context(task, ctxn, &flags);
3527 	if (ctx) {
3528 		clone_ctx = unclone_ctx(ctx);
3529 		++ctx->pin_count;
3530 
3531 		if (task_ctx_data && !ctx->task_ctx_data) {
3532 			ctx->task_ctx_data = task_ctx_data;
3533 			task_ctx_data = NULL;
3534 		}
3535 		raw_spin_unlock_irqrestore(&ctx->lock, flags);
3536 
3537 		if (clone_ctx)
3538 			put_ctx(clone_ctx);
3539 	} else {
3540 		ctx = alloc_perf_context(pmu, task);
3541 		err = -ENOMEM;
3542 		if (!ctx)
3543 			goto errout;
3544 
3545 		if (task_ctx_data) {
3546 			ctx->task_ctx_data = task_ctx_data;
3547 			task_ctx_data = NULL;
3548 		}
3549 
3550 		err = 0;
3551 		mutex_lock(&task->perf_event_mutex);
3552 		/*
3553 		 * If it has already passed perf_event_exit_task().
3554 		 * we must see PF_EXITING, it takes this mutex too.
3555 		 */
3556 		if (task->flags & PF_EXITING)
3557 			err = -ESRCH;
3558 		else if (task->perf_event_ctxp[ctxn])
3559 			err = -EAGAIN;
3560 		else {
3561 			get_ctx(ctx);
3562 			++ctx->pin_count;
3563 			rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
3564 		}
3565 		mutex_unlock(&task->perf_event_mutex);
3566 
3567 		if (unlikely(err)) {
3568 			put_ctx(ctx);
3569 
3570 			if (err == -EAGAIN)
3571 				goto retry;
3572 			goto errout;
3573 		}
3574 	}
3575 
3576 	kfree(task_ctx_data);
3577 	return ctx;
3578 
3579 errout:
3580 	kfree(task_ctx_data);
3581 	return ERR_PTR(err);
3582 }
3583 
3584 static void perf_event_free_filter(struct perf_event *event);
3585 static void perf_event_free_bpf_prog(struct perf_event *event);
3586 
free_event_rcu(struct rcu_head * head)3587 static void free_event_rcu(struct rcu_head *head)
3588 {
3589 	struct perf_event *event;
3590 
3591 	event = container_of(head, struct perf_event, rcu_head);
3592 	if (event->ns)
3593 		put_pid_ns(event->ns);
3594 	perf_event_free_filter(event);
3595 	kfree(event);
3596 }
3597 
3598 static void ring_buffer_attach(struct perf_event *event,
3599 			       struct ring_buffer *rb);
3600 
unaccount_event_cpu(struct perf_event * event,int cpu)3601 static void unaccount_event_cpu(struct perf_event *event, int cpu)
3602 {
3603 	if (event->parent)
3604 		return;
3605 
3606 	if (is_cgroup_event(event))
3607 		atomic_dec(&per_cpu(perf_cgroup_events, cpu));
3608 }
3609 
unaccount_event(struct perf_event * event)3610 static void unaccount_event(struct perf_event *event)
3611 {
3612 	if (event->parent)
3613 		return;
3614 
3615 	if (event->attach_state & PERF_ATTACH_TASK)
3616 		static_key_slow_dec_deferred(&perf_sched_events);
3617 	if (event->attr.mmap || event->attr.mmap_data)
3618 		atomic_dec(&nr_mmap_events);
3619 	if (event->attr.comm)
3620 		atomic_dec(&nr_comm_events);
3621 	if (event->attr.task)
3622 		atomic_dec(&nr_task_events);
3623 	if (event->attr.freq)
3624 		atomic_dec(&nr_freq_events);
3625 	if (event->attr.context_switch) {
3626 		static_key_slow_dec_deferred(&perf_sched_events);
3627 		atomic_dec(&nr_switch_events);
3628 	}
3629 	if (is_cgroup_event(event))
3630 		static_key_slow_dec_deferred(&perf_sched_events);
3631 	if (has_branch_stack(event))
3632 		static_key_slow_dec_deferred(&perf_sched_events);
3633 
3634 	unaccount_event_cpu(event, event->cpu);
3635 }
3636 
3637 /*
3638  * The following implement mutual exclusion of events on "exclusive" pmus
3639  * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
3640  * at a time, so we disallow creating events that might conflict, namely:
3641  *
3642  *  1) cpu-wide events in the presence of per-task events,
3643  *  2) per-task events in the presence of cpu-wide events,
3644  *  3) two matching events on the same context.
3645  *
3646  * The former two cases are handled in the allocation path (perf_event_alloc(),
3647  * __free_event()), the latter -- before the first perf_install_in_context().
3648  */
exclusive_event_init(struct perf_event * event)3649 static int exclusive_event_init(struct perf_event *event)
3650 {
3651 	struct pmu *pmu = event->pmu;
3652 
3653 	if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3654 		return 0;
3655 
3656 	/*
3657 	 * Prevent co-existence of per-task and cpu-wide events on the
3658 	 * same exclusive pmu.
3659 	 *
3660 	 * Negative pmu::exclusive_cnt means there are cpu-wide
3661 	 * events on this "exclusive" pmu, positive means there are
3662 	 * per-task events.
3663 	 *
3664 	 * Since this is called in perf_event_alloc() path, event::ctx
3665 	 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
3666 	 * to mean "per-task event", because unlike other attach states it
3667 	 * never gets cleared.
3668 	 */
3669 	if (event->attach_state & PERF_ATTACH_TASK) {
3670 		if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
3671 			return -EBUSY;
3672 	} else {
3673 		if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
3674 			return -EBUSY;
3675 	}
3676 
3677 	return 0;
3678 }
3679 
exclusive_event_destroy(struct perf_event * event)3680 static void exclusive_event_destroy(struct perf_event *event)
3681 {
3682 	struct pmu *pmu = event->pmu;
3683 
3684 	if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3685 		return;
3686 
3687 	/* see comment in exclusive_event_init() */
3688 	if (event->attach_state & PERF_ATTACH_TASK)
3689 		atomic_dec(&pmu->exclusive_cnt);
3690 	else
3691 		atomic_inc(&pmu->exclusive_cnt);
3692 }
3693 
exclusive_event_match(struct perf_event * e1,struct perf_event * e2)3694 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
3695 {
3696 	if ((e1->pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) &&
3697 	    (e1->cpu == e2->cpu ||
3698 	     e1->cpu == -1 ||
3699 	     e2->cpu == -1))
3700 		return true;
3701 	return false;
3702 }
3703 
3704 /* Called under the same ctx::mutex as perf_install_in_context() */
exclusive_event_installable(struct perf_event * event,struct perf_event_context * ctx)3705 static bool exclusive_event_installable(struct perf_event *event,
3706 					struct perf_event_context *ctx)
3707 {
3708 	struct perf_event *iter_event;
3709 	struct pmu *pmu = event->pmu;
3710 
3711 	if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3712 		return true;
3713 
3714 	list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
3715 		if (exclusive_event_match(iter_event, event))
3716 			return false;
3717 	}
3718 
3719 	return true;
3720 }
3721 
__free_event(struct perf_event * event)3722 static void __free_event(struct perf_event *event)
3723 {
3724 	if (!event->parent) {
3725 		if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
3726 			put_callchain_buffers();
3727 	}
3728 
3729 	perf_event_free_bpf_prog(event);
3730 
3731 	if (event->destroy)
3732 		event->destroy(event);
3733 
3734 	if (event->ctx)
3735 		put_ctx(event->ctx);
3736 
3737 	if (event->pmu) {
3738 		exclusive_event_destroy(event);
3739 		module_put(event->pmu->module);
3740 	}
3741 
3742 	call_rcu(&event->rcu_head, free_event_rcu);
3743 }
3744 
_free_event(struct perf_event * event)3745 static void _free_event(struct perf_event *event)
3746 {
3747 	irq_work_sync(&event->pending);
3748 
3749 	unaccount_event(event);
3750 
3751 	if (event->rb) {
3752 		/*
3753 		 * Can happen when we close an event with re-directed output.
3754 		 *
3755 		 * Since we have a 0 refcount, perf_mmap_close() will skip
3756 		 * over us; possibly making our ring_buffer_put() the last.
3757 		 */
3758 		mutex_lock(&event->mmap_mutex);
3759 		ring_buffer_attach(event, NULL);
3760 		mutex_unlock(&event->mmap_mutex);
3761 	}
3762 
3763 	if (is_cgroup_event(event))
3764 		perf_detach_cgroup(event);
3765 
3766 	__free_event(event);
3767 }
3768 
3769 /*
3770  * Used to free events which have a known refcount of 1, such as in error paths
3771  * where the event isn't exposed yet and inherited events.
3772  */
free_event(struct perf_event * event)3773 static void free_event(struct perf_event *event)
3774 {
3775 	if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
3776 				"unexpected event refcount: %ld; ptr=%p\n",
3777 				atomic_long_read(&event->refcount), event)) {
3778 		/* leak to avoid use-after-free */
3779 		return;
3780 	}
3781 
3782 	_free_event(event);
3783 }
3784 
3785 /*
3786  * Remove user event from the owner task.
3787  */
perf_remove_from_owner(struct perf_event * event)3788 static void perf_remove_from_owner(struct perf_event *event)
3789 {
3790 	struct task_struct *owner;
3791 
3792 	rcu_read_lock();
3793 	owner = ACCESS_ONCE(event->owner);
3794 	/*
3795 	 * Matches the smp_wmb() in perf_event_exit_task(). If we observe
3796 	 * !owner it means the list deletion is complete and we can indeed
3797 	 * free this event, otherwise we need to serialize on
3798 	 * owner->perf_event_mutex.
3799 	 */
3800 	smp_read_barrier_depends();
3801 	if (owner) {
3802 		/*
3803 		 * Since delayed_put_task_struct() also drops the last
3804 		 * task reference we can safely take a new reference
3805 		 * while holding the rcu_read_lock().
3806 		 */
3807 		get_task_struct(owner);
3808 	}
3809 	rcu_read_unlock();
3810 
3811 	if (owner) {
3812 		/*
3813 		 * If we're here through perf_event_exit_task() we're already
3814 		 * holding ctx->mutex which would be an inversion wrt. the
3815 		 * normal lock order.
3816 		 *
3817 		 * However we can safely take this lock because its the child
3818 		 * ctx->mutex.
3819 		 */
3820 		mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
3821 
3822 		/*
3823 		 * We have to re-check the event->owner field, if it is cleared
3824 		 * we raced with perf_event_exit_task(), acquiring the mutex
3825 		 * ensured they're done, and we can proceed with freeing the
3826 		 * event.
3827 		 */
3828 		if (event->owner)
3829 			list_del_init(&event->owner_entry);
3830 		mutex_unlock(&owner->perf_event_mutex);
3831 		put_task_struct(owner);
3832 	}
3833 }
3834 
put_event(struct perf_event * event)3835 static void put_event(struct perf_event *event)
3836 {
3837 	struct perf_event_context *ctx;
3838 
3839 	if (!atomic_long_dec_and_test(&event->refcount))
3840 		return;
3841 
3842 	if (!is_kernel_event(event))
3843 		perf_remove_from_owner(event);
3844 
3845 	/*
3846 	 * There are two ways this annotation is useful:
3847 	 *
3848 	 *  1) there is a lock recursion from perf_event_exit_task
3849 	 *     see the comment there.
3850 	 *
3851 	 *  2) there is a lock-inversion with mmap_sem through
3852 	 *     perf_read_group(), which takes faults while
3853 	 *     holding ctx->mutex, however this is called after
3854 	 *     the last filedesc died, so there is no possibility
3855 	 *     to trigger the AB-BA case.
3856 	 */
3857 	ctx = perf_event_ctx_lock_nested(event, SINGLE_DEPTH_NESTING);
3858 	WARN_ON_ONCE(ctx->parent_ctx);
3859 	perf_remove_from_context(event, true);
3860 	perf_event_ctx_unlock(event, ctx);
3861 
3862 	_free_event(event);
3863 }
3864 
perf_event_release_kernel(struct perf_event * event)3865 int perf_event_release_kernel(struct perf_event *event)
3866 {
3867 	put_event(event);
3868 	return 0;
3869 }
3870 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
3871 
3872 /*
3873  * Called when the last reference to the file is gone.
3874  */
perf_release(struct inode * inode,struct file * file)3875 static int perf_release(struct inode *inode, struct file *file)
3876 {
3877 	put_event(file->private_data);
3878 	return 0;
3879 }
3880 
3881 /*
3882  * Remove all orphanes events from the context.
3883  */
orphans_remove_work(struct work_struct * work)3884 static void orphans_remove_work(struct work_struct *work)
3885 {
3886 	struct perf_event_context *ctx;
3887 	struct perf_event *event, *tmp;
3888 
3889 	ctx = container_of(work, struct perf_event_context,
3890 			   orphans_remove.work);
3891 
3892 	mutex_lock(&ctx->mutex);
3893 	list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry) {
3894 		struct perf_event *parent_event = event->parent;
3895 
3896 		if (!is_orphaned_child(event))
3897 			continue;
3898 
3899 		perf_remove_from_context(event, true);
3900 
3901 		mutex_lock(&parent_event->child_mutex);
3902 		list_del_init(&event->child_list);
3903 		mutex_unlock(&parent_event->child_mutex);
3904 
3905 		free_event(event);
3906 		put_event(parent_event);
3907 	}
3908 
3909 	raw_spin_lock_irq(&ctx->lock);
3910 	ctx->orphans_remove_sched = false;
3911 	raw_spin_unlock_irq(&ctx->lock);
3912 	mutex_unlock(&ctx->mutex);
3913 
3914 	put_ctx(ctx);
3915 }
3916 
perf_event_read_value(struct perf_event * event,u64 * enabled,u64 * running)3917 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
3918 {
3919 	struct perf_event *child;
3920 	u64 total = 0;
3921 
3922 	*enabled = 0;
3923 	*running = 0;
3924 
3925 	mutex_lock(&event->child_mutex);
3926 
3927 	(void)perf_event_read(event, false);
3928 	total += perf_event_count(event);
3929 
3930 	*enabled += event->total_time_enabled +
3931 			atomic64_read(&event->child_total_time_enabled);
3932 	*running += event->total_time_running +
3933 			atomic64_read(&event->child_total_time_running);
3934 
3935 	list_for_each_entry(child, &event->child_list, child_list) {
3936 		(void)perf_event_read(child, false);
3937 		total += perf_event_count(child);
3938 		*enabled += child->total_time_enabled;
3939 		*running += child->total_time_running;
3940 	}
3941 	mutex_unlock(&event->child_mutex);
3942 
3943 	return total;
3944 }
3945 EXPORT_SYMBOL_GPL(perf_event_read_value);
3946 
__perf_read_group_add(struct perf_event * leader,u64 read_format,u64 * values)3947 static int __perf_read_group_add(struct perf_event *leader,
3948 					u64 read_format, u64 *values)
3949 {
3950 	struct perf_event_context *ctx = leader->ctx;
3951 	struct perf_event *sub;
3952 	unsigned long flags;
3953 	int n = 1; /* skip @nr */
3954 	int ret;
3955 
3956 	ret = perf_event_read(leader, true);
3957 	if (ret)
3958 		return ret;
3959 
3960 	/*
3961 	 * Since we co-schedule groups, {enabled,running} times of siblings
3962 	 * will be identical to those of the leader, so we only publish one
3963 	 * set.
3964 	 */
3965 	if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
3966 		values[n++] += leader->total_time_enabled +
3967 			atomic64_read(&leader->child_total_time_enabled);
3968 	}
3969 
3970 	if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
3971 		values[n++] += leader->total_time_running +
3972 			atomic64_read(&leader->child_total_time_running);
3973 	}
3974 
3975 	/*
3976 	 * Write {count,id} tuples for every sibling.
3977 	 */
3978 	values[n++] += perf_event_count(leader);
3979 	if (read_format & PERF_FORMAT_ID)
3980 		values[n++] = primary_event_id(leader);
3981 
3982 	raw_spin_lock_irqsave(&ctx->lock, flags);
3983 
3984 	list_for_each_entry(sub, &leader->sibling_list, group_entry) {
3985 		values[n++] += perf_event_count(sub);
3986 		if (read_format & PERF_FORMAT_ID)
3987 			values[n++] = primary_event_id(sub);
3988 	}
3989 
3990 	raw_spin_unlock_irqrestore(&ctx->lock, flags);
3991 	return 0;
3992 }
3993 
perf_read_group(struct perf_event * event,u64 read_format,char __user * buf)3994 static int perf_read_group(struct perf_event *event,
3995 				   u64 read_format, char __user *buf)
3996 {
3997 	struct perf_event *leader = event->group_leader, *child;
3998 	struct perf_event_context *ctx = leader->ctx;
3999 	int ret;
4000 	u64 *values;
4001 
4002 	lockdep_assert_held(&ctx->mutex);
4003 
4004 	values = kzalloc(event->read_size, GFP_KERNEL);
4005 	if (!values)
4006 		return -ENOMEM;
4007 
4008 	values[0] = 1 + leader->nr_siblings;
4009 
4010 	/*
4011 	 * By locking the child_mutex of the leader we effectively
4012 	 * lock the child list of all siblings.. XXX explain how.
4013 	 */
4014 	mutex_lock(&leader->child_mutex);
4015 
4016 	ret = __perf_read_group_add(leader, read_format, values);
4017 	if (ret)
4018 		goto unlock;
4019 
4020 	list_for_each_entry(child, &leader->child_list, child_list) {
4021 		ret = __perf_read_group_add(child, read_format, values);
4022 		if (ret)
4023 			goto unlock;
4024 	}
4025 
4026 	mutex_unlock(&leader->child_mutex);
4027 
4028 	ret = event->read_size;
4029 	if (copy_to_user(buf, values, event->read_size))
4030 		ret = -EFAULT;
4031 	goto out;
4032 
4033 unlock:
4034 	mutex_unlock(&leader->child_mutex);
4035 out:
4036 	kfree(values);
4037 	return ret;
4038 }
4039 
perf_read_one(struct perf_event * event,u64 read_format,char __user * buf)4040 static int perf_read_one(struct perf_event *event,
4041 				 u64 read_format, char __user *buf)
4042 {
4043 	u64 enabled, running;
4044 	u64 values[4];
4045 	int n = 0;
4046 
4047 	values[n++] = perf_event_read_value(event, &enabled, &running);
4048 	if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
4049 		values[n++] = enabled;
4050 	if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
4051 		values[n++] = running;
4052 	if (read_format & PERF_FORMAT_ID)
4053 		values[n++] = primary_event_id(event);
4054 
4055 	if (copy_to_user(buf, values, n * sizeof(u64)))
4056 		return -EFAULT;
4057 
4058 	return n * sizeof(u64);
4059 }
4060 
is_event_hup(struct perf_event * event)4061 static bool is_event_hup(struct perf_event *event)
4062 {
4063 	bool no_children;
4064 
4065 	if (event->state != PERF_EVENT_STATE_EXIT)
4066 		return false;
4067 
4068 	mutex_lock(&event->child_mutex);
4069 	no_children = list_empty(&event->child_list);
4070 	mutex_unlock(&event->child_mutex);
4071 	return no_children;
4072 }
4073 
4074 /*
4075  * Read the performance event - simple non blocking version for now
4076  */
4077 static ssize_t
__perf_read(struct perf_event * event,char __user * buf,size_t count)4078 __perf_read(struct perf_event *event, char __user *buf, size_t count)
4079 {
4080 	u64 read_format = event->attr.read_format;
4081 	int ret;
4082 
4083 	/*
4084 	 * Return end-of-file for a read on a event that is in
4085 	 * error state (i.e. because it was pinned but it couldn't be
4086 	 * scheduled on to the CPU at some point).
4087 	 */
4088 	if (event->state == PERF_EVENT_STATE_ERROR)
4089 		return 0;
4090 
4091 	if (count < event->read_size)
4092 		return -ENOSPC;
4093 
4094 	WARN_ON_ONCE(event->ctx->parent_ctx);
4095 	if (read_format & PERF_FORMAT_GROUP)
4096 		ret = perf_read_group(event, read_format, buf);
4097 	else
4098 		ret = perf_read_one(event, read_format, buf);
4099 
4100 	return ret;
4101 }
4102 
4103 static ssize_t
perf_read(struct file * file,char __user * buf,size_t count,loff_t * ppos)4104 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
4105 {
4106 	struct perf_event *event = file->private_data;
4107 	struct perf_event_context *ctx;
4108 	int ret;
4109 
4110 	ctx = perf_event_ctx_lock(event);
4111 	ret = __perf_read(event, buf, count);
4112 	perf_event_ctx_unlock(event, ctx);
4113 
4114 	return ret;
4115 }
4116 
perf_poll(struct file * file,poll_table * wait)4117 static unsigned int perf_poll(struct file *file, poll_table *wait)
4118 {
4119 	struct perf_event *event = file->private_data;
4120 	struct ring_buffer *rb;
4121 	unsigned int events = POLLHUP;
4122 
4123 	poll_wait(file, &event->waitq, wait);
4124 
4125 	if (is_event_hup(event))
4126 		return events;
4127 
4128 	/*
4129 	 * Pin the event->rb by taking event->mmap_mutex; otherwise
4130 	 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
4131 	 */
4132 	mutex_lock(&event->mmap_mutex);
4133 	rb = event->rb;
4134 	if (rb)
4135 		events = atomic_xchg(&rb->poll, 0);
4136 	mutex_unlock(&event->mmap_mutex);
4137 	return events;
4138 }
4139 
_perf_event_reset(struct perf_event * event)4140 static void _perf_event_reset(struct perf_event *event)
4141 {
4142 	(void)perf_event_read(event, false);
4143 	local64_set(&event->count, 0);
4144 	perf_event_update_userpage(event);
4145 }
4146 
4147 /*
4148  * Holding the top-level event's child_mutex means that any
4149  * descendant process that has inherited this event will block
4150  * in sync_child_event if it goes to exit, thus satisfying the
4151  * task existence requirements of perf_event_enable/disable.
4152  */
perf_event_for_each_child(struct perf_event * event,void (* func)(struct perf_event *))4153 static void perf_event_for_each_child(struct perf_event *event,
4154 					void (*func)(struct perf_event *))
4155 {
4156 	struct perf_event *child;
4157 
4158 	WARN_ON_ONCE(event->ctx->parent_ctx);
4159 
4160 	mutex_lock(&event->child_mutex);
4161 	func(event);
4162 	list_for_each_entry(child, &event->child_list, child_list)
4163 		func(child);
4164 	mutex_unlock(&event->child_mutex);
4165 }
4166 
perf_event_for_each(struct perf_event * event,void (* func)(struct perf_event *))4167 static void perf_event_for_each(struct perf_event *event,
4168 				  void (*func)(struct perf_event *))
4169 {
4170 	struct perf_event_context *ctx = event->ctx;
4171 	struct perf_event *sibling;
4172 
4173 	lockdep_assert_held(&ctx->mutex);
4174 
4175 	event = event->group_leader;
4176 
4177 	perf_event_for_each_child(event, func);
4178 	list_for_each_entry(sibling, &event->sibling_list, group_entry)
4179 		perf_event_for_each_child(sibling, func);
4180 }
4181 
4182 struct period_event {
4183 	struct perf_event *event;
4184 	u64 value;
4185 };
4186 
__perf_event_period(void * info)4187 static int __perf_event_period(void *info)
4188 {
4189 	struct period_event *pe = info;
4190 	struct perf_event *event = pe->event;
4191 	struct perf_event_context *ctx = event->ctx;
4192 	u64 value = pe->value;
4193 	bool active;
4194 
4195 	raw_spin_lock(&ctx->lock);
4196 	if (event->attr.freq) {
4197 		event->attr.sample_freq = value;
4198 	} else {
4199 		event->attr.sample_period = value;
4200 		event->hw.sample_period = value;
4201 	}
4202 
4203 	active = (event->state == PERF_EVENT_STATE_ACTIVE);
4204 	if (active) {
4205 		perf_pmu_disable(ctx->pmu);
4206 		event->pmu->stop(event, PERF_EF_UPDATE);
4207 	}
4208 
4209 	local64_set(&event->hw.period_left, 0);
4210 
4211 	if (active) {
4212 		event->pmu->start(event, PERF_EF_RELOAD);
4213 		perf_pmu_enable(ctx->pmu);
4214 	}
4215 	raw_spin_unlock(&ctx->lock);
4216 
4217 	return 0;
4218 }
4219 
perf_event_period(struct perf_event * event,u64 __user * arg)4220 static int perf_event_period(struct perf_event *event, u64 __user *arg)
4221 {
4222 	struct period_event pe = { .event = event, };
4223 	struct perf_event_context *ctx = event->ctx;
4224 	struct task_struct *task;
4225 	u64 value;
4226 
4227 	if (!is_sampling_event(event))
4228 		return -EINVAL;
4229 
4230 	if (copy_from_user(&value, arg, sizeof(value)))
4231 		return -EFAULT;
4232 
4233 	if (!value)
4234 		return -EINVAL;
4235 
4236 	if (event->attr.freq && value > sysctl_perf_event_sample_rate)
4237 		return -EINVAL;
4238 
4239 	task = ctx->task;
4240 	pe.value = value;
4241 
4242 	if (!task) {
4243 		cpu_function_call(event->cpu, __perf_event_period, &pe);
4244 		return 0;
4245 	}
4246 
4247 retry:
4248 	if (!task_function_call(task, __perf_event_period, &pe))
4249 		return 0;
4250 
4251 	raw_spin_lock_irq(&ctx->lock);
4252 	if (ctx->is_active) {
4253 		raw_spin_unlock_irq(&ctx->lock);
4254 		task = ctx->task;
4255 		goto retry;
4256 	}
4257 
4258 	if (event->attr.freq) {
4259 		event->attr.sample_freq = value;
4260 	} else {
4261 		event->attr.sample_period = value;
4262 		event->hw.sample_period = value;
4263 	}
4264 
4265 	local64_set(&event->hw.period_left, 0);
4266 	raw_spin_unlock_irq(&ctx->lock);
4267 
4268 	return 0;
4269 }
4270 
4271 static const struct file_operations perf_fops;
4272 
perf_fget_light(int fd,struct fd * p)4273 static inline int perf_fget_light(int fd, struct fd *p)
4274 {
4275 	struct fd f = fdget(fd);
4276 	if (!f.file)
4277 		return -EBADF;
4278 
4279 	if (f.file->f_op != &perf_fops) {
4280 		fdput(f);
4281 		return -EBADF;
4282 	}
4283 	*p = f;
4284 	return 0;
4285 }
4286 
4287 static int perf_event_set_output(struct perf_event *event,
4288 				 struct perf_event *output_event);
4289 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
4290 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd);
4291 
_perf_ioctl(struct perf_event * event,unsigned int cmd,unsigned long arg)4292 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
4293 {
4294 	void (*func)(struct perf_event *);
4295 	u32 flags = arg;
4296 
4297 	switch (cmd) {
4298 	case PERF_EVENT_IOC_ENABLE:
4299 		func = _perf_event_enable;
4300 		break;
4301 	case PERF_EVENT_IOC_DISABLE:
4302 		func = _perf_event_disable;
4303 		break;
4304 	case PERF_EVENT_IOC_RESET:
4305 		func = _perf_event_reset;
4306 		break;
4307 
4308 	case PERF_EVENT_IOC_REFRESH:
4309 		return _perf_event_refresh(event, arg);
4310 
4311 	case PERF_EVENT_IOC_PERIOD:
4312 		return perf_event_period(event, (u64 __user *)arg);
4313 
4314 	case PERF_EVENT_IOC_ID:
4315 	{
4316 		u64 id = primary_event_id(event);
4317 
4318 		if (copy_to_user((void __user *)arg, &id, sizeof(id)))
4319 			return -EFAULT;
4320 		return 0;
4321 	}
4322 
4323 	case PERF_EVENT_IOC_SET_OUTPUT:
4324 	{
4325 		int ret;
4326 		if (arg != -1) {
4327 			struct perf_event *output_event;
4328 			struct fd output;
4329 			ret = perf_fget_light(arg, &output);
4330 			if (ret)
4331 				return ret;
4332 			output_event = output.file->private_data;
4333 			ret = perf_event_set_output(event, output_event);
4334 			fdput(output);
4335 		} else {
4336 			ret = perf_event_set_output(event, NULL);
4337 		}
4338 		return ret;
4339 	}
4340 
4341 	case PERF_EVENT_IOC_SET_FILTER:
4342 		return perf_event_set_filter(event, (void __user *)arg);
4343 
4344 	case PERF_EVENT_IOC_SET_BPF:
4345 		return perf_event_set_bpf_prog(event, arg);
4346 
4347 	default:
4348 		return -ENOTTY;
4349 	}
4350 
4351 	if (flags & PERF_IOC_FLAG_GROUP)
4352 		perf_event_for_each(event, func);
4353 	else
4354 		perf_event_for_each_child(event, func);
4355 
4356 	return 0;
4357 }
4358 
perf_ioctl(struct file * file,unsigned int cmd,unsigned long arg)4359 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
4360 {
4361 	struct perf_event *event = file->private_data;
4362 	struct perf_event_context *ctx;
4363 	long ret;
4364 
4365 	ctx = perf_event_ctx_lock(event);
4366 	ret = _perf_ioctl(event, cmd, arg);
4367 	perf_event_ctx_unlock(event, ctx);
4368 
4369 	return ret;
4370 }
4371 
4372 #ifdef CONFIG_COMPAT
perf_compat_ioctl(struct file * file,unsigned int cmd,unsigned long arg)4373 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
4374 				unsigned long arg)
4375 {
4376 	switch (_IOC_NR(cmd)) {
4377 	case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
4378 	case _IOC_NR(PERF_EVENT_IOC_ID):
4379 		/* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
4380 		if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
4381 			cmd &= ~IOCSIZE_MASK;
4382 			cmd |= sizeof(void *) << IOCSIZE_SHIFT;
4383 		}
4384 		break;
4385 	}
4386 	return perf_ioctl(file, cmd, arg);
4387 }
4388 #else
4389 # define perf_compat_ioctl NULL
4390 #endif
4391 
perf_event_task_enable(void)4392 int perf_event_task_enable(void)
4393 {
4394 	struct perf_event_context *ctx;
4395 	struct perf_event *event;
4396 
4397 	mutex_lock(&current->perf_event_mutex);
4398 	list_for_each_entry(event, &current->perf_event_list, owner_entry) {
4399 		ctx = perf_event_ctx_lock(event);
4400 		perf_event_for_each_child(event, _perf_event_enable);
4401 		perf_event_ctx_unlock(event, ctx);
4402 	}
4403 	mutex_unlock(&current->perf_event_mutex);
4404 
4405 	return 0;
4406 }
4407 
perf_event_task_disable(void)4408 int perf_event_task_disable(void)
4409 {
4410 	struct perf_event_context *ctx;
4411 	struct perf_event *event;
4412 
4413 	mutex_lock(&current->perf_event_mutex);
4414 	list_for_each_entry(event, &current->perf_event_list, owner_entry) {
4415 		ctx = perf_event_ctx_lock(event);
4416 		perf_event_for_each_child(event, _perf_event_disable);
4417 		perf_event_ctx_unlock(event, ctx);
4418 	}
4419 	mutex_unlock(&current->perf_event_mutex);
4420 
4421 	return 0;
4422 }
4423 
perf_event_index(struct perf_event * event)4424 static int perf_event_index(struct perf_event *event)
4425 {
4426 	if (event->hw.state & PERF_HES_STOPPED)
4427 		return 0;
4428 
4429 	if (event->state != PERF_EVENT_STATE_ACTIVE)
4430 		return 0;
4431 
4432 	return event->pmu->event_idx(event);
4433 }
4434 
calc_timer_values(struct perf_event * event,u64 * now,u64 * enabled,u64 * running)4435 static void calc_timer_values(struct perf_event *event,
4436 				u64 *now,
4437 				u64 *enabled,
4438 				u64 *running)
4439 {
4440 	u64 ctx_time;
4441 
4442 	*now = perf_clock();
4443 	ctx_time = event->shadow_ctx_time + *now;
4444 	*enabled = ctx_time - event->tstamp_enabled;
4445 	*running = ctx_time - event->tstamp_running;
4446 }
4447 
perf_event_init_userpage(struct perf_event * event)4448 static void perf_event_init_userpage(struct perf_event *event)
4449 {
4450 	struct perf_event_mmap_page *userpg;
4451 	struct ring_buffer *rb;
4452 
4453 	rcu_read_lock();
4454 	rb = rcu_dereference(event->rb);
4455 	if (!rb)
4456 		goto unlock;
4457 
4458 	userpg = rb->user_page;
4459 
4460 	/* Allow new userspace to detect that bit 0 is deprecated */
4461 	userpg->cap_bit0_is_deprecated = 1;
4462 	userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
4463 	userpg->data_offset = PAGE_SIZE;
4464 	userpg->data_size = perf_data_size(rb);
4465 
4466 unlock:
4467 	rcu_read_unlock();
4468 }
4469 
arch_perf_update_userpage(struct perf_event * event,struct perf_event_mmap_page * userpg,u64 now)4470 void __weak arch_perf_update_userpage(
4471 	struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
4472 {
4473 }
4474 
4475 /*
4476  * Callers need to ensure there can be no nesting of this function, otherwise
4477  * the seqlock logic goes bad. We can not serialize this because the arch
4478  * code calls this from NMI context.
4479  */
perf_event_update_userpage(struct perf_event * event)4480 void perf_event_update_userpage(struct perf_event *event)
4481 {
4482 	struct perf_event_mmap_page *userpg;
4483 	struct ring_buffer *rb;
4484 	u64 enabled, running, now;
4485 
4486 	rcu_read_lock();
4487 	rb = rcu_dereference(event->rb);
4488 	if (!rb)
4489 		goto unlock;
4490 
4491 	/*
4492 	 * compute total_time_enabled, total_time_running
4493 	 * based on snapshot values taken when the event
4494 	 * was last scheduled in.
4495 	 *
4496 	 * we cannot simply called update_context_time()
4497 	 * because of locking issue as we can be called in
4498 	 * NMI context
4499 	 */
4500 	calc_timer_values(event, &now, &enabled, &running);
4501 
4502 	userpg = rb->user_page;
4503 	/*
4504 	 * Disable preemption so as to not let the corresponding user-space
4505 	 * spin too long if we get preempted.
4506 	 */
4507 	preempt_disable();
4508 	++userpg->lock;
4509 	barrier();
4510 	userpg->index = perf_event_index(event);
4511 	userpg->offset = perf_event_count(event);
4512 	if (userpg->index)
4513 		userpg->offset -= local64_read(&event->hw.prev_count);
4514 
4515 	userpg->time_enabled = enabled +
4516 			atomic64_read(&event->child_total_time_enabled);
4517 
4518 	userpg->time_running = running +
4519 			atomic64_read(&event->child_total_time_running);
4520 
4521 	arch_perf_update_userpage(event, userpg, now);
4522 
4523 	barrier();
4524 	++userpg->lock;
4525 	preempt_enable();
4526 unlock:
4527 	rcu_read_unlock();
4528 }
4529 
perf_mmap_fault(struct vm_area_struct * vma,struct vm_fault * vmf)4530 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
4531 {
4532 	struct perf_event *event = vma->vm_file->private_data;
4533 	struct ring_buffer *rb;
4534 	int ret = VM_FAULT_SIGBUS;
4535 
4536 	if (vmf->flags & FAULT_FLAG_MKWRITE) {
4537 		if (vmf->pgoff == 0)
4538 			ret = 0;
4539 		return ret;
4540 	}
4541 
4542 	rcu_read_lock();
4543 	rb = rcu_dereference(event->rb);
4544 	if (!rb)
4545 		goto unlock;
4546 
4547 	if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
4548 		goto unlock;
4549 
4550 	vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
4551 	if (!vmf->page)
4552 		goto unlock;
4553 
4554 	get_page(vmf->page);
4555 	vmf->page->mapping = vma->vm_file->f_mapping;
4556 	vmf->page->index   = vmf->pgoff;
4557 
4558 	ret = 0;
4559 unlock:
4560 	rcu_read_unlock();
4561 
4562 	return ret;
4563 }
4564 
ring_buffer_attach(struct perf_event * event,struct ring_buffer * rb)4565 static void ring_buffer_attach(struct perf_event *event,
4566 			       struct ring_buffer *rb)
4567 {
4568 	struct ring_buffer *old_rb = NULL;
4569 	unsigned long flags;
4570 
4571 	if (event->rb) {
4572 		/*
4573 		 * Should be impossible, we set this when removing
4574 		 * event->rb_entry and wait/clear when adding event->rb_entry.
4575 		 */
4576 		WARN_ON_ONCE(event->rcu_pending);
4577 
4578 		old_rb = event->rb;
4579 		spin_lock_irqsave(&old_rb->event_lock, flags);
4580 		list_del_rcu(&event->rb_entry);
4581 		spin_unlock_irqrestore(&old_rb->event_lock, flags);
4582 
4583 		event->rcu_batches = get_state_synchronize_rcu();
4584 		event->rcu_pending = 1;
4585 	}
4586 
4587 	if (rb) {
4588 		if (event->rcu_pending) {
4589 			cond_synchronize_rcu(event->rcu_batches);
4590 			event->rcu_pending = 0;
4591 		}
4592 
4593 		spin_lock_irqsave(&rb->event_lock, flags);
4594 		list_add_rcu(&event->rb_entry, &rb->event_list);
4595 		spin_unlock_irqrestore(&rb->event_lock, flags);
4596 	}
4597 
4598 	rcu_assign_pointer(event->rb, rb);
4599 
4600 	if (old_rb) {
4601 		ring_buffer_put(old_rb);
4602 		/*
4603 		 * Since we detached before setting the new rb, so that we
4604 		 * could attach the new rb, we could have missed a wakeup.
4605 		 * Provide it now.
4606 		 */
4607 		wake_up_all(&event->waitq);
4608 	}
4609 }
4610 
ring_buffer_wakeup(struct perf_event * event)4611 static void ring_buffer_wakeup(struct perf_event *event)
4612 {
4613 	struct ring_buffer *rb;
4614 
4615 	rcu_read_lock();
4616 	rb = rcu_dereference(event->rb);
4617 	if (rb) {
4618 		list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
4619 			wake_up_all(&event->waitq);
4620 	}
4621 	rcu_read_unlock();
4622 }
4623 
ring_buffer_get(struct perf_event * event)4624 struct ring_buffer *ring_buffer_get(struct perf_event *event)
4625 {
4626 	struct ring_buffer *rb;
4627 
4628 	rcu_read_lock();
4629 	rb = rcu_dereference(event->rb);
4630 	if (rb) {
4631 		if (!atomic_inc_not_zero(&rb->refcount))
4632 			rb = NULL;
4633 	}
4634 	rcu_read_unlock();
4635 
4636 	return rb;
4637 }
4638 
ring_buffer_put(struct ring_buffer * rb)4639 void ring_buffer_put(struct ring_buffer *rb)
4640 {
4641 	if (!atomic_dec_and_test(&rb->refcount))
4642 		return;
4643 
4644 	WARN_ON_ONCE(!list_empty(&rb->event_list));
4645 
4646 	call_rcu(&rb->rcu_head, rb_free_rcu);
4647 }
4648 
perf_mmap_open(struct vm_area_struct * vma)4649 static void perf_mmap_open(struct vm_area_struct *vma)
4650 {
4651 	struct perf_event *event = vma->vm_file->private_data;
4652 
4653 	atomic_inc(&event->mmap_count);
4654 	atomic_inc(&event->rb->mmap_count);
4655 
4656 	if (vma->vm_pgoff)
4657 		atomic_inc(&event->rb->aux_mmap_count);
4658 
4659 	if (event->pmu->event_mapped)
4660 		event->pmu->event_mapped(event);
4661 }
4662 
4663 /*
4664  * A buffer can be mmap()ed multiple times; either directly through the same
4665  * event, or through other events by use of perf_event_set_output().
4666  *
4667  * In order to undo the VM accounting done by perf_mmap() we need to destroy
4668  * the buffer here, where we still have a VM context. This means we need
4669  * to detach all events redirecting to us.
4670  */
perf_mmap_close(struct vm_area_struct * vma)4671 static void perf_mmap_close(struct vm_area_struct *vma)
4672 {
4673 	struct perf_event *event = vma->vm_file->private_data;
4674 	struct ring_buffer *rb = ring_buffer_get(event);
4675 	struct user_struct *mmap_user = rb->mmap_user;
4676 	int mmap_locked = rb->mmap_locked;
4677 	unsigned long size = perf_data_size(rb);
4678 	bool detach_rest = false;
4679 
4680 	if (event->pmu->event_unmapped)
4681 		event->pmu->event_unmapped(event);
4682 
4683 	/*
4684 	 * rb->aux_mmap_count will always drop before rb->mmap_count and
4685 	 * event->mmap_count, so it is ok to use event->mmap_mutex to
4686 	 * serialize with perf_mmap here.
4687 	 */
4688 	if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
4689 	    atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
4690 		atomic_long_sub(rb->aux_nr_pages, &mmap_user->locked_vm);
4691 		vma->vm_mm->pinned_vm -= rb->aux_mmap_locked;
4692 
4693 		rb_free_aux(rb);
4694 		mutex_unlock(&event->mmap_mutex);
4695 	}
4696 
4697 	if (atomic_dec_and_test(&rb->mmap_count))
4698 		detach_rest = true;
4699 
4700 	if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
4701 		goto out_put;
4702 
4703 	ring_buffer_attach(event, NULL);
4704 	mutex_unlock(&event->mmap_mutex);
4705 
4706 	/* If there's still other mmap()s of this buffer, we're done. */
4707 	if (!detach_rest)
4708 		goto out_put;
4709 
4710 	/*
4711 	 * No other mmap()s, detach from all other events that might redirect
4712 	 * into the now unreachable buffer. Somewhat complicated by the
4713 	 * fact that rb::event_lock otherwise nests inside mmap_mutex.
4714 	 */
4715 again:
4716 	rcu_read_lock();
4717 	list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
4718 		if (!atomic_long_inc_not_zero(&event->refcount)) {
4719 			/*
4720 			 * This event is en-route to free_event() which will
4721 			 * detach it and remove it from the list.
4722 			 */
4723 			continue;
4724 		}
4725 		rcu_read_unlock();
4726 
4727 		mutex_lock(&event->mmap_mutex);
4728 		/*
4729 		 * Check we didn't race with perf_event_set_output() which can
4730 		 * swizzle the rb from under us while we were waiting to
4731 		 * acquire mmap_mutex.
4732 		 *
4733 		 * If we find a different rb; ignore this event, a next
4734 		 * iteration will no longer find it on the list. We have to
4735 		 * still restart the iteration to make sure we're not now
4736 		 * iterating the wrong list.
4737 		 */
4738 		if (event->rb == rb)
4739 			ring_buffer_attach(event, NULL);
4740 
4741 		mutex_unlock(&event->mmap_mutex);
4742 		put_event(event);
4743 
4744 		/*
4745 		 * Restart the iteration; either we're on the wrong list or
4746 		 * destroyed its integrity by doing a deletion.
4747 		 */
4748 		goto again;
4749 	}
4750 	rcu_read_unlock();
4751 
4752 	/*
4753 	 * It could be there's still a few 0-ref events on the list; they'll
4754 	 * get cleaned up by free_event() -- they'll also still have their
4755 	 * ref on the rb and will free it whenever they are done with it.
4756 	 *
4757 	 * Aside from that, this buffer is 'fully' detached and unmapped,
4758 	 * undo the VM accounting.
4759 	 */
4760 
4761 	atomic_long_sub((size >> PAGE_SHIFT) + 1, &mmap_user->locked_vm);
4762 	vma->vm_mm->pinned_vm -= mmap_locked;
4763 	free_uid(mmap_user);
4764 
4765 out_put:
4766 	ring_buffer_put(rb); /* could be last */
4767 }
4768 
4769 static const struct vm_operations_struct perf_mmap_vmops = {
4770 	.open		= perf_mmap_open,
4771 	.close		= perf_mmap_close, /* non mergable */
4772 	.fault		= perf_mmap_fault,
4773 	.page_mkwrite	= perf_mmap_fault,
4774 };
4775 
perf_mmap(struct file * file,struct vm_area_struct * vma)4776 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
4777 {
4778 	struct perf_event *event = file->private_data;
4779 	unsigned long user_locked, user_lock_limit;
4780 	struct user_struct *user = current_user();
4781 	unsigned long locked, lock_limit;
4782 	struct ring_buffer *rb = NULL;
4783 	unsigned long vma_size;
4784 	unsigned long nr_pages;
4785 	long user_extra = 0, extra = 0;
4786 	int ret = 0, flags = 0;
4787 
4788 	/*
4789 	 * Don't allow mmap() of inherited per-task counters. This would
4790 	 * create a performance issue due to all children writing to the
4791 	 * same rb.
4792 	 */
4793 	if (event->cpu == -1 && event->attr.inherit)
4794 		return -EINVAL;
4795 
4796 	if (!(vma->vm_flags & VM_SHARED))
4797 		return -EINVAL;
4798 
4799 	vma_size = vma->vm_end - vma->vm_start;
4800 
4801 	if (vma->vm_pgoff == 0) {
4802 		nr_pages = (vma_size / PAGE_SIZE) - 1;
4803 	} else {
4804 		/*
4805 		 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
4806 		 * mapped, all subsequent mappings should have the same size
4807 		 * and offset. Must be above the normal perf buffer.
4808 		 */
4809 		u64 aux_offset, aux_size;
4810 
4811 		if (!event->rb)
4812 			return -EINVAL;
4813 
4814 		nr_pages = vma_size / PAGE_SIZE;
4815 
4816 		mutex_lock(&event->mmap_mutex);
4817 		ret = -EINVAL;
4818 
4819 		rb = event->rb;
4820 		if (!rb)
4821 			goto aux_unlock;
4822 
4823 		aux_offset = ACCESS_ONCE(rb->user_page->aux_offset);
4824 		aux_size = ACCESS_ONCE(rb->user_page->aux_size);
4825 
4826 		if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
4827 			goto aux_unlock;
4828 
4829 		if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
4830 			goto aux_unlock;
4831 
4832 		/* already mapped with a different offset */
4833 		if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
4834 			goto aux_unlock;
4835 
4836 		if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
4837 			goto aux_unlock;
4838 
4839 		/* already mapped with a different size */
4840 		if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
4841 			goto aux_unlock;
4842 
4843 		if (!is_power_of_2(nr_pages))
4844 			goto aux_unlock;
4845 
4846 		if (!atomic_inc_not_zero(&rb->mmap_count))
4847 			goto aux_unlock;
4848 
4849 		if (rb_has_aux(rb)) {
4850 			atomic_inc(&rb->aux_mmap_count);
4851 			ret = 0;
4852 			goto unlock;
4853 		}
4854 
4855 		atomic_set(&rb->aux_mmap_count, 1);
4856 		user_extra = nr_pages;
4857 
4858 		goto accounting;
4859 	}
4860 
4861 	/*
4862 	 * If we have rb pages ensure they're a power-of-two number, so we
4863 	 * can do bitmasks instead of modulo.
4864 	 */
4865 	if (nr_pages != 0 && !is_power_of_2(nr_pages))
4866 		return -EINVAL;
4867 
4868 	if (vma_size != PAGE_SIZE * (1 + nr_pages))
4869 		return -EINVAL;
4870 
4871 	WARN_ON_ONCE(event->ctx->parent_ctx);
4872 again:
4873 	mutex_lock(&event->mmap_mutex);
4874 	if (event->rb) {
4875 		if (event->rb->nr_pages != nr_pages) {
4876 			ret = -EINVAL;
4877 			goto unlock;
4878 		}
4879 
4880 		if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
4881 			/*
4882 			 * Raced against perf_mmap_close() through
4883 			 * perf_event_set_output(). Try again, hope for better
4884 			 * luck.
4885 			 */
4886 			mutex_unlock(&event->mmap_mutex);
4887 			goto again;
4888 		}
4889 
4890 		goto unlock;
4891 	}
4892 
4893 	user_extra = nr_pages + 1;
4894 
4895 accounting:
4896 	user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
4897 
4898 	/*
4899 	 * Increase the limit linearly with more CPUs:
4900 	 */
4901 	user_lock_limit *= num_online_cpus();
4902 
4903 	user_locked = atomic_long_read(&user->locked_vm);
4904 
4905 	/*
4906 	 * sysctl_perf_event_mlock may have changed, so that
4907 	 *     user->locked_vm > user_lock_limit
4908 	 */
4909 	if (user_locked > user_lock_limit)
4910 		user_locked = user_lock_limit;
4911 	user_locked += user_extra;
4912 
4913 	if (user_locked > user_lock_limit)
4914 		extra = user_locked - user_lock_limit;
4915 
4916 	lock_limit = rlimit(RLIMIT_MEMLOCK);
4917 	lock_limit >>= PAGE_SHIFT;
4918 	locked = vma->vm_mm->pinned_vm + extra;
4919 
4920 	if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
4921 		!capable(CAP_IPC_LOCK)) {
4922 		ret = -EPERM;
4923 		goto unlock;
4924 	}
4925 
4926 	WARN_ON(!rb && event->rb);
4927 
4928 	if (vma->vm_flags & VM_WRITE)
4929 		flags |= RING_BUFFER_WRITABLE;
4930 
4931 	if (!rb) {
4932 		rb = rb_alloc(nr_pages,
4933 			      event->attr.watermark ? event->attr.wakeup_watermark : 0,
4934 			      event->cpu, flags);
4935 
4936 		if (!rb) {
4937 			ret = -ENOMEM;
4938 			goto unlock;
4939 		}
4940 
4941 		atomic_set(&rb->mmap_count, 1);
4942 		rb->mmap_user = get_current_user();
4943 		rb->mmap_locked = extra;
4944 
4945 		ring_buffer_attach(event, rb);
4946 
4947 		perf_event_init_userpage(event);
4948 		perf_event_update_userpage(event);
4949 	} else {
4950 		ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
4951 				   event->attr.aux_watermark, flags);
4952 		if (!ret)
4953 			rb->aux_mmap_locked = extra;
4954 	}
4955 
4956 unlock:
4957 	if (!ret) {
4958 		atomic_long_add(user_extra, &user->locked_vm);
4959 		vma->vm_mm->pinned_vm += extra;
4960 
4961 		atomic_inc(&event->mmap_count);
4962 	} else if (rb) {
4963 		atomic_dec(&rb->mmap_count);
4964 	}
4965 aux_unlock:
4966 	mutex_unlock(&event->mmap_mutex);
4967 
4968 	/*
4969 	 * Since pinned accounting is per vm we cannot allow fork() to copy our
4970 	 * vma.
4971 	 */
4972 	vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
4973 	vma->vm_ops = &perf_mmap_vmops;
4974 
4975 	if (event->pmu->event_mapped)
4976 		event->pmu->event_mapped(event);
4977 
4978 	return ret;
4979 }
4980 
perf_fasync(int fd,struct file * filp,int on)4981 static int perf_fasync(int fd, struct file *filp, int on)
4982 {
4983 	struct inode *inode = file_inode(filp);
4984 	struct perf_event *event = filp->private_data;
4985 	int retval;
4986 
4987 	mutex_lock(&inode->i_mutex);
4988 	retval = fasync_helper(fd, filp, on, &event->fasync);
4989 	mutex_unlock(&inode->i_mutex);
4990 
4991 	if (retval < 0)
4992 		return retval;
4993 
4994 	return 0;
4995 }
4996 
4997 static const struct file_operations perf_fops = {
4998 	.llseek			= no_llseek,
4999 	.release		= perf_release,
5000 	.read			= perf_read,
5001 	.poll			= perf_poll,
5002 	.unlocked_ioctl		= perf_ioctl,
5003 	.compat_ioctl		= perf_compat_ioctl,
5004 	.mmap			= perf_mmap,
5005 	.fasync			= perf_fasync,
5006 };
5007 
5008 /*
5009  * Perf event wakeup
5010  *
5011  * If there's data, ensure we set the poll() state and publish everything
5012  * to user-space before waking everybody up.
5013  */
5014 
perf_event_fasync(struct perf_event * event)5015 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
5016 {
5017 	/* only the parent has fasync state */
5018 	if (event->parent)
5019 		event = event->parent;
5020 	return &event->fasync;
5021 }
5022 
perf_event_wakeup(struct perf_event * event)5023 void perf_event_wakeup(struct perf_event *event)
5024 {
5025 	ring_buffer_wakeup(event);
5026 
5027 	if (event->pending_kill) {
5028 		kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
5029 		event->pending_kill = 0;
5030 	}
5031 }
5032 
perf_pending_event(struct irq_work * entry)5033 static void perf_pending_event(struct irq_work *entry)
5034 {
5035 	struct perf_event *event = container_of(entry,
5036 			struct perf_event, pending);
5037 	int rctx;
5038 
5039 	rctx = perf_swevent_get_recursion_context();
5040 	/*
5041 	 * If we 'fail' here, that's OK, it means recursion is already disabled
5042 	 * and we won't recurse 'further'.
5043 	 */
5044 
5045 	if (event->pending_disable) {
5046 		event->pending_disable = 0;
5047 		__perf_event_disable(event);
5048 	}
5049 
5050 	if (event->pending_wakeup) {
5051 		event->pending_wakeup = 0;
5052 		perf_event_wakeup(event);
5053 	}
5054 
5055 	if (rctx >= 0)
5056 		perf_swevent_put_recursion_context(rctx);
5057 }
5058 
5059 /*
5060  * We assume there is only KVM supporting the callbacks.
5061  * Later on, we might change it to a list if there is
5062  * another virtualization implementation supporting the callbacks.
5063  */
5064 struct perf_guest_info_callbacks *perf_guest_cbs;
5065 
perf_register_guest_info_callbacks(struct perf_guest_info_callbacks * cbs)5066 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
5067 {
5068 	perf_guest_cbs = cbs;
5069 	return 0;
5070 }
5071 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
5072 
perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks * cbs)5073 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
5074 {
5075 	perf_guest_cbs = NULL;
5076 	return 0;
5077 }
5078 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
5079 
5080 static void
perf_output_sample_regs(struct perf_output_handle * handle,struct pt_regs * regs,u64 mask)5081 perf_output_sample_regs(struct perf_output_handle *handle,
5082 			struct pt_regs *regs, u64 mask)
5083 {
5084 	int bit;
5085 
5086 	for_each_set_bit(bit, (const unsigned long *) &mask,
5087 			 sizeof(mask) * BITS_PER_BYTE) {
5088 		u64 val;
5089 
5090 		val = perf_reg_value(regs, bit);
5091 		perf_output_put(handle, val);
5092 	}
5093 }
5094 
perf_sample_regs_user(struct perf_regs * regs_user,struct pt_regs * regs,struct pt_regs * regs_user_copy)5095 static void perf_sample_regs_user(struct perf_regs *regs_user,
5096 				  struct pt_regs *regs,
5097 				  struct pt_regs *regs_user_copy)
5098 {
5099 	if (user_mode(regs)) {
5100 		regs_user->abi = perf_reg_abi(current);
5101 		regs_user->regs = regs;
5102 	} else if (!(current->flags & PF_KTHREAD)) {
5103 		perf_get_regs_user(regs_user, regs, regs_user_copy);
5104 	} else {
5105 		regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
5106 		regs_user->regs = NULL;
5107 	}
5108 }
5109 
perf_sample_regs_intr(struct perf_regs * regs_intr,struct pt_regs * regs)5110 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
5111 				  struct pt_regs *regs)
5112 {
5113 	regs_intr->regs = regs;
5114 	regs_intr->abi  = perf_reg_abi(current);
5115 }
5116 
5117 
5118 /*
5119  * Get remaining task size from user stack pointer.
5120  *
5121  * It'd be better to take stack vma map and limit this more
5122  * precisly, but there's no way to get it safely under interrupt,
5123  * so using TASK_SIZE as limit.
5124  */
perf_ustack_task_size(struct pt_regs * regs)5125 static u64 perf_ustack_task_size(struct pt_regs *regs)
5126 {
5127 	unsigned long addr = perf_user_stack_pointer(regs);
5128 
5129 	if (!addr || addr >= TASK_SIZE)
5130 		return 0;
5131 
5132 	return TASK_SIZE - addr;
5133 }
5134 
5135 static u16
perf_sample_ustack_size(u16 stack_size,u16 header_size,struct pt_regs * regs)5136 perf_sample_ustack_size(u16 stack_size, u16 header_size,
5137 			struct pt_regs *regs)
5138 {
5139 	u64 task_size;
5140 
5141 	/* No regs, no stack pointer, no dump. */
5142 	if (!regs)
5143 		return 0;
5144 
5145 	/*
5146 	 * Check if we fit in with the requested stack size into the:
5147 	 * - TASK_SIZE
5148 	 *   If we don't, we limit the size to the TASK_SIZE.
5149 	 *
5150 	 * - remaining sample size
5151 	 *   If we don't, we customize the stack size to
5152 	 *   fit in to the remaining sample size.
5153 	 */
5154 
5155 	task_size  = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
5156 	stack_size = min(stack_size, (u16) task_size);
5157 
5158 	/* Current header size plus static size and dynamic size. */
5159 	header_size += 2 * sizeof(u64);
5160 
5161 	/* Do we fit in with the current stack dump size? */
5162 	if ((u16) (header_size + stack_size) < header_size) {
5163 		/*
5164 		 * If we overflow the maximum size for the sample,
5165 		 * we customize the stack dump size to fit in.
5166 		 */
5167 		stack_size = USHRT_MAX - header_size - sizeof(u64);
5168 		stack_size = round_up(stack_size, sizeof(u64));
5169 	}
5170 
5171 	return stack_size;
5172 }
5173 
5174 static void
perf_output_sample_ustack(struct perf_output_handle * handle,u64 dump_size,struct pt_regs * regs)5175 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
5176 			  struct pt_regs *regs)
5177 {
5178 	/* Case of a kernel thread, nothing to dump */
5179 	if (!regs) {
5180 		u64 size = 0;
5181 		perf_output_put(handle, size);
5182 	} else {
5183 		unsigned long sp;
5184 		unsigned int rem;
5185 		u64 dyn_size;
5186 
5187 		/*
5188 		 * We dump:
5189 		 * static size
5190 		 *   - the size requested by user or the best one we can fit
5191 		 *     in to the sample max size
5192 		 * data
5193 		 *   - user stack dump data
5194 		 * dynamic size
5195 		 *   - the actual dumped size
5196 		 */
5197 
5198 		/* Static size. */
5199 		perf_output_put(handle, dump_size);
5200 
5201 		/* Data. */
5202 		sp = perf_user_stack_pointer(regs);
5203 		rem = __output_copy_user(handle, (void *) sp, dump_size);
5204 		dyn_size = dump_size - rem;
5205 
5206 		perf_output_skip(handle, rem);
5207 
5208 		/* Dynamic size. */
5209 		perf_output_put(handle, dyn_size);
5210 	}
5211 }
5212 
__perf_event_header__init_id(struct perf_event_header * header,struct perf_sample_data * data,struct perf_event * event)5213 static void __perf_event_header__init_id(struct perf_event_header *header,
5214 					 struct perf_sample_data *data,
5215 					 struct perf_event *event)
5216 {
5217 	u64 sample_type = event->attr.sample_type;
5218 
5219 	data->type = sample_type;
5220 	header->size += event->id_header_size;
5221 
5222 	if (sample_type & PERF_SAMPLE_TID) {
5223 		/* namespace issues */
5224 		data->tid_entry.pid = perf_event_pid(event, current);
5225 		data->tid_entry.tid = perf_event_tid(event, current);
5226 	}
5227 
5228 	if (sample_type & PERF_SAMPLE_TIME)
5229 		data->time = perf_event_clock(event);
5230 
5231 	if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
5232 		data->id = primary_event_id(event);
5233 
5234 	if (sample_type & PERF_SAMPLE_STREAM_ID)
5235 		data->stream_id = event->id;
5236 
5237 	if (sample_type & PERF_SAMPLE_CPU) {
5238 		data->cpu_entry.cpu	 = raw_smp_processor_id();
5239 		data->cpu_entry.reserved = 0;
5240 	}
5241 }
5242 
perf_event_header__init_id(struct perf_event_header * header,struct perf_sample_data * data,struct perf_event * event)5243 void perf_event_header__init_id(struct perf_event_header *header,
5244 				struct perf_sample_data *data,
5245 				struct perf_event *event)
5246 {
5247 	if (event->attr.sample_id_all)
5248 		__perf_event_header__init_id(header, data, event);
5249 }
5250 
__perf_event__output_id_sample(struct perf_output_handle * handle,struct perf_sample_data * data)5251 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
5252 					   struct perf_sample_data *data)
5253 {
5254 	u64 sample_type = data->type;
5255 
5256 	if (sample_type & PERF_SAMPLE_TID)
5257 		perf_output_put(handle, data->tid_entry);
5258 
5259 	if (sample_type & PERF_SAMPLE_TIME)
5260 		perf_output_put(handle, data->time);
5261 
5262 	if (sample_type & PERF_SAMPLE_ID)
5263 		perf_output_put(handle, data->id);
5264 
5265 	if (sample_type & PERF_SAMPLE_STREAM_ID)
5266 		perf_output_put(handle, data->stream_id);
5267 
5268 	if (sample_type & PERF_SAMPLE_CPU)
5269 		perf_output_put(handle, data->cpu_entry);
5270 
5271 	if (sample_type & PERF_SAMPLE_IDENTIFIER)
5272 		perf_output_put(handle, data->id);
5273 }
5274 
perf_event__output_id_sample(struct perf_event * event,struct perf_output_handle * handle,struct perf_sample_data * sample)5275 void perf_event__output_id_sample(struct perf_event *event,
5276 				  struct perf_output_handle *handle,
5277 				  struct perf_sample_data *sample)
5278 {
5279 	if (event->attr.sample_id_all)
5280 		__perf_event__output_id_sample(handle, sample);
5281 }
5282 
perf_output_read_one(struct perf_output_handle * handle,struct perf_event * event,u64 enabled,u64 running)5283 static void perf_output_read_one(struct perf_output_handle *handle,
5284 				 struct perf_event *event,
5285 				 u64 enabled, u64 running)
5286 {
5287 	u64 read_format = event->attr.read_format;
5288 	u64 values[4];
5289 	int n = 0;
5290 
5291 	values[n++] = perf_event_count(event);
5292 	if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5293 		values[n++] = enabled +
5294 			atomic64_read(&event->child_total_time_enabled);
5295 	}
5296 	if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5297 		values[n++] = running +
5298 			atomic64_read(&event->child_total_time_running);
5299 	}
5300 	if (read_format & PERF_FORMAT_ID)
5301 		values[n++] = primary_event_id(event);
5302 
5303 	__output_copy(handle, values, n * sizeof(u64));
5304 }
5305 
perf_output_read_group(struct perf_output_handle * handle,struct perf_event * event,u64 enabled,u64 running)5306 static void perf_output_read_group(struct perf_output_handle *handle,
5307 			    struct perf_event *event,
5308 			    u64 enabled, u64 running)
5309 {
5310 	struct perf_event *leader = event->group_leader, *sub;
5311 	u64 read_format = event->attr.read_format;
5312 	u64 values[5];
5313 	int n = 0;
5314 
5315 	values[n++] = 1 + leader->nr_siblings;
5316 
5317 	if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
5318 		values[n++] = enabled;
5319 
5320 	if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
5321 		values[n++] = running;
5322 
5323 	if ((leader != event) &&
5324 	    (leader->state == PERF_EVENT_STATE_ACTIVE))
5325 		leader->pmu->read(leader);
5326 
5327 	values[n++] = perf_event_count(leader);
5328 	if (read_format & PERF_FORMAT_ID)
5329 		values[n++] = primary_event_id(leader);
5330 
5331 	__output_copy(handle, values, n * sizeof(u64));
5332 
5333 	list_for_each_entry(sub, &leader->sibling_list, group_entry) {
5334 		n = 0;
5335 
5336 		if ((sub != event) &&
5337 		    (sub->state == PERF_EVENT_STATE_ACTIVE))
5338 			sub->pmu->read(sub);
5339 
5340 		values[n++] = perf_event_count(sub);
5341 		if (read_format & PERF_FORMAT_ID)
5342 			values[n++] = primary_event_id(sub);
5343 
5344 		__output_copy(handle, values, n * sizeof(u64));
5345 	}
5346 }
5347 
5348 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
5349 				 PERF_FORMAT_TOTAL_TIME_RUNNING)
5350 
5351 /*
5352  * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
5353  *
5354  * The problem is that its both hard and excessively expensive to iterate the
5355  * child list, not to mention that its impossible to IPI the children running
5356  * on another CPU, from interrupt/NMI context.
5357  */
perf_output_read(struct perf_output_handle * handle,struct perf_event * event)5358 static void perf_output_read(struct perf_output_handle *handle,
5359 			     struct perf_event *event)
5360 {
5361 	u64 enabled = 0, running = 0, now;
5362 	u64 read_format = event->attr.read_format;
5363 
5364 	/*
5365 	 * compute total_time_enabled, total_time_running
5366 	 * based on snapshot values taken when the event
5367 	 * was last scheduled in.
5368 	 *
5369 	 * we cannot simply called update_context_time()
5370 	 * because of locking issue as we are called in
5371 	 * NMI context
5372 	 */
5373 	if (read_format & PERF_FORMAT_TOTAL_TIMES)
5374 		calc_timer_values(event, &now, &enabled, &running);
5375 
5376 	if (event->attr.read_format & PERF_FORMAT_GROUP)
5377 		perf_output_read_group(handle, event, enabled, running);
5378 	else
5379 		perf_output_read_one(handle, event, enabled, running);
5380 }
5381 
perf_output_sample(struct perf_output_handle * handle,struct perf_event_header * header,struct perf_sample_data * data,struct perf_event * event)5382 void perf_output_sample(struct perf_output_handle *handle,
5383 			struct perf_event_header *header,
5384 			struct perf_sample_data *data,
5385 			struct perf_event *event)
5386 {
5387 	u64 sample_type = data->type;
5388 
5389 	perf_output_put(handle, *header);
5390 
5391 	if (sample_type & PERF_SAMPLE_IDENTIFIER)
5392 		perf_output_put(handle, data->id);
5393 
5394 	if (sample_type & PERF_SAMPLE_IP)
5395 		perf_output_put(handle, data->ip);
5396 
5397 	if (sample_type & PERF_SAMPLE_TID)
5398 		perf_output_put(handle, data->tid_entry);
5399 
5400 	if (sample_type & PERF_SAMPLE_TIME)
5401 		perf_output_put(handle, data->time);
5402 
5403 	if (sample_type & PERF_SAMPLE_ADDR)
5404 		perf_output_put(handle, data->addr);
5405 
5406 	if (sample_type & PERF_SAMPLE_ID)
5407 		perf_output_put(handle, data->id);
5408 
5409 	if (sample_type & PERF_SAMPLE_STREAM_ID)
5410 		perf_output_put(handle, data->stream_id);
5411 
5412 	if (sample_type & PERF_SAMPLE_CPU)
5413 		perf_output_put(handle, data->cpu_entry);
5414 
5415 	if (sample_type & PERF_SAMPLE_PERIOD)
5416 		perf_output_put(handle, data->period);
5417 
5418 	if (sample_type & PERF_SAMPLE_READ)
5419 		perf_output_read(handle, event);
5420 
5421 	if (sample_type & PERF_SAMPLE_CALLCHAIN) {
5422 		if (data->callchain) {
5423 			int size = 1;
5424 
5425 			if (data->callchain)
5426 				size += data->callchain->nr;
5427 
5428 			size *= sizeof(u64);
5429 
5430 			__output_copy(handle, data->callchain, size);
5431 		} else {
5432 			u64 nr = 0;
5433 			perf_output_put(handle, nr);
5434 		}
5435 	}
5436 
5437 	if (sample_type & PERF_SAMPLE_RAW) {
5438 		if (data->raw) {
5439 			u32 raw_size = data->raw->size;
5440 			u32 real_size = round_up(raw_size + sizeof(u32),
5441 						 sizeof(u64)) - sizeof(u32);
5442 			u64 zero = 0;
5443 
5444 			perf_output_put(handle, real_size);
5445 			__output_copy(handle, data->raw->data, raw_size);
5446 			if (real_size - raw_size)
5447 				__output_copy(handle, &zero, real_size - raw_size);
5448 		} else {
5449 			struct {
5450 				u32	size;
5451 				u32	data;
5452 			} raw = {
5453 				.size = sizeof(u32),
5454 				.data = 0,
5455 			};
5456 			perf_output_put(handle, raw);
5457 		}
5458 	}
5459 
5460 	if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
5461 		if (data->br_stack) {
5462 			size_t size;
5463 
5464 			size = data->br_stack->nr
5465 			     * sizeof(struct perf_branch_entry);
5466 
5467 			perf_output_put(handle, data->br_stack->nr);
5468 			perf_output_copy(handle, data->br_stack->entries, size);
5469 		} else {
5470 			/*
5471 			 * we always store at least the value of nr
5472 			 */
5473 			u64 nr = 0;
5474 			perf_output_put(handle, nr);
5475 		}
5476 	}
5477 
5478 	if (sample_type & PERF_SAMPLE_REGS_USER) {
5479 		u64 abi = data->regs_user.abi;
5480 
5481 		/*
5482 		 * If there are no regs to dump, notice it through
5483 		 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
5484 		 */
5485 		perf_output_put(handle, abi);
5486 
5487 		if (abi) {
5488 			u64 mask = event->attr.sample_regs_user;
5489 			perf_output_sample_regs(handle,
5490 						data->regs_user.regs,
5491 						mask);
5492 		}
5493 	}
5494 
5495 	if (sample_type & PERF_SAMPLE_STACK_USER) {
5496 		perf_output_sample_ustack(handle,
5497 					  data->stack_user_size,
5498 					  data->regs_user.regs);
5499 	}
5500 
5501 	if (sample_type & PERF_SAMPLE_WEIGHT)
5502 		perf_output_put(handle, data->weight);
5503 
5504 	if (sample_type & PERF_SAMPLE_DATA_SRC)
5505 		perf_output_put(handle, data->data_src.val);
5506 
5507 	if (sample_type & PERF_SAMPLE_TRANSACTION)
5508 		perf_output_put(handle, data->txn);
5509 
5510 	if (sample_type & PERF_SAMPLE_REGS_INTR) {
5511 		u64 abi = data->regs_intr.abi;
5512 		/*
5513 		 * If there are no regs to dump, notice it through
5514 		 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
5515 		 */
5516 		perf_output_put(handle, abi);
5517 
5518 		if (abi) {
5519 			u64 mask = event->attr.sample_regs_intr;
5520 
5521 			perf_output_sample_regs(handle,
5522 						data->regs_intr.regs,
5523 						mask);
5524 		}
5525 	}
5526 
5527 	if (!event->attr.watermark) {
5528 		int wakeup_events = event->attr.wakeup_events;
5529 
5530 		if (wakeup_events) {
5531 			struct ring_buffer *rb = handle->rb;
5532 			int events = local_inc_return(&rb->events);
5533 
5534 			if (events >= wakeup_events) {
5535 				local_sub(wakeup_events, &rb->events);
5536 				local_inc(&rb->wakeup);
5537 			}
5538 		}
5539 	}
5540 }
5541 
perf_prepare_sample(struct perf_event_header * header,struct perf_sample_data * data,struct perf_event * event,struct pt_regs * regs)5542 void perf_prepare_sample(struct perf_event_header *header,
5543 			 struct perf_sample_data *data,
5544 			 struct perf_event *event,
5545 			 struct pt_regs *regs)
5546 {
5547 	u64 sample_type = event->attr.sample_type;
5548 
5549 	header->type = PERF_RECORD_SAMPLE;
5550 	header->size = sizeof(*header) + event->header_size;
5551 
5552 	header->misc = 0;
5553 	header->misc |= perf_misc_flags(regs);
5554 
5555 	__perf_event_header__init_id(header, data, event);
5556 
5557 	if (sample_type & PERF_SAMPLE_IP)
5558 		data->ip = perf_instruction_pointer(regs);
5559 
5560 	if (sample_type & PERF_SAMPLE_CALLCHAIN) {
5561 		int size = 1;
5562 
5563 		data->callchain = perf_callchain(event, regs);
5564 
5565 		if (data->callchain)
5566 			size += data->callchain->nr;
5567 
5568 		header->size += size * sizeof(u64);
5569 	}
5570 
5571 	if (sample_type & PERF_SAMPLE_RAW) {
5572 		int size = sizeof(u32);
5573 
5574 		if (data->raw)
5575 			size += data->raw->size;
5576 		else
5577 			size += sizeof(u32);
5578 
5579 		header->size += round_up(size, sizeof(u64));
5580 	}
5581 
5582 	if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
5583 		int size = sizeof(u64); /* nr */
5584 		if (data->br_stack) {
5585 			size += data->br_stack->nr
5586 			      * sizeof(struct perf_branch_entry);
5587 		}
5588 		header->size += size;
5589 	}
5590 
5591 	if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
5592 		perf_sample_regs_user(&data->regs_user, regs,
5593 				      &data->regs_user_copy);
5594 
5595 	if (sample_type & PERF_SAMPLE_REGS_USER) {
5596 		/* regs dump ABI info */
5597 		int size = sizeof(u64);
5598 
5599 		if (data->regs_user.regs) {
5600 			u64 mask = event->attr.sample_regs_user;
5601 			size += hweight64(mask) * sizeof(u64);
5602 		}
5603 
5604 		header->size += size;
5605 	}
5606 
5607 	if (sample_type & PERF_SAMPLE_STACK_USER) {
5608 		/*
5609 		 * Either we need PERF_SAMPLE_STACK_USER bit to be allways
5610 		 * processed as the last one or have additional check added
5611 		 * in case new sample type is added, because we could eat
5612 		 * up the rest of the sample size.
5613 		 */
5614 		u16 stack_size = event->attr.sample_stack_user;
5615 		u16 size = sizeof(u64);
5616 
5617 		stack_size = perf_sample_ustack_size(stack_size, header->size,
5618 						     data->regs_user.regs);
5619 
5620 		/*
5621 		 * If there is something to dump, add space for the dump
5622 		 * itself and for the field that tells the dynamic size,
5623 		 * which is how many have been actually dumped.
5624 		 */
5625 		if (stack_size)
5626 			size += sizeof(u64) + stack_size;
5627 
5628 		data->stack_user_size = stack_size;
5629 		header->size += size;
5630 	}
5631 
5632 	if (sample_type & PERF_SAMPLE_REGS_INTR) {
5633 		/* regs dump ABI info */
5634 		int size = sizeof(u64);
5635 
5636 		perf_sample_regs_intr(&data->regs_intr, regs);
5637 
5638 		if (data->regs_intr.regs) {
5639 			u64 mask = event->attr.sample_regs_intr;
5640 
5641 			size += hweight64(mask) * sizeof(u64);
5642 		}
5643 
5644 		header->size += size;
5645 	}
5646 }
5647 
perf_event_output(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)5648 void perf_event_output(struct perf_event *event,
5649 			struct perf_sample_data *data,
5650 			struct pt_regs *regs)
5651 {
5652 	struct perf_output_handle handle;
5653 	struct perf_event_header header;
5654 
5655 	/* protect the callchain buffers */
5656 	rcu_read_lock();
5657 
5658 	perf_prepare_sample(&header, data, event, regs);
5659 
5660 	if (perf_output_begin(&handle, event, header.size))
5661 		goto exit;
5662 
5663 	perf_output_sample(&handle, &header, data, event);
5664 
5665 	perf_output_end(&handle);
5666 
5667 exit:
5668 	rcu_read_unlock();
5669 }
5670 
5671 /*
5672  * read event_id
5673  */
5674 
5675 struct perf_read_event {
5676 	struct perf_event_header	header;
5677 
5678 	u32				pid;
5679 	u32				tid;
5680 };
5681 
5682 static void
perf_event_read_event(struct perf_event * event,struct task_struct * task)5683 perf_event_read_event(struct perf_event *event,
5684 			struct task_struct *task)
5685 {
5686 	struct perf_output_handle handle;
5687 	struct perf_sample_data sample;
5688 	struct perf_read_event read_event = {
5689 		.header = {
5690 			.type = PERF_RECORD_READ,
5691 			.misc = 0,
5692 			.size = sizeof(read_event) + event->read_size,
5693 		},
5694 		.pid = perf_event_pid(event, task),
5695 		.tid = perf_event_tid(event, task),
5696 	};
5697 	int ret;
5698 
5699 	perf_event_header__init_id(&read_event.header, &sample, event);
5700 	ret = perf_output_begin(&handle, event, read_event.header.size);
5701 	if (ret)
5702 		return;
5703 
5704 	perf_output_put(&handle, read_event);
5705 	perf_output_read(&handle, event);
5706 	perf_event__output_id_sample(event, &handle, &sample);
5707 
5708 	perf_output_end(&handle);
5709 }
5710 
5711 typedef void (perf_event_aux_output_cb)(struct perf_event *event, void *data);
5712 
5713 static void
perf_event_aux_ctx(struct perf_event_context * ctx,perf_event_aux_output_cb output,void * data)5714 perf_event_aux_ctx(struct perf_event_context *ctx,
5715 		   perf_event_aux_output_cb output,
5716 		   void *data)
5717 {
5718 	struct perf_event *event;
5719 
5720 	list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
5721 		if (event->state < PERF_EVENT_STATE_INACTIVE)
5722 			continue;
5723 		if (!event_filter_match(event))
5724 			continue;
5725 		output(event, data);
5726 	}
5727 }
5728 
5729 static void
perf_event_aux_task_ctx(perf_event_aux_output_cb output,void * data,struct perf_event_context * task_ctx)5730 perf_event_aux_task_ctx(perf_event_aux_output_cb output, void *data,
5731 			struct perf_event_context *task_ctx)
5732 {
5733 	rcu_read_lock();
5734 	preempt_disable();
5735 	perf_event_aux_ctx(task_ctx, output, data);
5736 	preempt_enable();
5737 	rcu_read_unlock();
5738 }
5739 
5740 static void
perf_event_aux(perf_event_aux_output_cb output,void * data,struct perf_event_context * task_ctx)5741 perf_event_aux(perf_event_aux_output_cb output, void *data,
5742 	       struct perf_event_context *task_ctx)
5743 {
5744 	struct perf_cpu_context *cpuctx;
5745 	struct perf_event_context *ctx;
5746 	struct pmu *pmu;
5747 	int ctxn;
5748 
5749 	/*
5750 	 * If we have task_ctx != NULL we only notify
5751 	 * the task context itself. The task_ctx is set
5752 	 * only for EXIT events before releasing task
5753 	 * context.
5754 	 */
5755 	if (task_ctx) {
5756 		perf_event_aux_task_ctx(output, data, task_ctx);
5757 		return;
5758 	}
5759 
5760 	rcu_read_lock();
5761 	list_for_each_entry_rcu(pmu, &pmus, entry) {
5762 		cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
5763 		if (cpuctx->unique_pmu != pmu)
5764 			goto next;
5765 		perf_event_aux_ctx(&cpuctx->ctx, output, data);
5766 		ctxn = pmu->task_ctx_nr;
5767 		if (ctxn < 0)
5768 			goto next;
5769 		ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
5770 		if (ctx)
5771 			perf_event_aux_ctx(ctx, output, data);
5772 next:
5773 		put_cpu_ptr(pmu->pmu_cpu_context);
5774 	}
5775 	rcu_read_unlock();
5776 }
5777 
5778 /*
5779  * task tracking -- fork/exit
5780  *
5781  * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
5782  */
5783 
5784 struct perf_task_event {
5785 	struct task_struct		*task;
5786 	struct perf_event_context	*task_ctx;
5787 
5788 	struct {
5789 		struct perf_event_header	header;
5790 
5791 		u32				pid;
5792 		u32				ppid;
5793 		u32				tid;
5794 		u32				ptid;
5795 		u64				time;
5796 	} event_id;
5797 };
5798 
perf_event_task_match(struct perf_event * event)5799 static int perf_event_task_match(struct perf_event *event)
5800 {
5801 	return event->attr.comm  || event->attr.mmap ||
5802 	       event->attr.mmap2 || event->attr.mmap_data ||
5803 	       event->attr.task;
5804 }
5805 
perf_event_task_output(struct perf_event * event,void * data)5806 static void perf_event_task_output(struct perf_event *event,
5807 				   void *data)
5808 {
5809 	struct perf_task_event *task_event = data;
5810 	struct perf_output_handle handle;
5811 	struct perf_sample_data	sample;
5812 	struct task_struct *task = task_event->task;
5813 	int ret, size = task_event->event_id.header.size;
5814 
5815 	if (!perf_event_task_match(event))
5816 		return;
5817 
5818 	perf_event_header__init_id(&task_event->event_id.header, &sample, event);
5819 
5820 	ret = perf_output_begin(&handle, event,
5821 				task_event->event_id.header.size);
5822 	if (ret)
5823 		goto out;
5824 
5825 	task_event->event_id.pid = perf_event_pid(event, task);
5826 	task_event->event_id.tid = perf_event_tid(event, task);
5827 
5828 	if (task_event->event_id.header.type == PERF_RECORD_EXIT) {
5829 		task_event->event_id.ppid = perf_event_pid(event,
5830 							task->real_parent);
5831 		task_event->event_id.ptid = perf_event_pid(event,
5832 							task->real_parent);
5833 	} else {  /* PERF_RECORD_FORK */
5834 		task_event->event_id.ppid = perf_event_pid(event, current);
5835 		task_event->event_id.ptid = perf_event_tid(event, current);
5836 	}
5837 
5838 	task_event->event_id.time = perf_event_clock(event);
5839 
5840 	perf_output_put(&handle, task_event->event_id);
5841 
5842 	perf_event__output_id_sample(event, &handle, &sample);
5843 
5844 	perf_output_end(&handle);
5845 out:
5846 	task_event->event_id.header.size = size;
5847 }
5848 
perf_event_task(struct task_struct * task,struct perf_event_context * task_ctx,int new)5849 static void perf_event_task(struct task_struct *task,
5850 			      struct perf_event_context *task_ctx,
5851 			      int new)
5852 {
5853 	struct perf_task_event task_event;
5854 
5855 	if (!atomic_read(&nr_comm_events) &&
5856 	    !atomic_read(&nr_mmap_events) &&
5857 	    !atomic_read(&nr_task_events))
5858 		return;
5859 
5860 	task_event = (struct perf_task_event){
5861 		.task	  = task,
5862 		.task_ctx = task_ctx,
5863 		.event_id    = {
5864 			.header = {
5865 				.type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
5866 				.misc = 0,
5867 				.size = sizeof(task_event.event_id),
5868 			},
5869 			/* .pid  */
5870 			/* .ppid */
5871 			/* .tid  */
5872 			/* .ptid */
5873 			/* .time */
5874 		},
5875 	};
5876 
5877 	perf_event_aux(perf_event_task_output,
5878 		       &task_event,
5879 		       task_ctx);
5880 }
5881 
perf_event_fork(struct task_struct * task)5882 void perf_event_fork(struct task_struct *task)
5883 {
5884 	perf_event_task(task, NULL, 1);
5885 }
5886 
5887 /*
5888  * comm tracking
5889  */
5890 
5891 struct perf_comm_event {
5892 	struct task_struct	*task;
5893 	char			*comm;
5894 	int			comm_size;
5895 
5896 	struct {
5897 		struct perf_event_header	header;
5898 
5899 		u32				pid;
5900 		u32				tid;
5901 	} event_id;
5902 };
5903 
perf_event_comm_match(struct perf_event * event)5904 static int perf_event_comm_match(struct perf_event *event)
5905 {
5906 	return event->attr.comm;
5907 }
5908 
perf_event_comm_output(struct perf_event * event,void * data)5909 static void perf_event_comm_output(struct perf_event *event,
5910 				   void *data)
5911 {
5912 	struct perf_comm_event *comm_event = data;
5913 	struct perf_output_handle handle;
5914 	struct perf_sample_data sample;
5915 	int size = comm_event->event_id.header.size;
5916 	int ret;
5917 
5918 	if (!perf_event_comm_match(event))
5919 		return;
5920 
5921 	perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
5922 	ret = perf_output_begin(&handle, event,
5923 				comm_event->event_id.header.size);
5924 
5925 	if (ret)
5926 		goto out;
5927 
5928 	comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
5929 	comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
5930 
5931 	perf_output_put(&handle, comm_event->event_id);
5932 	__output_copy(&handle, comm_event->comm,
5933 				   comm_event->comm_size);
5934 
5935 	perf_event__output_id_sample(event, &handle, &sample);
5936 
5937 	perf_output_end(&handle);
5938 out:
5939 	comm_event->event_id.header.size = size;
5940 }
5941 
perf_event_comm_event(struct perf_comm_event * comm_event)5942 static void perf_event_comm_event(struct perf_comm_event *comm_event)
5943 {
5944 	char comm[TASK_COMM_LEN];
5945 	unsigned int size;
5946 
5947 	memset(comm, 0, sizeof(comm));
5948 	strlcpy(comm, comm_event->task->comm, sizeof(comm));
5949 	size = ALIGN(strlen(comm)+1, sizeof(u64));
5950 
5951 	comm_event->comm = comm;
5952 	comm_event->comm_size = size;
5953 
5954 	comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
5955 
5956 	perf_event_aux(perf_event_comm_output,
5957 		       comm_event,
5958 		       NULL);
5959 }
5960 
perf_event_comm(struct task_struct * task,bool exec)5961 void perf_event_comm(struct task_struct *task, bool exec)
5962 {
5963 	struct perf_comm_event comm_event;
5964 
5965 	if (!atomic_read(&nr_comm_events))
5966 		return;
5967 
5968 	comm_event = (struct perf_comm_event){
5969 		.task	= task,
5970 		/* .comm      */
5971 		/* .comm_size */
5972 		.event_id  = {
5973 			.header = {
5974 				.type = PERF_RECORD_COMM,
5975 				.misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
5976 				/* .size */
5977 			},
5978 			/* .pid */
5979 			/* .tid */
5980 		},
5981 	};
5982 
5983 	perf_event_comm_event(&comm_event);
5984 }
5985 
5986 /*
5987  * mmap tracking
5988  */
5989 
5990 struct perf_mmap_event {
5991 	struct vm_area_struct	*vma;
5992 
5993 	const char		*file_name;
5994 	int			file_size;
5995 	int			maj, min;
5996 	u64			ino;
5997 	u64			ino_generation;
5998 	u32			prot, flags;
5999 
6000 	struct {
6001 		struct perf_event_header	header;
6002 
6003 		u32				pid;
6004 		u32				tid;
6005 		u64				start;
6006 		u64				len;
6007 		u64				pgoff;
6008 	} event_id;
6009 };
6010 
perf_event_mmap_match(struct perf_event * event,void * data)6011 static int perf_event_mmap_match(struct perf_event *event,
6012 				 void *data)
6013 {
6014 	struct perf_mmap_event *mmap_event = data;
6015 	struct vm_area_struct *vma = mmap_event->vma;
6016 	int executable = vma->vm_flags & VM_EXEC;
6017 
6018 	return (!executable && event->attr.mmap_data) ||
6019 	       (executable && (event->attr.mmap || event->attr.mmap2));
6020 }
6021 
perf_event_mmap_output(struct perf_event * event,void * data)6022 static void perf_event_mmap_output(struct perf_event *event,
6023 				   void *data)
6024 {
6025 	struct perf_mmap_event *mmap_event = data;
6026 	struct perf_output_handle handle;
6027 	struct perf_sample_data sample;
6028 	int size = mmap_event->event_id.header.size;
6029 	u32 type = mmap_event->event_id.header.type;
6030 	int ret;
6031 
6032 	if (!perf_event_mmap_match(event, data))
6033 		return;
6034 
6035 	if (event->attr.mmap2) {
6036 		mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
6037 		mmap_event->event_id.header.size += sizeof(mmap_event->maj);
6038 		mmap_event->event_id.header.size += sizeof(mmap_event->min);
6039 		mmap_event->event_id.header.size += sizeof(mmap_event->ino);
6040 		mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
6041 		mmap_event->event_id.header.size += sizeof(mmap_event->prot);
6042 		mmap_event->event_id.header.size += sizeof(mmap_event->flags);
6043 	}
6044 
6045 	perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
6046 	ret = perf_output_begin(&handle, event,
6047 				mmap_event->event_id.header.size);
6048 	if (ret)
6049 		goto out;
6050 
6051 	mmap_event->event_id.pid = perf_event_pid(event, current);
6052 	mmap_event->event_id.tid = perf_event_tid(event, current);
6053 
6054 	perf_output_put(&handle, mmap_event->event_id);
6055 
6056 	if (event->attr.mmap2) {
6057 		perf_output_put(&handle, mmap_event->maj);
6058 		perf_output_put(&handle, mmap_event->min);
6059 		perf_output_put(&handle, mmap_event->ino);
6060 		perf_output_put(&handle, mmap_event->ino_generation);
6061 		perf_output_put(&handle, mmap_event->prot);
6062 		perf_output_put(&handle, mmap_event->flags);
6063 	}
6064 
6065 	__output_copy(&handle, mmap_event->file_name,
6066 				   mmap_event->file_size);
6067 
6068 	perf_event__output_id_sample(event, &handle, &sample);
6069 
6070 	perf_output_end(&handle);
6071 out:
6072 	mmap_event->event_id.header.size = size;
6073 	mmap_event->event_id.header.type = type;
6074 }
6075 
perf_event_mmap_event(struct perf_mmap_event * mmap_event)6076 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
6077 {
6078 	struct vm_area_struct *vma = mmap_event->vma;
6079 	struct file *file = vma->vm_file;
6080 	int maj = 0, min = 0;
6081 	u64 ino = 0, gen = 0;
6082 	u32 prot = 0, flags = 0;
6083 	unsigned int size;
6084 	char tmp[16];
6085 	char *buf = NULL;
6086 	char *name;
6087 
6088 	if (vma->vm_flags & VM_READ)
6089 		prot |= PROT_READ;
6090 	if (vma->vm_flags & VM_WRITE)
6091 		prot |= PROT_WRITE;
6092 	if (vma->vm_flags & VM_EXEC)
6093 		prot |= PROT_EXEC;
6094 
6095 	if (vma->vm_flags & VM_MAYSHARE)
6096 		flags = MAP_SHARED;
6097 	else
6098 		flags = MAP_PRIVATE;
6099 
6100 	if (vma->vm_flags & VM_DENYWRITE)
6101 		flags |= MAP_DENYWRITE;
6102 	if (vma->vm_flags & VM_MAYEXEC)
6103 		flags |= MAP_EXECUTABLE;
6104 	if (vma->vm_flags & VM_LOCKED)
6105 		flags |= MAP_LOCKED;
6106 	if (vma->vm_flags & VM_HUGETLB)
6107 		flags |= MAP_HUGETLB;
6108 
6109 	if (file) {
6110 		struct inode *inode;
6111 		dev_t dev;
6112 
6113 		buf = kmalloc(PATH_MAX, GFP_KERNEL);
6114 		if (!buf) {
6115 			name = "//enomem";
6116 			goto cpy_name;
6117 		}
6118 		/*
6119 		 * d_path() works from the end of the rb backwards, so we
6120 		 * need to add enough zero bytes after the string to handle
6121 		 * the 64bit alignment we do later.
6122 		 */
6123 		name = file_path(file, buf, PATH_MAX - sizeof(u64));
6124 		if (IS_ERR(name)) {
6125 			name = "//toolong";
6126 			goto cpy_name;
6127 		}
6128 		inode = file_inode(vma->vm_file);
6129 		dev = inode->i_sb->s_dev;
6130 		ino = inode->i_ino;
6131 		gen = inode->i_generation;
6132 		maj = MAJOR(dev);
6133 		min = MINOR(dev);
6134 
6135 		goto got_name;
6136 	} else {
6137 		if (vma->vm_ops && vma->vm_ops->name) {
6138 			name = (char *) vma->vm_ops->name(vma);
6139 			if (name)
6140 				goto cpy_name;
6141 		}
6142 
6143 		name = (char *)arch_vma_name(vma);
6144 		if (name)
6145 			goto cpy_name;
6146 
6147 		if (vma->vm_start <= vma->vm_mm->start_brk &&
6148 				vma->vm_end >= vma->vm_mm->brk) {
6149 			name = "[heap]";
6150 			goto cpy_name;
6151 		}
6152 		if (vma->vm_start <= vma->vm_mm->start_stack &&
6153 				vma->vm_end >= vma->vm_mm->start_stack) {
6154 			name = "[stack]";
6155 			goto cpy_name;
6156 		}
6157 
6158 		name = "//anon";
6159 		goto cpy_name;
6160 	}
6161 
6162 cpy_name:
6163 	strlcpy(tmp, name, sizeof(tmp));
6164 	name = tmp;
6165 got_name:
6166 	/*
6167 	 * Since our buffer works in 8 byte units we need to align our string
6168 	 * size to a multiple of 8. However, we must guarantee the tail end is
6169 	 * zero'd out to avoid leaking random bits to userspace.
6170 	 */
6171 	size = strlen(name)+1;
6172 	while (!IS_ALIGNED(size, sizeof(u64)))
6173 		name[size++] = '\0';
6174 
6175 	mmap_event->file_name = name;
6176 	mmap_event->file_size = size;
6177 	mmap_event->maj = maj;
6178 	mmap_event->min = min;
6179 	mmap_event->ino = ino;
6180 	mmap_event->ino_generation = gen;
6181 	mmap_event->prot = prot;
6182 	mmap_event->flags = flags;
6183 
6184 	if (!(vma->vm_flags & VM_EXEC))
6185 		mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
6186 
6187 	mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
6188 
6189 	perf_event_aux(perf_event_mmap_output,
6190 		       mmap_event,
6191 		       NULL);
6192 
6193 	kfree(buf);
6194 }
6195 
perf_event_mmap(struct vm_area_struct * vma)6196 void perf_event_mmap(struct vm_area_struct *vma)
6197 {
6198 	struct perf_mmap_event mmap_event;
6199 
6200 	if (!atomic_read(&nr_mmap_events))
6201 		return;
6202 
6203 	mmap_event = (struct perf_mmap_event){
6204 		.vma	= vma,
6205 		/* .file_name */
6206 		/* .file_size */
6207 		.event_id  = {
6208 			.header = {
6209 				.type = PERF_RECORD_MMAP,
6210 				.misc = PERF_RECORD_MISC_USER,
6211 				/* .size */
6212 			},
6213 			/* .pid */
6214 			/* .tid */
6215 			.start  = vma->vm_start,
6216 			.len    = vma->vm_end - vma->vm_start,
6217 			.pgoff  = (u64)vma->vm_pgoff << PAGE_SHIFT,
6218 		},
6219 		/* .maj (attr_mmap2 only) */
6220 		/* .min (attr_mmap2 only) */
6221 		/* .ino (attr_mmap2 only) */
6222 		/* .ino_generation (attr_mmap2 only) */
6223 		/* .prot (attr_mmap2 only) */
6224 		/* .flags (attr_mmap2 only) */
6225 	};
6226 
6227 	perf_event_mmap_event(&mmap_event);
6228 }
6229 
perf_event_aux_event(struct perf_event * event,unsigned long head,unsigned long size,u64 flags)6230 void perf_event_aux_event(struct perf_event *event, unsigned long head,
6231 			  unsigned long size, u64 flags)
6232 {
6233 	struct perf_output_handle handle;
6234 	struct perf_sample_data sample;
6235 	struct perf_aux_event {
6236 		struct perf_event_header	header;
6237 		u64				offset;
6238 		u64				size;
6239 		u64				flags;
6240 	} rec = {
6241 		.header = {
6242 			.type = PERF_RECORD_AUX,
6243 			.misc = 0,
6244 			.size = sizeof(rec),
6245 		},
6246 		.offset		= head,
6247 		.size		= size,
6248 		.flags		= flags,
6249 	};
6250 	int ret;
6251 
6252 	perf_event_header__init_id(&rec.header, &sample, event);
6253 	ret = perf_output_begin(&handle, event, rec.header.size);
6254 
6255 	if (ret)
6256 		return;
6257 
6258 	perf_output_put(&handle, rec);
6259 	perf_event__output_id_sample(event, &handle, &sample);
6260 
6261 	perf_output_end(&handle);
6262 }
6263 
6264 /*
6265  * Lost/dropped samples logging
6266  */
perf_log_lost_samples(struct perf_event * event,u64 lost)6267 void perf_log_lost_samples(struct perf_event *event, u64 lost)
6268 {
6269 	struct perf_output_handle handle;
6270 	struct perf_sample_data sample;
6271 	int ret;
6272 
6273 	struct {
6274 		struct perf_event_header	header;
6275 		u64				lost;
6276 	} lost_samples_event = {
6277 		.header = {
6278 			.type = PERF_RECORD_LOST_SAMPLES,
6279 			.misc = 0,
6280 			.size = sizeof(lost_samples_event),
6281 		},
6282 		.lost		= lost,
6283 	};
6284 
6285 	perf_event_header__init_id(&lost_samples_event.header, &sample, event);
6286 
6287 	ret = perf_output_begin(&handle, event,
6288 				lost_samples_event.header.size);
6289 	if (ret)
6290 		return;
6291 
6292 	perf_output_put(&handle, lost_samples_event);
6293 	perf_event__output_id_sample(event, &handle, &sample);
6294 	perf_output_end(&handle);
6295 }
6296 
6297 /*
6298  * context_switch tracking
6299  */
6300 
6301 struct perf_switch_event {
6302 	struct task_struct	*task;
6303 	struct task_struct	*next_prev;
6304 
6305 	struct {
6306 		struct perf_event_header	header;
6307 		u32				next_prev_pid;
6308 		u32				next_prev_tid;
6309 	} event_id;
6310 };
6311 
perf_event_switch_match(struct perf_event * event)6312 static int perf_event_switch_match(struct perf_event *event)
6313 {
6314 	return event->attr.context_switch;
6315 }
6316 
perf_event_switch_output(struct perf_event * event,void * data)6317 static void perf_event_switch_output(struct perf_event *event, void *data)
6318 {
6319 	struct perf_switch_event *se = data;
6320 	struct perf_output_handle handle;
6321 	struct perf_sample_data sample;
6322 	int ret;
6323 
6324 	if (!perf_event_switch_match(event))
6325 		return;
6326 
6327 	/* Only CPU-wide events are allowed to see next/prev pid/tid */
6328 	if (event->ctx->task) {
6329 		se->event_id.header.type = PERF_RECORD_SWITCH;
6330 		se->event_id.header.size = sizeof(se->event_id.header);
6331 	} else {
6332 		se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
6333 		se->event_id.header.size = sizeof(se->event_id);
6334 		se->event_id.next_prev_pid =
6335 					perf_event_pid(event, se->next_prev);
6336 		se->event_id.next_prev_tid =
6337 					perf_event_tid(event, se->next_prev);
6338 	}
6339 
6340 	perf_event_header__init_id(&se->event_id.header, &sample, event);
6341 
6342 	ret = perf_output_begin(&handle, event, se->event_id.header.size);
6343 	if (ret)
6344 		return;
6345 
6346 	if (event->ctx->task)
6347 		perf_output_put(&handle, se->event_id.header);
6348 	else
6349 		perf_output_put(&handle, se->event_id);
6350 
6351 	perf_event__output_id_sample(event, &handle, &sample);
6352 
6353 	perf_output_end(&handle);
6354 }
6355 
perf_event_switch(struct task_struct * task,struct task_struct * next_prev,bool sched_in)6356 static void perf_event_switch(struct task_struct *task,
6357 			      struct task_struct *next_prev, bool sched_in)
6358 {
6359 	struct perf_switch_event switch_event;
6360 
6361 	/* N.B. caller checks nr_switch_events != 0 */
6362 
6363 	switch_event = (struct perf_switch_event){
6364 		.task		= task,
6365 		.next_prev	= next_prev,
6366 		.event_id	= {
6367 			.header = {
6368 				/* .type */
6369 				.misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
6370 				/* .size */
6371 			},
6372 			/* .next_prev_pid */
6373 			/* .next_prev_tid */
6374 		},
6375 	};
6376 
6377 	perf_event_aux(perf_event_switch_output,
6378 		       &switch_event,
6379 		       NULL);
6380 }
6381 
6382 /*
6383  * IRQ throttle logging
6384  */
6385 
perf_log_throttle(struct perf_event * event,int enable)6386 static void perf_log_throttle(struct perf_event *event, int enable)
6387 {
6388 	struct perf_output_handle handle;
6389 	struct perf_sample_data sample;
6390 	int ret;
6391 
6392 	struct {
6393 		struct perf_event_header	header;
6394 		u64				time;
6395 		u64				id;
6396 		u64				stream_id;
6397 	} throttle_event = {
6398 		.header = {
6399 			.type = PERF_RECORD_THROTTLE,
6400 			.misc = 0,
6401 			.size = sizeof(throttle_event),
6402 		},
6403 		.time		= perf_event_clock(event),
6404 		.id		= primary_event_id(event),
6405 		.stream_id	= event->id,
6406 	};
6407 
6408 	if (enable)
6409 		throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
6410 
6411 	perf_event_header__init_id(&throttle_event.header, &sample, event);
6412 
6413 	ret = perf_output_begin(&handle, event,
6414 				throttle_event.header.size);
6415 	if (ret)
6416 		return;
6417 
6418 	perf_output_put(&handle, throttle_event);
6419 	perf_event__output_id_sample(event, &handle, &sample);
6420 	perf_output_end(&handle);
6421 }
6422 
perf_log_itrace_start(struct perf_event * event)6423 static void perf_log_itrace_start(struct perf_event *event)
6424 {
6425 	struct perf_output_handle handle;
6426 	struct perf_sample_data sample;
6427 	struct perf_aux_event {
6428 		struct perf_event_header        header;
6429 		u32				pid;
6430 		u32				tid;
6431 	} rec;
6432 	int ret;
6433 
6434 	if (event->parent)
6435 		event = event->parent;
6436 
6437 	if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
6438 	    event->hw.itrace_started)
6439 		return;
6440 
6441 	rec.header.type	= PERF_RECORD_ITRACE_START;
6442 	rec.header.misc	= 0;
6443 	rec.header.size	= sizeof(rec);
6444 	rec.pid	= perf_event_pid(event, current);
6445 	rec.tid	= perf_event_tid(event, current);
6446 
6447 	perf_event_header__init_id(&rec.header, &sample, event);
6448 	ret = perf_output_begin(&handle, event, rec.header.size);
6449 
6450 	if (ret)
6451 		return;
6452 
6453 	perf_output_put(&handle, rec);
6454 	perf_event__output_id_sample(event, &handle, &sample);
6455 
6456 	perf_output_end(&handle);
6457 }
6458 
6459 /*
6460  * Generic event overflow handling, sampling.
6461  */
6462 
__perf_event_overflow(struct perf_event * event,int throttle,struct perf_sample_data * data,struct pt_regs * regs)6463 static int __perf_event_overflow(struct perf_event *event,
6464 				   int throttle, struct perf_sample_data *data,
6465 				   struct pt_regs *regs)
6466 {
6467 	int events = atomic_read(&event->event_limit);
6468 	struct hw_perf_event *hwc = &event->hw;
6469 	u64 seq;
6470 	int ret = 0;
6471 
6472 	/*
6473 	 * Non-sampling counters might still use the PMI to fold short
6474 	 * hardware counters, ignore those.
6475 	 */
6476 	if (unlikely(!is_sampling_event(event)))
6477 		return 0;
6478 
6479 	seq = __this_cpu_read(perf_throttled_seq);
6480 	if (seq != hwc->interrupts_seq) {
6481 		hwc->interrupts_seq = seq;
6482 		hwc->interrupts = 1;
6483 	} else {
6484 		hwc->interrupts++;
6485 		if (unlikely(throttle
6486 			     && hwc->interrupts >= max_samples_per_tick)) {
6487 			__this_cpu_inc(perf_throttled_count);
6488 			hwc->interrupts = MAX_INTERRUPTS;
6489 			perf_log_throttle(event, 0);
6490 			tick_nohz_full_kick();
6491 			ret = 1;
6492 		}
6493 	}
6494 
6495 	if (event->attr.freq) {
6496 		u64 now = perf_clock();
6497 		s64 delta = now - hwc->freq_time_stamp;
6498 
6499 		hwc->freq_time_stamp = now;
6500 
6501 		if (delta > 0 && delta < 2*TICK_NSEC)
6502 			perf_adjust_period(event, delta, hwc->last_period, true);
6503 	}
6504 
6505 	/*
6506 	 * XXX event_limit might not quite work as expected on inherited
6507 	 * events
6508 	 */
6509 
6510 	event->pending_kill = POLL_IN;
6511 	if (events && atomic_dec_and_test(&event->event_limit)) {
6512 		ret = 1;
6513 		event->pending_kill = POLL_HUP;
6514 		event->pending_disable = 1;
6515 		irq_work_queue(&event->pending);
6516 	}
6517 
6518 	if (event->overflow_handler)
6519 		event->overflow_handler(event, data, regs);
6520 	else
6521 		perf_event_output(event, data, regs);
6522 
6523 	if (*perf_event_fasync(event) && event->pending_kill) {
6524 		event->pending_wakeup = 1;
6525 		irq_work_queue(&event->pending);
6526 	}
6527 
6528 	return ret;
6529 }
6530 
perf_event_overflow(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)6531 int perf_event_overflow(struct perf_event *event,
6532 			  struct perf_sample_data *data,
6533 			  struct pt_regs *regs)
6534 {
6535 	return __perf_event_overflow(event, 1, data, regs);
6536 }
6537 
6538 /*
6539  * Generic software event infrastructure
6540  */
6541 
6542 struct swevent_htable {
6543 	struct swevent_hlist		*swevent_hlist;
6544 	struct mutex			hlist_mutex;
6545 	int				hlist_refcount;
6546 
6547 	/* Recursion avoidance in each contexts */
6548 	int				recursion[PERF_NR_CONTEXTS];
6549 };
6550 
6551 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
6552 
6553 /*
6554  * We directly increment event->count and keep a second value in
6555  * event->hw.period_left to count intervals. This period event
6556  * is kept in the range [-sample_period, 0] so that we can use the
6557  * sign as trigger.
6558  */
6559 
perf_swevent_set_period(struct perf_event * event)6560 u64 perf_swevent_set_period(struct perf_event *event)
6561 {
6562 	struct hw_perf_event *hwc = &event->hw;
6563 	u64 period = hwc->last_period;
6564 	u64 nr, offset;
6565 	s64 old, val;
6566 
6567 	hwc->last_period = hwc->sample_period;
6568 
6569 again:
6570 	old = val = local64_read(&hwc->period_left);
6571 	if (val < 0)
6572 		return 0;
6573 
6574 	nr = div64_u64(period + val, period);
6575 	offset = nr * period;
6576 	val -= offset;
6577 	if (local64_cmpxchg(&hwc->period_left, old, val) != old)
6578 		goto again;
6579 
6580 	return nr;
6581 }
6582 
perf_swevent_overflow(struct perf_event * event,u64 overflow,struct perf_sample_data * data,struct pt_regs * regs)6583 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
6584 				    struct perf_sample_data *data,
6585 				    struct pt_regs *regs)
6586 {
6587 	struct hw_perf_event *hwc = &event->hw;
6588 	int throttle = 0;
6589 
6590 	if (!overflow)
6591 		overflow = perf_swevent_set_period(event);
6592 
6593 	if (hwc->interrupts == MAX_INTERRUPTS)
6594 		return;
6595 
6596 	for (; overflow; overflow--) {
6597 		if (__perf_event_overflow(event, throttle,
6598 					    data, regs)) {
6599 			/*
6600 			 * We inhibit the overflow from happening when
6601 			 * hwc->interrupts == MAX_INTERRUPTS.
6602 			 */
6603 			break;
6604 		}
6605 		throttle = 1;
6606 	}
6607 }
6608 
perf_swevent_event(struct perf_event * event,u64 nr,struct perf_sample_data * data,struct pt_regs * regs)6609 static void perf_swevent_event(struct perf_event *event, u64 nr,
6610 			       struct perf_sample_data *data,
6611 			       struct pt_regs *regs)
6612 {
6613 	struct hw_perf_event *hwc = &event->hw;
6614 
6615 	local64_add(nr, &event->count);
6616 
6617 	if (!regs)
6618 		return;
6619 
6620 	if (!is_sampling_event(event))
6621 		return;
6622 
6623 	if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
6624 		data->period = nr;
6625 		return perf_swevent_overflow(event, 1, data, regs);
6626 	} else
6627 		data->period = event->hw.last_period;
6628 
6629 	if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
6630 		return perf_swevent_overflow(event, 1, data, regs);
6631 
6632 	if (local64_add_negative(nr, &hwc->period_left))
6633 		return;
6634 
6635 	perf_swevent_overflow(event, 0, data, regs);
6636 }
6637 
perf_exclude_event(struct perf_event * event,struct pt_regs * regs)6638 static int perf_exclude_event(struct perf_event *event,
6639 			      struct pt_regs *regs)
6640 {
6641 	if (event->hw.state & PERF_HES_STOPPED)
6642 		return 1;
6643 
6644 	if (regs) {
6645 		if (event->attr.exclude_user && user_mode(regs))
6646 			return 1;
6647 
6648 		if (event->attr.exclude_kernel && !user_mode(regs))
6649 			return 1;
6650 	}
6651 
6652 	return 0;
6653 }
6654 
perf_swevent_match(struct perf_event * event,enum perf_type_id type,u32 event_id,struct perf_sample_data * data,struct pt_regs * regs)6655 static int perf_swevent_match(struct perf_event *event,
6656 				enum perf_type_id type,
6657 				u32 event_id,
6658 				struct perf_sample_data *data,
6659 				struct pt_regs *regs)
6660 {
6661 	if (event->attr.type != type)
6662 		return 0;
6663 
6664 	if (event->attr.config != event_id)
6665 		return 0;
6666 
6667 	if (perf_exclude_event(event, regs))
6668 		return 0;
6669 
6670 	return 1;
6671 }
6672 
swevent_hash(u64 type,u32 event_id)6673 static inline u64 swevent_hash(u64 type, u32 event_id)
6674 {
6675 	u64 val = event_id | (type << 32);
6676 
6677 	return hash_64(val, SWEVENT_HLIST_BITS);
6678 }
6679 
6680 static inline struct hlist_head *
__find_swevent_head(struct swevent_hlist * hlist,u64 type,u32 event_id)6681 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
6682 {
6683 	u64 hash = swevent_hash(type, event_id);
6684 
6685 	return &hlist->heads[hash];
6686 }
6687 
6688 /* For the read side: events when they trigger */
6689 static inline struct hlist_head *
find_swevent_head_rcu(struct swevent_htable * swhash,u64 type,u32 event_id)6690 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
6691 {
6692 	struct swevent_hlist *hlist;
6693 
6694 	hlist = rcu_dereference(swhash->swevent_hlist);
6695 	if (!hlist)
6696 		return NULL;
6697 
6698 	return __find_swevent_head(hlist, type, event_id);
6699 }
6700 
6701 /* For the event head insertion and removal in the hlist */
6702 static inline struct hlist_head *
find_swevent_head(struct swevent_htable * swhash,struct perf_event * event)6703 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
6704 {
6705 	struct swevent_hlist *hlist;
6706 	u32 event_id = event->attr.config;
6707 	u64 type = event->attr.type;
6708 
6709 	/*
6710 	 * Event scheduling is always serialized against hlist allocation
6711 	 * and release. Which makes the protected version suitable here.
6712 	 * The context lock guarantees that.
6713 	 */
6714 	hlist = rcu_dereference_protected(swhash->swevent_hlist,
6715 					  lockdep_is_held(&event->ctx->lock));
6716 	if (!hlist)
6717 		return NULL;
6718 
6719 	return __find_swevent_head(hlist, type, event_id);
6720 }
6721 
do_perf_sw_event(enum perf_type_id type,u32 event_id,u64 nr,struct perf_sample_data * data,struct pt_regs * regs)6722 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
6723 				    u64 nr,
6724 				    struct perf_sample_data *data,
6725 				    struct pt_regs *regs)
6726 {
6727 	struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6728 	struct perf_event *event;
6729 	struct hlist_head *head;
6730 
6731 	rcu_read_lock();
6732 	head = find_swevent_head_rcu(swhash, type, event_id);
6733 	if (!head)
6734 		goto end;
6735 
6736 	hlist_for_each_entry_rcu(event, head, hlist_entry) {
6737 		if (perf_swevent_match(event, type, event_id, data, regs))
6738 			perf_swevent_event(event, nr, data, regs);
6739 	}
6740 end:
6741 	rcu_read_unlock();
6742 }
6743 
6744 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
6745 
perf_swevent_get_recursion_context(void)6746 int perf_swevent_get_recursion_context(void)
6747 {
6748 	struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6749 
6750 	return get_recursion_context(swhash->recursion);
6751 }
6752 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
6753 
perf_swevent_put_recursion_context(int rctx)6754 inline void perf_swevent_put_recursion_context(int rctx)
6755 {
6756 	struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6757 
6758 	put_recursion_context(swhash->recursion, rctx);
6759 }
6760 
___perf_sw_event(u32 event_id,u64 nr,struct pt_regs * regs,u64 addr)6761 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
6762 {
6763 	struct perf_sample_data data;
6764 
6765 	if (WARN_ON_ONCE(!regs))
6766 		return;
6767 
6768 	perf_sample_data_init(&data, addr, 0);
6769 	do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
6770 }
6771 
__perf_sw_event(u32 event_id,u64 nr,struct pt_regs * regs,u64 addr)6772 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
6773 {
6774 	int rctx;
6775 
6776 	preempt_disable_notrace();
6777 	rctx = perf_swevent_get_recursion_context();
6778 	if (unlikely(rctx < 0))
6779 		goto fail;
6780 
6781 	___perf_sw_event(event_id, nr, regs, addr);
6782 
6783 	perf_swevent_put_recursion_context(rctx);
6784 fail:
6785 	preempt_enable_notrace();
6786 }
6787 
perf_swevent_read(struct perf_event * event)6788 static void perf_swevent_read(struct perf_event *event)
6789 {
6790 }
6791 
perf_swevent_add(struct perf_event * event,int flags)6792 static int perf_swevent_add(struct perf_event *event, int flags)
6793 {
6794 	struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6795 	struct hw_perf_event *hwc = &event->hw;
6796 	struct hlist_head *head;
6797 
6798 	if (is_sampling_event(event)) {
6799 		hwc->last_period = hwc->sample_period;
6800 		perf_swevent_set_period(event);
6801 	}
6802 
6803 	hwc->state = !(flags & PERF_EF_START);
6804 
6805 	head = find_swevent_head(swhash, event);
6806 	if (WARN_ON_ONCE(!head))
6807 		return -EINVAL;
6808 
6809 	hlist_add_head_rcu(&event->hlist_entry, head);
6810 	perf_event_update_userpage(event);
6811 
6812 	return 0;
6813 }
6814 
perf_swevent_del(struct perf_event * event,int flags)6815 static void perf_swevent_del(struct perf_event *event, int flags)
6816 {
6817 	hlist_del_rcu(&event->hlist_entry);
6818 }
6819 
perf_swevent_start(struct perf_event * event,int flags)6820 static void perf_swevent_start(struct perf_event *event, int flags)
6821 {
6822 	event->hw.state = 0;
6823 }
6824 
perf_swevent_stop(struct perf_event * event,int flags)6825 static void perf_swevent_stop(struct perf_event *event, int flags)
6826 {
6827 	event->hw.state = PERF_HES_STOPPED;
6828 }
6829 
6830 /* Deref the hlist from the update side */
6831 static inline struct swevent_hlist *
swevent_hlist_deref(struct swevent_htable * swhash)6832 swevent_hlist_deref(struct swevent_htable *swhash)
6833 {
6834 	return rcu_dereference_protected(swhash->swevent_hlist,
6835 					 lockdep_is_held(&swhash->hlist_mutex));
6836 }
6837 
swevent_hlist_release(struct swevent_htable * swhash)6838 static void swevent_hlist_release(struct swevent_htable *swhash)
6839 {
6840 	struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
6841 
6842 	if (!hlist)
6843 		return;
6844 
6845 	RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
6846 	kfree_rcu(hlist, rcu_head);
6847 }
6848 
swevent_hlist_put_cpu(struct perf_event * event,int cpu)6849 static void swevent_hlist_put_cpu(struct perf_event *event, int cpu)
6850 {
6851 	struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
6852 
6853 	mutex_lock(&swhash->hlist_mutex);
6854 
6855 	if (!--swhash->hlist_refcount)
6856 		swevent_hlist_release(swhash);
6857 
6858 	mutex_unlock(&swhash->hlist_mutex);
6859 }
6860 
swevent_hlist_put(struct perf_event * event)6861 static void swevent_hlist_put(struct perf_event *event)
6862 {
6863 	int cpu;
6864 
6865 	for_each_possible_cpu(cpu)
6866 		swevent_hlist_put_cpu(event, cpu);
6867 }
6868 
swevent_hlist_get_cpu(struct perf_event * event,int cpu)6869 static int swevent_hlist_get_cpu(struct perf_event *event, int cpu)
6870 {
6871 	struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
6872 	int err = 0;
6873 
6874 	mutex_lock(&swhash->hlist_mutex);
6875 	if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
6876 		struct swevent_hlist *hlist;
6877 
6878 		hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
6879 		if (!hlist) {
6880 			err = -ENOMEM;
6881 			goto exit;
6882 		}
6883 		rcu_assign_pointer(swhash->swevent_hlist, hlist);
6884 	}
6885 	swhash->hlist_refcount++;
6886 exit:
6887 	mutex_unlock(&swhash->hlist_mutex);
6888 
6889 	return err;
6890 }
6891 
swevent_hlist_get(struct perf_event * event)6892 static int swevent_hlist_get(struct perf_event *event)
6893 {
6894 	int err;
6895 	int cpu, failed_cpu;
6896 
6897 	get_online_cpus();
6898 	for_each_possible_cpu(cpu) {
6899 		err = swevent_hlist_get_cpu(event, cpu);
6900 		if (err) {
6901 			failed_cpu = cpu;
6902 			goto fail;
6903 		}
6904 	}
6905 	put_online_cpus();
6906 
6907 	return 0;
6908 fail:
6909 	for_each_possible_cpu(cpu) {
6910 		if (cpu == failed_cpu)
6911 			break;
6912 		swevent_hlist_put_cpu(event, cpu);
6913 	}
6914 
6915 	put_online_cpus();
6916 	return err;
6917 }
6918 
6919 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
6920 
sw_perf_event_destroy(struct perf_event * event)6921 static void sw_perf_event_destroy(struct perf_event *event)
6922 {
6923 	u64 event_id = event->attr.config;
6924 
6925 	WARN_ON(event->parent);
6926 
6927 	static_key_slow_dec(&perf_swevent_enabled[event_id]);
6928 	swevent_hlist_put(event);
6929 }
6930 
perf_swevent_init(struct perf_event * event)6931 static int perf_swevent_init(struct perf_event *event)
6932 {
6933 	u64 event_id = event->attr.config;
6934 
6935 	if (event->attr.type != PERF_TYPE_SOFTWARE)
6936 		return -ENOENT;
6937 
6938 	/*
6939 	 * no branch sampling for software events
6940 	 */
6941 	if (has_branch_stack(event))
6942 		return -EOPNOTSUPP;
6943 
6944 	switch (event_id) {
6945 	case PERF_COUNT_SW_CPU_CLOCK:
6946 	case PERF_COUNT_SW_TASK_CLOCK:
6947 		return -ENOENT;
6948 
6949 	default:
6950 		break;
6951 	}
6952 
6953 	if (event_id >= PERF_COUNT_SW_MAX)
6954 		return -ENOENT;
6955 
6956 	if (!event->parent) {
6957 		int err;
6958 
6959 		err = swevent_hlist_get(event);
6960 		if (err)
6961 			return err;
6962 
6963 		static_key_slow_inc(&perf_swevent_enabled[event_id]);
6964 		event->destroy = sw_perf_event_destroy;
6965 	}
6966 
6967 	return 0;
6968 }
6969 
6970 static struct pmu perf_swevent = {
6971 	.task_ctx_nr	= perf_sw_context,
6972 
6973 	.capabilities	= PERF_PMU_CAP_NO_NMI,
6974 
6975 	.event_init	= perf_swevent_init,
6976 	.add		= perf_swevent_add,
6977 	.del		= perf_swevent_del,
6978 	.start		= perf_swevent_start,
6979 	.stop		= perf_swevent_stop,
6980 	.read		= perf_swevent_read,
6981 };
6982 
6983 #ifdef CONFIG_EVENT_TRACING
6984 
perf_tp_filter_match(struct perf_event * event,struct perf_sample_data * data)6985 static int perf_tp_filter_match(struct perf_event *event,
6986 				struct perf_sample_data *data)
6987 {
6988 	void *record = data->raw->data;
6989 
6990 	/* only top level events have filters set */
6991 	if (event->parent)
6992 		event = event->parent;
6993 
6994 	if (likely(!event->filter) || filter_match_preds(event->filter, record))
6995 		return 1;
6996 	return 0;
6997 }
6998 
perf_tp_event_match(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)6999 static int perf_tp_event_match(struct perf_event *event,
7000 				struct perf_sample_data *data,
7001 				struct pt_regs *regs)
7002 {
7003 	if (event->hw.state & PERF_HES_STOPPED)
7004 		return 0;
7005 	/*
7006 	 * All tracepoints are from kernel-space.
7007 	 */
7008 	if (event->attr.exclude_kernel)
7009 		return 0;
7010 
7011 	if (!perf_tp_filter_match(event, data))
7012 		return 0;
7013 
7014 	return 1;
7015 }
7016 
perf_tp_event(u64 addr,u64 count,void * record,int entry_size,struct pt_regs * regs,struct hlist_head * head,int rctx,struct task_struct * task)7017 void perf_tp_event(u64 addr, u64 count, void *record, int entry_size,
7018 		   struct pt_regs *regs, struct hlist_head *head, int rctx,
7019 		   struct task_struct *task)
7020 {
7021 	struct perf_sample_data data;
7022 	struct perf_event *event;
7023 
7024 	struct perf_raw_record raw = {
7025 		.size = entry_size,
7026 		.data = record,
7027 	};
7028 
7029 	perf_sample_data_init(&data, addr, 0);
7030 	data.raw = &raw;
7031 
7032 	hlist_for_each_entry_rcu(event, head, hlist_entry) {
7033 		if (perf_tp_event_match(event, &data, regs))
7034 			perf_swevent_event(event, count, &data, regs);
7035 	}
7036 
7037 	/*
7038 	 * If we got specified a target task, also iterate its context and
7039 	 * deliver this event there too.
7040 	 */
7041 	if (task && task != current) {
7042 		struct perf_event_context *ctx;
7043 		struct trace_entry *entry = record;
7044 
7045 		rcu_read_lock();
7046 		ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
7047 		if (!ctx)
7048 			goto unlock;
7049 
7050 		list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
7051 			if (event->cpu != smp_processor_id())
7052 				continue;
7053 			if (event->attr.type != PERF_TYPE_TRACEPOINT)
7054 				continue;
7055 			if (event->attr.config != entry->type)
7056 				continue;
7057 			if (perf_tp_event_match(event, &data, regs))
7058 				perf_swevent_event(event, count, &data, regs);
7059 		}
7060 unlock:
7061 		rcu_read_unlock();
7062 	}
7063 
7064 	perf_swevent_put_recursion_context(rctx);
7065 }
7066 EXPORT_SYMBOL_GPL(perf_tp_event);
7067 
tp_perf_event_destroy(struct perf_event * event)7068 static void tp_perf_event_destroy(struct perf_event *event)
7069 {
7070 	perf_trace_destroy(event);
7071 }
7072 
perf_tp_event_init(struct perf_event * event)7073 static int perf_tp_event_init(struct perf_event *event)
7074 {
7075 	int err;
7076 
7077 	if (event->attr.type != PERF_TYPE_TRACEPOINT)
7078 		return -ENOENT;
7079 
7080 	/*
7081 	 * no branch sampling for tracepoint events
7082 	 */
7083 	if (has_branch_stack(event))
7084 		return -EOPNOTSUPP;
7085 
7086 	err = perf_trace_init(event);
7087 	if (err)
7088 		return err;
7089 
7090 	event->destroy = tp_perf_event_destroy;
7091 
7092 	return 0;
7093 }
7094 
7095 static struct pmu perf_tracepoint = {
7096 	.task_ctx_nr	= perf_sw_context,
7097 
7098 	.event_init	= perf_tp_event_init,
7099 	.add		= perf_trace_add,
7100 	.del		= perf_trace_del,
7101 	.start		= perf_swevent_start,
7102 	.stop		= perf_swevent_stop,
7103 	.read		= perf_swevent_read,
7104 };
7105 
perf_tp_register(void)7106 static inline void perf_tp_register(void)
7107 {
7108 	perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
7109 }
7110 
perf_event_set_filter(struct perf_event * event,void __user * arg)7111 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
7112 {
7113 	char *filter_str;
7114 	int ret;
7115 
7116 	if (event->attr.type != PERF_TYPE_TRACEPOINT)
7117 		return -EINVAL;
7118 
7119 	filter_str = strndup_user(arg, PAGE_SIZE);
7120 	if (IS_ERR(filter_str))
7121 		return PTR_ERR(filter_str);
7122 
7123 	ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
7124 
7125 	kfree(filter_str);
7126 	return ret;
7127 }
7128 
perf_event_free_filter(struct perf_event * event)7129 static void perf_event_free_filter(struct perf_event *event)
7130 {
7131 	ftrace_profile_free_filter(event);
7132 }
7133 
perf_event_set_bpf_prog(struct perf_event * event,u32 prog_fd)7134 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
7135 {
7136 	struct bpf_prog *prog;
7137 
7138 	if (event->attr.type != PERF_TYPE_TRACEPOINT)
7139 		return -EINVAL;
7140 
7141 	if (event->tp_event->prog)
7142 		return -EEXIST;
7143 
7144 	if (!(event->tp_event->flags & TRACE_EVENT_FL_UKPROBE))
7145 		/* bpf programs can only be attached to u/kprobes */
7146 		return -EINVAL;
7147 
7148 	prog = bpf_prog_get(prog_fd);
7149 	if (IS_ERR(prog))
7150 		return PTR_ERR(prog);
7151 
7152 	if (prog->type != BPF_PROG_TYPE_KPROBE) {
7153 		/* valid fd, but invalid bpf program type */
7154 		bpf_prog_put(prog);
7155 		return -EINVAL;
7156 	}
7157 
7158 	event->tp_event->prog = prog;
7159 	event->tp_event->bpf_prog_owner = event;
7160 
7161 	return 0;
7162 }
7163 
perf_event_free_bpf_prog(struct perf_event * event)7164 static void perf_event_free_bpf_prog(struct perf_event *event)
7165 {
7166 	struct bpf_prog *prog;
7167 
7168 	if (!event->tp_event)
7169 		return;
7170 
7171 	prog = event->tp_event->prog;
7172 	if (prog && event->tp_event->bpf_prog_owner == event) {
7173 		event->tp_event->prog = NULL;
7174 		bpf_prog_put(prog);
7175 	}
7176 }
7177 
7178 #else
7179 
perf_tp_register(void)7180 static inline void perf_tp_register(void)
7181 {
7182 }
7183 
perf_event_set_filter(struct perf_event * event,void __user * arg)7184 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
7185 {
7186 	return -ENOENT;
7187 }
7188 
perf_event_free_filter(struct perf_event * event)7189 static void perf_event_free_filter(struct perf_event *event)
7190 {
7191 }
7192 
perf_event_set_bpf_prog(struct perf_event * event,u32 prog_fd)7193 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
7194 {
7195 	return -ENOENT;
7196 }
7197 
perf_event_free_bpf_prog(struct perf_event * event)7198 static void perf_event_free_bpf_prog(struct perf_event *event)
7199 {
7200 }
7201 #endif /* CONFIG_EVENT_TRACING */
7202 
7203 #ifdef CONFIG_HAVE_HW_BREAKPOINT
perf_bp_event(struct perf_event * bp,void * data)7204 void perf_bp_event(struct perf_event *bp, void *data)
7205 {
7206 	struct perf_sample_data sample;
7207 	struct pt_regs *regs = data;
7208 
7209 	perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
7210 
7211 	if (!bp->hw.state && !perf_exclude_event(bp, regs))
7212 		perf_swevent_event(bp, 1, &sample, regs);
7213 }
7214 #endif
7215 
7216 /*
7217  * hrtimer based swevent callback
7218  */
7219 
perf_swevent_hrtimer(struct hrtimer * hrtimer)7220 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
7221 {
7222 	enum hrtimer_restart ret = HRTIMER_RESTART;
7223 	struct perf_sample_data data;
7224 	struct pt_regs *regs;
7225 	struct perf_event *event;
7226 	u64 period;
7227 
7228 	event = container_of(hrtimer, struct perf_event, hw.hrtimer);
7229 
7230 	if (event->state != PERF_EVENT_STATE_ACTIVE)
7231 		return HRTIMER_NORESTART;
7232 
7233 	event->pmu->read(event);
7234 
7235 	perf_sample_data_init(&data, 0, event->hw.last_period);
7236 	regs = get_irq_regs();
7237 
7238 	if (regs && !perf_exclude_event(event, regs)) {
7239 		if (!(event->attr.exclude_idle && is_idle_task(current)))
7240 			if (__perf_event_overflow(event, 1, &data, regs))
7241 				ret = HRTIMER_NORESTART;
7242 	}
7243 
7244 	period = max_t(u64, 10000, event->hw.sample_period);
7245 	hrtimer_forward_now(hrtimer, ns_to_ktime(period));
7246 
7247 	return ret;
7248 }
7249 
perf_swevent_start_hrtimer(struct perf_event * event)7250 static void perf_swevent_start_hrtimer(struct perf_event *event)
7251 {
7252 	struct hw_perf_event *hwc = &event->hw;
7253 	s64 period;
7254 
7255 	if (!is_sampling_event(event))
7256 		return;
7257 
7258 	period = local64_read(&hwc->period_left);
7259 	if (period) {
7260 		if (period < 0)
7261 			period = 10000;
7262 
7263 		local64_set(&hwc->period_left, 0);
7264 	} else {
7265 		period = max_t(u64, 10000, hwc->sample_period);
7266 	}
7267 	hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
7268 		      HRTIMER_MODE_REL_PINNED);
7269 }
7270 
perf_swevent_cancel_hrtimer(struct perf_event * event)7271 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
7272 {
7273 	struct hw_perf_event *hwc = &event->hw;
7274 
7275 	if (is_sampling_event(event)) {
7276 		ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
7277 		local64_set(&hwc->period_left, ktime_to_ns(remaining));
7278 
7279 		hrtimer_cancel(&hwc->hrtimer);
7280 	}
7281 }
7282 
perf_swevent_init_hrtimer(struct perf_event * event)7283 static void perf_swevent_init_hrtimer(struct perf_event *event)
7284 {
7285 	struct hw_perf_event *hwc = &event->hw;
7286 
7287 	if (!is_sampling_event(event))
7288 		return;
7289 
7290 	hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
7291 	hwc->hrtimer.function = perf_swevent_hrtimer;
7292 
7293 	/*
7294 	 * Since hrtimers have a fixed rate, we can do a static freq->period
7295 	 * mapping and avoid the whole period adjust feedback stuff.
7296 	 */
7297 	if (event->attr.freq) {
7298 		long freq = event->attr.sample_freq;
7299 
7300 		event->attr.sample_period = NSEC_PER_SEC / freq;
7301 		hwc->sample_period = event->attr.sample_period;
7302 		local64_set(&hwc->period_left, hwc->sample_period);
7303 		hwc->last_period = hwc->sample_period;
7304 		event->attr.freq = 0;
7305 	}
7306 }
7307 
7308 /*
7309  * Software event: cpu wall time clock
7310  */
7311 
cpu_clock_event_update(struct perf_event * event)7312 static void cpu_clock_event_update(struct perf_event *event)
7313 {
7314 	s64 prev;
7315 	u64 now;
7316 
7317 	now = local_clock();
7318 	prev = local64_xchg(&event->hw.prev_count, now);
7319 	local64_add(now - prev, &event->count);
7320 }
7321 
cpu_clock_event_start(struct perf_event * event,int flags)7322 static void cpu_clock_event_start(struct perf_event *event, int flags)
7323 {
7324 	local64_set(&event->hw.prev_count, local_clock());
7325 	perf_swevent_start_hrtimer(event);
7326 }
7327 
cpu_clock_event_stop(struct perf_event * event,int flags)7328 static void cpu_clock_event_stop(struct perf_event *event, int flags)
7329 {
7330 	perf_swevent_cancel_hrtimer(event);
7331 	cpu_clock_event_update(event);
7332 }
7333 
cpu_clock_event_add(struct perf_event * event,int flags)7334 static int cpu_clock_event_add(struct perf_event *event, int flags)
7335 {
7336 	if (flags & PERF_EF_START)
7337 		cpu_clock_event_start(event, flags);
7338 	perf_event_update_userpage(event);
7339 
7340 	return 0;
7341 }
7342 
cpu_clock_event_del(struct perf_event * event,int flags)7343 static void cpu_clock_event_del(struct perf_event *event, int flags)
7344 {
7345 	cpu_clock_event_stop(event, flags);
7346 }
7347 
cpu_clock_event_read(struct perf_event * event)7348 static void cpu_clock_event_read(struct perf_event *event)
7349 {
7350 	cpu_clock_event_update(event);
7351 }
7352 
cpu_clock_event_init(struct perf_event * event)7353 static int cpu_clock_event_init(struct perf_event *event)
7354 {
7355 	if (event->attr.type != PERF_TYPE_SOFTWARE)
7356 		return -ENOENT;
7357 
7358 	if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
7359 		return -ENOENT;
7360 
7361 	/*
7362 	 * no branch sampling for software events
7363 	 */
7364 	if (has_branch_stack(event))
7365 		return -EOPNOTSUPP;
7366 
7367 	perf_swevent_init_hrtimer(event);
7368 
7369 	return 0;
7370 }
7371 
7372 static struct pmu perf_cpu_clock = {
7373 	.task_ctx_nr	= perf_sw_context,
7374 
7375 	.capabilities	= PERF_PMU_CAP_NO_NMI,
7376 
7377 	.event_init	= cpu_clock_event_init,
7378 	.add		= cpu_clock_event_add,
7379 	.del		= cpu_clock_event_del,
7380 	.start		= cpu_clock_event_start,
7381 	.stop		= cpu_clock_event_stop,
7382 	.read		= cpu_clock_event_read,
7383 };
7384 
7385 /*
7386  * Software event: task time clock
7387  */
7388 
task_clock_event_update(struct perf_event * event,u64 now)7389 static void task_clock_event_update(struct perf_event *event, u64 now)
7390 {
7391 	u64 prev;
7392 	s64 delta;
7393 
7394 	prev = local64_xchg(&event->hw.prev_count, now);
7395 	delta = now - prev;
7396 	local64_add(delta, &event->count);
7397 }
7398 
task_clock_event_start(struct perf_event * event,int flags)7399 static void task_clock_event_start(struct perf_event *event, int flags)
7400 {
7401 	local64_set(&event->hw.prev_count, event->ctx->time);
7402 	perf_swevent_start_hrtimer(event);
7403 }
7404 
task_clock_event_stop(struct perf_event * event,int flags)7405 static void task_clock_event_stop(struct perf_event *event, int flags)
7406 {
7407 	perf_swevent_cancel_hrtimer(event);
7408 	task_clock_event_update(event, event->ctx->time);
7409 }
7410 
task_clock_event_add(struct perf_event * event,int flags)7411 static int task_clock_event_add(struct perf_event *event, int flags)
7412 {
7413 	if (flags & PERF_EF_START)
7414 		task_clock_event_start(event, flags);
7415 	perf_event_update_userpage(event);
7416 
7417 	return 0;
7418 }
7419 
task_clock_event_del(struct perf_event * event,int flags)7420 static void task_clock_event_del(struct perf_event *event, int flags)
7421 {
7422 	task_clock_event_stop(event, PERF_EF_UPDATE);
7423 }
7424 
task_clock_event_read(struct perf_event * event)7425 static void task_clock_event_read(struct perf_event *event)
7426 {
7427 	u64 now = perf_clock();
7428 	u64 delta = now - event->ctx->timestamp;
7429 	u64 time = event->ctx->time + delta;
7430 
7431 	task_clock_event_update(event, time);
7432 }
7433 
task_clock_event_init(struct perf_event * event)7434 static int task_clock_event_init(struct perf_event *event)
7435 {
7436 	if (event->attr.type != PERF_TYPE_SOFTWARE)
7437 		return -ENOENT;
7438 
7439 	if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
7440 		return -ENOENT;
7441 
7442 	/*
7443 	 * no branch sampling for software events
7444 	 */
7445 	if (has_branch_stack(event))
7446 		return -EOPNOTSUPP;
7447 
7448 	perf_swevent_init_hrtimer(event);
7449 
7450 	return 0;
7451 }
7452 
7453 static struct pmu perf_task_clock = {
7454 	.task_ctx_nr	= perf_sw_context,
7455 
7456 	.capabilities	= PERF_PMU_CAP_NO_NMI,
7457 
7458 	.event_init	= task_clock_event_init,
7459 	.add		= task_clock_event_add,
7460 	.del		= task_clock_event_del,
7461 	.start		= task_clock_event_start,
7462 	.stop		= task_clock_event_stop,
7463 	.read		= task_clock_event_read,
7464 };
7465 
perf_pmu_nop_void(struct pmu * pmu)7466 static void perf_pmu_nop_void(struct pmu *pmu)
7467 {
7468 }
7469 
perf_pmu_nop_txn(struct pmu * pmu,unsigned int flags)7470 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
7471 {
7472 }
7473 
perf_pmu_nop_int(struct pmu * pmu)7474 static int perf_pmu_nop_int(struct pmu *pmu)
7475 {
7476 	return 0;
7477 }
7478 
7479 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
7480 
perf_pmu_start_txn(struct pmu * pmu,unsigned int flags)7481 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
7482 {
7483 	__this_cpu_write(nop_txn_flags, flags);
7484 
7485 	if (flags & ~PERF_PMU_TXN_ADD)
7486 		return;
7487 
7488 	perf_pmu_disable(pmu);
7489 }
7490 
perf_pmu_commit_txn(struct pmu * pmu)7491 static int perf_pmu_commit_txn(struct pmu *pmu)
7492 {
7493 	unsigned int flags = __this_cpu_read(nop_txn_flags);
7494 
7495 	__this_cpu_write(nop_txn_flags, 0);
7496 
7497 	if (flags & ~PERF_PMU_TXN_ADD)
7498 		return 0;
7499 
7500 	perf_pmu_enable(pmu);
7501 	return 0;
7502 }
7503 
perf_pmu_cancel_txn(struct pmu * pmu)7504 static void perf_pmu_cancel_txn(struct pmu *pmu)
7505 {
7506 	unsigned int flags =  __this_cpu_read(nop_txn_flags);
7507 
7508 	__this_cpu_write(nop_txn_flags, 0);
7509 
7510 	if (flags & ~PERF_PMU_TXN_ADD)
7511 		return;
7512 
7513 	perf_pmu_enable(pmu);
7514 }
7515 
perf_event_idx_default(struct perf_event * event)7516 static int perf_event_idx_default(struct perf_event *event)
7517 {
7518 	return 0;
7519 }
7520 
7521 /*
7522  * Ensures all contexts with the same task_ctx_nr have the same
7523  * pmu_cpu_context too.
7524  */
find_pmu_context(int ctxn)7525 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
7526 {
7527 	struct pmu *pmu;
7528 
7529 	if (ctxn < 0)
7530 		return NULL;
7531 
7532 	list_for_each_entry(pmu, &pmus, entry) {
7533 		if (pmu->task_ctx_nr == ctxn)
7534 			return pmu->pmu_cpu_context;
7535 	}
7536 
7537 	return NULL;
7538 }
7539 
update_pmu_context(struct pmu * pmu,struct pmu * old_pmu)7540 static void update_pmu_context(struct pmu *pmu, struct pmu *old_pmu)
7541 {
7542 	int cpu;
7543 
7544 	for_each_possible_cpu(cpu) {
7545 		struct perf_cpu_context *cpuctx;
7546 
7547 		cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
7548 
7549 		if (cpuctx->unique_pmu == old_pmu)
7550 			cpuctx->unique_pmu = pmu;
7551 	}
7552 }
7553 
free_pmu_context(struct pmu * pmu)7554 static void free_pmu_context(struct pmu *pmu)
7555 {
7556 	struct pmu *i;
7557 
7558 	mutex_lock(&pmus_lock);
7559 	/*
7560 	 * Like a real lame refcount.
7561 	 */
7562 	list_for_each_entry(i, &pmus, entry) {
7563 		if (i->pmu_cpu_context == pmu->pmu_cpu_context) {
7564 			update_pmu_context(i, pmu);
7565 			goto out;
7566 		}
7567 	}
7568 
7569 	free_percpu(pmu->pmu_cpu_context);
7570 out:
7571 	mutex_unlock(&pmus_lock);
7572 }
7573 static struct idr pmu_idr;
7574 
7575 static ssize_t
type_show(struct device * dev,struct device_attribute * attr,char * page)7576 type_show(struct device *dev, struct device_attribute *attr, char *page)
7577 {
7578 	struct pmu *pmu = dev_get_drvdata(dev);
7579 
7580 	return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
7581 }
7582 static DEVICE_ATTR_RO(type);
7583 
7584 static ssize_t
perf_event_mux_interval_ms_show(struct device * dev,struct device_attribute * attr,char * page)7585 perf_event_mux_interval_ms_show(struct device *dev,
7586 				struct device_attribute *attr,
7587 				char *page)
7588 {
7589 	struct pmu *pmu = dev_get_drvdata(dev);
7590 
7591 	return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
7592 }
7593 
7594 static DEFINE_MUTEX(mux_interval_mutex);
7595 
7596 static ssize_t
perf_event_mux_interval_ms_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)7597 perf_event_mux_interval_ms_store(struct device *dev,
7598 				 struct device_attribute *attr,
7599 				 const char *buf, size_t count)
7600 {
7601 	struct pmu *pmu = dev_get_drvdata(dev);
7602 	int timer, cpu, ret;
7603 
7604 	ret = kstrtoint(buf, 0, &timer);
7605 	if (ret)
7606 		return ret;
7607 
7608 	if (timer < 1)
7609 		return -EINVAL;
7610 
7611 	/* same value, noting to do */
7612 	if (timer == pmu->hrtimer_interval_ms)
7613 		return count;
7614 
7615 	mutex_lock(&mux_interval_mutex);
7616 	pmu->hrtimer_interval_ms = timer;
7617 
7618 	/* update all cpuctx for this PMU */
7619 	get_online_cpus();
7620 	for_each_online_cpu(cpu) {
7621 		struct perf_cpu_context *cpuctx;
7622 		cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
7623 		cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
7624 
7625 		cpu_function_call(cpu,
7626 			(remote_function_f)perf_mux_hrtimer_restart, cpuctx);
7627 	}
7628 	put_online_cpus();
7629 	mutex_unlock(&mux_interval_mutex);
7630 
7631 	return count;
7632 }
7633 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
7634 
7635 static struct attribute *pmu_dev_attrs[] = {
7636 	&dev_attr_type.attr,
7637 	&dev_attr_perf_event_mux_interval_ms.attr,
7638 	NULL,
7639 };
7640 ATTRIBUTE_GROUPS(pmu_dev);
7641 
7642 static int pmu_bus_running;
7643 static struct bus_type pmu_bus = {
7644 	.name		= "event_source",
7645 	.dev_groups	= pmu_dev_groups,
7646 };
7647 
pmu_dev_release(struct device * dev)7648 static void pmu_dev_release(struct device *dev)
7649 {
7650 	kfree(dev);
7651 }
7652 
pmu_dev_alloc(struct pmu * pmu)7653 static int pmu_dev_alloc(struct pmu *pmu)
7654 {
7655 	int ret = -ENOMEM;
7656 
7657 	pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
7658 	if (!pmu->dev)
7659 		goto out;
7660 
7661 	pmu->dev->groups = pmu->attr_groups;
7662 	device_initialize(pmu->dev);
7663 	ret = dev_set_name(pmu->dev, "%s", pmu->name);
7664 	if (ret)
7665 		goto free_dev;
7666 
7667 	dev_set_drvdata(pmu->dev, pmu);
7668 	pmu->dev->bus = &pmu_bus;
7669 	pmu->dev->release = pmu_dev_release;
7670 	ret = device_add(pmu->dev);
7671 	if (ret)
7672 		goto free_dev;
7673 
7674 out:
7675 	return ret;
7676 
7677 free_dev:
7678 	put_device(pmu->dev);
7679 	goto out;
7680 }
7681 
7682 static struct lock_class_key cpuctx_mutex;
7683 static struct lock_class_key cpuctx_lock;
7684 
perf_pmu_register(struct pmu * pmu,const char * name,int type)7685 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
7686 {
7687 	int cpu, ret;
7688 
7689 	mutex_lock(&pmus_lock);
7690 	ret = -ENOMEM;
7691 	pmu->pmu_disable_count = alloc_percpu(int);
7692 	if (!pmu->pmu_disable_count)
7693 		goto unlock;
7694 
7695 	pmu->type = -1;
7696 	if (!name)
7697 		goto skip_type;
7698 	pmu->name = name;
7699 
7700 	if (type < 0) {
7701 		type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
7702 		if (type < 0) {
7703 			ret = type;
7704 			goto free_pdc;
7705 		}
7706 	}
7707 	pmu->type = type;
7708 
7709 	if (pmu_bus_running) {
7710 		ret = pmu_dev_alloc(pmu);
7711 		if (ret)
7712 			goto free_idr;
7713 	}
7714 
7715 skip_type:
7716 	pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
7717 	if (pmu->pmu_cpu_context)
7718 		goto got_cpu_context;
7719 
7720 	ret = -ENOMEM;
7721 	pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
7722 	if (!pmu->pmu_cpu_context)
7723 		goto free_dev;
7724 
7725 	for_each_possible_cpu(cpu) {
7726 		struct perf_cpu_context *cpuctx;
7727 
7728 		cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
7729 		__perf_event_init_context(&cpuctx->ctx);
7730 		lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
7731 		lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
7732 		cpuctx->ctx.pmu = pmu;
7733 
7734 		__perf_mux_hrtimer_init(cpuctx, cpu);
7735 
7736 		cpuctx->unique_pmu = pmu;
7737 	}
7738 
7739 got_cpu_context:
7740 	if (!pmu->start_txn) {
7741 		if (pmu->pmu_enable) {
7742 			/*
7743 			 * If we have pmu_enable/pmu_disable calls, install
7744 			 * transaction stubs that use that to try and batch
7745 			 * hardware accesses.
7746 			 */
7747 			pmu->start_txn  = perf_pmu_start_txn;
7748 			pmu->commit_txn = perf_pmu_commit_txn;
7749 			pmu->cancel_txn = perf_pmu_cancel_txn;
7750 		} else {
7751 			pmu->start_txn  = perf_pmu_nop_txn;
7752 			pmu->commit_txn = perf_pmu_nop_int;
7753 			pmu->cancel_txn = perf_pmu_nop_void;
7754 		}
7755 	}
7756 
7757 	if (!pmu->pmu_enable) {
7758 		pmu->pmu_enable  = perf_pmu_nop_void;
7759 		pmu->pmu_disable = perf_pmu_nop_void;
7760 	}
7761 
7762 	if (!pmu->event_idx)
7763 		pmu->event_idx = perf_event_idx_default;
7764 
7765 	list_add_rcu(&pmu->entry, &pmus);
7766 	atomic_set(&pmu->exclusive_cnt, 0);
7767 	ret = 0;
7768 unlock:
7769 	mutex_unlock(&pmus_lock);
7770 
7771 	return ret;
7772 
7773 free_dev:
7774 	device_del(pmu->dev);
7775 	put_device(pmu->dev);
7776 
7777 free_idr:
7778 	if (pmu->type >= PERF_TYPE_MAX)
7779 		idr_remove(&pmu_idr, pmu->type);
7780 
7781 free_pdc:
7782 	free_percpu(pmu->pmu_disable_count);
7783 	goto unlock;
7784 }
7785 EXPORT_SYMBOL_GPL(perf_pmu_register);
7786 
perf_pmu_unregister(struct pmu * pmu)7787 void perf_pmu_unregister(struct pmu *pmu)
7788 {
7789 	mutex_lock(&pmus_lock);
7790 	list_del_rcu(&pmu->entry);
7791 	mutex_unlock(&pmus_lock);
7792 
7793 	/*
7794 	 * We dereference the pmu list under both SRCU and regular RCU, so
7795 	 * synchronize against both of those.
7796 	 */
7797 	synchronize_srcu(&pmus_srcu);
7798 	synchronize_rcu();
7799 
7800 	free_percpu(pmu->pmu_disable_count);
7801 	if (pmu->type >= PERF_TYPE_MAX)
7802 		idr_remove(&pmu_idr, pmu->type);
7803 	device_del(pmu->dev);
7804 	put_device(pmu->dev);
7805 	free_pmu_context(pmu);
7806 }
7807 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
7808 
perf_try_init_event(struct pmu * pmu,struct perf_event * event)7809 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
7810 {
7811 	struct perf_event_context *ctx = NULL;
7812 	int ret;
7813 
7814 	if (!try_module_get(pmu->module))
7815 		return -ENODEV;
7816 
7817 	if (event->group_leader != event) {
7818 		/*
7819 		 * This ctx->mutex can nest when we're called through
7820 		 * inheritance. See the perf_event_ctx_lock_nested() comment.
7821 		 */
7822 		ctx = perf_event_ctx_lock_nested(event->group_leader,
7823 						 SINGLE_DEPTH_NESTING);
7824 		BUG_ON(!ctx);
7825 	}
7826 
7827 	event->pmu = pmu;
7828 	ret = pmu->event_init(event);
7829 
7830 	if (ctx)
7831 		perf_event_ctx_unlock(event->group_leader, ctx);
7832 
7833 	if (ret)
7834 		module_put(pmu->module);
7835 
7836 	return ret;
7837 }
7838 
perf_init_event(struct perf_event * event)7839 static struct pmu *perf_init_event(struct perf_event *event)
7840 {
7841 	struct pmu *pmu = NULL;
7842 	int idx;
7843 	int ret;
7844 
7845 	idx = srcu_read_lock(&pmus_srcu);
7846 
7847 	rcu_read_lock();
7848 	pmu = idr_find(&pmu_idr, event->attr.type);
7849 	rcu_read_unlock();
7850 	if (pmu) {
7851 		ret = perf_try_init_event(pmu, event);
7852 		if (ret)
7853 			pmu = ERR_PTR(ret);
7854 		goto unlock;
7855 	}
7856 
7857 	list_for_each_entry_rcu(pmu, &pmus, entry) {
7858 		ret = perf_try_init_event(pmu, event);
7859 		if (!ret)
7860 			goto unlock;
7861 
7862 		if (ret != -ENOENT) {
7863 			pmu = ERR_PTR(ret);
7864 			goto unlock;
7865 		}
7866 	}
7867 	pmu = ERR_PTR(-ENOENT);
7868 unlock:
7869 	srcu_read_unlock(&pmus_srcu, idx);
7870 
7871 	return pmu;
7872 }
7873 
account_event_cpu(struct perf_event * event,int cpu)7874 static void account_event_cpu(struct perf_event *event, int cpu)
7875 {
7876 	if (event->parent)
7877 		return;
7878 
7879 	if (is_cgroup_event(event))
7880 		atomic_inc(&per_cpu(perf_cgroup_events, cpu));
7881 }
7882 
account_event(struct perf_event * event)7883 static void account_event(struct perf_event *event)
7884 {
7885 	if (event->parent)
7886 		return;
7887 
7888 	if (event->attach_state & PERF_ATTACH_TASK)
7889 		static_key_slow_inc(&perf_sched_events.key);
7890 	if (event->attr.mmap || event->attr.mmap_data)
7891 		atomic_inc(&nr_mmap_events);
7892 	if (event->attr.comm)
7893 		atomic_inc(&nr_comm_events);
7894 	if (event->attr.task)
7895 		atomic_inc(&nr_task_events);
7896 	if (event->attr.freq) {
7897 		if (atomic_inc_return(&nr_freq_events) == 1)
7898 			tick_nohz_full_kick_all();
7899 	}
7900 	if (event->attr.context_switch) {
7901 		atomic_inc(&nr_switch_events);
7902 		static_key_slow_inc(&perf_sched_events.key);
7903 	}
7904 	if (has_branch_stack(event))
7905 		static_key_slow_inc(&perf_sched_events.key);
7906 	if (is_cgroup_event(event))
7907 		static_key_slow_inc(&perf_sched_events.key);
7908 
7909 	account_event_cpu(event, event->cpu);
7910 }
7911 
7912 /*
7913  * Allocate and initialize a event structure
7914  */
7915 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)7916 perf_event_alloc(struct perf_event_attr *attr, int cpu,
7917 		 struct task_struct *task,
7918 		 struct perf_event *group_leader,
7919 		 struct perf_event *parent_event,
7920 		 perf_overflow_handler_t overflow_handler,
7921 		 void *context, int cgroup_fd)
7922 {
7923 	struct pmu *pmu;
7924 	struct perf_event *event;
7925 	struct hw_perf_event *hwc;
7926 	long err = -EINVAL;
7927 
7928 	if ((unsigned)cpu >= nr_cpu_ids) {
7929 		if (!task || cpu != -1)
7930 			return ERR_PTR(-EINVAL);
7931 	}
7932 
7933 	event = kzalloc(sizeof(*event), GFP_KERNEL);
7934 	if (!event)
7935 		return ERR_PTR(-ENOMEM);
7936 
7937 	/*
7938 	 * Single events are their own group leaders, with an
7939 	 * empty sibling list:
7940 	 */
7941 	if (!group_leader)
7942 		group_leader = event;
7943 
7944 	mutex_init(&event->child_mutex);
7945 	INIT_LIST_HEAD(&event->child_list);
7946 
7947 	INIT_LIST_HEAD(&event->group_entry);
7948 	INIT_LIST_HEAD(&event->event_entry);
7949 	INIT_LIST_HEAD(&event->sibling_list);
7950 	INIT_LIST_HEAD(&event->rb_entry);
7951 	INIT_LIST_HEAD(&event->active_entry);
7952 	INIT_HLIST_NODE(&event->hlist_entry);
7953 
7954 
7955 	init_waitqueue_head(&event->waitq);
7956 	init_irq_work(&event->pending, perf_pending_event);
7957 
7958 	mutex_init(&event->mmap_mutex);
7959 
7960 	atomic_long_set(&event->refcount, 1);
7961 	event->cpu		= cpu;
7962 	event->attr		= *attr;
7963 	event->group_leader	= group_leader;
7964 	event->pmu		= NULL;
7965 	event->oncpu		= -1;
7966 
7967 	event->parent		= parent_event;
7968 
7969 	event->ns		= get_pid_ns(task_active_pid_ns(current));
7970 	event->id		= atomic64_inc_return(&perf_event_id);
7971 
7972 	event->state		= PERF_EVENT_STATE_INACTIVE;
7973 
7974 	if (task) {
7975 		event->attach_state = PERF_ATTACH_TASK;
7976 		/*
7977 		 * XXX pmu::event_init needs to know what task to account to
7978 		 * and we cannot use the ctx information because we need the
7979 		 * pmu before we get a ctx.
7980 		 */
7981 		event->hw.target = task;
7982 	}
7983 
7984 	event->clock = &local_clock;
7985 	if (parent_event)
7986 		event->clock = parent_event->clock;
7987 
7988 	if (!overflow_handler && parent_event) {
7989 		overflow_handler = parent_event->overflow_handler;
7990 		context = parent_event->overflow_handler_context;
7991 	}
7992 
7993 	event->overflow_handler	= overflow_handler;
7994 	event->overflow_handler_context = context;
7995 
7996 	perf_event__state_init(event);
7997 
7998 	pmu = NULL;
7999 
8000 	hwc = &event->hw;
8001 	hwc->sample_period = attr->sample_period;
8002 	if (attr->freq && attr->sample_freq)
8003 		hwc->sample_period = 1;
8004 	hwc->last_period = hwc->sample_period;
8005 
8006 	local64_set(&hwc->period_left, hwc->sample_period);
8007 
8008 	/*
8009 	 * We currently do not support PERF_SAMPLE_READ on inherited events.
8010 	 * See perf_output_read().
8011 	 */
8012 	if (attr->inherit && (attr->sample_type & PERF_SAMPLE_READ))
8013 		goto err_ns;
8014 
8015 	if (!has_branch_stack(event))
8016 		event->attr.branch_sample_type = 0;
8017 
8018 	if (cgroup_fd != -1) {
8019 		err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
8020 		if (err)
8021 			goto err_ns;
8022 	}
8023 
8024 	pmu = perf_init_event(event);
8025 	if (!pmu)
8026 		goto err_ns;
8027 	else if (IS_ERR(pmu)) {
8028 		err = PTR_ERR(pmu);
8029 		goto err_ns;
8030 	}
8031 
8032 	err = exclusive_event_init(event);
8033 	if (err)
8034 		goto err_pmu;
8035 
8036 	if (!event->parent) {
8037 		if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
8038 			err = get_callchain_buffers();
8039 			if (err)
8040 				goto err_per_task;
8041 		}
8042 	}
8043 
8044 	/* symmetric to unaccount_event() in _free_event() */
8045 	account_event(event);
8046 
8047 	return event;
8048 
8049 err_per_task:
8050 	exclusive_event_destroy(event);
8051 
8052 err_pmu:
8053 	if (event->destroy)
8054 		event->destroy(event);
8055 	module_put(pmu->module);
8056 err_ns:
8057 	if (is_cgroup_event(event))
8058 		perf_detach_cgroup(event);
8059 	if (event->ns)
8060 		put_pid_ns(event->ns);
8061 	kfree(event);
8062 
8063 	return ERR_PTR(err);
8064 }
8065 
perf_copy_attr(struct perf_event_attr __user * uattr,struct perf_event_attr * attr)8066 static int perf_copy_attr(struct perf_event_attr __user *uattr,
8067 			  struct perf_event_attr *attr)
8068 {
8069 	u32 size;
8070 	int ret;
8071 
8072 	if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
8073 		return -EFAULT;
8074 
8075 	/*
8076 	 * zero the full structure, so that a short copy will be nice.
8077 	 */
8078 	memset(attr, 0, sizeof(*attr));
8079 
8080 	ret = get_user(size, &uattr->size);
8081 	if (ret)
8082 		return ret;
8083 
8084 	if (size > PAGE_SIZE)	/* silly large */
8085 		goto err_size;
8086 
8087 	if (!size)		/* abi compat */
8088 		size = PERF_ATTR_SIZE_VER0;
8089 
8090 	if (size < PERF_ATTR_SIZE_VER0)
8091 		goto err_size;
8092 
8093 	/*
8094 	 * If we're handed a bigger struct than we know of,
8095 	 * ensure all the unknown bits are 0 - i.e. new
8096 	 * user-space does not rely on any kernel feature
8097 	 * extensions we dont know about yet.
8098 	 */
8099 	if (size > sizeof(*attr)) {
8100 		unsigned char __user *addr;
8101 		unsigned char __user *end;
8102 		unsigned char val;
8103 
8104 		addr = (void __user *)uattr + sizeof(*attr);
8105 		end  = (void __user *)uattr + size;
8106 
8107 		for (; addr < end; addr++) {
8108 			ret = get_user(val, addr);
8109 			if (ret)
8110 				return ret;
8111 			if (val)
8112 				goto err_size;
8113 		}
8114 		size = sizeof(*attr);
8115 	}
8116 
8117 	ret = copy_from_user(attr, uattr, size);
8118 	if (ret)
8119 		return -EFAULT;
8120 
8121 	if (attr->__reserved_1)
8122 		return -EINVAL;
8123 
8124 	if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
8125 		return -EINVAL;
8126 
8127 	if (attr->read_format & ~(PERF_FORMAT_MAX-1))
8128 		return -EINVAL;
8129 
8130 	if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
8131 		u64 mask = attr->branch_sample_type;
8132 
8133 		/* only using defined bits */
8134 		if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
8135 			return -EINVAL;
8136 
8137 		/* at least one branch bit must be set */
8138 		if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
8139 			return -EINVAL;
8140 
8141 		/* propagate priv level, when not set for branch */
8142 		if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
8143 
8144 			/* exclude_kernel checked on syscall entry */
8145 			if (!attr->exclude_kernel)
8146 				mask |= PERF_SAMPLE_BRANCH_KERNEL;
8147 
8148 			if (!attr->exclude_user)
8149 				mask |= PERF_SAMPLE_BRANCH_USER;
8150 
8151 			if (!attr->exclude_hv)
8152 				mask |= PERF_SAMPLE_BRANCH_HV;
8153 			/*
8154 			 * adjust user setting (for HW filter setup)
8155 			 */
8156 			attr->branch_sample_type = mask;
8157 		}
8158 		/* privileged levels capture (kernel, hv): check permissions */
8159 		if ((mask & PERF_SAMPLE_BRANCH_PERM_PLM)
8160 		    && perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
8161 			return -EACCES;
8162 	}
8163 
8164 	if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
8165 		ret = perf_reg_validate(attr->sample_regs_user);
8166 		if (ret)
8167 			return ret;
8168 	}
8169 
8170 	if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
8171 		if (!arch_perf_have_user_stack_dump())
8172 			return -ENOSYS;
8173 
8174 		/*
8175 		 * We have __u32 type for the size, but so far
8176 		 * we can only use __u16 as maximum due to the
8177 		 * __u16 sample size limit.
8178 		 */
8179 		if (attr->sample_stack_user >= USHRT_MAX)
8180 			return -EINVAL;
8181 		else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
8182 			return -EINVAL;
8183 	}
8184 
8185 	if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
8186 		ret = perf_reg_validate(attr->sample_regs_intr);
8187 out:
8188 	return ret;
8189 
8190 err_size:
8191 	put_user(sizeof(*attr), &uattr->size);
8192 	ret = -E2BIG;
8193 	goto out;
8194 }
8195 
8196 static int
perf_event_set_output(struct perf_event * event,struct perf_event * output_event)8197 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
8198 {
8199 	struct ring_buffer *rb = NULL;
8200 	int ret = -EINVAL;
8201 
8202 	if (!output_event)
8203 		goto set;
8204 
8205 	/* don't allow circular references */
8206 	if (event == output_event)
8207 		goto out;
8208 
8209 	/*
8210 	 * Don't allow cross-cpu buffers
8211 	 */
8212 	if (output_event->cpu != event->cpu)
8213 		goto out;
8214 
8215 	/*
8216 	 * If its not a per-cpu rb, it must be the same task.
8217 	 */
8218 	if (output_event->cpu == -1 && output_event->ctx != event->ctx)
8219 		goto out;
8220 
8221 	/*
8222 	 * Mixing clocks in the same buffer is trouble you don't need.
8223 	 */
8224 	if (output_event->clock != event->clock)
8225 		goto out;
8226 
8227 	/*
8228 	 * If both events generate aux data, they must be on the same PMU
8229 	 */
8230 	if (has_aux(event) && has_aux(output_event) &&
8231 	    event->pmu != output_event->pmu)
8232 		goto out;
8233 
8234 set:
8235 	mutex_lock(&event->mmap_mutex);
8236 	/* Can't redirect output if we've got an active mmap() */
8237 	if (atomic_read(&event->mmap_count))
8238 		goto unlock;
8239 
8240 	if (output_event) {
8241 		/* get the rb we want to redirect to */
8242 		rb = ring_buffer_get(output_event);
8243 		if (!rb)
8244 			goto unlock;
8245 	}
8246 
8247 	ring_buffer_attach(event, rb);
8248 
8249 	ret = 0;
8250 unlock:
8251 	mutex_unlock(&event->mmap_mutex);
8252 
8253 out:
8254 	return ret;
8255 }
8256 
mutex_lock_double(struct mutex * a,struct mutex * b)8257 static void mutex_lock_double(struct mutex *a, struct mutex *b)
8258 {
8259 	if (b < a)
8260 		swap(a, b);
8261 
8262 	mutex_lock(a);
8263 	mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
8264 }
8265 
perf_event_set_clock(struct perf_event * event,clockid_t clk_id)8266 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
8267 {
8268 	bool nmi_safe = false;
8269 
8270 	switch (clk_id) {
8271 	case CLOCK_MONOTONIC:
8272 		event->clock = &ktime_get_mono_fast_ns;
8273 		nmi_safe = true;
8274 		break;
8275 
8276 	case CLOCK_MONOTONIC_RAW:
8277 		event->clock = &ktime_get_raw_fast_ns;
8278 		nmi_safe = true;
8279 		break;
8280 
8281 	case CLOCK_REALTIME:
8282 		event->clock = &ktime_get_real_ns;
8283 		break;
8284 
8285 	case CLOCK_BOOTTIME:
8286 		event->clock = &ktime_get_boot_ns;
8287 		break;
8288 
8289 	case CLOCK_TAI:
8290 		event->clock = &ktime_get_tai_ns;
8291 		break;
8292 
8293 	default:
8294 		return -EINVAL;
8295 	}
8296 
8297 	if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
8298 		return -EINVAL;
8299 
8300 	return 0;
8301 }
8302 
8303 /*
8304  * Variation on perf_event_ctx_lock_nested(), except we take two context
8305  * mutexes.
8306  */
8307 static struct perf_event_context *
__perf_event_ctx_lock_double(struct perf_event * group_leader,struct perf_event_context * ctx)8308 __perf_event_ctx_lock_double(struct perf_event *group_leader,
8309 			     struct perf_event_context *ctx)
8310 {
8311 	struct perf_event_context *gctx;
8312 
8313 again:
8314 	rcu_read_lock();
8315 	gctx = READ_ONCE(group_leader->ctx);
8316 	if (!atomic_inc_not_zero(&gctx->refcount)) {
8317 		rcu_read_unlock();
8318 		goto again;
8319 	}
8320 	rcu_read_unlock();
8321 
8322 	mutex_lock_double(&gctx->mutex, &ctx->mutex);
8323 
8324 	if (group_leader->ctx != gctx) {
8325 		mutex_unlock(&ctx->mutex);
8326 		mutex_unlock(&gctx->mutex);
8327 		put_ctx(gctx);
8328 		goto again;
8329 	}
8330 
8331 	return gctx;
8332 }
8333 
8334 /**
8335  * sys_perf_event_open - open a performance event, associate it to a task/cpu
8336  *
8337  * @attr_uptr:	event_id type attributes for monitoring/sampling
8338  * @pid:		target pid
8339  * @cpu:		target cpu
8340  * @group_fd:		group leader event fd
8341  */
SYSCALL_DEFINE5(perf_event_open,struct perf_event_attr __user *,attr_uptr,pid_t,pid,int,cpu,int,group_fd,unsigned long,flags)8342 SYSCALL_DEFINE5(perf_event_open,
8343 		struct perf_event_attr __user *, attr_uptr,
8344 		pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
8345 {
8346 	struct perf_event *group_leader = NULL, *output_event = NULL;
8347 	struct perf_event *event, *sibling;
8348 	struct perf_event_attr attr;
8349 	struct perf_event_context *ctx, *uninitialized_var(gctx);
8350 	struct file *event_file = NULL;
8351 	struct fd group = {NULL, 0};
8352 	struct task_struct *task = NULL;
8353 	struct pmu *pmu;
8354 	int event_fd;
8355 	int move_group = 0;
8356 	int err;
8357 	int f_flags = O_RDWR;
8358 	int cgroup_fd = -1;
8359 
8360 	/* for future expandability... */
8361 	if (flags & ~PERF_FLAG_ALL)
8362 		return -EINVAL;
8363 
8364 	if (perf_paranoid_any() && !capable(CAP_SYS_ADMIN))
8365 		return -EACCES;
8366 
8367 	err = perf_copy_attr(attr_uptr, &attr);
8368 	if (err)
8369 		return err;
8370 
8371 	if (!attr.exclude_kernel) {
8372 		if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
8373 			return -EACCES;
8374 	}
8375 
8376 	if (attr.freq) {
8377 		if (attr.sample_freq > sysctl_perf_event_sample_rate)
8378 			return -EINVAL;
8379 	} else {
8380 		if (attr.sample_period & (1ULL << 63))
8381 			return -EINVAL;
8382 	}
8383 
8384 	/*
8385 	 * In cgroup mode, the pid argument is used to pass the fd
8386 	 * opened to the cgroup directory in cgroupfs. The cpu argument
8387 	 * designates the cpu on which to monitor threads from that
8388 	 * cgroup.
8389 	 */
8390 	if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
8391 		return -EINVAL;
8392 
8393 	if (flags & PERF_FLAG_FD_CLOEXEC)
8394 		f_flags |= O_CLOEXEC;
8395 
8396 	event_fd = get_unused_fd_flags(f_flags);
8397 	if (event_fd < 0)
8398 		return event_fd;
8399 
8400 	if (group_fd != -1) {
8401 		err = perf_fget_light(group_fd, &group);
8402 		if (err)
8403 			goto err_fd;
8404 		group_leader = group.file->private_data;
8405 		if (flags & PERF_FLAG_FD_OUTPUT)
8406 			output_event = group_leader;
8407 		if (flags & PERF_FLAG_FD_NO_GROUP)
8408 			group_leader = NULL;
8409 	}
8410 
8411 	if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
8412 		task = find_lively_task_by_vpid(pid);
8413 		if (IS_ERR(task)) {
8414 			err = PTR_ERR(task);
8415 			goto err_group_fd;
8416 		}
8417 	}
8418 
8419 	if (task && group_leader &&
8420 	    group_leader->attr.inherit != attr.inherit) {
8421 		err = -EINVAL;
8422 		goto err_task;
8423 	}
8424 
8425 	get_online_cpus();
8426 
8427 	if (task) {
8428 		err = mutex_lock_interruptible(&task->signal->cred_guard_mutex);
8429 		if (err)
8430 			goto err_cpus;
8431 
8432 		/*
8433 		 * Reuse ptrace permission checks for now.
8434 		 *
8435 		 * We must hold cred_guard_mutex across this and any potential
8436 		 * perf_install_in_context() call for this new event to
8437 		 * serialize against exec() altering our credentials (and the
8438 		 * perf_event_exit_task() that could imply).
8439 		 */
8440 		err = -EACCES;
8441 		if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS))
8442 			goto err_cred;
8443 	}
8444 
8445 	if (flags & PERF_FLAG_PID_CGROUP)
8446 		cgroup_fd = pid;
8447 
8448 	event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
8449 				 NULL, NULL, cgroup_fd);
8450 	if (IS_ERR(event)) {
8451 		err = PTR_ERR(event);
8452 		goto err_cred;
8453 	}
8454 
8455 	if (is_sampling_event(event)) {
8456 		if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
8457 			err = -ENOTSUPP;
8458 			goto err_alloc;
8459 		}
8460 	}
8461 
8462 	/*
8463 	 * Special case software events and allow them to be part of
8464 	 * any hardware group.
8465 	 */
8466 	pmu = event->pmu;
8467 
8468 	if (attr.use_clockid) {
8469 		err = perf_event_set_clock(event, attr.clockid);
8470 		if (err)
8471 			goto err_alloc;
8472 	}
8473 
8474 	if (group_leader &&
8475 	    (is_software_event(event) != is_software_event(group_leader))) {
8476 		if (is_software_event(event)) {
8477 			/*
8478 			 * If event and group_leader are not both a software
8479 			 * event, and event is, then group leader is not.
8480 			 *
8481 			 * Allow the addition of software events to !software
8482 			 * groups, this is safe because software events never
8483 			 * fail to schedule.
8484 			 */
8485 			pmu = group_leader->pmu;
8486 		} else if (is_software_event(group_leader) &&
8487 			   (group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
8488 			/*
8489 			 * In case the group is a pure software group, and we
8490 			 * try to add a hardware event, move the whole group to
8491 			 * the hardware context.
8492 			 */
8493 			move_group = 1;
8494 		}
8495 	}
8496 
8497 	/*
8498 	 * Get the target context (task or percpu):
8499 	 */
8500 	ctx = find_get_context(pmu, task, event);
8501 	if (IS_ERR(ctx)) {
8502 		err = PTR_ERR(ctx);
8503 		goto err_alloc;
8504 	}
8505 
8506 	if ((pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) && group_leader) {
8507 		err = -EBUSY;
8508 		goto err_context;
8509 	}
8510 
8511 	/*
8512 	 * Look up the group leader (we will attach this event to it):
8513 	 */
8514 	if (group_leader) {
8515 		err = -EINVAL;
8516 
8517 		/*
8518 		 * Do not allow a recursive hierarchy (this new sibling
8519 		 * becoming part of another group-sibling):
8520 		 */
8521 		if (group_leader->group_leader != group_leader)
8522 			goto err_context;
8523 
8524 		/* All events in a group should have the same clock */
8525 		if (group_leader->clock != event->clock)
8526 			goto err_context;
8527 
8528 		/*
8529 		 * Make sure we're both events for the same CPU;
8530 		 * grouping events for different CPUs is broken; since
8531 		 * you can never concurrently schedule them anyhow.
8532 		 */
8533 		if (group_leader->cpu != event->cpu)
8534 			goto err_context;
8535 
8536 		/*
8537 		 * Make sure we're both on the same task, or both
8538 		 * per-CPU events.
8539 		 */
8540 		if (group_leader->ctx->task != ctx->task)
8541 			goto err_context;
8542 
8543 		/*
8544 		 * Do not allow to attach to a group in a different task
8545 		 * or CPU context. If we're moving SW events, we'll fix
8546 		 * this up later, so allow that.
8547 		 */
8548 		if (!move_group && group_leader->ctx != ctx)
8549 			goto err_context;
8550 
8551 		/*
8552 		 * Only a group leader can be exclusive or pinned
8553 		 */
8554 		if (attr.exclusive || attr.pinned)
8555 			goto err_context;
8556 	}
8557 
8558 	if (output_event) {
8559 		err = perf_event_set_output(event, output_event);
8560 		if (err)
8561 			goto err_context;
8562 	}
8563 
8564 	event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
8565 					f_flags);
8566 	if (IS_ERR(event_file)) {
8567 		err = PTR_ERR(event_file);
8568 		event_file = NULL;
8569 		goto err_context;
8570 	}
8571 
8572 	if (move_group) {
8573 		gctx = __perf_event_ctx_lock_double(group_leader, ctx);
8574 
8575 		/*
8576 		 * Check if we raced against another sys_perf_event_open() call
8577 		 * moving the software group underneath us.
8578 		 */
8579 		if (!(group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
8580 			/*
8581 			 * If someone moved the group out from under us, check
8582 			 * if this new event wound up on the same ctx, if so
8583 			 * its the regular !move_group case, otherwise fail.
8584 			 */
8585 			if (gctx != ctx) {
8586 				err = -EINVAL;
8587 				goto err_locked;
8588 			} else {
8589 				perf_event_ctx_unlock(group_leader, gctx);
8590 				move_group = 0;
8591 			}
8592 		}
8593 	} else {
8594 		mutex_lock(&ctx->mutex);
8595 	}
8596 
8597 	if (!perf_event_validate_size(event)) {
8598 		err = -E2BIG;
8599 		goto err_locked;
8600 	}
8601 
8602 	/*
8603 	 * Must be under the same ctx::mutex as perf_install_in_context(),
8604 	 * because we need to serialize with concurrent event creation.
8605 	 */
8606 	if (!exclusive_event_installable(event, ctx)) {
8607 		/* exclusive and group stuff are assumed mutually exclusive */
8608 		WARN_ON_ONCE(move_group);
8609 
8610 		err = -EBUSY;
8611 		goto err_locked;
8612 	}
8613 
8614 	WARN_ON_ONCE(ctx->parent_ctx);
8615 
8616 	/*
8617 	 * This is the point on no return; we cannot fail hereafter. This is
8618 	 * where we start modifying current state.
8619 	 */
8620 
8621 	if (move_group) {
8622 		/*
8623 		 * See perf_event_ctx_lock() for comments on the details
8624 		 * of swizzling perf_event::ctx.
8625 		 */
8626 		perf_remove_from_context(group_leader, false);
8627 
8628 		list_for_each_entry(sibling, &group_leader->sibling_list,
8629 				    group_entry) {
8630 			perf_remove_from_context(sibling, false);
8631 			put_ctx(gctx);
8632 		}
8633 
8634 		/*
8635 		 * Wait for everybody to stop referencing the events through
8636 		 * the old lists, before installing it on new lists.
8637 		 */
8638 		synchronize_rcu();
8639 
8640 		/*
8641 		 * Install the group siblings before the group leader.
8642 		 *
8643 		 * Because a group leader will try and install the entire group
8644 		 * (through the sibling list, which is still in-tact), we can
8645 		 * end up with siblings installed in the wrong context.
8646 		 *
8647 		 * By installing siblings first we NO-OP because they're not
8648 		 * reachable through the group lists.
8649 		 */
8650 		list_for_each_entry(sibling, &group_leader->sibling_list,
8651 				    group_entry) {
8652 			perf_event__state_init(sibling);
8653 			perf_install_in_context(ctx, sibling, sibling->cpu);
8654 			get_ctx(ctx);
8655 		}
8656 
8657 		/*
8658 		 * Removing from the context ends up with disabled
8659 		 * event. What we want here is event in the initial
8660 		 * startup state, ready to be add into new context.
8661 		 */
8662 		perf_event__state_init(group_leader);
8663 		perf_install_in_context(ctx, group_leader, group_leader->cpu);
8664 		get_ctx(ctx);
8665 
8666 		/*
8667 		 * Now that all events are installed in @ctx, nothing
8668 		 * references @gctx anymore, so drop the last reference we have
8669 		 * on it.
8670 		 */
8671 		put_ctx(gctx);
8672 	}
8673 
8674 	/*
8675 	 * Precalculate sample_data sizes; do while holding ctx::mutex such
8676 	 * that we're serialized against further additions and before
8677 	 * perf_install_in_context() which is the point the event is active and
8678 	 * can use these values.
8679 	 */
8680 	perf_event__header_size(event);
8681 	perf_event__id_header_size(event);
8682 
8683 	perf_install_in_context(ctx, event, event->cpu);
8684 	perf_unpin_context(ctx);
8685 
8686 	if (move_group)
8687 		perf_event_ctx_unlock(group_leader, gctx);
8688 	mutex_unlock(&ctx->mutex);
8689 
8690 	if (task) {
8691 		mutex_unlock(&task->signal->cred_guard_mutex);
8692 		put_task_struct(task);
8693 	}
8694 
8695 	put_online_cpus();
8696 
8697 	event->owner = current;
8698 
8699 	mutex_lock(&current->perf_event_mutex);
8700 	list_add_tail(&event->owner_entry, &current->perf_event_list);
8701 	mutex_unlock(&current->perf_event_mutex);
8702 
8703 	/*
8704 	 * Drop the reference on the group_event after placing the
8705 	 * new event on the sibling_list. This ensures destruction
8706 	 * of the group leader will find the pointer to itself in
8707 	 * perf_group_detach().
8708 	 */
8709 	fdput(group);
8710 	fd_install(event_fd, event_file);
8711 	return event_fd;
8712 
8713 err_locked:
8714 	if (move_group)
8715 		perf_event_ctx_unlock(group_leader, gctx);
8716 	mutex_unlock(&ctx->mutex);
8717 /* err_file: */
8718 	fput(event_file);
8719 err_context:
8720 	perf_unpin_context(ctx);
8721 	put_ctx(ctx);
8722 err_alloc:
8723 	/*
8724 	 * If event_file is set, the fput() above will have called ->release()
8725 	 * and that will take care of freeing the event.
8726 	 */
8727 	if (!event_file)
8728 		free_event(event);
8729 err_cred:
8730 	if (task)
8731 		mutex_unlock(&task->signal->cred_guard_mutex);
8732 err_cpus:
8733 	put_online_cpus();
8734 err_task:
8735 	if (task)
8736 		put_task_struct(task);
8737 err_group_fd:
8738 	fdput(group);
8739 err_fd:
8740 	put_unused_fd(event_fd);
8741 	return err;
8742 }
8743 
8744 /**
8745  * perf_event_create_kernel_counter
8746  *
8747  * @attr: attributes of the counter to create
8748  * @cpu: cpu in which the counter is bound
8749  * @task: task to profile (NULL for percpu)
8750  */
8751 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)8752 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
8753 				 struct task_struct *task,
8754 				 perf_overflow_handler_t overflow_handler,
8755 				 void *context)
8756 {
8757 	struct perf_event_context *ctx;
8758 	struct perf_event *event;
8759 	int err;
8760 
8761 	/*
8762 	 * Get the target context (task or percpu):
8763 	 */
8764 
8765 	event = perf_event_alloc(attr, cpu, task, NULL, NULL,
8766 				 overflow_handler, context, -1);
8767 	if (IS_ERR(event)) {
8768 		err = PTR_ERR(event);
8769 		goto err;
8770 	}
8771 
8772 	/* Mark owner so we could distinguish it from user events. */
8773 	event->owner = EVENT_OWNER_KERNEL;
8774 
8775 	ctx = find_get_context(event->pmu, task, event);
8776 	if (IS_ERR(ctx)) {
8777 		err = PTR_ERR(ctx);
8778 		goto err_free;
8779 	}
8780 
8781 	WARN_ON_ONCE(ctx->parent_ctx);
8782 	mutex_lock(&ctx->mutex);
8783 	if (!exclusive_event_installable(event, ctx)) {
8784 		mutex_unlock(&ctx->mutex);
8785 		perf_unpin_context(ctx);
8786 		put_ctx(ctx);
8787 		err = -EBUSY;
8788 		goto err_free;
8789 	}
8790 
8791 	perf_install_in_context(ctx, event, event->cpu);
8792 	perf_unpin_context(ctx);
8793 	mutex_unlock(&ctx->mutex);
8794 
8795 	return event;
8796 
8797 err_free:
8798 	free_event(event);
8799 err:
8800 	return ERR_PTR(err);
8801 }
8802 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
8803 
perf_pmu_migrate_context(struct pmu * pmu,int src_cpu,int dst_cpu)8804 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
8805 {
8806 	struct perf_event_context *src_ctx;
8807 	struct perf_event_context *dst_ctx;
8808 	struct perf_event *event, *tmp;
8809 	LIST_HEAD(events);
8810 
8811 	src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
8812 	dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
8813 
8814 	/*
8815 	 * See perf_event_ctx_lock() for comments on the details
8816 	 * of swizzling perf_event::ctx.
8817 	 */
8818 	mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
8819 	list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
8820 				 event_entry) {
8821 		perf_remove_from_context(event, false);
8822 		unaccount_event_cpu(event, src_cpu);
8823 		put_ctx(src_ctx);
8824 		list_add(&event->migrate_entry, &events);
8825 	}
8826 
8827 	/*
8828 	 * Wait for the events to quiesce before re-instating them.
8829 	 */
8830 	synchronize_rcu();
8831 
8832 	/*
8833 	 * Re-instate events in 2 passes.
8834 	 *
8835 	 * Skip over group leaders and only install siblings on this first
8836 	 * pass, siblings will not get enabled without a leader, however a
8837 	 * leader will enable its siblings, even if those are still on the old
8838 	 * context.
8839 	 */
8840 	list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
8841 		if (event->group_leader == event)
8842 			continue;
8843 
8844 		list_del(&event->migrate_entry);
8845 		if (event->state >= PERF_EVENT_STATE_OFF)
8846 			event->state = PERF_EVENT_STATE_INACTIVE;
8847 		account_event_cpu(event, dst_cpu);
8848 		perf_install_in_context(dst_ctx, event, dst_cpu);
8849 		get_ctx(dst_ctx);
8850 	}
8851 
8852 	/*
8853 	 * Once all the siblings are setup properly, install the group leaders
8854 	 * to make it go.
8855 	 */
8856 	list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
8857 		list_del(&event->migrate_entry);
8858 		if (event->state >= PERF_EVENT_STATE_OFF)
8859 			event->state = PERF_EVENT_STATE_INACTIVE;
8860 		account_event_cpu(event, dst_cpu);
8861 		perf_install_in_context(dst_ctx, event, dst_cpu);
8862 		get_ctx(dst_ctx);
8863 	}
8864 	mutex_unlock(&dst_ctx->mutex);
8865 	mutex_unlock(&src_ctx->mutex);
8866 }
8867 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
8868 
sync_child_event(struct perf_event * child_event,struct task_struct * child)8869 static void sync_child_event(struct perf_event *child_event,
8870 			       struct task_struct *child)
8871 {
8872 	struct perf_event *parent_event = child_event->parent;
8873 	u64 child_val;
8874 
8875 	if (child_event->attr.inherit_stat)
8876 		perf_event_read_event(child_event, child);
8877 
8878 	child_val = perf_event_count(child_event);
8879 
8880 	/*
8881 	 * Add back the child's count to the parent's count:
8882 	 */
8883 	atomic64_add(child_val, &parent_event->child_count);
8884 	atomic64_add(child_event->total_time_enabled,
8885 		     &parent_event->child_total_time_enabled);
8886 	atomic64_add(child_event->total_time_running,
8887 		     &parent_event->child_total_time_running);
8888 
8889 	/*
8890 	 * Remove this event from the parent's list
8891 	 */
8892 	WARN_ON_ONCE(parent_event->ctx->parent_ctx);
8893 	mutex_lock(&parent_event->child_mutex);
8894 	list_del_init(&child_event->child_list);
8895 	mutex_unlock(&parent_event->child_mutex);
8896 
8897 	/*
8898 	 * Make sure user/parent get notified, that we just
8899 	 * lost one event.
8900 	 */
8901 	perf_event_wakeup(parent_event);
8902 
8903 	/*
8904 	 * Release the parent event, if this was the last
8905 	 * reference to it.
8906 	 */
8907 	put_event(parent_event);
8908 }
8909 
8910 static void
__perf_event_exit_task(struct perf_event * child_event,struct perf_event_context * child_ctx,struct task_struct * child)8911 __perf_event_exit_task(struct perf_event *child_event,
8912 			 struct perf_event_context *child_ctx,
8913 			 struct task_struct *child)
8914 {
8915 	/*
8916 	 * Do not destroy the 'original' grouping; because of the context
8917 	 * switch optimization the original events could've ended up in a
8918 	 * random child task.
8919 	 *
8920 	 * If we were to destroy the original group, all group related
8921 	 * operations would cease to function properly after this random
8922 	 * child dies.
8923 	 *
8924 	 * Do destroy all inherited groups, we don't care about those
8925 	 * and being thorough is better.
8926 	 */
8927 	perf_remove_from_context(child_event, !!child_event->parent);
8928 
8929 	/*
8930 	 * It can happen that the parent exits first, and has events
8931 	 * that are still around due to the child reference. These
8932 	 * events need to be zapped.
8933 	 */
8934 	if (child_event->parent) {
8935 		sync_child_event(child_event, child);
8936 		free_event(child_event);
8937 	} else {
8938 		child_event->state = PERF_EVENT_STATE_EXIT;
8939 		perf_event_wakeup(child_event);
8940 	}
8941 }
8942 
perf_event_exit_task_context(struct task_struct * child,int ctxn)8943 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
8944 {
8945 	struct perf_event *child_event, *next;
8946 	struct perf_event_context *child_ctx, *clone_ctx = NULL;
8947 	unsigned long flags;
8948 
8949 	if (likely(!child->perf_event_ctxp[ctxn]))
8950 		return;
8951 
8952 	local_irq_save(flags);
8953 	/*
8954 	 * We can't reschedule here because interrupts are disabled,
8955 	 * and either child is current or it is a task that can't be
8956 	 * scheduled, so we are now safe from rescheduling changing
8957 	 * our context.
8958 	 */
8959 	child_ctx = rcu_dereference_raw(child->perf_event_ctxp[ctxn]);
8960 
8961 	/*
8962 	 * Take the context lock here so that if find_get_context is
8963 	 * reading child->perf_event_ctxp, we wait until it has
8964 	 * incremented the context's refcount before we do put_ctx below.
8965 	 */
8966 	raw_spin_lock(&child_ctx->lock);
8967 	task_ctx_sched_out(child_ctx);
8968 	child->perf_event_ctxp[ctxn] = NULL;
8969 
8970 	/*
8971 	 * If this context is a clone; unclone it so it can't get
8972 	 * swapped to another process while we're removing all
8973 	 * the events from it.
8974 	 */
8975 	clone_ctx = unclone_ctx(child_ctx);
8976 	update_context_time(child_ctx);
8977 	raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
8978 
8979 	if (clone_ctx)
8980 		put_ctx(clone_ctx);
8981 
8982 	/*
8983 	 * Report the task dead after unscheduling the events so that we
8984 	 * won't get any samples after PERF_RECORD_EXIT. We can however still
8985 	 * get a few PERF_RECORD_READ events.
8986 	 */
8987 	perf_event_task(child, child_ctx, 0);
8988 
8989 	/*
8990 	 * We can recurse on the same lock type through:
8991 	 *
8992 	 *   __perf_event_exit_task()
8993 	 *     sync_child_event()
8994 	 *       put_event()
8995 	 *         mutex_lock(&ctx->mutex)
8996 	 *
8997 	 * But since its the parent context it won't be the same instance.
8998 	 */
8999 	mutex_lock(&child_ctx->mutex);
9000 
9001 	list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
9002 		__perf_event_exit_task(child_event, child_ctx, child);
9003 
9004 	mutex_unlock(&child_ctx->mutex);
9005 
9006 	put_ctx(child_ctx);
9007 }
9008 
9009 /*
9010  * When a child task exits, feed back event values to parent events.
9011  *
9012  * Can be called with cred_guard_mutex held when called from
9013  * install_exec_creds().
9014  */
perf_event_exit_task(struct task_struct * child)9015 void perf_event_exit_task(struct task_struct *child)
9016 {
9017 	struct perf_event *event, *tmp;
9018 	int ctxn;
9019 
9020 	mutex_lock(&child->perf_event_mutex);
9021 	list_for_each_entry_safe(event, tmp, &child->perf_event_list,
9022 				 owner_entry) {
9023 		list_del_init(&event->owner_entry);
9024 
9025 		/*
9026 		 * Ensure the list deletion is visible before we clear
9027 		 * the owner, closes a race against perf_release() where
9028 		 * we need to serialize on the owner->perf_event_mutex.
9029 		 */
9030 		smp_wmb();
9031 		event->owner = NULL;
9032 	}
9033 	mutex_unlock(&child->perf_event_mutex);
9034 
9035 	for_each_task_context_nr(ctxn)
9036 		perf_event_exit_task_context(child, ctxn);
9037 
9038 	/*
9039 	 * The perf_event_exit_task_context calls perf_event_task
9040 	 * with child's task_ctx, which generates EXIT events for
9041 	 * child contexts and sets child->perf_event_ctxp[] to NULL.
9042 	 * At this point we need to send EXIT events to cpu contexts.
9043 	 */
9044 	perf_event_task(child, NULL, 0);
9045 }
9046 
perf_free_event(struct perf_event * event,struct perf_event_context * ctx)9047 static void perf_free_event(struct perf_event *event,
9048 			    struct perf_event_context *ctx)
9049 {
9050 	struct perf_event *parent = event->parent;
9051 
9052 	if (WARN_ON_ONCE(!parent))
9053 		return;
9054 
9055 	mutex_lock(&parent->child_mutex);
9056 	list_del_init(&event->child_list);
9057 	mutex_unlock(&parent->child_mutex);
9058 
9059 	put_event(parent);
9060 
9061 	raw_spin_lock_irq(&ctx->lock);
9062 	perf_group_detach(event);
9063 	list_del_event(event, ctx);
9064 	raw_spin_unlock_irq(&ctx->lock);
9065 	free_event(event);
9066 }
9067 
9068 /*
9069  * Free an unexposed, unused context as created by inheritance by
9070  * perf_event_init_task below, used by fork() in case of fail.
9071  *
9072  * Not all locks are strictly required, but take them anyway to be nice and
9073  * help out with the lockdep assertions.
9074  */
perf_event_free_task(struct task_struct * task)9075 void perf_event_free_task(struct task_struct *task)
9076 {
9077 	struct perf_event_context *ctx;
9078 	struct perf_event *event, *tmp;
9079 	int ctxn;
9080 
9081 	for_each_task_context_nr(ctxn) {
9082 		ctx = task->perf_event_ctxp[ctxn];
9083 		if (!ctx)
9084 			continue;
9085 
9086 		mutex_lock(&ctx->mutex);
9087 again:
9088 		list_for_each_entry_safe(event, tmp, &ctx->pinned_groups,
9089 				group_entry)
9090 			perf_free_event(event, ctx);
9091 
9092 		list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
9093 				group_entry)
9094 			perf_free_event(event, ctx);
9095 
9096 		if (!list_empty(&ctx->pinned_groups) ||
9097 				!list_empty(&ctx->flexible_groups))
9098 			goto again;
9099 
9100 		mutex_unlock(&ctx->mutex);
9101 
9102 		put_ctx(ctx);
9103 	}
9104 }
9105 
perf_event_delayed_put(struct task_struct * task)9106 void perf_event_delayed_put(struct task_struct *task)
9107 {
9108 	int ctxn;
9109 
9110 	for_each_task_context_nr(ctxn)
9111 		WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
9112 }
9113 
perf_event_get(unsigned int fd)9114 struct perf_event *perf_event_get(unsigned int fd)
9115 {
9116 	int err;
9117 	struct fd f;
9118 	struct perf_event *event;
9119 
9120 	err = perf_fget_light(fd, &f);
9121 	if (err)
9122 		return ERR_PTR(err);
9123 
9124 	event = f.file->private_data;
9125 	atomic_long_inc(&event->refcount);
9126 	fdput(f);
9127 
9128 	return event;
9129 }
9130 
perf_event_attrs(struct perf_event * event)9131 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
9132 {
9133 	if (!event)
9134 		return ERR_PTR(-EINVAL);
9135 
9136 	return &event->attr;
9137 }
9138 
9139 /*
9140  * inherit a event from parent task to child task:
9141  */
9142 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)9143 inherit_event(struct perf_event *parent_event,
9144 	      struct task_struct *parent,
9145 	      struct perf_event_context *parent_ctx,
9146 	      struct task_struct *child,
9147 	      struct perf_event *group_leader,
9148 	      struct perf_event_context *child_ctx)
9149 {
9150 	enum perf_event_active_state parent_state = parent_event->state;
9151 	struct perf_event *child_event;
9152 	unsigned long flags;
9153 
9154 	/*
9155 	 * Instead of creating recursive hierarchies of events,
9156 	 * we link inherited events back to the original parent,
9157 	 * which has a filp for sure, which we use as the reference
9158 	 * count:
9159 	 */
9160 	if (parent_event->parent)
9161 		parent_event = parent_event->parent;
9162 
9163 	child_event = perf_event_alloc(&parent_event->attr,
9164 					   parent_event->cpu,
9165 					   child,
9166 					   group_leader, parent_event,
9167 					   NULL, NULL, -1);
9168 	if (IS_ERR(child_event))
9169 		return child_event;
9170 
9171 	if (is_orphaned_event(parent_event) ||
9172 	    !atomic_long_inc_not_zero(&parent_event->refcount)) {
9173 		free_event(child_event);
9174 		return NULL;
9175 	}
9176 
9177 	get_ctx(child_ctx);
9178 
9179 	/*
9180 	 * Make the child state follow the state of the parent event,
9181 	 * not its attr.disabled bit.  We hold the parent's mutex,
9182 	 * so we won't race with perf_event_{en, dis}able_family.
9183 	 */
9184 	if (parent_state >= PERF_EVENT_STATE_INACTIVE)
9185 		child_event->state = PERF_EVENT_STATE_INACTIVE;
9186 	else
9187 		child_event->state = PERF_EVENT_STATE_OFF;
9188 
9189 	if (parent_event->attr.freq) {
9190 		u64 sample_period = parent_event->hw.sample_period;
9191 		struct hw_perf_event *hwc = &child_event->hw;
9192 
9193 		hwc->sample_period = sample_period;
9194 		hwc->last_period   = sample_period;
9195 
9196 		local64_set(&hwc->period_left, sample_period);
9197 	}
9198 
9199 	child_event->ctx = child_ctx;
9200 	child_event->overflow_handler = parent_event->overflow_handler;
9201 	child_event->overflow_handler_context
9202 		= parent_event->overflow_handler_context;
9203 
9204 	/*
9205 	 * Precalculate sample_data sizes
9206 	 */
9207 	perf_event__header_size(child_event);
9208 	perf_event__id_header_size(child_event);
9209 
9210 	/*
9211 	 * Link it up in the child's context:
9212 	 */
9213 	raw_spin_lock_irqsave(&child_ctx->lock, flags);
9214 	add_event_to_ctx(child_event, child_ctx);
9215 	raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
9216 
9217 	/*
9218 	 * Link this into the parent event's child list
9219 	 */
9220 	WARN_ON_ONCE(parent_event->ctx->parent_ctx);
9221 	mutex_lock(&parent_event->child_mutex);
9222 	list_add_tail(&child_event->child_list, &parent_event->child_list);
9223 	mutex_unlock(&parent_event->child_mutex);
9224 
9225 	return child_event;
9226 }
9227 
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)9228 static int inherit_group(struct perf_event *parent_event,
9229 	      struct task_struct *parent,
9230 	      struct perf_event_context *parent_ctx,
9231 	      struct task_struct *child,
9232 	      struct perf_event_context *child_ctx)
9233 {
9234 	struct perf_event *leader;
9235 	struct perf_event *sub;
9236 	struct perf_event *child_ctr;
9237 
9238 	leader = inherit_event(parent_event, parent, parent_ctx,
9239 				 child, NULL, child_ctx);
9240 	if (IS_ERR(leader))
9241 		return PTR_ERR(leader);
9242 	list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
9243 		child_ctr = inherit_event(sub, parent, parent_ctx,
9244 					    child, leader, child_ctx);
9245 		if (IS_ERR(child_ctr))
9246 			return PTR_ERR(child_ctr);
9247 	}
9248 	return 0;
9249 }
9250 
9251 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)9252 inherit_task_group(struct perf_event *event, struct task_struct *parent,
9253 		   struct perf_event_context *parent_ctx,
9254 		   struct task_struct *child, int ctxn,
9255 		   int *inherited_all)
9256 {
9257 	int ret;
9258 	struct perf_event_context *child_ctx;
9259 
9260 	if (!event->attr.inherit) {
9261 		*inherited_all = 0;
9262 		return 0;
9263 	}
9264 
9265 	child_ctx = child->perf_event_ctxp[ctxn];
9266 	if (!child_ctx) {
9267 		/*
9268 		 * This is executed from the parent task context, so
9269 		 * inherit events that have been marked for cloning.
9270 		 * First allocate and initialize a context for the
9271 		 * child.
9272 		 */
9273 
9274 		child_ctx = alloc_perf_context(parent_ctx->pmu, child);
9275 		if (!child_ctx)
9276 			return -ENOMEM;
9277 
9278 		child->perf_event_ctxp[ctxn] = child_ctx;
9279 	}
9280 
9281 	ret = inherit_group(event, parent, parent_ctx,
9282 			    child, child_ctx);
9283 
9284 	if (ret)
9285 		*inherited_all = 0;
9286 
9287 	return ret;
9288 }
9289 
9290 /*
9291  * Initialize the perf_event context in task_struct
9292  */
perf_event_init_context(struct task_struct * child,int ctxn)9293 static int perf_event_init_context(struct task_struct *child, int ctxn)
9294 {
9295 	struct perf_event_context *child_ctx, *parent_ctx;
9296 	struct perf_event_context *cloned_ctx;
9297 	struct perf_event *event;
9298 	struct task_struct *parent = current;
9299 	int inherited_all = 1;
9300 	unsigned long flags;
9301 	int ret = 0;
9302 
9303 	if (likely(!parent->perf_event_ctxp[ctxn]))
9304 		return 0;
9305 
9306 	/*
9307 	 * If the parent's context is a clone, pin it so it won't get
9308 	 * swapped under us.
9309 	 */
9310 	parent_ctx = perf_pin_task_context(parent, ctxn);
9311 	if (!parent_ctx)
9312 		return 0;
9313 
9314 	/*
9315 	 * No need to check if parent_ctx != NULL here; since we saw
9316 	 * it non-NULL earlier, the only reason for it to become NULL
9317 	 * is if we exit, and since we're currently in the middle of
9318 	 * a fork we can't be exiting at the same time.
9319 	 */
9320 
9321 	/*
9322 	 * Lock the parent list. No need to lock the child - not PID
9323 	 * hashed yet and not running, so nobody can access it.
9324 	 */
9325 	mutex_lock(&parent_ctx->mutex);
9326 
9327 	/*
9328 	 * We dont have to disable NMIs - we are only looking at
9329 	 * the list, not manipulating it:
9330 	 */
9331 	list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
9332 		ret = inherit_task_group(event, parent, parent_ctx,
9333 					 child, ctxn, &inherited_all);
9334 		if (ret)
9335 			goto out_unlock;
9336 	}
9337 
9338 	/*
9339 	 * We can't hold ctx->lock when iterating the ->flexible_group list due
9340 	 * to allocations, but we need to prevent rotation because
9341 	 * rotate_ctx() will change the list from interrupt context.
9342 	 */
9343 	raw_spin_lock_irqsave(&parent_ctx->lock, flags);
9344 	parent_ctx->rotate_disable = 1;
9345 	raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
9346 
9347 	list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
9348 		ret = inherit_task_group(event, parent, parent_ctx,
9349 					 child, ctxn, &inherited_all);
9350 		if (ret)
9351 			goto out_unlock;
9352 	}
9353 
9354 	raw_spin_lock_irqsave(&parent_ctx->lock, flags);
9355 	parent_ctx->rotate_disable = 0;
9356 
9357 	child_ctx = child->perf_event_ctxp[ctxn];
9358 
9359 	if (child_ctx && inherited_all) {
9360 		/*
9361 		 * Mark the child context as a clone of the parent
9362 		 * context, or of whatever the parent is a clone of.
9363 		 *
9364 		 * Note that if the parent is a clone, the holding of
9365 		 * parent_ctx->lock avoids it from being uncloned.
9366 		 */
9367 		cloned_ctx = parent_ctx->parent_ctx;
9368 		if (cloned_ctx) {
9369 			child_ctx->parent_ctx = cloned_ctx;
9370 			child_ctx->parent_gen = parent_ctx->parent_gen;
9371 		} else {
9372 			child_ctx->parent_ctx = parent_ctx;
9373 			child_ctx->parent_gen = parent_ctx->generation;
9374 		}
9375 		get_ctx(child_ctx->parent_ctx);
9376 	}
9377 
9378 	raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
9379 out_unlock:
9380 	mutex_unlock(&parent_ctx->mutex);
9381 
9382 	perf_unpin_context(parent_ctx);
9383 	put_ctx(parent_ctx);
9384 
9385 	return ret;
9386 }
9387 
9388 /*
9389  * Initialize the perf_event context in task_struct
9390  */
perf_event_init_task(struct task_struct * child)9391 int perf_event_init_task(struct task_struct *child)
9392 {
9393 	int ctxn, ret;
9394 
9395 	memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
9396 	mutex_init(&child->perf_event_mutex);
9397 	INIT_LIST_HEAD(&child->perf_event_list);
9398 
9399 	for_each_task_context_nr(ctxn) {
9400 		ret = perf_event_init_context(child, ctxn);
9401 		if (ret) {
9402 			perf_event_free_task(child);
9403 			return ret;
9404 		}
9405 	}
9406 
9407 	return 0;
9408 }
9409 
perf_event_init_all_cpus(void)9410 static void __init perf_event_init_all_cpus(void)
9411 {
9412 	struct swevent_htable *swhash;
9413 	int cpu;
9414 
9415 	for_each_possible_cpu(cpu) {
9416 		swhash = &per_cpu(swevent_htable, cpu);
9417 		mutex_init(&swhash->hlist_mutex);
9418 		INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
9419 	}
9420 }
9421 
perf_event_init_cpu(int cpu)9422 static void perf_event_init_cpu(int cpu)
9423 {
9424 	struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9425 
9426 	mutex_lock(&swhash->hlist_mutex);
9427 	if (swhash->hlist_refcount > 0) {
9428 		struct swevent_hlist *hlist;
9429 
9430 		hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
9431 		WARN_ON(!hlist);
9432 		rcu_assign_pointer(swhash->swevent_hlist, hlist);
9433 	}
9434 	mutex_unlock(&swhash->hlist_mutex);
9435 }
9436 
9437 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
__perf_event_exit_context(void * __info)9438 static void __perf_event_exit_context(void *__info)
9439 {
9440 	struct remove_event re = { .detach_group = true };
9441 	struct perf_event_context *ctx = __info;
9442 
9443 	rcu_read_lock();
9444 	list_for_each_entry_rcu(re.event, &ctx->event_list, event_entry)
9445 		__perf_remove_from_context(&re);
9446 	rcu_read_unlock();
9447 }
9448 
perf_event_exit_cpu_context(int cpu)9449 static void perf_event_exit_cpu_context(int cpu)
9450 {
9451 	struct perf_event_context *ctx;
9452 	struct pmu *pmu;
9453 	int idx;
9454 
9455 	idx = srcu_read_lock(&pmus_srcu);
9456 	list_for_each_entry_rcu(pmu, &pmus, entry) {
9457 		ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx;
9458 
9459 		mutex_lock(&ctx->mutex);
9460 		smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
9461 		mutex_unlock(&ctx->mutex);
9462 	}
9463 	srcu_read_unlock(&pmus_srcu, idx);
9464 }
9465 
perf_event_exit_cpu(int cpu)9466 static void perf_event_exit_cpu(int cpu)
9467 {
9468 	perf_event_exit_cpu_context(cpu);
9469 }
9470 #else
perf_event_exit_cpu(int cpu)9471 static inline void perf_event_exit_cpu(int cpu) { }
9472 #endif
9473 
9474 static int
perf_reboot(struct notifier_block * notifier,unsigned long val,void * v)9475 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
9476 {
9477 	int cpu;
9478 
9479 	for_each_online_cpu(cpu)
9480 		perf_event_exit_cpu(cpu);
9481 
9482 	return NOTIFY_OK;
9483 }
9484 
9485 /*
9486  * Run the perf reboot notifier at the very last possible moment so that
9487  * the generic watchdog code runs as long as possible.
9488  */
9489 static struct notifier_block perf_reboot_notifier = {
9490 	.notifier_call = perf_reboot,
9491 	.priority = INT_MIN,
9492 };
9493 
9494 static int
perf_cpu_notify(struct notifier_block * self,unsigned long action,void * hcpu)9495 perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
9496 {
9497 	unsigned int cpu = (long)hcpu;
9498 
9499 	switch (action & ~CPU_TASKS_FROZEN) {
9500 
9501 	case CPU_UP_PREPARE:
9502 	case CPU_DOWN_FAILED:
9503 		perf_event_init_cpu(cpu);
9504 		break;
9505 
9506 	case CPU_UP_CANCELED:
9507 	case CPU_DOWN_PREPARE:
9508 		perf_event_exit_cpu(cpu);
9509 		break;
9510 	default:
9511 		break;
9512 	}
9513 
9514 	return NOTIFY_OK;
9515 }
9516 
perf_event_init(void)9517 void __init perf_event_init(void)
9518 {
9519 	int ret;
9520 
9521 	idr_init(&pmu_idr);
9522 
9523 	perf_event_init_all_cpus();
9524 	init_srcu_struct(&pmus_srcu);
9525 	perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
9526 	perf_pmu_register(&perf_cpu_clock, NULL, -1);
9527 	perf_pmu_register(&perf_task_clock, NULL, -1);
9528 	perf_tp_register();
9529 	perf_cpu_notifier(perf_cpu_notify);
9530 	register_reboot_notifier(&perf_reboot_notifier);
9531 
9532 	ret = init_hw_breakpoint();
9533 	WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
9534 
9535 	/* do not patch jump label more than once per second */
9536 	jump_label_rate_limit(&perf_sched_events, HZ);
9537 
9538 	/*
9539 	 * Build time assertion that we keep the data_head at the intended
9540 	 * location.  IOW, validation we got the __reserved[] size right.
9541 	 */
9542 	BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
9543 		     != 1024);
9544 }
9545 
perf_event_sysfs_show(struct device * dev,struct device_attribute * attr,char * page)9546 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
9547 			      char *page)
9548 {
9549 	struct perf_pmu_events_attr *pmu_attr =
9550 		container_of(attr, struct perf_pmu_events_attr, attr);
9551 
9552 	if (pmu_attr->event_str)
9553 		return sprintf(page, "%s\n", pmu_attr->event_str);
9554 
9555 	return 0;
9556 }
9557 
perf_event_sysfs_init(void)9558 static int __init perf_event_sysfs_init(void)
9559 {
9560 	struct pmu *pmu;
9561 	int ret;
9562 
9563 	mutex_lock(&pmus_lock);
9564 
9565 	ret = bus_register(&pmu_bus);
9566 	if (ret)
9567 		goto unlock;
9568 
9569 	list_for_each_entry(pmu, &pmus, entry) {
9570 		if (!pmu->name || pmu->type < 0)
9571 			continue;
9572 
9573 		ret = pmu_dev_alloc(pmu);
9574 		WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
9575 	}
9576 	pmu_bus_running = 1;
9577 	ret = 0;
9578 
9579 unlock:
9580 	mutex_unlock(&pmus_lock);
9581 
9582 	return ret;
9583 }
9584 device_initcall(perf_event_sysfs_init);
9585 
9586 #ifdef CONFIG_CGROUP_PERF
9587 static struct cgroup_subsys_state *
perf_cgroup_css_alloc(struct cgroup_subsys_state * parent_css)9588 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
9589 {
9590 	struct perf_cgroup *jc;
9591 
9592 	jc = kzalloc(sizeof(*jc), GFP_KERNEL);
9593 	if (!jc)
9594 		return ERR_PTR(-ENOMEM);
9595 
9596 	jc->info = alloc_percpu(struct perf_cgroup_info);
9597 	if (!jc->info) {
9598 		kfree(jc);
9599 		return ERR_PTR(-ENOMEM);
9600 	}
9601 
9602 	return &jc->css;
9603 }
9604 
perf_cgroup_css_free(struct cgroup_subsys_state * css)9605 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
9606 {
9607 	struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
9608 
9609 	free_percpu(jc->info);
9610 	kfree(jc);
9611 }
9612 
__perf_cgroup_move(void * info)9613 static int __perf_cgroup_move(void *info)
9614 {
9615 	struct task_struct *task = info;
9616 	rcu_read_lock();
9617 	perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
9618 	rcu_read_unlock();
9619 	return 0;
9620 }
9621 
perf_cgroup_attach(struct cgroup_taskset * tset)9622 static void perf_cgroup_attach(struct cgroup_taskset *tset)
9623 {
9624 	struct task_struct *task;
9625 	struct cgroup_subsys_state *css;
9626 
9627 	cgroup_taskset_for_each(task, css, tset)
9628 		task_function_call(task, __perf_cgroup_move, task);
9629 }
9630 
9631 struct cgroup_subsys perf_event_cgrp_subsys = {
9632 	.css_alloc	= perf_cgroup_css_alloc,
9633 	.css_free	= perf_cgroup_css_free,
9634 	.attach		= perf_cgroup_attach,
9635 };
9636 #endif /* CONFIG_CGROUP_PERF */
9637