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