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