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