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