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