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