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