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