]> git.proxmox.com Git - mirror_ubuntu-zesty-kernel.git/blob - kernel/events/core.c
perf/core: Fix use-after-free in perf_release()
[mirror_ubuntu-zesty-kernel.git] / kernel / events / core.c
1 /*
2 * Performance events core code:
3 *
4 * Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
5 * Copyright (C) 2008-2011 Red Hat, Inc., Ingo Molnar
6 * Copyright (C) 2008-2011 Red Hat, Inc., Peter Zijlstra
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/trace_events.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 #include <linux/namei.h>
48 #include <linux/parser.h>
49
50 #include "internal.h"
51
52 #include <asm/irq_regs.h>
53
54 typedef int (*remote_function_f)(void *);
55
56 struct remote_function_call {
57 struct task_struct *p;
58 remote_function_f func;
59 void *info;
60 int ret;
61 };
62
63 static void remote_function(void *data)
64 {
65 struct remote_function_call *tfc = data;
66 struct task_struct *p = tfc->p;
67
68 if (p) {
69 /* -EAGAIN */
70 if (task_cpu(p) != smp_processor_id())
71 return;
72
73 /*
74 * Now that we're on right CPU with IRQs disabled, we can test
75 * if we hit the right task without races.
76 */
77
78 tfc->ret = -ESRCH; /* No such (running) process */
79 if (p != current)
80 return;
81 }
82
83 tfc->ret = tfc->func(tfc->info);
84 }
85
86 /**
87 * task_function_call - call a function on the cpu on which a task runs
88 * @p: the task to evaluate
89 * @func: the function to be called
90 * @info: the function call argument
91 *
92 * Calls the function @func when the task is currently running. This might
93 * be on the current CPU, which just calls the function directly
94 *
95 * returns: @func return value, or
96 * -ESRCH - when the process isn't running
97 * -EAGAIN - when the process moved away
98 */
99 static int
100 task_function_call(struct task_struct *p, remote_function_f func, void *info)
101 {
102 struct remote_function_call data = {
103 .p = p,
104 .func = func,
105 .info = info,
106 .ret = -EAGAIN,
107 };
108 int ret;
109
110 do {
111 ret = smp_call_function_single(task_cpu(p), remote_function, &data, 1);
112 if (!ret)
113 ret = data.ret;
114 } while (ret == -EAGAIN);
115
116 return ret;
117 }
118
119 /**
120 * cpu_function_call - call a function on the cpu
121 * @func: the function to be called
122 * @info: the function call argument
123 *
124 * Calls the function @func on the remote cpu.
125 *
126 * returns: @func return value or -ENXIO when the cpu is offline
127 */
128 static int cpu_function_call(int cpu, remote_function_f func, void *info)
129 {
130 struct remote_function_call data = {
131 .p = NULL,
132 .func = func,
133 .info = info,
134 .ret = -ENXIO, /* No such CPU */
135 };
136
137 smp_call_function_single(cpu, remote_function, &data, 1);
138
139 return data.ret;
140 }
141
142 static inline struct perf_cpu_context *
143 __get_cpu_context(struct perf_event_context *ctx)
144 {
145 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
146 }
147
148 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
149 struct perf_event_context *ctx)
150 {
151 raw_spin_lock(&cpuctx->ctx.lock);
152 if (ctx)
153 raw_spin_lock(&ctx->lock);
154 }
155
156 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
157 struct perf_event_context *ctx)
158 {
159 if (ctx)
160 raw_spin_unlock(&ctx->lock);
161 raw_spin_unlock(&cpuctx->ctx.lock);
162 }
163
164 #define TASK_TOMBSTONE ((void *)-1L)
165
166 static bool is_kernel_event(struct perf_event *event)
167 {
168 return READ_ONCE(event->owner) == TASK_TOMBSTONE;
169 }
170
171 /*
172 * On task ctx scheduling...
173 *
174 * When !ctx->nr_events a task context will not be scheduled. This means
175 * we can disable the scheduler hooks (for performance) without leaving
176 * pending task ctx state.
177 *
178 * This however results in two special cases:
179 *
180 * - removing the last event from a task ctx; this is relatively straight
181 * forward and is done in __perf_remove_from_context.
182 *
183 * - adding the first event to a task ctx; this is tricky because we cannot
184 * rely on ctx->is_active and therefore cannot use event_function_call().
185 * See perf_install_in_context().
186 *
187 * If ctx->nr_events, then ctx->is_active and cpuctx->task_ctx are set.
188 */
189
190 typedef void (*event_f)(struct perf_event *, struct perf_cpu_context *,
191 struct perf_event_context *, void *);
192
193 struct event_function_struct {
194 struct perf_event *event;
195 event_f func;
196 void *data;
197 };
198
199 static int event_function(void *info)
200 {
201 struct event_function_struct *efs = info;
202 struct perf_event *event = efs->event;
203 struct perf_event_context *ctx = event->ctx;
204 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
205 struct perf_event_context *task_ctx = cpuctx->task_ctx;
206 int ret = 0;
207
208 WARN_ON_ONCE(!irqs_disabled());
209
210 perf_ctx_lock(cpuctx, task_ctx);
211 /*
212 * Since we do the IPI call without holding ctx->lock things can have
213 * changed, double check we hit the task we set out to hit.
214 */
215 if (ctx->task) {
216 if (ctx->task != current) {
217 ret = -ESRCH;
218 goto unlock;
219 }
220
221 /*
222 * We only use event_function_call() on established contexts,
223 * and event_function() is only ever called when active (or
224 * rather, we'll have bailed in task_function_call() or the
225 * above ctx->task != current test), therefore we must have
226 * ctx->is_active here.
227 */
228 WARN_ON_ONCE(!ctx->is_active);
229 /*
230 * And since we have ctx->is_active, cpuctx->task_ctx must
231 * match.
232 */
233 WARN_ON_ONCE(task_ctx != ctx);
234 } else {
235 WARN_ON_ONCE(&cpuctx->ctx != ctx);
236 }
237
238 efs->func(event, cpuctx, ctx, efs->data);
239 unlock:
240 perf_ctx_unlock(cpuctx, task_ctx);
241
242 return ret;
243 }
244
245 static void event_function_call(struct perf_event *event, event_f func, void *data)
246 {
247 struct perf_event_context *ctx = event->ctx;
248 struct task_struct *task = READ_ONCE(ctx->task); /* verified in event_function */
249 struct event_function_struct efs = {
250 .event = event,
251 .func = func,
252 .data = data,
253 };
254
255 if (!event->parent) {
256 /*
257 * If this is a !child event, we must hold ctx::mutex to
258 * stabilize the the event->ctx relation. See
259 * perf_event_ctx_lock().
260 */
261 lockdep_assert_held(&ctx->mutex);
262 }
263
264 if (!task) {
265 cpu_function_call(event->cpu, event_function, &efs);
266 return;
267 }
268
269 if (task == TASK_TOMBSTONE)
270 return;
271
272 again:
273 if (!task_function_call(task, event_function, &efs))
274 return;
275
276 raw_spin_lock_irq(&ctx->lock);
277 /*
278 * Reload the task pointer, it might have been changed by
279 * a concurrent perf_event_context_sched_out().
280 */
281 task = ctx->task;
282 if (task == TASK_TOMBSTONE) {
283 raw_spin_unlock_irq(&ctx->lock);
284 return;
285 }
286 if (ctx->is_active) {
287 raw_spin_unlock_irq(&ctx->lock);
288 goto again;
289 }
290 func(event, NULL, ctx, data);
291 raw_spin_unlock_irq(&ctx->lock);
292 }
293
294 /*
295 * Similar to event_function_call() + event_function(), but hard assumes IRQs
296 * are already disabled and we're on the right CPU.
297 */
298 static void event_function_local(struct perf_event *event, event_f func, void *data)
299 {
300 struct perf_event_context *ctx = event->ctx;
301 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
302 struct task_struct *task = READ_ONCE(ctx->task);
303 struct perf_event_context *task_ctx = NULL;
304
305 WARN_ON_ONCE(!irqs_disabled());
306
307 if (task) {
308 if (task == TASK_TOMBSTONE)
309 return;
310
311 task_ctx = ctx;
312 }
313
314 perf_ctx_lock(cpuctx, task_ctx);
315
316 task = ctx->task;
317 if (task == TASK_TOMBSTONE)
318 goto unlock;
319
320 if (task) {
321 /*
322 * We must be either inactive or active and the right task,
323 * otherwise we're screwed, since we cannot IPI to somewhere
324 * else.
325 */
326 if (ctx->is_active) {
327 if (WARN_ON_ONCE(task != current))
328 goto unlock;
329
330 if (WARN_ON_ONCE(cpuctx->task_ctx != ctx))
331 goto unlock;
332 }
333 } else {
334 WARN_ON_ONCE(&cpuctx->ctx != ctx);
335 }
336
337 func(event, cpuctx, ctx, data);
338 unlock:
339 perf_ctx_unlock(cpuctx, task_ctx);
340 }
341
342 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
343 PERF_FLAG_FD_OUTPUT |\
344 PERF_FLAG_PID_CGROUP |\
345 PERF_FLAG_FD_CLOEXEC)
346
347 /*
348 * branch priv levels that need permission checks
349 */
350 #define PERF_SAMPLE_BRANCH_PERM_PLM \
351 (PERF_SAMPLE_BRANCH_KERNEL |\
352 PERF_SAMPLE_BRANCH_HV)
353
354 enum event_type_t {
355 EVENT_FLEXIBLE = 0x1,
356 EVENT_PINNED = 0x2,
357 EVENT_TIME = 0x4,
358 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
359 };
360
361 /*
362 * perf_sched_events : >0 events exist
363 * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
364 */
365
366 static void perf_sched_delayed(struct work_struct *work);
367 DEFINE_STATIC_KEY_FALSE(perf_sched_events);
368 static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed);
369 static DEFINE_MUTEX(perf_sched_mutex);
370 static atomic_t perf_sched_count;
371
372 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
373 static DEFINE_PER_CPU(int, perf_sched_cb_usages);
374 static DEFINE_PER_CPU(struct pmu_event_list, pmu_sb_events);
375
376 static atomic_t nr_mmap_events __read_mostly;
377 static atomic_t nr_comm_events __read_mostly;
378 static atomic_t nr_task_events __read_mostly;
379 static atomic_t nr_freq_events __read_mostly;
380 static atomic_t nr_switch_events __read_mostly;
381
382 static LIST_HEAD(pmus);
383 static DEFINE_MUTEX(pmus_lock);
384 static struct srcu_struct pmus_srcu;
385
386 /*
387 * perf event paranoia level:
388 * -1 - not paranoid at all
389 * 0 - disallow raw tracepoint access for unpriv
390 * 1 - disallow cpu events for unpriv
391 * 2 - disallow kernel profiling for unpriv
392 * 3 - disallow all unpriv perf event use
393 */
394 #ifdef CONFIG_SECURITY_PERF_EVENTS_RESTRICT
395 int sysctl_perf_event_paranoid __read_mostly = 3;
396 #else
397 int sysctl_perf_event_paranoid __read_mostly = 1;
398 #endif
399
400 /* Minimum for 512 kiB + 1 user control page */
401 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
402
403 /*
404 * max perf event sample rate
405 */
406 #define DEFAULT_MAX_SAMPLE_RATE 100000
407 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
408 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
409
410 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
411
412 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
413 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
414
415 static int perf_sample_allowed_ns __read_mostly =
416 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
417
418 static void update_perf_cpu_limits(void)
419 {
420 u64 tmp = perf_sample_period_ns;
421
422 tmp *= sysctl_perf_cpu_time_max_percent;
423 tmp = div_u64(tmp, 100);
424 if (!tmp)
425 tmp = 1;
426
427 WRITE_ONCE(perf_sample_allowed_ns, tmp);
428 }
429
430 static int perf_rotate_context(struct perf_cpu_context *cpuctx);
431
432 int perf_proc_update_handler(struct ctl_table *table, int write,
433 void __user *buffer, size_t *lenp,
434 loff_t *ppos)
435 {
436 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
437
438 if (ret || !write)
439 return ret;
440
441 /*
442 * If throttling is disabled don't allow the write:
443 */
444 if (sysctl_perf_cpu_time_max_percent == 100 ||
445 sysctl_perf_cpu_time_max_percent == 0)
446 return -EINVAL;
447
448 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
449 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
450 update_perf_cpu_limits();
451
452 return 0;
453 }
454
455 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
456
457 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
458 void __user *buffer, size_t *lenp,
459 loff_t *ppos)
460 {
461 int ret = proc_dointvec(table, write, buffer, lenp, ppos);
462
463 if (ret || !write)
464 return ret;
465
466 if (sysctl_perf_cpu_time_max_percent == 100 ||
467 sysctl_perf_cpu_time_max_percent == 0) {
468 printk(KERN_WARNING
469 "perf: Dynamic interrupt throttling disabled, can hang your system!\n");
470 WRITE_ONCE(perf_sample_allowed_ns, 0);
471 } else {
472 update_perf_cpu_limits();
473 }
474
475 return 0;
476 }
477
478 /*
479 * perf samples are done in some very critical code paths (NMIs).
480 * If they take too much CPU time, the system can lock up and not
481 * get any real work done. This will drop the sample rate when
482 * we detect that events are taking too long.
483 */
484 #define NR_ACCUMULATED_SAMPLES 128
485 static DEFINE_PER_CPU(u64, running_sample_length);
486
487 static u64 __report_avg;
488 static u64 __report_allowed;
489
490 static void perf_duration_warn(struct irq_work *w)
491 {
492 printk_ratelimited(KERN_INFO
493 "perf: interrupt took too long (%lld > %lld), lowering "
494 "kernel.perf_event_max_sample_rate to %d\n",
495 __report_avg, __report_allowed,
496 sysctl_perf_event_sample_rate);
497 }
498
499 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
500
501 void perf_sample_event_took(u64 sample_len_ns)
502 {
503 u64 max_len = READ_ONCE(perf_sample_allowed_ns);
504 u64 running_len;
505 u64 avg_len;
506 u32 max;
507
508 if (max_len == 0)
509 return;
510
511 /* Decay the counter by 1 average sample. */
512 running_len = __this_cpu_read(running_sample_length);
513 running_len -= running_len/NR_ACCUMULATED_SAMPLES;
514 running_len += sample_len_ns;
515 __this_cpu_write(running_sample_length, running_len);
516
517 /*
518 * Note: this will be biased artifically low until we have
519 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
520 * from having to maintain a count.
521 */
522 avg_len = running_len/NR_ACCUMULATED_SAMPLES;
523 if (avg_len <= max_len)
524 return;
525
526 __report_avg = avg_len;
527 __report_allowed = max_len;
528
529 /*
530 * Compute a throttle threshold 25% below the current duration.
531 */
532 avg_len += avg_len / 4;
533 max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent;
534 if (avg_len < max)
535 max /= (u32)avg_len;
536 else
537 max = 1;
538
539 WRITE_ONCE(perf_sample_allowed_ns, avg_len);
540 WRITE_ONCE(max_samples_per_tick, max);
541
542 sysctl_perf_event_sample_rate = max * HZ;
543 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
544
545 if (!irq_work_queue(&perf_duration_work)) {
546 early_printk("perf: interrupt took too long (%lld > %lld), lowering "
547 "kernel.perf_event_max_sample_rate to %d\n",
548 __report_avg, __report_allowed,
549 sysctl_perf_event_sample_rate);
550 }
551 }
552
553 static atomic64_t perf_event_id;
554
555 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
556 enum event_type_t event_type);
557
558 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
559 enum event_type_t event_type,
560 struct task_struct *task);
561
562 static void update_context_time(struct perf_event_context *ctx);
563 static u64 perf_event_time(struct perf_event *event);
564
565 void __weak perf_event_print_debug(void) { }
566
567 extern __weak const char *perf_pmu_name(void)
568 {
569 return "pmu";
570 }
571
572 static inline u64 perf_clock(void)
573 {
574 return local_clock();
575 }
576
577 static inline u64 perf_event_clock(struct perf_event *event)
578 {
579 return event->clock();
580 }
581
582 #ifdef CONFIG_CGROUP_PERF
583
584 static inline bool
585 perf_cgroup_match(struct perf_event *event)
586 {
587 struct perf_event_context *ctx = event->ctx;
588 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
589
590 /* @event doesn't care about cgroup */
591 if (!event->cgrp)
592 return true;
593
594 /* wants specific cgroup scope but @cpuctx isn't associated with any */
595 if (!cpuctx->cgrp)
596 return false;
597
598 /*
599 * Cgroup scoping is recursive. An event enabled for a cgroup is
600 * also enabled for all its descendant cgroups. If @cpuctx's
601 * cgroup is a descendant of @event's (the test covers identity
602 * case), it's a match.
603 */
604 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
605 event->cgrp->css.cgroup);
606 }
607
608 static inline void perf_detach_cgroup(struct perf_event *event)
609 {
610 css_put(&event->cgrp->css);
611 event->cgrp = NULL;
612 }
613
614 static inline int is_cgroup_event(struct perf_event *event)
615 {
616 return event->cgrp != NULL;
617 }
618
619 static inline u64 perf_cgroup_event_time(struct perf_event *event)
620 {
621 struct perf_cgroup_info *t;
622
623 t = per_cpu_ptr(event->cgrp->info, event->cpu);
624 return t->time;
625 }
626
627 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
628 {
629 struct perf_cgroup_info *info;
630 u64 now;
631
632 now = perf_clock();
633
634 info = this_cpu_ptr(cgrp->info);
635
636 info->time += now - info->timestamp;
637 info->timestamp = now;
638 }
639
640 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
641 {
642 struct perf_cgroup *cgrp_out = cpuctx->cgrp;
643 if (cgrp_out)
644 __update_cgrp_time(cgrp_out);
645 }
646
647 static inline void update_cgrp_time_from_event(struct perf_event *event)
648 {
649 struct perf_cgroup *cgrp;
650
651 /*
652 * ensure we access cgroup data only when needed and
653 * when we know the cgroup is pinned (css_get)
654 */
655 if (!is_cgroup_event(event))
656 return;
657
658 cgrp = perf_cgroup_from_task(current, event->ctx);
659 /*
660 * Do not update time when cgroup is not active
661 */
662 if (cgrp == event->cgrp)
663 __update_cgrp_time(event->cgrp);
664 }
665
666 static inline void
667 perf_cgroup_set_timestamp(struct task_struct *task,
668 struct perf_event_context *ctx)
669 {
670 struct perf_cgroup *cgrp;
671 struct perf_cgroup_info *info;
672
673 /*
674 * ctx->lock held by caller
675 * ensure we do not access cgroup data
676 * unless we have the cgroup pinned (css_get)
677 */
678 if (!task || !ctx->nr_cgroups)
679 return;
680
681 cgrp = perf_cgroup_from_task(task, ctx);
682 info = this_cpu_ptr(cgrp->info);
683 info->timestamp = ctx->timestamp;
684 }
685
686 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
687 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
688
689 /*
690 * reschedule events based on the cgroup constraint of task.
691 *
692 * mode SWOUT : schedule out everything
693 * mode SWIN : schedule in based on cgroup for next
694 */
695 static void perf_cgroup_switch(struct task_struct *task, int mode)
696 {
697 struct perf_cpu_context *cpuctx;
698 struct pmu *pmu;
699 unsigned long flags;
700
701 /*
702 * disable interrupts to avoid geting nr_cgroup
703 * changes via __perf_event_disable(). Also
704 * avoids preemption.
705 */
706 local_irq_save(flags);
707
708 /*
709 * we reschedule only in the presence of cgroup
710 * constrained events.
711 */
712
713 list_for_each_entry_rcu(pmu, &pmus, entry) {
714 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
715 if (cpuctx->unique_pmu != pmu)
716 continue; /* ensure we process each cpuctx once */
717
718 /*
719 * perf_cgroup_events says at least one
720 * context on this CPU has cgroup events.
721 *
722 * ctx->nr_cgroups reports the number of cgroup
723 * events for a context.
724 */
725 if (cpuctx->ctx.nr_cgroups > 0) {
726 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
727 perf_pmu_disable(cpuctx->ctx.pmu);
728
729 if (mode & PERF_CGROUP_SWOUT) {
730 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
731 /*
732 * must not be done before ctxswout due
733 * to event_filter_match() in event_sched_out()
734 */
735 cpuctx->cgrp = NULL;
736 }
737
738 if (mode & PERF_CGROUP_SWIN) {
739 WARN_ON_ONCE(cpuctx->cgrp);
740 /*
741 * set cgrp before ctxsw in to allow
742 * event_filter_match() to not have to pass
743 * task around
744 * we pass the cpuctx->ctx to perf_cgroup_from_task()
745 * because cgorup events are only per-cpu
746 */
747 cpuctx->cgrp = perf_cgroup_from_task(task, &cpuctx->ctx);
748 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
749 }
750 perf_pmu_enable(cpuctx->ctx.pmu);
751 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
752 }
753 }
754
755 local_irq_restore(flags);
756 }
757
758 static inline void perf_cgroup_sched_out(struct task_struct *task,
759 struct task_struct *next)
760 {
761 struct perf_cgroup *cgrp1;
762 struct perf_cgroup *cgrp2 = NULL;
763
764 rcu_read_lock();
765 /*
766 * we come here when we know perf_cgroup_events > 0
767 * we do not need to pass the ctx here because we know
768 * we are holding the rcu lock
769 */
770 cgrp1 = perf_cgroup_from_task(task, NULL);
771 cgrp2 = perf_cgroup_from_task(next, NULL);
772
773 /*
774 * only schedule out current cgroup events if we know
775 * that we are switching to a different cgroup. Otherwise,
776 * do no touch the cgroup events.
777 */
778 if (cgrp1 != cgrp2)
779 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
780
781 rcu_read_unlock();
782 }
783
784 static inline void perf_cgroup_sched_in(struct task_struct *prev,
785 struct task_struct *task)
786 {
787 struct perf_cgroup *cgrp1;
788 struct perf_cgroup *cgrp2 = NULL;
789
790 rcu_read_lock();
791 /*
792 * we come here when we know perf_cgroup_events > 0
793 * we do not need to pass the ctx here because we know
794 * we are holding the rcu lock
795 */
796 cgrp1 = perf_cgroup_from_task(task, NULL);
797 cgrp2 = perf_cgroup_from_task(prev, NULL);
798
799 /*
800 * only need to schedule in cgroup events if we are changing
801 * cgroup during ctxsw. Cgroup events were not scheduled
802 * out of ctxsw out if that was not the case.
803 */
804 if (cgrp1 != cgrp2)
805 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
806
807 rcu_read_unlock();
808 }
809
810 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
811 struct perf_event_attr *attr,
812 struct perf_event *group_leader)
813 {
814 struct perf_cgroup *cgrp;
815 struct cgroup_subsys_state *css;
816 struct fd f = fdget(fd);
817 int ret = 0;
818
819 if (!f.file)
820 return -EBADF;
821
822 css = css_tryget_online_from_dir(f.file->f_path.dentry,
823 &perf_event_cgrp_subsys);
824 if (IS_ERR(css)) {
825 ret = PTR_ERR(css);
826 goto out;
827 }
828
829 cgrp = container_of(css, struct perf_cgroup, css);
830 event->cgrp = cgrp;
831
832 /*
833 * all events in a group must monitor
834 * the same cgroup because a task belongs
835 * to only one perf cgroup at a time
836 */
837 if (group_leader && group_leader->cgrp != cgrp) {
838 perf_detach_cgroup(event);
839 ret = -EINVAL;
840 }
841 out:
842 fdput(f);
843 return ret;
844 }
845
846 static inline void
847 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
848 {
849 struct perf_cgroup_info *t;
850 t = per_cpu_ptr(event->cgrp->info, event->cpu);
851 event->shadow_ctx_time = now - t->timestamp;
852 }
853
854 static inline void
855 perf_cgroup_defer_enabled(struct perf_event *event)
856 {
857 /*
858 * when the current task's perf cgroup does not match
859 * the event's, we need to remember to call the
860 * perf_mark_enable() function the first time a task with
861 * a matching perf cgroup is scheduled in.
862 */
863 if (is_cgroup_event(event) && !perf_cgroup_match(event))
864 event->cgrp_defer_enabled = 1;
865 }
866
867 static inline void
868 perf_cgroup_mark_enabled(struct perf_event *event,
869 struct perf_event_context *ctx)
870 {
871 struct perf_event *sub;
872 u64 tstamp = perf_event_time(event);
873
874 if (!event->cgrp_defer_enabled)
875 return;
876
877 event->cgrp_defer_enabled = 0;
878
879 event->tstamp_enabled = tstamp - event->total_time_enabled;
880 list_for_each_entry(sub, &event->sibling_list, group_entry) {
881 if (sub->state >= PERF_EVENT_STATE_INACTIVE) {
882 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
883 sub->cgrp_defer_enabled = 0;
884 }
885 }
886 }
887
888 /*
889 * Update cpuctx->cgrp so that it is set when first cgroup event is added and
890 * cleared when last cgroup event is removed.
891 */
892 static inline void
893 list_update_cgroup_event(struct perf_event *event,
894 struct perf_event_context *ctx, bool add)
895 {
896 struct perf_cpu_context *cpuctx;
897
898 if (!is_cgroup_event(event))
899 return;
900
901 if (add && ctx->nr_cgroups++)
902 return;
903 else if (!add && --ctx->nr_cgroups)
904 return;
905 /*
906 * Because cgroup events are always per-cpu events,
907 * this will always be called from the right CPU.
908 */
909 cpuctx = __get_cpu_context(ctx);
910
911 /*
912 * cpuctx->cgrp is NULL until a cgroup event is sched in or
913 * ctx->nr_cgroup == 0 .
914 */
915 if (add && perf_cgroup_from_task(current, ctx) == event->cgrp)
916 cpuctx->cgrp = event->cgrp;
917 else if (!add)
918 cpuctx->cgrp = NULL;
919 }
920
921 #else /* !CONFIG_CGROUP_PERF */
922
923 static inline bool
924 perf_cgroup_match(struct perf_event *event)
925 {
926 return true;
927 }
928
929 static inline void perf_detach_cgroup(struct perf_event *event)
930 {}
931
932 static inline int is_cgroup_event(struct perf_event *event)
933 {
934 return 0;
935 }
936
937 static inline u64 perf_cgroup_event_cgrp_time(struct perf_event *event)
938 {
939 return 0;
940 }
941
942 static inline void update_cgrp_time_from_event(struct perf_event *event)
943 {
944 }
945
946 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
947 {
948 }
949
950 static inline void perf_cgroup_sched_out(struct task_struct *task,
951 struct task_struct *next)
952 {
953 }
954
955 static inline void perf_cgroup_sched_in(struct task_struct *prev,
956 struct task_struct *task)
957 {
958 }
959
960 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
961 struct perf_event_attr *attr,
962 struct perf_event *group_leader)
963 {
964 return -EINVAL;
965 }
966
967 static inline void
968 perf_cgroup_set_timestamp(struct task_struct *task,
969 struct perf_event_context *ctx)
970 {
971 }
972
973 void
974 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
975 {
976 }
977
978 static inline void
979 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
980 {
981 }
982
983 static inline u64 perf_cgroup_event_time(struct perf_event *event)
984 {
985 return 0;
986 }
987
988 static inline void
989 perf_cgroup_defer_enabled(struct perf_event *event)
990 {
991 }
992
993 static inline void
994 perf_cgroup_mark_enabled(struct perf_event *event,
995 struct perf_event_context *ctx)
996 {
997 }
998
999 static inline void
1000 list_update_cgroup_event(struct perf_event *event,
1001 struct perf_event_context *ctx, bool add)
1002 {
1003 }
1004
1005 #endif
1006
1007 /*
1008 * set default to be dependent on timer tick just
1009 * like original code
1010 */
1011 #define PERF_CPU_HRTIMER (1000 / HZ)
1012 /*
1013 * function must be called with interrupts disbled
1014 */
1015 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
1016 {
1017 struct perf_cpu_context *cpuctx;
1018 int rotations = 0;
1019
1020 WARN_ON(!irqs_disabled());
1021
1022 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
1023 rotations = perf_rotate_context(cpuctx);
1024
1025 raw_spin_lock(&cpuctx->hrtimer_lock);
1026 if (rotations)
1027 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
1028 else
1029 cpuctx->hrtimer_active = 0;
1030 raw_spin_unlock(&cpuctx->hrtimer_lock);
1031
1032 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
1033 }
1034
1035 static void __perf_mux_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
1036 {
1037 struct hrtimer *timer = &cpuctx->hrtimer;
1038 struct pmu *pmu = cpuctx->ctx.pmu;
1039 u64 interval;
1040
1041 /* no multiplexing needed for SW PMU */
1042 if (pmu->task_ctx_nr == perf_sw_context)
1043 return;
1044
1045 /*
1046 * check default is sane, if not set then force to
1047 * default interval (1/tick)
1048 */
1049 interval = pmu->hrtimer_interval_ms;
1050 if (interval < 1)
1051 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
1052
1053 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
1054
1055 raw_spin_lock_init(&cpuctx->hrtimer_lock);
1056 hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
1057 timer->function = perf_mux_hrtimer_handler;
1058 }
1059
1060 static int perf_mux_hrtimer_restart(struct perf_cpu_context *cpuctx)
1061 {
1062 struct hrtimer *timer = &cpuctx->hrtimer;
1063 struct pmu *pmu = cpuctx->ctx.pmu;
1064 unsigned long flags;
1065
1066 /* not for SW PMU */
1067 if (pmu->task_ctx_nr == perf_sw_context)
1068 return 0;
1069
1070 raw_spin_lock_irqsave(&cpuctx->hrtimer_lock, flags);
1071 if (!cpuctx->hrtimer_active) {
1072 cpuctx->hrtimer_active = 1;
1073 hrtimer_forward_now(timer, cpuctx->hrtimer_interval);
1074 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
1075 }
1076 raw_spin_unlock_irqrestore(&cpuctx->hrtimer_lock, flags);
1077
1078 return 0;
1079 }
1080
1081 void perf_pmu_disable(struct pmu *pmu)
1082 {
1083 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1084 if (!(*count)++)
1085 pmu->pmu_disable(pmu);
1086 }
1087
1088 void perf_pmu_enable(struct pmu *pmu)
1089 {
1090 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1091 if (!--(*count))
1092 pmu->pmu_enable(pmu);
1093 }
1094
1095 static DEFINE_PER_CPU(struct list_head, active_ctx_list);
1096
1097 /*
1098 * perf_event_ctx_activate(), perf_event_ctx_deactivate(), and
1099 * perf_event_task_tick() are fully serialized because they're strictly cpu
1100 * affine and perf_event_ctx{activate,deactivate} are called with IRQs
1101 * disabled, while perf_event_task_tick is called from IRQ context.
1102 */
1103 static void perf_event_ctx_activate(struct perf_event_context *ctx)
1104 {
1105 struct list_head *head = this_cpu_ptr(&active_ctx_list);
1106
1107 WARN_ON(!irqs_disabled());
1108
1109 WARN_ON(!list_empty(&ctx->active_ctx_list));
1110
1111 list_add(&ctx->active_ctx_list, head);
1112 }
1113
1114 static void perf_event_ctx_deactivate(struct perf_event_context *ctx)
1115 {
1116 WARN_ON(!irqs_disabled());
1117
1118 WARN_ON(list_empty(&ctx->active_ctx_list));
1119
1120 list_del_init(&ctx->active_ctx_list);
1121 }
1122
1123 static void get_ctx(struct perf_event_context *ctx)
1124 {
1125 WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
1126 }
1127
1128 static void free_ctx(struct rcu_head *head)
1129 {
1130 struct perf_event_context *ctx;
1131
1132 ctx = container_of(head, struct perf_event_context, rcu_head);
1133 kfree(ctx->task_ctx_data);
1134 kfree(ctx);
1135 }
1136
1137 static void put_ctx(struct perf_event_context *ctx)
1138 {
1139 if (atomic_dec_and_test(&ctx->refcount)) {
1140 if (ctx->parent_ctx)
1141 put_ctx(ctx->parent_ctx);
1142 if (ctx->task && ctx->task != TASK_TOMBSTONE)
1143 put_task_struct(ctx->task);
1144 call_rcu(&ctx->rcu_head, free_ctx);
1145 }
1146 }
1147
1148 /*
1149 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
1150 * perf_pmu_migrate_context() we need some magic.
1151 *
1152 * Those places that change perf_event::ctx will hold both
1153 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
1154 *
1155 * Lock ordering is by mutex address. There are two other sites where
1156 * perf_event_context::mutex nests and those are:
1157 *
1158 * - perf_event_exit_task_context() [ child , 0 ]
1159 * perf_event_exit_event()
1160 * put_event() [ parent, 1 ]
1161 *
1162 * - perf_event_init_context() [ parent, 0 ]
1163 * inherit_task_group()
1164 * inherit_group()
1165 * inherit_event()
1166 * perf_event_alloc()
1167 * perf_init_event()
1168 * perf_try_init_event() [ child , 1 ]
1169 *
1170 * While it appears there is an obvious deadlock here -- the parent and child
1171 * nesting levels are inverted between the two. This is in fact safe because
1172 * life-time rules separate them. That is an exiting task cannot fork, and a
1173 * spawning task cannot (yet) exit.
1174 *
1175 * But remember that that these are parent<->child context relations, and
1176 * migration does not affect children, therefore these two orderings should not
1177 * interact.
1178 *
1179 * The change in perf_event::ctx does not affect children (as claimed above)
1180 * because the sys_perf_event_open() case will install a new event and break
1181 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
1182 * concerned with cpuctx and that doesn't have children.
1183 *
1184 * The places that change perf_event::ctx will issue:
1185 *
1186 * perf_remove_from_context();
1187 * synchronize_rcu();
1188 * perf_install_in_context();
1189 *
1190 * to affect the change. The remove_from_context() + synchronize_rcu() should
1191 * quiesce the event, after which we can install it in the new location. This
1192 * means that only external vectors (perf_fops, prctl) can perturb the event
1193 * while in transit. Therefore all such accessors should also acquire
1194 * perf_event_context::mutex to serialize against this.
1195 *
1196 * However; because event->ctx can change while we're waiting to acquire
1197 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
1198 * function.
1199 *
1200 * Lock order:
1201 * cred_guard_mutex
1202 * task_struct::perf_event_mutex
1203 * perf_event_context::mutex
1204 * perf_event::child_mutex;
1205 * perf_event_context::lock
1206 * perf_event::mmap_mutex
1207 * mmap_sem
1208 */
1209 static struct perf_event_context *
1210 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
1211 {
1212 struct perf_event_context *ctx;
1213
1214 again:
1215 rcu_read_lock();
1216 ctx = ACCESS_ONCE(event->ctx);
1217 if (!atomic_inc_not_zero(&ctx->refcount)) {
1218 rcu_read_unlock();
1219 goto again;
1220 }
1221 rcu_read_unlock();
1222
1223 mutex_lock_nested(&ctx->mutex, nesting);
1224 if (event->ctx != ctx) {
1225 mutex_unlock(&ctx->mutex);
1226 put_ctx(ctx);
1227 goto again;
1228 }
1229
1230 return ctx;
1231 }
1232
1233 static inline struct perf_event_context *
1234 perf_event_ctx_lock(struct perf_event *event)
1235 {
1236 return perf_event_ctx_lock_nested(event, 0);
1237 }
1238
1239 static void perf_event_ctx_unlock(struct perf_event *event,
1240 struct perf_event_context *ctx)
1241 {
1242 mutex_unlock(&ctx->mutex);
1243 put_ctx(ctx);
1244 }
1245
1246 /*
1247 * This must be done under the ctx->lock, such as to serialize against
1248 * context_equiv(), therefore we cannot call put_ctx() since that might end up
1249 * calling scheduler related locks and ctx->lock nests inside those.
1250 */
1251 static __must_check struct perf_event_context *
1252 unclone_ctx(struct perf_event_context *ctx)
1253 {
1254 struct perf_event_context *parent_ctx = ctx->parent_ctx;
1255
1256 lockdep_assert_held(&ctx->lock);
1257
1258 if (parent_ctx)
1259 ctx->parent_ctx = NULL;
1260 ctx->generation++;
1261
1262 return parent_ctx;
1263 }
1264
1265 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1266 {
1267 /*
1268 * only top level events have the pid namespace they were created in
1269 */
1270 if (event->parent)
1271 event = event->parent;
1272
1273 return task_tgid_nr_ns(p, event->ns);
1274 }
1275
1276 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1277 {
1278 /*
1279 * only top level events have the pid namespace they were created in
1280 */
1281 if (event->parent)
1282 event = event->parent;
1283
1284 return task_pid_nr_ns(p, event->ns);
1285 }
1286
1287 /*
1288 * If we inherit events we want to return the parent event id
1289 * to userspace.
1290 */
1291 static u64 primary_event_id(struct perf_event *event)
1292 {
1293 u64 id = event->id;
1294
1295 if (event->parent)
1296 id = event->parent->id;
1297
1298 return id;
1299 }
1300
1301 /*
1302 * Get the perf_event_context for a task and lock it.
1303 *
1304 * This has to cope with with the fact that until it is locked,
1305 * the context could get moved to another task.
1306 */
1307 static struct perf_event_context *
1308 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
1309 {
1310 struct perf_event_context *ctx;
1311
1312 retry:
1313 /*
1314 * One of the few rules of preemptible RCU is that one cannot do
1315 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1316 * part of the read side critical section was irqs-enabled -- see
1317 * rcu_read_unlock_special().
1318 *
1319 * Since ctx->lock nests under rq->lock we must ensure the entire read
1320 * side critical section has interrupts disabled.
1321 */
1322 local_irq_save(*flags);
1323 rcu_read_lock();
1324 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
1325 if (ctx) {
1326 /*
1327 * If this context is a clone of another, it might
1328 * get swapped for another underneath us by
1329 * perf_event_task_sched_out, though the
1330 * rcu_read_lock() protects us from any context
1331 * getting freed. Lock the context and check if it
1332 * got swapped before we could get the lock, and retry
1333 * if so. If we locked the right context, then it
1334 * can't get swapped on us any more.
1335 */
1336 raw_spin_lock(&ctx->lock);
1337 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
1338 raw_spin_unlock(&ctx->lock);
1339 rcu_read_unlock();
1340 local_irq_restore(*flags);
1341 goto retry;
1342 }
1343
1344 if (ctx->task == TASK_TOMBSTONE ||
1345 !atomic_inc_not_zero(&ctx->refcount)) {
1346 raw_spin_unlock(&ctx->lock);
1347 ctx = NULL;
1348 } else {
1349 WARN_ON_ONCE(ctx->task != task);
1350 }
1351 }
1352 rcu_read_unlock();
1353 if (!ctx)
1354 local_irq_restore(*flags);
1355 return ctx;
1356 }
1357
1358 /*
1359 * Get the context for a task and increment its pin_count so it
1360 * can't get swapped to another task. This also increments its
1361 * reference count so that the context can't get freed.
1362 */
1363 static struct perf_event_context *
1364 perf_pin_task_context(struct task_struct *task, int ctxn)
1365 {
1366 struct perf_event_context *ctx;
1367 unsigned long flags;
1368
1369 ctx = perf_lock_task_context(task, ctxn, &flags);
1370 if (ctx) {
1371 ++ctx->pin_count;
1372 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1373 }
1374 return ctx;
1375 }
1376
1377 static void perf_unpin_context(struct perf_event_context *ctx)
1378 {
1379 unsigned long flags;
1380
1381 raw_spin_lock_irqsave(&ctx->lock, flags);
1382 --ctx->pin_count;
1383 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1384 }
1385
1386 /*
1387 * Update the record of the current time in a context.
1388 */
1389 static void update_context_time(struct perf_event_context *ctx)
1390 {
1391 u64 now = perf_clock();
1392
1393 ctx->time += now - ctx->timestamp;
1394 ctx->timestamp = now;
1395 }
1396
1397 static u64 perf_event_time(struct perf_event *event)
1398 {
1399 struct perf_event_context *ctx = event->ctx;
1400
1401 if (is_cgroup_event(event))
1402 return perf_cgroup_event_time(event);
1403
1404 return ctx ? ctx->time : 0;
1405 }
1406
1407 /*
1408 * Update the total_time_enabled and total_time_running fields for a event.
1409 */
1410 static void update_event_times(struct perf_event *event)
1411 {
1412 struct perf_event_context *ctx = event->ctx;
1413 u64 run_end;
1414
1415 lockdep_assert_held(&ctx->lock);
1416
1417 if (event->state < PERF_EVENT_STATE_INACTIVE ||
1418 event->group_leader->state < PERF_EVENT_STATE_INACTIVE)
1419 return;
1420
1421 /*
1422 * in cgroup mode, time_enabled represents
1423 * the time the event was enabled AND active
1424 * tasks were in the monitored cgroup. This is
1425 * independent of the activity of the context as
1426 * there may be a mix of cgroup and non-cgroup events.
1427 *
1428 * That is why we treat cgroup events differently
1429 * here.
1430 */
1431 if (is_cgroup_event(event))
1432 run_end = perf_cgroup_event_time(event);
1433 else if (ctx->is_active)
1434 run_end = ctx->time;
1435 else
1436 run_end = event->tstamp_stopped;
1437
1438 event->total_time_enabled = run_end - event->tstamp_enabled;
1439
1440 if (event->state == PERF_EVENT_STATE_INACTIVE)
1441 run_end = event->tstamp_stopped;
1442 else
1443 run_end = perf_event_time(event);
1444
1445 event->total_time_running = run_end - event->tstamp_running;
1446
1447 }
1448
1449 /*
1450 * Update total_time_enabled and total_time_running for all events in a group.
1451 */
1452 static void update_group_times(struct perf_event *leader)
1453 {
1454 struct perf_event *event;
1455
1456 update_event_times(leader);
1457 list_for_each_entry(event, &leader->sibling_list, group_entry)
1458 update_event_times(event);
1459 }
1460
1461 static struct list_head *
1462 ctx_group_list(struct perf_event *event, struct perf_event_context *ctx)
1463 {
1464 if (event->attr.pinned)
1465 return &ctx->pinned_groups;
1466 else
1467 return &ctx->flexible_groups;
1468 }
1469
1470 /*
1471 * Add a event from the lists for its context.
1472 * Must be called with ctx->mutex and ctx->lock held.
1473 */
1474 static void
1475 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1476 {
1477 lockdep_assert_held(&ctx->lock);
1478
1479 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1480 event->attach_state |= PERF_ATTACH_CONTEXT;
1481
1482 /*
1483 * If we're a stand alone event or group leader, we go to the context
1484 * list, group events are kept attached to the group so that
1485 * perf_group_detach can, at all times, locate all siblings.
1486 */
1487 if (event->group_leader == event) {
1488 struct list_head *list;
1489
1490 event->group_caps = event->event_caps;
1491
1492 list = ctx_group_list(event, ctx);
1493 list_add_tail(&event->group_entry, list);
1494 }
1495
1496 list_update_cgroup_event(event, ctx, true);
1497
1498 list_add_rcu(&event->event_entry, &ctx->event_list);
1499 ctx->nr_events++;
1500 if (event->attr.inherit_stat)
1501 ctx->nr_stat++;
1502
1503 ctx->generation++;
1504 }
1505
1506 /*
1507 * Initialize event state based on the perf_event_attr::disabled.
1508 */
1509 static inline void perf_event__state_init(struct perf_event *event)
1510 {
1511 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1512 PERF_EVENT_STATE_INACTIVE;
1513 }
1514
1515 static void __perf_event_read_size(struct perf_event *event, int nr_siblings)
1516 {
1517 int entry = sizeof(u64); /* value */
1518 int size = 0;
1519 int nr = 1;
1520
1521 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1522 size += sizeof(u64);
1523
1524 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1525 size += sizeof(u64);
1526
1527 if (event->attr.read_format & PERF_FORMAT_ID)
1528 entry += sizeof(u64);
1529
1530 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1531 nr += nr_siblings;
1532 size += sizeof(u64);
1533 }
1534
1535 size += entry * nr;
1536 event->read_size = size;
1537 }
1538
1539 static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
1540 {
1541 struct perf_sample_data *data;
1542 u16 size = 0;
1543
1544 if (sample_type & PERF_SAMPLE_IP)
1545 size += sizeof(data->ip);
1546
1547 if (sample_type & PERF_SAMPLE_ADDR)
1548 size += sizeof(data->addr);
1549
1550 if (sample_type & PERF_SAMPLE_PERIOD)
1551 size += sizeof(data->period);
1552
1553 if (sample_type & PERF_SAMPLE_WEIGHT)
1554 size += sizeof(data->weight);
1555
1556 if (sample_type & PERF_SAMPLE_READ)
1557 size += event->read_size;
1558
1559 if (sample_type & PERF_SAMPLE_DATA_SRC)
1560 size += sizeof(data->data_src.val);
1561
1562 if (sample_type & PERF_SAMPLE_TRANSACTION)
1563 size += sizeof(data->txn);
1564
1565 event->header_size = size;
1566 }
1567
1568 /*
1569 * Called at perf_event creation and when events are attached/detached from a
1570 * group.
1571 */
1572 static void perf_event__header_size(struct perf_event *event)
1573 {
1574 __perf_event_read_size(event,
1575 event->group_leader->nr_siblings);
1576 __perf_event_header_size(event, event->attr.sample_type);
1577 }
1578
1579 static void perf_event__id_header_size(struct perf_event *event)
1580 {
1581 struct perf_sample_data *data;
1582 u64 sample_type = event->attr.sample_type;
1583 u16 size = 0;
1584
1585 if (sample_type & PERF_SAMPLE_TID)
1586 size += sizeof(data->tid_entry);
1587
1588 if (sample_type & PERF_SAMPLE_TIME)
1589 size += sizeof(data->time);
1590
1591 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1592 size += sizeof(data->id);
1593
1594 if (sample_type & PERF_SAMPLE_ID)
1595 size += sizeof(data->id);
1596
1597 if (sample_type & PERF_SAMPLE_STREAM_ID)
1598 size += sizeof(data->stream_id);
1599
1600 if (sample_type & PERF_SAMPLE_CPU)
1601 size += sizeof(data->cpu_entry);
1602
1603 event->id_header_size = size;
1604 }
1605
1606 static bool perf_event_validate_size(struct perf_event *event)
1607 {
1608 /*
1609 * The values computed here will be over-written when we actually
1610 * attach the event.
1611 */
1612 __perf_event_read_size(event, event->group_leader->nr_siblings + 1);
1613 __perf_event_header_size(event, event->attr.sample_type & ~PERF_SAMPLE_READ);
1614 perf_event__id_header_size(event);
1615
1616 /*
1617 * Sum the lot; should not exceed the 64k limit we have on records.
1618 * Conservative limit to allow for callchains and other variable fields.
1619 */
1620 if (event->read_size + event->header_size +
1621 event->id_header_size + sizeof(struct perf_event_header) >= 16*1024)
1622 return false;
1623
1624 return true;
1625 }
1626
1627 static void perf_group_attach(struct perf_event *event)
1628 {
1629 struct perf_event *group_leader = event->group_leader, *pos;
1630
1631 lockdep_assert_held(&event->ctx->lock);
1632
1633 /*
1634 * We can have double attach due to group movement in perf_event_open.
1635 */
1636 if (event->attach_state & PERF_ATTACH_GROUP)
1637 return;
1638
1639 event->attach_state |= PERF_ATTACH_GROUP;
1640
1641 if (group_leader == event)
1642 return;
1643
1644 WARN_ON_ONCE(group_leader->ctx != event->ctx);
1645
1646 group_leader->group_caps &= event->event_caps;
1647
1648 list_add_tail(&event->group_entry, &group_leader->sibling_list);
1649 group_leader->nr_siblings++;
1650
1651 perf_event__header_size(group_leader);
1652
1653 list_for_each_entry(pos, &group_leader->sibling_list, group_entry)
1654 perf_event__header_size(pos);
1655 }
1656
1657 /*
1658 * Remove a event from the lists for its context.
1659 * Must be called with ctx->mutex and ctx->lock held.
1660 */
1661 static void
1662 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1663 {
1664 WARN_ON_ONCE(event->ctx != ctx);
1665 lockdep_assert_held(&ctx->lock);
1666
1667 /*
1668 * We can have double detach due to exit/hot-unplug + close.
1669 */
1670 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1671 return;
1672
1673 event->attach_state &= ~PERF_ATTACH_CONTEXT;
1674
1675 list_update_cgroup_event(event, ctx, false);
1676
1677 ctx->nr_events--;
1678 if (event->attr.inherit_stat)
1679 ctx->nr_stat--;
1680
1681 list_del_rcu(&event->event_entry);
1682
1683 if (event->group_leader == event)
1684 list_del_init(&event->group_entry);
1685
1686 update_group_times(event);
1687
1688 /*
1689 * If event was in error state, then keep it
1690 * that way, otherwise bogus counts will be
1691 * returned on read(). The only way to get out
1692 * of error state is by explicit re-enabling
1693 * of the event
1694 */
1695 if (event->state > PERF_EVENT_STATE_OFF)
1696 event->state = PERF_EVENT_STATE_OFF;
1697
1698 ctx->generation++;
1699 }
1700
1701 static void perf_group_detach(struct perf_event *event)
1702 {
1703 struct perf_event *sibling, *tmp;
1704 struct list_head *list = NULL;
1705
1706 lockdep_assert_held(&event->ctx->lock);
1707
1708 /*
1709 * We can have double detach due to exit/hot-unplug + close.
1710 */
1711 if (!(event->attach_state & PERF_ATTACH_GROUP))
1712 return;
1713
1714 event->attach_state &= ~PERF_ATTACH_GROUP;
1715
1716 /*
1717 * If this is a sibling, remove it from its group.
1718 */
1719 if (event->group_leader != event) {
1720 list_del_init(&event->group_entry);
1721 event->group_leader->nr_siblings--;
1722 goto out;
1723 }
1724
1725 if (!list_empty(&event->group_entry))
1726 list = &event->group_entry;
1727
1728 /*
1729 * If this was a group event with sibling events then
1730 * upgrade the siblings to singleton events by adding them
1731 * to whatever list we are on.
1732 */
1733 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) {
1734 if (list)
1735 list_move_tail(&sibling->group_entry, list);
1736 sibling->group_leader = sibling;
1737
1738 /* Inherit group flags from the previous leader */
1739 sibling->group_caps = event->group_caps;
1740
1741 WARN_ON_ONCE(sibling->ctx != event->ctx);
1742 }
1743
1744 out:
1745 perf_event__header_size(event->group_leader);
1746
1747 list_for_each_entry(tmp, &event->group_leader->sibling_list, group_entry)
1748 perf_event__header_size(tmp);
1749 }
1750
1751 static bool is_orphaned_event(struct perf_event *event)
1752 {
1753 return event->state == PERF_EVENT_STATE_DEAD;
1754 }
1755
1756 static inline int __pmu_filter_match(struct perf_event *event)
1757 {
1758 struct pmu *pmu = event->pmu;
1759 return pmu->filter_match ? pmu->filter_match(event) : 1;
1760 }
1761
1762 /*
1763 * Check whether we should attempt to schedule an event group based on
1764 * PMU-specific filtering. An event group can consist of HW and SW events,
1765 * potentially with a SW leader, so we must check all the filters, to
1766 * determine whether a group is schedulable:
1767 */
1768 static inline int pmu_filter_match(struct perf_event *event)
1769 {
1770 struct perf_event *child;
1771
1772 if (!__pmu_filter_match(event))
1773 return 0;
1774
1775 list_for_each_entry(child, &event->sibling_list, group_entry) {
1776 if (!__pmu_filter_match(child))
1777 return 0;
1778 }
1779
1780 return 1;
1781 }
1782
1783 static inline int
1784 event_filter_match(struct perf_event *event)
1785 {
1786 return (event->cpu == -1 || event->cpu == smp_processor_id()) &&
1787 perf_cgroup_match(event) && pmu_filter_match(event);
1788 }
1789
1790 static void
1791 event_sched_out(struct perf_event *event,
1792 struct perf_cpu_context *cpuctx,
1793 struct perf_event_context *ctx)
1794 {
1795 u64 tstamp = perf_event_time(event);
1796 u64 delta;
1797
1798 WARN_ON_ONCE(event->ctx != ctx);
1799 lockdep_assert_held(&ctx->lock);
1800
1801 /*
1802 * An event which could not be activated because of
1803 * filter mismatch still needs to have its timings
1804 * maintained, otherwise bogus information is return
1805 * via read() for time_enabled, time_running:
1806 */
1807 if (event->state == PERF_EVENT_STATE_INACTIVE &&
1808 !event_filter_match(event)) {
1809 delta = tstamp - event->tstamp_stopped;
1810 event->tstamp_running += delta;
1811 event->tstamp_stopped = tstamp;
1812 }
1813
1814 if (event->state != PERF_EVENT_STATE_ACTIVE)
1815 return;
1816
1817 perf_pmu_disable(event->pmu);
1818
1819 event->tstamp_stopped = tstamp;
1820 event->pmu->del(event, 0);
1821 event->oncpu = -1;
1822 event->state = PERF_EVENT_STATE_INACTIVE;
1823 if (event->pending_disable) {
1824 event->pending_disable = 0;
1825 event->state = PERF_EVENT_STATE_OFF;
1826 }
1827
1828 if (!is_software_event(event))
1829 cpuctx->active_oncpu--;
1830 if (!--ctx->nr_active)
1831 perf_event_ctx_deactivate(ctx);
1832 if (event->attr.freq && event->attr.sample_freq)
1833 ctx->nr_freq--;
1834 if (event->attr.exclusive || !cpuctx->active_oncpu)
1835 cpuctx->exclusive = 0;
1836
1837 perf_pmu_enable(event->pmu);
1838 }
1839
1840 static void
1841 group_sched_out(struct perf_event *group_event,
1842 struct perf_cpu_context *cpuctx,
1843 struct perf_event_context *ctx)
1844 {
1845 struct perf_event *event;
1846 int state = group_event->state;
1847
1848 perf_pmu_disable(ctx->pmu);
1849
1850 event_sched_out(group_event, cpuctx, ctx);
1851
1852 /*
1853 * Schedule out siblings (if any):
1854 */
1855 list_for_each_entry(event, &group_event->sibling_list, group_entry)
1856 event_sched_out(event, cpuctx, ctx);
1857
1858 perf_pmu_enable(ctx->pmu);
1859
1860 if (state == PERF_EVENT_STATE_ACTIVE && group_event->attr.exclusive)
1861 cpuctx->exclusive = 0;
1862 }
1863
1864 #define DETACH_GROUP 0x01UL
1865
1866 /*
1867 * Cross CPU call to remove a performance event
1868 *
1869 * We disable the event on the hardware level first. After that we
1870 * remove it from the context list.
1871 */
1872 static void
1873 __perf_remove_from_context(struct perf_event *event,
1874 struct perf_cpu_context *cpuctx,
1875 struct perf_event_context *ctx,
1876 void *info)
1877 {
1878 unsigned long flags = (unsigned long)info;
1879
1880 event_sched_out(event, cpuctx, ctx);
1881 if (flags & DETACH_GROUP)
1882 perf_group_detach(event);
1883 list_del_event(event, ctx);
1884
1885 if (!ctx->nr_events && ctx->is_active) {
1886 ctx->is_active = 0;
1887 if (ctx->task) {
1888 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
1889 cpuctx->task_ctx = NULL;
1890 }
1891 }
1892 }
1893
1894 /*
1895 * Remove the event from a task's (or a CPU's) list of events.
1896 *
1897 * If event->ctx is a cloned context, callers must make sure that
1898 * every task struct that event->ctx->task could possibly point to
1899 * remains valid. This is OK when called from perf_release since
1900 * that only calls us on the top-level context, which can't be a clone.
1901 * When called from perf_event_exit_task, it's OK because the
1902 * context has been detached from its task.
1903 */
1904 static void perf_remove_from_context(struct perf_event *event, unsigned long flags)
1905 {
1906 struct perf_event_context *ctx = event->ctx;
1907
1908 lockdep_assert_held(&ctx->mutex);
1909
1910 event_function_call(event, __perf_remove_from_context, (void *)flags);
1911
1912 /*
1913 * The above event_function_call() can NO-OP when it hits
1914 * TASK_TOMBSTONE. In that case we must already have been detached
1915 * from the context (by perf_event_exit_event()) but the grouping
1916 * might still be in-tact.
1917 */
1918 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1919 if ((flags & DETACH_GROUP) &&
1920 (event->attach_state & PERF_ATTACH_GROUP)) {
1921 /*
1922 * Since in that case we cannot possibly be scheduled, simply
1923 * detach now.
1924 */
1925 raw_spin_lock_irq(&ctx->lock);
1926 perf_group_detach(event);
1927 raw_spin_unlock_irq(&ctx->lock);
1928 }
1929 }
1930
1931 /*
1932 * Cross CPU call to disable a performance event
1933 */
1934 static void __perf_event_disable(struct perf_event *event,
1935 struct perf_cpu_context *cpuctx,
1936 struct perf_event_context *ctx,
1937 void *info)
1938 {
1939 if (event->state < PERF_EVENT_STATE_INACTIVE)
1940 return;
1941
1942 update_context_time(ctx);
1943 update_cgrp_time_from_event(event);
1944 update_group_times(event);
1945 if (event == event->group_leader)
1946 group_sched_out(event, cpuctx, ctx);
1947 else
1948 event_sched_out(event, cpuctx, ctx);
1949 event->state = PERF_EVENT_STATE_OFF;
1950 }
1951
1952 /*
1953 * Disable a event.
1954 *
1955 * If event->ctx is a cloned context, callers must make sure that
1956 * every task struct that event->ctx->task could possibly point to
1957 * remains valid. This condition is satisifed when called through
1958 * perf_event_for_each_child or perf_event_for_each because they
1959 * hold the top-level event's child_mutex, so any descendant that
1960 * goes to exit will block in perf_event_exit_event().
1961 *
1962 * When called from perf_pending_event it's OK because event->ctx
1963 * is the current context on this CPU and preemption is disabled,
1964 * hence we can't get into perf_event_task_sched_out for this context.
1965 */
1966 static void _perf_event_disable(struct perf_event *event)
1967 {
1968 struct perf_event_context *ctx = event->ctx;
1969
1970 raw_spin_lock_irq(&ctx->lock);
1971 if (event->state <= PERF_EVENT_STATE_OFF) {
1972 raw_spin_unlock_irq(&ctx->lock);
1973 return;
1974 }
1975 raw_spin_unlock_irq(&ctx->lock);
1976
1977 event_function_call(event, __perf_event_disable, NULL);
1978 }
1979
1980 void perf_event_disable_local(struct perf_event *event)
1981 {
1982 event_function_local(event, __perf_event_disable, NULL);
1983 }
1984
1985 /*
1986 * Strictly speaking kernel users cannot create groups and therefore this
1987 * interface does not need the perf_event_ctx_lock() magic.
1988 */
1989 void perf_event_disable(struct perf_event *event)
1990 {
1991 struct perf_event_context *ctx;
1992
1993 ctx = perf_event_ctx_lock(event);
1994 _perf_event_disable(event);
1995 perf_event_ctx_unlock(event, ctx);
1996 }
1997 EXPORT_SYMBOL_GPL(perf_event_disable);
1998
1999 void perf_event_disable_inatomic(struct perf_event *event)
2000 {
2001 event->pending_disable = 1;
2002 irq_work_queue(&event->pending);
2003 }
2004
2005 static void perf_set_shadow_time(struct perf_event *event,
2006 struct perf_event_context *ctx,
2007 u64 tstamp)
2008 {
2009 /*
2010 * use the correct time source for the time snapshot
2011 *
2012 * We could get by without this by leveraging the
2013 * fact that to get to this function, the caller
2014 * has most likely already called update_context_time()
2015 * and update_cgrp_time_xx() and thus both timestamp
2016 * are identical (or very close). Given that tstamp is,
2017 * already adjusted for cgroup, we could say that:
2018 * tstamp - ctx->timestamp
2019 * is equivalent to
2020 * tstamp - cgrp->timestamp.
2021 *
2022 * Then, in perf_output_read(), the calculation would
2023 * work with no changes because:
2024 * - event is guaranteed scheduled in
2025 * - no scheduled out in between
2026 * - thus the timestamp would be the same
2027 *
2028 * But this is a bit hairy.
2029 *
2030 * So instead, we have an explicit cgroup call to remain
2031 * within the time time source all along. We believe it
2032 * is cleaner and simpler to understand.
2033 */
2034 if (is_cgroup_event(event))
2035 perf_cgroup_set_shadow_time(event, tstamp);
2036 else
2037 event->shadow_ctx_time = tstamp - ctx->timestamp;
2038 }
2039
2040 #define MAX_INTERRUPTS (~0ULL)
2041
2042 static void perf_log_throttle(struct perf_event *event, int enable);
2043 static void perf_log_itrace_start(struct perf_event *event);
2044
2045 static int
2046 event_sched_in(struct perf_event *event,
2047 struct perf_cpu_context *cpuctx,
2048 struct perf_event_context *ctx)
2049 {
2050 u64 tstamp = perf_event_time(event);
2051 int ret = 0;
2052
2053 lockdep_assert_held(&ctx->lock);
2054
2055 if (event->state <= PERF_EVENT_STATE_OFF)
2056 return 0;
2057
2058 WRITE_ONCE(event->oncpu, smp_processor_id());
2059 /*
2060 * Order event::oncpu write to happen before the ACTIVE state
2061 * is visible.
2062 */
2063 smp_wmb();
2064 WRITE_ONCE(event->state, PERF_EVENT_STATE_ACTIVE);
2065
2066 /*
2067 * Unthrottle events, since we scheduled we might have missed several
2068 * ticks already, also for a heavily scheduling task there is little
2069 * guarantee it'll get a tick in a timely manner.
2070 */
2071 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
2072 perf_log_throttle(event, 1);
2073 event->hw.interrupts = 0;
2074 }
2075
2076 /*
2077 * The new state must be visible before we turn it on in the hardware:
2078 */
2079 smp_wmb();
2080
2081 perf_pmu_disable(event->pmu);
2082
2083 perf_set_shadow_time(event, ctx, tstamp);
2084
2085 perf_log_itrace_start(event);
2086
2087 if (event->pmu->add(event, PERF_EF_START)) {
2088 event->state = PERF_EVENT_STATE_INACTIVE;
2089 event->oncpu = -1;
2090 ret = -EAGAIN;
2091 goto out;
2092 }
2093
2094 event->tstamp_running += tstamp - event->tstamp_stopped;
2095
2096 if (!is_software_event(event))
2097 cpuctx->active_oncpu++;
2098 if (!ctx->nr_active++)
2099 perf_event_ctx_activate(ctx);
2100 if (event->attr.freq && event->attr.sample_freq)
2101 ctx->nr_freq++;
2102
2103 if (event->attr.exclusive)
2104 cpuctx->exclusive = 1;
2105
2106 out:
2107 perf_pmu_enable(event->pmu);
2108
2109 return ret;
2110 }
2111
2112 static int
2113 group_sched_in(struct perf_event *group_event,
2114 struct perf_cpu_context *cpuctx,
2115 struct perf_event_context *ctx)
2116 {
2117 struct perf_event *event, *partial_group = NULL;
2118 struct pmu *pmu = ctx->pmu;
2119 u64 now = ctx->time;
2120 bool simulate = false;
2121
2122 if (group_event->state == PERF_EVENT_STATE_OFF)
2123 return 0;
2124
2125 pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
2126
2127 if (event_sched_in(group_event, cpuctx, ctx)) {
2128 pmu->cancel_txn(pmu);
2129 perf_mux_hrtimer_restart(cpuctx);
2130 return -EAGAIN;
2131 }
2132
2133 /*
2134 * Schedule in siblings as one group (if any):
2135 */
2136 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
2137 if (event_sched_in(event, cpuctx, ctx)) {
2138 partial_group = event;
2139 goto group_error;
2140 }
2141 }
2142
2143 if (!pmu->commit_txn(pmu))
2144 return 0;
2145
2146 group_error:
2147 /*
2148 * Groups can be scheduled in as one unit only, so undo any
2149 * partial group before returning:
2150 * The events up to the failed event are scheduled out normally,
2151 * tstamp_stopped will be updated.
2152 *
2153 * The failed events and the remaining siblings need to have
2154 * their timings updated as if they had gone thru event_sched_in()
2155 * and event_sched_out(). This is required to get consistent timings
2156 * across the group. This also takes care of the case where the group
2157 * could never be scheduled by ensuring tstamp_stopped is set to mark
2158 * the time the event was actually stopped, such that time delta
2159 * calculation in update_event_times() is correct.
2160 */
2161 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
2162 if (event == partial_group)
2163 simulate = true;
2164
2165 if (simulate) {
2166 event->tstamp_running += now - event->tstamp_stopped;
2167 event->tstamp_stopped = now;
2168 } else {
2169 event_sched_out(event, cpuctx, ctx);
2170 }
2171 }
2172 event_sched_out(group_event, cpuctx, ctx);
2173
2174 pmu->cancel_txn(pmu);
2175
2176 perf_mux_hrtimer_restart(cpuctx);
2177
2178 return -EAGAIN;
2179 }
2180
2181 /*
2182 * Work out whether we can put this event group on the CPU now.
2183 */
2184 static int group_can_go_on(struct perf_event *event,
2185 struct perf_cpu_context *cpuctx,
2186 int can_add_hw)
2187 {
2188 /*
2189 * Groups consisting entirely of software events can always go on.
2190 */
2191 if (event->group_caps & PERF_EV_CAP_SOFTWARE)
2192 return 1;
2193 /*
2194 * If an exclusive group is already on, no other hardware
2195 * events can go on.
2196 */
2197 if (cpuctx->exclusive)
2198 return 0;
2199 /*
2200 * If this group is exclusive and there are already
2201 * events on the CPU, it can't go on.
2202 */
2203 if (event->attr.exclusive && cpuctx->active_oncpu)
2204 return 0;
2205 /*
2206 * Otherwise, try to add it if all previous groups were able
2207 * to go on.
2208 */
2209 return can_add_hw;
2210 }
2211
2212 static void add_event_to_ctx(struct perf_event *event,
2213 struct perf_event_context *ctx)
2214 {
2215 u64 tstamp = perf_event_time(event);
2216
2217 list_add_event(event, ctx);
2218 perf_group_attach(event);
2219 event->tstamp_enabled = tstamp;
2220 event->tstamp_running = tstamp;
2221 event->tstamp_stopped = tstamp;
2222 }
2223
2224 static void ctx_sched_out(struct perf_event_context *ctx,
2225 struct perf_cpu_context *cpuctx,
2226 enum event_type_t event_type);
2227 static void
2228 ctx_sched_in(struct perf_event_context *ctx,
2229 struct perf_cpu_context *cpuctx,
2230 enum event_type_t event_type,
2231 struct task_struct *task);
2232
2233 static void task_ctx_sched_out(struct perf_cpu_context *cpuctx,
2234 struct perf_event_context *ctx)
2235 {
2236 if (!cpuctx->task_ctx)
2237 return;
2238
2239 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2240 return;
2241
2242 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2243 }
2244
2245 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2246 struct perf_event_context *ctx,
2247 struct task_struct *task)
2248 {
2249 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
2250 if (ctx)
2251 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
2252 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
2253 if (ctx)
2254 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
2255 }
2256
2257 static void ctx_resched(struct perf_cpu_context *cpuctx,
2258 struct perf_event_context *task_ctx)
2259 {
2260 perf_pmu_disable(cpuctx->ctx.pmu);
2261 if (task_ctx)
2262 task_ctx_sched_out(cpuctx, task_ctx);
2263 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
2264 perf_event_sched_in(cpuctx, task_ctx, current);
2265 perf_pmu_enable(cpuctx->ctx.pmu);
2266 }
2267
2268 /*
2269 * Cross CPU call to install and enable a performance event
2270 *
2271 * Very similar to remote_function() + event_function() but cannot assume that
2272 * things like ctx->is_active and cpuctx->task_ctx are set.
2273 */
2274 static int __perf_install_in_context(void *info)
2275 {
2276 struct perf_event *event = info;
2277 struct perf_event_context *ctx = event->ctx;
2278 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2279 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2280 bool reprogram = true;
2281 int ret = 0;
2282
2283 raw_spin_lock(&cpuctx->ctx.lock);
2284 if (ctx->task) {
2285 raw_spin_lock(&ctx->lock);
2286 task_ctx = ctx;
2287
2288 reprogram = (ctx->task == current);
2289
2290 /*
2291 * If the task is running, it must be running on this CPU,
2292 * otherwise we cannot reprogram things.
2293 *
2294 * If its not running, we don't care, ctx->lock will
2295 * serialize against it becoming runnable.
2296 */
2297 if (task_curr(ctx->task) && !reprogram) {
2298 ret = -ESRCH;
2299 goto unlock;
2300 }
2301
2302 WARN_ON_ONCE(reprogram && cpuctx->task_ctx && cpuctx->task_ctx != ctx);
2303 } else if (task_ctx) {
2304 raw_spin_lock(&task_ctx->lock);
2305 }
2306
2307 if (reprogram) {
2308 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2309 add_event_to_ctx(event, ctx);
2310 ctx_resched(cpuctx, task_ctx);
2311 } else {
2312 add_event_to_ctx(event, ctx);
2313 }
2314
2315 unlock:
2316 perf_ctx_unlock(cpuctx, task_ctx);
2317
2318 return ret;
2319 }
2320
2321 /*
2322 * Attach a performance event to a context.
2323 *
2324 * Very similar to event_function_call, see comment there.
2325 */
2326 static void
2327 perf_install_in_context(struct perf_event_context *ctx,
2328 struct perf_event *event,
2329 int cpu)
2330 {
2331 struct task_struct *task = READ_ONCE(ctx->task);
2332
2333 lockdep_assert_held(&ctx->mutex);
2334
2335 if (event->cpu != -1)
2336 event->cpu = cpu;
2337
2338 /*
2339 * Ensures that if we can observe event->ctx, both the event and ctx
2340 * will be 'complete'. See perf_iterate_sb_cpu().
2341 */
2342 smp_store_release(&event->ctx, ctx);
2343
2344 if (!task) {
2345 cpu_function_call(cpu, __perf_install_in_context, event);
2346 return;
2347 }
2348
2349 /*
2350 * Should not happen, we validate the ctx is still alive before calling.
2351 */
2352 if (WARN_ON_ONCE(task == TASK_TOMBSTONE))
2353 return;
2354
2355 /*
2356 * Installing events is tricky because we cannot rely on ctx->is_active
2357 * to be set in case this is the nr_events 0 -> 1 transition.
2358 *
2359 * Instead we use task_curr(), which tells us if the task is running.
2360 * However, since we use task_curr() outside of rq::lock, we can race
2361 * against the actual state. This means the result can be wrong.
2362 *
2363 * If we get a false positive, we retry, this is harmless.
2364 *
2365 * If we get a false negative, things are complicated. If we are after
2366 * perf_event_context_sched_in() ctx::lock will serialize us, and the
2367 * value must be correct. If we're before, it doesn't matter since
2368 * perf_event_context_sched_in() will program the counter.
2369 *
2370 * However, this hinges on the remote context switch having observed
2371 * our task->perf_event_ctxp[] store, such that it will in fact take
2372 * ctx::lock in perf_event_context_sched_in().
2373 *
2374 * We do this by task_function_call(), if the IPI fails to hit the task
2375 * we know any future context switch of task must see the
2376 * perf_event_ctpx[] store.
2377 */
2378
2379 /*
2380 * This smp_mb() orders the task->perf_event_ctxp[] store with the
2381 * task_cpu() load, such that if the IPI then does not find the task
2382 * running, a future context switch of that task must observe the
2383 * store.
2384 */
2385 smp_mb();
2386 again:
2387 if (!task_function_call(task, __perf_install_in_context, event))
2388 return;
2389
2390 raw_spin_lock_irq(&ctx->lock);
2391 task = ctx->task;
2392 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) {
2393 /*
2394 * Cannot happen because we already checked above (which also
2395 * cannot happen), and we hold ctx->mutex, which serializes us
2396 * against perf_event_exit_task_context().
2397 */
2398 raw_spin_unlock_irq(&ctx->lock);
2399 return;
2400 }
2401 /*
2402 * If the task is not running, ctx->lock will avoid it becoming so,
2403 * thus we can safely install the event.
2404 */
2405 if (task_curr(task)) {
2406 raw_spin_unlock_irq(&ctx->lock);
2407 goto again;
2408 }
2409 add_event_to_ctx(event, ctx);
2410 raw_spin_unlock_irq(&ctx->lock);
2411 }
2412
2413 /*
2414 * Put a event into inactive state and update time fields.
2415 * Enabling the leader of a group effectively enables all
2416 * the group members that aren't explicitly disabled, so we
2417 * have to update their ->tstamp_enabled also.
2418 * Note: this works for group members as well as group leaders
2419 * since the non-leader members' sibling_lists will be empty.
2420 */
2421 static void __perf_event_mark_enabled(struct perf_event *event)
2422 {
2423 struct perf_event *sub;
2424 u64 tstamp = perf_event_time(event);
2425
2426 event->state = PERF_EVENT_STATE_INACTIVE;
2427 event->tstamp_enabled = tstamp - event->total_time_enabled;
2428 list_for_each_entry(sub, &event->sibling_list, group_entry) {
2429 if (sub->state >= PERF_EVENT_STATE_INACTIVE)
2430 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
2431 }
2432 }
2433
2434 /*
2435 * Cross CPU call to enable a performance event
2436 */
2437 static void __perf_event_enable(struct perf_event *event,
2438 struct perf_cpu_context *cpuctx,
2439 struct perf_event_context *ctx,
2440 void *info)
2441 {
2442 struct perf_event *leader = event->group_leader;
2443 struct perf_event_context *task_ctx;
2444
2445 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2446 event->state <= PERF_EVENT_STATE_ERROR)
2447 return;
2448
2449 if (ctx->is_active)
2450 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2451
2452 __perf_event_mark_enabled(event);
2453
2454 if (!ctx->is_active)
2455 return;
2456
2457 if (!event_filter_match(event)) {
2458 if (is_cgroup_event(event))
2459 perf_cgroup_defer_enabled(event);
2460 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2461 return;
2462 }
2463
2464 /*
2465 * If the event is in a group and isn't the group leader,
2466 * then don't put it on unless the group is on.
2467 */
2468 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE) {
2469 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2470 return;
2471 }
2472
2473 task_ctx = cpuctx->task_ctx;
2474 if (ctx->task)
2475 WARN_ON_ONCE(task_ctx != ctx);
2476
2477 ctx_resched(cpuctx, task_ctx);
2478 }
2479
2480 /*
2481 * Enable a event.
2482 *
2483 * If event->ctx is a cloned context, callers must make sure that
2484 * every task struct that event->ctx->task could possibly point to
2485 * remains valid. This condition is satisfied when called through
2486 * perf_event_for_each_child or perf_event_for_each as described
2487 * for perf_event_disable.
2488 */
2489 static void _perf_event_enable(struct perf_event *event)
2490 {
2491 struct perf_event_context *ctx = event->ctx;
2492
2493 raw_spin_lock_irq(&ctx->lock);
2494 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2495 event->state < PERF_EVENT_STATE_ERROR) {
2496 raw_spin_unlock_irq(&ctx->lock);
2497 return;
2498 }
2499
2500 /*
2501 * If the event is in error state, clear that first.
2502 *
2503 * That way, if we see the event in error state below, we know that it
2504 * has gone back into error state, as distinct from the task having
2505 * been scheduled away before the cross-call arrived.
2506 */
2507 if (event->state == PERF_EVENT_STATE_ERROR)
2508 event->state = PERF_EVENT_STATE_OFF;
2509 raw_spin_unlock_irq(&ctx->lock);
2510
2511 event_function_call(event, __perf_event_enable, NULL);
2512 }
2513
2514 /*
2515 * See perf_event_disable();
2516 */
2517 void perf_event_enable(struct perf_event *event)
2518 {
2519 struct perf_event_context *ctx;
2520
2521 ctx = perf_event_ctx_lock(event);
2522 _perf_event_enable(event);
2523 perf_event_ctx_unlock(event, ctx);
2524 }
2525 EXPORT_SYMBOL_GPL(perf_event_enable);
2526
2527 struct stop_event_data {
2528 struct perf_event *event;
2529 unsigned int restart;
2530 };
2531
2532 static int __perf_event_stop(void *info)
2533 {
2534 struct stop_event_data *sd = info;
2535 struct perf_event *event = sd->event;
2536
2537 /* if it's already INACTIVE, do nothing */
2538 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
2539 return 0;
2540
2541 /* matches smp_wmb() in event_sched_in() */
2542 smp_rmb();
2543
2544 /*
2545 * There is a window with interrupts enabled before we get here,
2546 * so we need to check again lest we try to stop another CPU's event.
2547 */
2548 if (READ_ONCE(event->oncpu) != smp_processor_id())
2549 return -EAGAIN;
2550
2551 event->pmu->stop(event, PERF_EF_UPDATE);
2552
2553 /*
2554 * May race with the actual stop (through perf_pmu_output_stop()),
2555 * but it is only used for events with AUX ring buffer, and such
2556 * events will refuse to restart because of rb::aux_mmap_count==0,
2557 * see comments in perf_aux_output_begin().
2558 *
2559 * Since this is happening on a event-local CPU, no trace is lost
2560 * while restarting.
2561 */
2562 if (sd->restart)
2563 event->pmu->start(event, 0);
2564
2565 return 0;
2566 }
2567
2568 static int perf_event_stop(struct perf_event *event, int restart)
2569 {
2570 struct stop_event_data sd = {
2571 .event = event,
2572 .restart = restart,
2573 };
2574 int ret = 0;
2575
2576 do {
2577 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
2578 return 0;
2579
2580 /* matches smp_wmb() in event_sched_in() */
2581 smp_rmb();
2582
2583 /*
2584 * We only want to restart ACTIVE events, so if the event goes
2585 * inactive here (event->oncpu==-1), there's nothing more to do;
2586 * fall through with ret==-ENXIO.
2587 */
2588 ret = cpu_function_call(READ_ONCE(event->oncpu),
2589 __perf_event_stop, &sd);
2590 } while (ret == -EAGAIN);
2591
2592 return ret;
2593 }
2594
2595 /*
2596 * In order to contain the amount of racy and tricky in the address filter
2597 * configuration management, it is a two part process:
2598 *
2599 * (p1) when userspace mappings change as a result of (1) or (2) or (3) below,
2600 * we update the addresses of corresponding vmas in
2601 * event::addr_filters_offs array and bump the event::addr_filters_gen;
2602 * (p2) when an event is scheduled in (pmu::add), it calls
2603 * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync()
2604 * if the generation has changed since the previous call.
2605 *
2606 * If (p1) happens while the event is active, we restart it to force (p2).
2607 *
2608 * (1) perf_addr_filters_apply(): adjusting filters' offsets based on
2609 * pre-existing mappings, called once when new filters arrive via SET_FILTER
2610 * ioctl;
2611 * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly
2612 * registered mapping, called for every new mmap(), with mm::mmap_sem down
2613 * for reading;
2614 * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process
2615 * of exec.
2616 */
2617 void perf_event_addr_filters_sync(struct perf_event *event)
2618 {
2619 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
2620
2621 if (!has_addr_filter(event))
2622 return;
2623
2624 raw_spin_lock(&ifh->lock);
2625 if (event->addr_filters_gen != event->hw.addr_filters_gen) {
2626 event->pmu->addr_filters_sync(event);
2627 event->hw.addr_filters_gen = event->addr_filters_gen;
2628 }
2629 raw_spin_unlock(&ifh->lock);
2630 }
2631 EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync);
2632
2633 static int _perf_event_refresh(struct perf_event *event, int refresh)
2634 {
2635 /*
2636 * not supported on inherited events
2637 */
2638 if (event->attr.inherit || !is_sampling_event(event))
2639 return -EINVAL;
2640
2641 atomic_add(refresh, &event->event_limit);
2642 _perf_event_enable(event);
2643
2644 return 0;
2645 }
2646
2647 /*
2648 * See perf_event_disable()
2649 */
2650 int perf_event_refresh(struct perf_event *event, int refresh)
2651 {
2652 struct perf_event_context *ctx;
2653 int ret;
2654
2655 ctx = perf_event_ctx_lock(event);
2656 ret = _perf_event_refresh(event, refresh);
2657 perf_event_ctx_unlock(event, ctx);
2658
2659 return ret;
2660 }
2661 EXPORT_SYMBOL_GPL(perf_event_refresh);
2662
2663 static void ctx_sched_out(struct perf_event_context *ctx,
2664 struct perf_cpu_context *cpuctx,
2665 enum event_type_t event_type)
2666 {
2667 int is_active = ctx->is_active;
2668 struct perf_event *event;
2669
2670 lockdep_assert_held(&ctx->lock);
2671
2672 if (likely(!ctx->nr_events)) {
2673 /*
2674 * See __perf_remove_from_context().
2675 */
2676 WARN_ON_ONCE(ctx->is_active);
2677 if (ctx->task)
2678 WARN_ON_ONCE(cpuctx->task_ctx);
2679 return;
2680 }
2681
2682 ctx->is_active &= ~event_type;
2683 if (!(ctx->is_active & EVENT_ALL))
2684 ctx->is_active = 0;
2685
2686 if (ctx->task) {
2687 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2688 if (!ctx->is_active)
2689 cpuctx->task_ctx = NULL;
2690 }
2691
2692 /*
2693 * Always update time if it was set; not only when it changes.
2694 * Otherwise we can 'forget' to update time for any but the last
2695 * context we sched out. For example:
2696 *
2697 * ctx_sched_out(.event_type = EVENT_FLEXIBLE)
2698 * ctx_sched_out(.event_type = EVENT_PINNED)
2699 *
2700 * would only update time for the pinned events.
2701 */
2702 if (is_active & EVENT_TIME) {
2703 /* update (and stop) ctx time */
2704 update_context_time(ctx);
2705 update_cgrp_time_from_cpuctx(cpuctx);
2706 }
2707
2708 is_active ^= ctx->is_active; /* changed bits */
2709
2710 if (!ctx->nr_active || !(is_active & EVENT_ALL))
2711 return;
2712
2713 perf_pmu_disable(ctx->pmu);
2714 if (is_active & EVENT_PINNED) {
2715 list_for_each_entry(event, &ctx->pinned_groups, group_entry)
2716 group_sched_out(event, cpuctx, ctx);
2717 }
2718
2719 if (is_active & EVENT_FLEXIBLE) {
2720 list_for_each_entry(event, &ctx->flexible_groups, group_entry)
2721 group_sched_out(event, cpuctx, ctx);
2722 }
2723 perf_pmu_enable(ctx->pmu);
2724 }
2725
2726 /*
2727 * Test whether two contexts are equivalent, i.e. whether they have both been
2728 * cloned from the same version of the same context.
2729 *
2730 * Equivalence is measured using a generation number in the context that is
2731 * incremented on each modification to it; see unclone_ctx(), list_add_event()
2732 * and list_del_event().
2733 */
2734 static int context_equiv(struct perf_event_context *ctx1,
2735 struct perf_event_context *ctx2)
2736 {
2737 lockdep_assert_held(&ctx1->lock);
2738 lockdep_assert_held(&ctx2->lock);
2739
2740 /* Pinning disables the swap optimization */
2741 if (ctx1->pin_count || ctx2->pin_count)
2742 return 0;
2743
2744 /* If ctx1 is the parent of ctx2 */
2745 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
2746 return 1;
2747
2748 /* If ctx2 is the parent of ctx1 */
2749 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
2750 return 1;
2751
2752 /*
2753 * If ctx1 and ctx2 have the same parent; we flatten the parent
2754 * hierarchy, see perf_event_init_context().
2755 */
2756 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
2757 ctx1->parent_gen == ctx2->parent_gen)
2758 return 1;
2759
2760 /* Unmatched */
2761 return 0;
2762 }
2763
2764 static void __perf_event_sync_stat(struct perf_event *event,
2765 struct perf_event *next_event)
2766 {
2767 u64 value;
2768
2769 if (!event->attr.inherit_stat)
2770 return;
2771
2772 /*
2773 * Update the event value, we cannot use perf_event_read()
2774 * because we're in the middle of a context switch and have IRQs
2775 * disabled, which upsets smp_call_function_single(), however
2776 * we know the event must be on the current CPU, therefore we
2777 * don't need to use it.
2778 */
2779 switch (event->state) {
2780 case PERF_EVENT_STATE_ACTIVE:
2781 event->pmu->read(event);
2782 /* fall-through */
2783
2784 case PERF_EVENT_STATE_INACTIVE:
2785 update_event_times(event);
2786 break;
2787
2788 default:
2789 break;
2790 }
2791
2792 /*
2793 * In order to keep per-task stats reliable we need to flip the event
2794 * values when we flip the contexts.
2795 */
2796 value = local64_read(&next_event->count);
2797 value = local64_xchg(&event->count, value);
2798 local64_set(&next_event->count, value);
2799
2800 swap(event->total_time_enabled, next_event->total_time_enabled);
2801 swap(event->total_time_running, next_event->total_time_running);
2802
2803 /*
2804 * Since we swizzled the values, update the user visible data too.
2805 */
2806 perf_event_update_userpage(event);
2807 perf_event_update_userpage(next_event);
2808 }
2809
2810 static void perf_event_sync_stat(struct perf_event_context *ctx,
2811 struct perf_event_context *next_ctx)
2812 {
2813 struct perf_event *event, *next_event;
2814
2815 if (!ctx->nr_stat)
2816 return;
2817
2818 update_context_time(ctx);
2819
2820 event = list_first_entry(&ctx->event_list,
2821 struct perf_event, event_entry);
2822
2823 next_event = list_first_entry(&next_ctx->event_list,
2824 struct perf_event, event_entry);
2825
2826 while (&event->event_entry != &ctx->event_list &&
2827 &next_event->event_entry != &next_ctx->event_list) {
2828
2829 __perf_event_sync_stat(event, next_event);
2830
2831 event = list_next_entry(event, event_entry);
2832 next_event = list_next_entry(next_event, event_entry);
2833 }
2834 }
2835
2836 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
2837 struct task_struct *next)
2838 {
2839 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
2840 struct perf_event_context *next_ctx;
2841 struct perf_event_context *parent, *next_parent;
2842 struct perf_cpu_context *cpuctx;
2843 int do_switch = 1;
2844
2845 if (likely(!ctx))
2846 return;
2847
2848 cpuctx = __get_cpu_context(ctx);
2849 if (!cpuctx->task_ctx)
2850 return;
2851
2852 rcu_read_lock();
2853 next_ctx = next->perf_event_ctxp[ctxn];
2854 if (!next_ctx)
2855 goto unlock;
2856
2857 parent = rcu_dereference(ctx->parent_ctx);
2858 next_parent = rcu_dereference(next_ctx->parent_ctx);
2859
2860 /* If neither context have a parent context; they cannot be clones. */
2861 if (!parent && !next_parent)
2862 goto unlock;
2863
2864 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
2865 /*
2866 * Looks like the two contexts are clones, so we might be
2867 * able to optimize the context switch. We lock both
2868 * contexts and check that they are clones under the
2869 * lock (including re-checking that neither has been
2870 * uncloned in the meantime). It doesn't matter which
2871 * order we take the locks because no other cpu could
2872 * be trying to lock both of these tasks.
2873 */
2874 raw_spin_lock(&ctx->lock);
2875 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
2876 if (context_equiv(ctx, next_ctx)) {
2877 WRITE_ONCE(ctx->task, next);
2878 WRITE_ONCE(next_ctx->task, task);
2879
2880 swap(ctx->task_ctx_data, next_ctx->task_ctx_data);
2881
2882 /*
2883 * RCU_INIT_POINTER here is safe because we've not
2884 * modified the ctx and the above modification of
2885 * ctx->task and ctx->task_ctx_data are immaterial
2886 * since those values are always verified under
2887 * ctx->lock which we're now holding.
2888 */
2889 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], next_ctx);
2890 RCU_INIT_POINTER(next->perf_event_ctxp[ctxn], ctx);
2891
2892 do_switch = 0;
2893
2894 perf_event_sync_stat(ctx, next_ctx);
2895 }
2896 raw_spin_unlock(&next_ctx->lock);
2897 raw_spin_unlock(&ctx->lock);
2898 }
2899 unlock:
2900 rcu_read_unlock();
2901
2902 if (do_switch) {
2903 raw_spin_lock(&ctx->lock);
2904 task_ctx_sched_out(cpuctx, ctx);
2905 raw_spin_unlock(&ctx->lock);
2906 }
2907 }
2908
2909 static DEFINE_PER_CPU(struct list_head, sched_cb_list);
2910
2911 void perf_sched_cb_dec(struct pmu *pmu)
2912 {
2913 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2914
2915 this_cpu_dec(perf_sched_cb_usages);
2916
2917 if (!--cpuctx->sched_cb_usage)
2918 list_del(&cpuctx->sched_cb_entry);
2919 }
2920
2921
2922 void perf_sched_cb_inc(struct pmu *pmu)
2923 {
2924 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2925
2926 if (!cpuctx->sched_cb_usage++)
2927 list_add(&cpuctx->sched_cb_entry, this_cpu_ptr(&sched_cb_list));
2928
2929 this_cpu_inc(perf_sched_cb_usages);
2930 }
2931
2932 /*
2933 * This function provides the context switch callback to the lower code
2934 * layer. It is invoked ONLY when the context switch callback is enabled.
2935 *
2936 * This callback is relevant even to per-cpu events; for example multi event
2937 * PEBS requires this to provide PID/TID information. This requires we flush
2938 * all queued PEBS records before we context switch to a new task.
2939 */
2940 static void perf_pmu_sched_task(struct task_struct *prev,
2941 struct task_struct *next,
2942 bool sched_in)
2943 {
2944 struct perf_cpu_context *cpuctx;
2945 struct pmu *pmu;
2946
2947 if (prev == next)
2948 return;
2949
2950 list_for_each_entry(cpuctx, this_cpu_ptr(&sched_cb_list), sched_cb_entry) {
2951 pmu = cpuctx->unique_pmu; /* software PMUs will not have sched_task */
2952
2953 if (WARN_ON_ONCE(!pmu->sched_task))
2954 continue;
2955
2956 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2957 perf_pmu_disable(pmu);
2958
2959 pmu->sched_task(cpuctx->task_ctx, sched_in);
2960
2961 perf_pmu_enable(pmu);
2962 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2963 }
2964 }
2965
2966 static void perf_event_switch(struct task_struct *task,
2967 struct task_struct *next_prev, bool sched_in);
2968
2969 #define for_each_task_context_nr(ctxn) \
2970 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
2971
2972 /*
2973 * Called from scheduler to remove the events of the current task,
2974 * with interrupts disabled.
2975 *
2976 * We stop each event and update the event value in event->count.
2977 *
2978 * This does not protect us against NMI, but disable()
2979 * sets the disabled bit in the control field of event _before_
2980 * accessing the event control register. If a NMI hits, then it will
2981 * not restart the event.
2982 */
2983 void __perf_event_task_sched_out(struct task_struct *task,
2984 struct task_struct *next)
2985 {
2986 int ctxn;
2987
2988 if (__this_cpu_read(perf_sched_cb_usages))
2989 perf_pmu_sched_task(task, next, false);
2990
2991 if (atomic_read(&nr_switch_events))
2992 perf_event_switch(task, next, false);
2993
2994 for_each_task_context_nr(ctxn)
2995 perf_event_context_sched_out(task, ctxn, next);
2996
2997 /*
2998 * if cgroup events exist on this CPU, then we need
2999 * to check if we have to switch out PMU state.
3000 * cgroup event are system-wide mode only
3001 */
3002 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3003 perf_cgroup_sched_out(task, next);
3004 }
3005
3006 /*
3007 * Called with IRQs disabled
3008 */
3009 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
3010 enum event_type_t event_type)
3011 {
3012 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
3013 }
3014
3015 static void
3016 ctx_pinned_sched_in(struct perf_event_context *ctx,
3017 struct perf_cpu_context *cpuctx)
3018 {
3019 struct perf_event *event;
3020
3021 list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
3022 if (event->state <= PERF_EVENT_STATE_OFF)
3023 continue;
3024 if (!event_filter_match(event))
3025 continue;
3026
3027 /* may need to reset tstamp_enabled */
3028 if (is_cgroup_event(event))
3029 perf_cgroup_mark_enabled(event, ctx);
3030
3031 if (group_can_go_on(event, cpuctx, 1))
3032 group_sched_in(event, cpuctx, ctx);
3033
3034 /*
3035 * If this pinned group hasn't been scheduled,
3036 * put it in error state.
3037 */
3038 if (event->state == PERF_EVENT_STATE_INACTIVE) {
3039 update_group_times(event);
3040 event->state = PERF_EVENT_STATE_ERROR;
3041 }
3042 }
3043 }
3044
3045 static void
3046 ctx_flexible_sched_in(struct perf_event_context *ctx,
3047 struct perf_cpu_context *cpuctx)
3048 {
3049 struct perf_event *event;
3050 int can_add_hw = 1;
3051
3052 list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
3053 /* Ignore events in OFF or ERROR state */
3054 if (event->state <= PERF_EVENT_STATE_OFF)
3055 continue;
3056 /*
3057 * Listen to the 'cpu' scheduling filter constraint
3058 * of events:
3059 */
3060 if (!event_filter_match(event))
3061 continue;
3062
3063 /* may need to reset tstamp_enabled */
3064 if (is_cgroup_event(event))
3065 perf_cgroup_mark_enabled(event, ctx);
3066
3067 if (group_can_go_on(event, cpuctx, can_add_hw)) {
3068 if (group_sched_in(event, cpuctx, ctx))
3069 can_add_hw = 0;
3070 }
3071 }
3072 }
3073
3074 static void
3075 ctx_sched_in(struct perf_event_context *ctx,
3076 struct perf_cpu_context *cpuctx,
3077 enum event_type_t event_type,
3078 struct task_struct *task)
3079 {
3080 int is_active = ctx->is_active;
3081 u64 now;
3082
3083 lockdep_assert_held(&ctx->lock);
3084
3085 if (likely(!ctx->nr_events))
3086 return;
3087
3088 ctx->is_active |= (event_type | EVENT_TIME);
3089 if (ctx->task) {
3090 if (!is_active)
3091 cpuctx->task_ctx = ctx;
3092 else
3093 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3094 }
3095
3096 is_active ^= ctx->is_active; /* changed bits */
3097
3098 if (is_active & EVENT_TIME) {
3099 /* start ctx time */
3100 now = perf_clock();
3101 ctx->timestamp = now;
3102 perf_cgroup_set_timestamp(task, ctx);
3103 }
3104
3105 /*
3106 * First go through the list and put on any pinned groups
3107 * in order to give them the best chance of going on.
3108 */
3109 if (is_active & EVENT_PINNED)
3110 ctx_pinned_sched_in(ctx, cpuctx);
3111
3112 /* Then walk through the lower prio flexible groups */
3113 if (is_active & EVENT_FLEXIBLE)
3114 ctx_flexible_sched_in(ctx, cpuctx);
3115 }
3116
3117 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
3118 enum event_type_t event_type,
3119 struct task_struct *task)
3120 {
3121 struct perf_event_context *ctx = &cpuctx->ctx;
3122
3123 ctx_sched_in(ctx, cpuctx, event_type, task);
3124 }
3125
3126 static void perf_event_context_sched_in(struct perf_event_context *ctx,
3127 struct task_struct *task)
3128 {
3129 struct perf_cpu_context *cpuctx;
3130
3131 cpuctx = __get_cpu_context(ctx);
3132 if (cpuctx->task_ctx == ctx)
3133 return;
3134
3135 perf_ctx_lock(cpuctx, ctx);
3136 perf_pmu_disable(ctx->pmu);
3137 /*
3138 * We want to keep the following priority order:
3139 * cpu pinned (that don't need to move), task pinned,
3140 * cpu flexible, task flexible.
3141 */
3142 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3143 perf_event_sched_in(cpuctx, ctx, task);
3144 perf_pmu_enable(ctx->pmu);
3145 perf_ctx_unlock(cpuctx, ctx);
3146 }
3147
3148 /*
3149 * Called from scheduler to add the events of the current task
3150 * with interrupts disabled.
3151 *
3152 * We restore the event value and then enable it.
3153 *
3154 * This does not protect us against NMI, but enable()
3155 * sets the enabled bit in the control field of event _before_
3156 * accessing the event control register. If a NMI hits, then it will
3157 * keep the event running.
3158 */
3159 void __perf_event_task_sched_in(struct task_struct *prev,
3160 struct task_struct *task)
3161 {
3162 struct perf_event_context *ctx;
3163 int ctxn;
3164
3165 /*
3166 * If cgroup events exist on this CPU, then we need to check if we have
3167 * to switch in PMU state; cgroup event are system-wide mode only.
3168 *
3169 * Since cgroup events are CPU events, we must schedule these in before
3170 * we schedule in the task events.
3171 */
3172 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3173 perf_cgroup_sched_in(prev, task);
3174
3175 for_each_task_context_nr(ctxn) {
3176 ctx = task->perf_event_ctxp[ctxn];
3177 if (likely(!ctx))
3178 continue;
3179
3180 perf_event_context_sched_in(ctx, task);
3181 }
3182
3183 if (atomic_read(&nr_switch_events))
3184 perf_event_switch(task, prev, true);
3185
3186 if (__this_cpu_read(perf_sched_cb_usages))
3187 perf_pmu_sched_task(prev, task, true);
3188 }
3189
3190 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
3191 {
3192 u64 frequency = event->attr.sample_freq;
3193 u64 sec = NSEC_PER_SEC;
3194 u64 divisor, dividend;
3195
3196 int count_fls, nsec_fls, frequency_fls, sec_fls;
3197
3198 count_fls = fls64(count);
3199 nsec_fls = fls64(nsec);
3200 frequency_fls = fls64(frequency);
3201 sec_fls = 30;
3202
3203 /*
3204 * We got @count in @nsec, with a target of sample_freq HZ
3205 * the target period becomes:
3206 *
3207 * @count * 10^9
3208 * period = -------------------
3209 * @nsec * sample_freq
3210 *
3211 */
3212
3213 /*
3214 * Reduce accuracy by one bit such that @a and @b converge
3215 * to a similar magnitude.
3216 */
3217 #define REDUCE_FLS(a, b) \
3218 do { \
3219 if (a##_fls > b##_fls) { \
3220 a >>= 1; \
3221 a##_fls--; \
3222 } else { \
3223 b >>= 1; \
3224 b##_fls--; \
3225 } \
3226 } while (0)
3227
3228 /*
3229 * Reduce accuracy until either term fits in a u64, then proceed with
3230 * the other, so that finally we can do a u64/u64 division.
3231 */
3232 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
3233 REDUCE_FLS(nsec, frequency);
3234 REDUCE_FLS(sec, count);
3235 }
3236
3237 if (count_fls + sec_fls > 64) {
3238 divisor = nsec * frequency;
3239
3240 while (count_fls + sec_fls > 64) {
3241 REDUCE_FLS(count, sec);
3242 divisor >>= 1;
3243 }
3244
3245 dividend = count * sec;
3246 } else {
3247 dividend = count * sec;
3248
3249 while (nsec_fls + frequency_fls > 64) {
3250 REDUCE_FLS(nsec, frequency);
3251 dividend >>= 1;
3252 }
3253
3254 divisor = nsec * frequency;
3255 }
3256
3257 if (!divisor)
3258 return dividend;
3259
3260 return div64_u64(dividend, divisor);
3261 }
3262
3263 static DEFINE_PER_CPU(int, perf_throttled_count);
3264 static DEFINE_PER_CPU(u64, perf_throttled_seq);
3265
3266 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
3267 {
3268 struct hw_perf_event *hwc = &event->hw;
3269 s64 period, sample_period;
3270 s64 delta;
3271
3272 period = perf_calculate_period(event, nsec, count);
3273
3274 delta = (s64)(period - hwc->sample_period);
3275 delta = (delta + 7) / 8; /* low pass filter */
3276
3277 sample_period = hwc->sample_period + delta;
3278
3279 if (!sample_period)
3280 sample_period = 1;
3281
3282 hwc->sample_period = sample_period;
3283
3284 if (local64_read(&hwc->period_left) > 8*sample_period) {
3285 if (disable)
3286 event->pmu->stop(event, PERF_EF_UPDATE);
3287
3288 local64_set(&hwc->period_left, 0);
3289
3290 if (disable)
3291 event->pmu->start(event, PERF_EF_RELOAD);
3292 }
3293 }
3294
3295 /*
3296 * combine freq adjustment with unthrottling to avoid two passes over the
3297 * events. At the same time, make sure, having freq events does not change
3298 * the rate of unthrottling as that would introduce bias.
3299 */
3300 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
3301 int needs_unthr)
3302 {
3303 struct perf_event *event;
3304 struct hw_perf_event *hwc;
3305 u64 now, period = TICK_NSEC;
3306 s64 delta;
3307
3308 /*
3309 * only need to iterate over all events iff:
3310 * - context have events in frequency mode (needs freq adjust)
3311 * - there are events to unthrottle on this cpu
3312 */
3313 if (!(ctx->nr_freq || needs_unthr))
3314 return;
3315
3316 raw_spin_lock(&ctx->lock);
3317 perf_pmu_disable(ctx->pmu);
3318
3319 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
3320 if (event->state != PERF_EVENT_STATE_ACTIVE)
3321 continue;
3322
3323 if (!event_filter_match(event))
3324 continue;
3325
3326 perf_pmu_disable(event->pmu);
3327
3328 hwc = &event->hw;
3329
3330 if (hwc->interrupts == MAX_INTERRUPTS) {
3331 hwc->interrupts = 0;
3332 perf_log_throttle(event, 1);
3333 event->pmu->start(event, 0);
3334 }
3335
3336 if (!event->attr.freq || !event->attr.sample_freq)
3337 goto next;
3338
3339 /*
3340 * stop the event and update event->count
3341 */
3342 event->pmu->stop(event, PERF_EF_UPDATE);
3343
3344 now = local64_read(&event->count);
3345 delta = now - hwc->freq_count_stamp;
3346 hwc->freq_count_stamp = now;
3347
3348 /*
3349 * restart the event
3350 * reload only if value has changed
3351 * we have stopped the event so tell that
3352 * to perf_adjust_period() to avoid stopping it
3353 * twice.
3354 */
3355 if (delta > 0)
3356 perf_adjust_period(event, period, delta, false);
3357
3358 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
3359 next:
3360 perf_pmu_enable(event->pmu);
3361 }
3362
3363 perf_pmu_enable(ctx->pmu);
3364 raw_spin_unlock(&ctx->lock);
3365 }
3366
3367 /*
3368 * Round-robin a context's events:
3369 */
3370 static void rotate_ctx(struct perf_event_context *ctx)
3371 {
3372 /*
3373 * Rotate the first entry last of non-pinned groups. Rotation might be
3374 * disabled by the inheritance code.
3375 */
3376 if (!ctx->rotate_disable)
3377 list_rotate_left(&ctx->flexible_groups);
3378 }
3379
3380 static int perf_rotate_context(struct perf_cpu_context *cpuctx)
3381 {
3382 struct perf_event_context *ctx = NULL;
3383 int rotate = 0;
3384
3385 if (cpuctx->ctx.nr_events) {
3386 if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
3387 rotate = 1;
3388 }
3389
3390 ctx = cpuctx->task_ctx;
3391 if (ctx && ctx->nr_events) {
3392 if (ctx->nr_events != ctx->nr_active)
3393 rotate = 1;
3394 }
3395
3396 if (!rotate)
3397 goto done;
3398
3399 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3400 perf_pmu_disable(cpuctx->ctx.pmu);
3401
3402 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3403 if (ctx)
3404 ctx_sched_out(ctx, cpuctx, EVENT_FLEXIBLE);
3405
3406 rotate_ctx(&cpuctx->ctx);
3407 if (ctx)
3408 rotate_ctx(ctx);
3409
3410 perf_event_sched_in(cpuctx, ctx, current);
3411
3412 perf_pmu_enable(cpuctx->ctx.pmu);
3413 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3414 done:
3415
3416 return rotate;
3417 }
3418
3419 void perf_event_task_tick(void)
3420 {
3421 struct list_head *head = this_cpu_ptr(&active_ctx_list);
3422 struct perf_event_context *ctx, *tmp;
3423 int throttled;
3424
3425 WARN_ON(!irqs_disabled());
3426
3427 __this_cpu_inc(perf_throttled_seq);
3428 throttled = __this_cpu_xchg(perf_throttled_count, 0);
3429 tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
3430
3431 list_for_each_entry_safe(ctx, tmp, head, active_ctx_list)
3432 perf_adjust_freq_unthr_context(ctx, throttled);
3433 }
3434
3435 static int event_enable_on_exec(struct perf_event *event,
3436 struct perf_event_context *ctx)
3437 {
3438 if (!event->attr.enable_on_exec)
3439 return 0;
3440
3441 event->attr.enable_on_exec = 0;
3442 if (event->state >= PERF_EVENT_STATE_INACTIVE)
3443 return 0;
3444
3445 __perf_event_mark_enabled(event);
3446
3447 return 1;
3448 }
3449
3450 /*
3451 * Enable all of a task's events that have been marked enable-on-exec.
3452 * This expects task == current.
3453 */
3454 static void perf_event_enable_on_exec(int ctxn)
3455 {
3456 struct perf_event_context *ctx, *clone_ctx = NULL;
3457 struct perf_cpu_context *cpuctx;
3458 struct perf_event *event;
3459 unsigned long flags;
3460 int enabled = 0;
3461
3462 local_irq_save(flags);
3463 ctx = current->perf_event_ctxp[ctxn];
3464 if (!ctx || !ctx->nr_events)
3465 goto out;
3466
3467 cpuctx = __get_cpu_context(ctx);
3468 perf_ctx_lock(cpuctx, ctx);
3469 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
3470 list_for_each_entry(event, &ctx->event_list, event_entry)
3471 enabled |= event_enable_on_exec(event, ctx);
3472
3473 /*
3474 * Unclone and reschedule this context if we enabled any event.
3475 */
3476 if (enabled) {
3477 clone_ctx = unclone_ctx(ctx);
3478 ctx_resched(cpuctx, ctx);
3479 }
3480 perf_ctx_unlock(cpuctx, ctx);
3481
3482 out:
3483 local_irq_restore(flags);
3484
3485 if (clone_ctx)
3486 put_ctx(clone_ctx);
3487 }
3488
3489 struct perf_read_data {
3490 struct perf_event *event;
3491 bool group;
3492 int ret;
3493 };
3494
3495 static int __perf_event_read_cpu(struct perf_event *event, int event_cpu)
3496 {
3497 u16 local_pkg, event_pkg;
3498
3499 if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) {
3500 int local_cpu = smp_processor_id();
3501
3502 event_pkg = topology_physical_package_id(event_cpu);
3503 local_pkg = topology_physical_package_id(local_cpu);
3504
3505 if (event_pkg == local_pkg)
3506 return local_cpu;
3507 }
3508
3509 return event_cpu;
3510 }
3511
3512 /*
3513 * Cross CPU call to read the hardware event
3514 */
3515 static void __perf_event_read(void *info)
3516 {
3517 struct perf_read_data *data = info;
3518 struct perf_event *sub, *event = data->event;
3519 struct perf_event_context *ctx = event->ctx;
3520 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3521 struct pmu *pmu = event->pmu;
3522
3523 /*
3524 * If this is a task context, we need to check whether it is
3525 * the current task context of this cpu. If not it has been
3526 * scheduled out before the smp call arrived. In that case
3527 * event->count would have been updated to a recent sample
3528 * when the event was scheduled out.
3529 */
3530 if (ctx->task && cpuctx->task_ctx != ctx)
3531 return;
3532
3533 raw_spin_lock(&ctx->lock);
3534 if (ctx->is_active) {
3535 update_context_time(ctx);
3536 update_cgrp_time_from_event(event);
3537 }
3538
3539 update_event_times(event);
3540 if (event->state != PERF_EVENT_STATE_ACTIVE)
3541 goto unlock;
3542
3543 if (!data->group) {
3544 pmu->read(event);
3545 data->ret = 0;
3546 goto unlock;
3547 }
3548
3549 pmu->start_txn(pmu, PERF_PMU_TXN_READ);
3550
3551 pmu->read(event);
3552
3553 list_for_each_entry(sub, &event->sibling_list, group_entry) {
3554 update_event_times(sub);
3555 if (sub->state == PERF_EVENT_STATE_ACTIVE) {
3556 /*
3557 * Use sibling's PMU rather than @event's since
3558 * sibling could be on different (eg: software) PMU.
3559 */
3560 sub->pmu->read(sub);
3561 }
3562 }
3563
3564 data->ret = pmu->commit_txn(pmu);
3565
3566 unlock:
3567 raw_spin_unlock(&ctx->lock);
3568 }
3569
3570 static inline u64 perf_event_count(struct perf_event *event)
3571 {
3572 if (event->pmu->count)
3573 return event->pmu->count(event);
3574
3575 return __perf_event_count(event);
3576 }
3577
3578 /*
3579 * NMI-safe method to read a local event, that is an event that
3580 * is:
3581 * - either for the current task, or for this CPU
3582 * - does not have inherit set, for inherited task events
3583 * will not be local and we cannot read them atomically
3584 * - must not have a pmu::count method
3585 */
3586 u64 perf_event_read_local(struct perf_event *event)
3587 {
3588 unsigned long flags;
3589 u64 val;
3590
3591 /*
3592 * Disabling interrupts avoids all counter scheduling (context
3593 * switches, timer based rotation and IPIs).
3594 */
3595 local_irq_save(flags);
3596
3597 /* If this is a per-task event, it must be for current */
3598 WARN_ON_ONCE((event->attach_state & PERF_ATTACH_TASK) &&
3599 event->hw.target != current);
3600
3601 /* If this is a per-CPU event, it must be for this CPU */
3602 WARN_ON_ONCE(!(event->attach_state & PERF_ATTACH_TASK) &&
3603 event->cpu != smp_processor_id());
3604
3605 /*
3606 * It must not be an event with inherit set, we cannot read
3607 * all child counters from atomic context.
3608 */
3609 WARN_ON_ONCE(event->attr.inherit);
3610
3611 /*
3612 * It must not have a pmu::count method, those are not
3613 * NMI safe.
3614 */
3615 WARN_ON_ONCE(event->pmu->count);
3616
3617 /*
3618 * If the event is currently on this CPU, its either a per-task event,
3619 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
3620 * oncpu == -1).
3621 */
3622 if (event->oncpu == smp_processor_id())
3623 event->pmu->read(event);
3624
3625 val = local64_read(&event->count);
3626 local_irq_restore(flags);
3627
3628 return val;
3629 }
3630
3631 static int perf_event_read(struct perf_event *event, bool group)
3632 {
3633 int event_cpu, ret = 0;
3634
3635 /*
3636 * If event is enabled and currently active on a CPU, update the
3637 * value in the event structure:
3638 */
3639 if (event->state == PERF_EVENT_STATE_ACTIVE) {
3640 struct perf_read_data data = {
3641 .event = event,
3642 .group = group,
3643 .ret = 0,
3644 };
3645
3646 event_cpu = READ_ONCE(event->oncpu);
3647 if ((unsigned)event_cpu >= nr_cpu_ids)
3648 return 0;
3649
3650 preempt_disable();
3651 event_cpu = __perf_event_read_cpu(event, event_cpu);
3652
3653 /*
3654 * Purposely ignore the smp_call_function_single() return
3655 * value.
3656 *
3657 * If event_cpu isn't a valid CPU it means the event got
3658 * scheduled out and that will have updated the event count.
3659 *
3660 * Therefore, either way, we'll have an up-to-date event count
3661 * after this.
3662 */
3663 (void)smp_call_function_single(event_cpu, __perf_event_read, &data, 1);
3664 preempt_enable();
3665 ret = data.ret;
3666 } else if (event->state == PERF_EVENT_STATE_INACTIVE) {
3667 struct perf_event_context *ctx = event->ctx;
3668 unsigned long flags;
3669
3670 raw_spin_lock_irqsave(&ctx->lock, flags);
3671 /*
3672 * may read while context is not active
3673 * (e.g., thread is blocked), in that case
3674 * we cannot update context time
3675 */
3676 if (ctx->is_active) {
3677 update_context_time(ctx);
3678 update_cgrp_time_from_event(event);
3679 }
3680 if (group)
3681 update_group_times(event);
3682 else
3683 update_event_times(event);
3684 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3685 }
3686
3687 return ret;
3688 }
3689
3690 /*
3691 * Initialize the perf_event context in a task_struct:
3692 */
3693 static void __perf_event_init_context(struct perf_event_context *ctx)
3694 {
3695 raw_spin_lock_init(&ctx->lock);
3696 mutex_init(&ctx->mutex);
3697 INIT_LIST_HEAD(&ctx->active_ctx_list);
3698 INIT_LIST_HEAD(&ctx->pinned_groups);
3699 INIT_LIST_HEAD(&ctx->flexible_groups);
3700 INIT_LIST_HEAD(&ctx->event_list);
3701 atomic_set(&ctx->refcount, 1);
3702 }
3703
3704 static struct perf_event_context *
3705 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
3706 {
3707 struct perf_event_context *ctx;
3708
3709 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
3710 if (!ctx)
3711 return NULL;
3712
3713 __perf_event_init_context(ctx);
3714 if (task) {
3715 ctx->task = task;
3716 get_task_struct(task);
3717 }
3718 ctx->pmu = pmu;
3719
3720 return ctx;
3721 }
3722
3723 static struct task_struct *
3724 find_lively_task_by_vpid(pid_t vpid)
3725 {
3726 struct task_struct *task;
3727
3728 rcu_read_lock();
3729 if (!vpid)
3730 task = current;
3731 else
3732 task = find_task_by_vpid(vpid);
3733 if (task)
3734 get_task_struct(task);
3735 rcu_read_unlock();
3736
3737 if (!task)
3738 return ERR_PTR(-ESRCH);
3739
3740 return task;
3741 }
3742
3743 /*
3744 * Returns a matching context with refcount and pincount.
3745 */
3746 static struct perf_event_context *
3747 find_get_context(struct pmu *pmu, struct task_struct *task,
3748 struct perf_event *event)
3749 {
3750 struct perf_event_context *ctx, *clone_ctx = NULL;
3751 struct perf_cpu_context *cpuctx;
3752 void *task_ctx_data = NULL;
3753 unsigned long flags;
3754 int ctxn, err;
3755 int cpu = event->cpu;
3756
3757 if (!task) {
3758 /* Must be root to operate on a CPU event: */
3759 if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
3760 return ERR_PTR(-EACCES);
3761
3762 /*
3763 * We could be clever and allow to attach a event to an
3764 * offline CPU and activate it when the CPU comes up, but
3765 * that's for later.
3766 */
3767 if (!cpu_online(cpu))
3768 return ERR_PTR(-ENODEV);
3769
3770 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
3771 ctx = &cpuctx->ctx;
3772 get_ctx(ctx);
3773 ++ctx->pin_count;
3774
3775 return ctx;
3776 }
3777
3778 err = -EINVAL;
3779 ctxn = pmu->task_ctx_nr;
3780 if (ctxn < 0)
3781 goto errout;
3782
3783 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
3784 task_ctx_data = kzalloc(pmu->task_ctx_size, GFP_KERNEL);
3785 if (!task_ctx_data) {
3786 err = -ENOMEM;
3787 goto errout;
3788 }
3789 }
3790
3791 retry:
3792 ctx = perf_lock_task_context(task, ctxn, &flags);
3793 if (ctx) {
3794 clone_ctx = unclone_ctx(ctx);
3795 ++ctx->pin_count;
3796
3797 if (task_ctx_data && !ctx->task_ctx_data) {
3798 ctx->task_ctx_data = task_ctx_data;
3799 task_ctx_data = NULL;
3800 }
3801 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3802
3803 if (clone_ctx)
3804 put_ctx(clone_ctx);
3805 } else {
3806 ctx = alloc_perf_context(pmu, task);
3807 err = -ENOMEM;
3808 if (!ctx)
3809 goto errout;
3810
3811 if (task_ctx_data) {
3812 ctx->task_ctx_data = task_ctx_data;
3813 task_ctx_data = NULL;
3814 }
3815
3816 err = 0;
3817 mutex_lock(&task->perf_event_mutex);
3818 /*
3819 * If it has already passed perf_event_exit_task().
3820 * we must see PF_EXITING, it takes this mutex too.
3821 */
3822 if (task->flags & PF_EXITING)
3823 err = -ESRCH;
3824 else if (task->perf_event_ctxp[ctxn])
3825 err = -EAGAIN;
3826 else {
3827 get_ctx(ctx);
3828 ++ctx->pin_count;
3829 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
3830 }
3831 mutex_unlock(&task->perf_event_mutex);
3832
3833 if (unlikely(err)) {
3834 put_ctx(ctx);
3835
3836 if (err == -EAGAIN)
3837 goto retry;
3838 goto errout;
3839 }
3840 }
3841
3842 kfree(task_ctx_data);
3843 return ctx;
3844
3845 errout:
3846 kfree(task_ctx_data);
3847 return ERR_PTR(err);
3848 }
3849
3850 static void perf_event_free_filter(struct perf_event *event);
3851 static void perf_event_free_bpf_prog(struct perf_event *event);
3852
3853 static void free_event_rcu(struct rcu_head *head)
3854 {
3855 struct perf_event *event;
3856
3857 event = container_of(head, struct perf_event, rcu_head);
3858 if (event->ns)
3859 put_pid_ns(event->ns);
3860 perf_event_free_filter(event);
3861 kfree(event);
3862 }
3863
3864 static void ring_buffer_attach(struct perf_event *event,
3865 struct ring_buffer *rb);
3866
3867 static void detach_sb_event(struct perf_event *event)
3868 {
3869 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
3870
3871 raw_spin_lock(&pel->lock);
3872 list_del_rcu(&event->sb_list);
3873 raw_spin_unlock(&pel->lock);
3874 }
3875
3876 static bool is_sb_event(struct perf_event *event)
3877 {
3878 struct perf_event_attr *attr = &event->attr;
3879
3880 if (event->parent)
3881 return false;
3882
3883 if (event->attach_state & PERF_ATTACH_TASK)
3884 return false;
3885
3886 if (attr->mmap || attr->mmap_data || attr->mmap2 ||
3887 attr->comm || attr->comm_exec ||
3888 attr->task ||
3889 attr->context_switch)
3890 return true;
3891 return false;
3892 }
3893
3894 static void unaccount_pmu_sb_event(struct perf_event *event)
3895 {
3896 if (is_sb_event(event))
3897 detach_sb_event(event);
3898 }
3899
3900 static void unaccount_event_cpu(struct perf_event *event, int cpu)
3901 {
3902 if (event->parent)
3903 return;
3904
3905 if (is_cgroup_event(event))
3906 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
3907 }
3908
3909 #ifdef CONFIG_NO_HZ_FULL
3910 static DEFINE_SPINLOCK(nr_freq_lock);
3911 #endif
3912
3913 static void unaccount_freq_event_nohz(void)
3914 {
3915 #ifdef CONFIG_NO_HZ_FULL
3916 spin_lock(&nr_freq_lock);
3917 if (atomic_dec_and_test(&nr_freq_events))
3918 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS);
3919 spin_unlock(&nr_freq_lock);
3920 #endif
3921 }
3922
3923 static void unaccount_freq_event(void)
3924 {
3925 if (tick_nohz_full_enabled())
3926 unaccount_freq_event_nohz();
3927 else
3928 atomic_dec(&nr_freq_events);
3929 }
3930
3931 static void unaccount_event(struct perf_event *event)
3932 {
3933 bool dec = false;
3934
3935 if (event->parent)
3936 return;
3937
3938 if (event->attach_state & PERF_ATTACH_TASK)
3939 dec = true;
3940 if (event->attr.mmap || event->attr.mmap_data)
3941 atomic_dec(&nr_mmap_events);
3942 if (event->attr.comm)
3943 atomic_dec(&nr_comm_events);
3944 if (event->attr.task)
3945 atomic_dec(&nr_task_events);
3946 if (event->attr.freq)
3947 unaccount_freq_event();
3948 if (event->attr.context_switch) {
3949 dec = true;
3950 atomic_dec(&nr_switch_events);
3951 }
3952 if (is_cgroup_event(event))
3953 dec = true;
3954 if (has_branch_stack(event))
3955 dec = true;
3956
3957 if (dec) {
3958 if (!atomic_add_unless(&perf_sched_count, -1, 1))
3959 schedule_delayed_work(&perf_sched_work, HZ);
3960 }
3961
3962 unaccount_event_cpu(event, event->cpu);
3963
3964 unaccount_pmu_sb_event(event);
3965 }
3966
3967 static void perf_sched_delayed(struct work_struct *work)
3968 {
3969 mutex_lock(&perf_sched_mutex);
3970 if (atomic_dec_and_test(&perf_sched_count))
3971 static_branch_disable(&perf_sched_events);
3972 mutex_unlock(&perf_sched_mutex);
3973 }
3974
3975 /*
3976 * The following implement mutual exclusion of events on "exclusive" pmus
3977 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
3978 * at a time, so we disallow creating events that might conflict, namely:
3979 *
3980 * 1) cpu-wide events in the presence of per-task events,
3981 * 2) per-task events in the presence of cpu-wide events,
3982 * 3) two matching events on the same context.
3983 *
3984 * The former two cases are handled in the allocation path (perf_event_alloc(),
3985 * _free_event()), the latter -- before the first perf_install_in_context().
3986 */
3987 static int exclusive_event_init(struct perf_event *event)
3988 {
3989 struct pmu *pmu = event->pmu;
3990
3991 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3992 return 0;
3993
3994 /*
3995 * Prevent co-existence of per-task and cpu-wide events on the
3996 * same exclusive pmu.
3997 *
3998 * Negative pmu::exclusive_cnt means there are cpu-wide
3999 * events on this "exclusive" pmu, positive means there are
4000 * per-task events.
4001 *
4002 * Since this is called in perf_event_alloc() path, event::ctx
4003 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
4004 * to mean "per-task event", because unlike other attach states it
4005 * never gets cleared.
4006 */
4007 if (event->attach_state & PERF_ATTACH_TASK) {
4008 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
4009 return -EBUSY;
4010 } else {
4011 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
4012 return -EBUSY;
4013 }
4014
4015 return 0;
4016 }
4017
4018 static void exclusive_event_destroy(struct perf_event *event)
4019 {
4020 struct pmu *pmu = event->pmu;
4021
4022 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
4023 return;
4024
4025 /* see comment in exclusive_event_init() */
4026 if (event->attach_state & PERF_ATTACH_TASK)
4027 atomic_dec(&pmu->exclusive_cnt);
4028 else
4029 atomic_inc(&pmu->exclusive_cnt);
4030 }
4031
4032 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
4033 {
4034 if ((e1->pmu == e2->pmu) &&
4035 (e1->cpu == e2->cpu ||
4036 e1->cpu == -1 ||
4037 e2->cpu == -1))
4038 return true;
4039 return false;
4040 }
4041
4042 /* Called under the same ctx::mutex as perf_install_in_context() */
4043 static bool exclusive_event_installable(struct perf_event *event,
4044 struct perf_event_context *ctx)
4045 {
4046 struct perf_event *iter_event;
4047 struct pmu *pmu = event->pmu;
4048
4049 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
4050 return true;
4051
4052 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
4053 if (exclusive_event_match(iter_event, event))
4054 return false;
4055 }
4056
4057 return true;
4058 }
4059
4060 static void perf_addr_filters_splice(struct perf_event *event,
4061 struct list_head *head);
4062
4063 static void _free_event(struct perf_event *event)
4064 {
4065 irq_work_sync(&event->pending);
4066
4067 unaccount_event(event);
4068
4069 if (event->rb) {
4070 /*
4071 * Can happen when we close an event with re-directed output.
4072 *
4073 * Since we have a 0 refcount, perf_mmap_close() will skip
4074 * over us; possibly making our ring_buffer_put() the last.
4075 */
4076 mutex_lock(&event->mmap_mutex);
4077 ring_buffer_attach(event, NULL);
4078 mutex_unlock(&event->mmap_mutex);
4079 }
4080
4081 if (is_cgroup_event(event))
4082 perf_detach_cgroup(event);
4083
4084 if (!event->parent) {
4085 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
4086 put_callchain_buffers();
4087 }
4088
4089 perf_event_free_bpf_prog(event);
4090 perf_addr_filters_splice(event, NULL);
4091 kfree(event->addr_filters_offs);
4092
4093 if (event->destroy)
4094 event->destroy(event);
4095
4096 if (event->ctx)
4097 put_ctx(event->ctx);
4098
4099 exclusive_event_destroy(event);
4100 module_put(event->pmu->module);
4101
4102 call_rcu(&event->rcu_head, free_event_rcu);
4103 }
4104
4105 /*
4106 * Used to free events which have a known refcount of 1, such as in error paths
4107 * where the event isn't exposed yet and inherited events.
4108 */
4109 static void free_event(struct perf_event *event)
4110 {
4111 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
4112 "unexpected event refcount: %ld; ptr=%p\n",
4113 atomic_long_read(&event->refcount), event)) {
4114 /* leak to avoid use-after-free */
4115 return;
4116 }
4117
4118 _free_event(event);
4119 }
4120
4121 /*
4122 * Remove user event from the owner task.
4123 */
4124 static void perf_remove_from_owner(struct perf_event *event)
4125 {
4126 struct task_struct *owner;
4127
4128 rcu_read_lock();
4129 /*
4130 * Matches the smp_store_release() in perf_event_exit_task(). If we
4131 * observe !owner it means the list deletion is complete and we can
4132 * indeed free this event, otherwise we need to serialize on
4133 * owner->perf_event_mutex.
4134 */
4135 owner = lockless_dereference(event->owner);
4136 if (owner) {
4137 /*
4138 * Since delayed_put_task_struct() also drops the last
4139 * task reference we can safely take a new reference
4140 * while holding the rcu_read_lock().
4141 */
4142 get_task_struct(owner);
4143 }
4144 rcu_read_unlock();
4145
4146 if (owner) {
4147 /*
4148 * If we're here through perf_event_exit_task() we're already
4149 * holding ctx->mutex which would be an inversion wrt. the
4150 * normal lock order.
4151 *
4152 * However we can safely take this lock because its the child
4153 * ctx->mutex.
4154 */
4155 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
4156
4157 /*
4158 * We have to re-check the event->owner field, if it is cleared
4159 * we raced with perf_event_exit_task(), acquiring the mutex
4160 * ensured they're done, and we can proceed with freeing the
4161 * event.
4162 */
4163 if (event->owner) {
4164 list_del_init(&event->owner_entry);
4165 smp_store_release(&event->owner, NULL);
4166 }
4167 mutex_unlock(&owner->perf_event_mutex);
4168 put_task_struct(owner);
4169 }
4170 }
4171
4172 static void put_event(struct perf_event *event)
4173 {
4174 if (!atomic_long_dec_and_test(&event->refcount))
4175 return;
4176
4177 _free_event(event);
4178 }
4179
4180 /*
4181 * Kill an event dead; while event:refcount will preserve the event
4182 * object, it will not preserve its functionality. Once the last 'user'
4183 * gives up the object, we'll destroy the thing.
4184 */
4185 int perf_event_release_kernel(struct perf_event *event)
4186 {
4187 struct perf_event_context *ctx = event->ctx;
4188 struct perf_event *child, *tmp;
4189
4190 /*
4191 * If we got here through err_file: fput(event_file); we will not have
4192 * attached to a context yet.
4193 */
4194 if (!ctx) {
4195 WARN_ON_ONCE(event->attach_state &
4196 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
4197 goto no_ctx;
4198 }
4199
4200 if (!is_kernel_event(event))
4201 perf_remove_from_owner(event);
4202
4203 ctx = perf_event_ctx_lock(event);
4204 WARN_ON_ONCE(ctx->parent_ctx);
4205 perf_remove_from_context(event, DETACH_GROUP);
4206
4207 raw_spin_lock_irq(&ctx->lock);
4208 /*
4209 * Mark this even as STATE_DEAD, there is no external reference to it
4210 * anymore.
4211 *
4212 * Anybody acquiring event->child_mutex after the below loop _must_
4213 * also see this, most importantly inherit_event() which will avoid
4214 * placing more children on the list.
4215 *
4216 * Thus this guarantees that we will in fact observe and kill _ALL_
4217 * child events.
4218 */
4219 event->state = PERF_EVENT_STATE_DEAD;
4220 raw_spin_unlock_irq(&ctx->lock);
4221
4222 perf_event_ctx_unlock(event, ctx);
4223
4224 again:
4225 mutex_lock(&event->child_mutex);
4226 list_for_each_entry(child, &event->child_list, child_list) {
4227
4228 /*
4229 * Cannot change, child events are not migrated, see the
4230 * comment with perf_event_ctx_lock_nested().
4231 */
4232 ctx = lockless_dereference(child->ctx);
4233 /*
4234 * Since child_mutex nests inside ctx::mutex, we must jump
4235 * through hoops. We start by grabbing a reference on the ctx.
4236 *
4237 * Since the event cannot get freed while we hold the
4238 * child_mutex, the context must also exist and have a !0
4239 * reference count.
4240 */
4241 get_ctx(ctx);
4242
4243 /*
4244 * Now that we have a ctx ref, we can drop child_mutex, and
4245 * acquire ctx::mutex without fear of it going away. Then we
4246 * can re-acquire child_mutex.
4247 */
4248 mutex_unlock(&event->child_mutex);
4249 mutex_lock(&ctx->mutex);
4250 mutex_lock(&event->child_mutex);
4251
4252 /*
4253 * Now that we hold ctx::mutex and child_mutex, revalidate our
4254 * state, if child is still the first entry, it didn't get freed
4255 * and we can continue doing so.
4256 */
4257 tmp = list_first_entry_or_null(&event->child_list,
4258 struct perf_event, child_list);
4259 if (tmp == child) {
4260 perf_remove_from_context(child, DETACH_GROUP);
4261 list_del(&child->child_list);
4262 free_event(child);
4263 /*
4264 * This matches the refcount bump in inherit_event();
4265 * this can't be the last reference.
4266 */
4267 put_event(event);
4268 }
4269
4270 mutex_unlock(&event->child_mutex);
4271 mutex_unlock(&ctx->mutex);
4272 put_ctx(ctx);
4273 goto again;
4274 }
4275 mutex_unlock(&event->child_mutex);
4276
4277 no_ctx:
4278 put_event(event); /* Must be the 'last' reference */
4279 return 0;
4280 }
4281 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
4282
4283 /*
4284 * Called when the last reference to the file is gone.
4285 */
4286 static int perf_release(struct inode *inode, struct file *file)
4287 {
4288 perf_event_release_kernel(file->private_data);
4289 return 0;
4290 }
4291
4292 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
4293 {
4294 struct perf_event *child;
4295 u64 total = 0;
4296
4297 *enabled = 0;
4298 *running = 0;
4299
4300 mutex_lock(&event->child_mutex);
4301
4302 (void)perf_event_read(event, false);
4303 total += perf_event_count(event);
4304
4305 *enabled += event->total_time_enabled +
4306 atomic64_read(&event->child_total_time_enabled);
4307 *running += event->total_time_running +
4308 atomic64_read(&event->child_total_time_running);
4309
4310 list_for_each_entry(child, &event->child_list, child_list) {
4311 (void)perf_event_read(child, false);
4312 total += perf_event_count(child);
4313 *enabled += child->total_time_enabled;
4314 *running += child->total_time_running;
4315 }
4316 mutex_unlock(&event->child_mutex);
4317
4318 return total;
4319 }
4320 EXPORT_SYMBOL_GPL(perf_event_read_value);
4321
4322 static int __perf_read_group_add(struct perf_event *leader,
4323 u64 read_format, u64 *values)
4324 {
4325 struct perf_event *sub;
4326 int n = 1; /* skip @nr */
4327 int ret;
4328
4329 ret = perf_event_read(leader, true);
4330 if (ret)
4331 return ret;
4332
4333 /*
4334 * Since we co-schedule groups, {enabled,running} times of siblings
4335 * will be identical to those of the leader, so we only publish one
4336 * set.
4337 */
4338 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
4339 values[n++] += leader->total_time_enabled +
4340 atomic64_read(&leader->child_total_time_enabled);
4341 }
4342
4343 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
4344 values[n++] += leader->total_time_running +
4345 atomic64_read(&leader->child_total_time_running);
4346 }
4347
4348 /*
4349 * Write {count,id} tuples for every sibling.
4350 */
4351 values[n++] += perf_event_count(leader);
4352 if (read_format & PERF_FORMAT_ID)
4353 values[n++] = primary_event_id(leader);
4354
4355 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
4356 values[n++] += perf_event_count(sub);
4357 if (read_format & PERF_FORMAT_ID)
4358 values[n++] = primary_event_id(sub);
4359 }
4360
4361 return 0;
4362 }
4363
4364 static int perf_read_group(struct perf_event *event,
4365 u64 read_format, char __user *buf)
4366 {
4367 struct perf_event *leader = event->group_leader, *child;
4368 struct perf_event_context *ctx = leader->ctx;
4369 int ret;
4370 u64 *values;
4371
4372 lockdep_assert_held(&ctx->mutex);
4373
4374 values = kzalloc(event->read_size, GFP_KERNEL);
4375 if (!values)
4376 return -ENOMEM;
4377
4378 values[0] = 1 + leader->nr_siblings;
4379
4380 /*
4381 * By locking the child_mutex of the leader we effectively
4382 * lock the child list of all siblings.. XXX explain how.
4383 */
4384 mutex_lock(&leader->child_mutex);
4385
4386 ret = __perf_read_group_add(leader, read_format, values);
4387 if (ret)
4388 goto unlock;
4389
4390 list_for_each_entry(child, &leader->child_list, child_list) {
4391 ret = __perf_read_group_add(child, read_format, values);
4392 if (ret)
4393 goto unlock;
4394 }
4395
4396 mutex_unlock(&leader->child_mutex);
4397
4398 ret = event->read_size;
4399 if (copy_to_user(buf, values, event->read_size))
4400 ret = -EFAULT;
4401 goto out;
4402
4403 unlock:
4404 mutex_unlock(&leader->child_mutex);
4405 out:
4406 kfree(values);
4407 return ret;
4408 }
4409
4410 static int perf_read_one(struct perf_event *event,
4411 u64 read_format, char __user *buf)
4412 {
4413 u64 enabled, running;
4414 u64 values[4];
4415 int n = 0;
4416
4417 values[n++] = perf_event_read_value(event, &enabled, &running);
4418 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
4419 values[n++] = enabled;
4420 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
4421 values[n++] = running;
4422 if (read_format & PERF_FORMAT_ID)
4423 values[n++] = primary_event_id(event);
4424
4425 if (copy_to_user(buf, values, n * sizeof(u64)))
4426 return -EFAULT;
4427
4428 return n * sizeof(u64);
4429 }
4430
4431 static bool is_event_hup(struct perf_event *event)
4432 {
4433 bool no_children;
4434
4435 if (event->state > PERF_EVENT_STATE_EXIT)
4436 return false;
4437
4438 mutex_lock(&event->child_mutex);
4439 no_children = list_empty(&event->child_list);
4440 mutex_unlock(&event->child_mutex);
4441 return no_children;
4442 }
4443
4444 /*
4445 * Read the performance event - simple non blocking version for now
4446 */
4447 static ssize_t
4448 __perf_read(struct perf_event *event, char __user *buf, size_t count)
4449 {
4450 u64 read_format = event->attr.read_format;
4451 int ret;
4452
4453 /*
4454 * Return end-of-file for a read on a event that is in
4455 * error state (i.e. because it was pinned but it couldn't be
4456 * scheduled on to the CPU at some point).
4457 */
4458 if (event->state == PERF_EVENT_STATE_ERROR)
4459 return 0;
4460
4461 if (count < event->read_size)
4462 return -ENOSPC;
4463
4464 WARN_ON_ONCE(event->ctx->parent_ctx);
4465 if (read_format & PERF_FORMAT_GROUP)
4466 ret = perf_read_group(event, read_format, buf);
4467 else
4468 ret = perf_read_one(event, read_format, buf);
4469
4470 return ret;
4471 }
4472
4473 static ssize_t
4474 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
4475 {
4476 struct perf_event *event = file->private_data;
4477 struct perf_event_context *ctx;
4478 int ret;
4479
4480 ctx = perf_event_ctx_lock(event);
4481 ret = __perf_read(event, buf, count);
4482 perf_event_ctx_unlock(event, ctx);
4483
4484 return ret;
4485 }
4486
4487 static unsigned int perf_poll(struct file *file, poll_table *wait)
4488 {
4489 struct perf_event *event = file->private_data;
4490 struct ring_buffer *rb;
4491 unsigned int events = POLLHUP;
4492
4493 poll_wait(file, &event->waitq, wait);
4494
4495 if (is_event_hup(event))
4496 return events;
4497
4498 /*
4499 * Pin the event->rb by taking event->mmap_mutex; otherwise
4500 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
4501 */
4502 mutex_lock(&event->mmap_mutex);
4503 rb = event->rb;
4504 if (rb)
4505 events = atomic_xchg(&rb->poll, 0);
4506 mutex_unlock(&event->mmap_mutex);
4507 return events;
4508 }
4509
4510 static void _perf_event_reset(struct perf_event *event)
4511 {
4512 (void)perf_event_read(event, false);
4513 local64_set(&event->count, 0);
4514 perf_event_update_userpage(event);
4515 }
4516
4517 /*
4518 * Holding the top-level event's child_mutex means that any
4519 * descendant process that has inherited this event will block
4520 * in perf_event_exit_event() if it goes to exit, thus satisfying the
4521 * task existence requirements of perf_event_enable/disable.
4522 */
4523 static void perf_event_for_each_child(struct perf_event *event,
4524 void (*func)(struct perf_event *))
4525 {
4526 struct perf_event *child;
4527
4528 WARN_ON_ONCE(event->ctx->parent_ctx);
4529
4530 mutex_lock(&event->child_mutex);
4531 func(event);
4532 list_for_each_entry(child, &event->child_list, child_list)
4533 func(child);
4534 mutex_unlock(&event->child_mutex);
4535 }
4536
4537 static void perf_event_for_each(struct perf_event *event,
4538 void (*func)(struct perf_event *))
4539 {
4540 struct perf_event_context *ctx = event->ctx;
4541 struct perf_event *sibling;
4542
4543 lockdep_assert_held(&ctx->mutex);
4544
4545 event = event->group_leader;
4546
4547 perf_event_for_each_child(event, func);
4548 list_for_each_entry(sibling, &event->sibling_list, group_entry)
4549 perf_event_for_each_child(sibling, func);
4550 }
4551
4552 static void __perf_event_period(struct perf_event *event,
4553 struct perf_cpu_context *cpuctx,
4554 struct perf_event_context *ctx,
4555 void *info)
4556 {
4557 u64 value = *((u64 *)info);
4558 bool active;
4559
4560 if (event->attr.freq) {
4561 event->attr.sample_freq = value;
4562 } else {
4563 event->attr.sample_period = value;
4564 event->hw.sample_period = value;
4565 }
4566
4567 active = (event->state == PERF_EVENT_STATE_ACTIVE);
4568 if (active) {
4569 perf_pmu_disable(ctx->pmu);
4570 /*
4571 * We could be throttled; unthrottle now to avoid the tick
4572 * trying to unthrottle while we already re-started the event.
4573 */
4574 if (event->hw.interrupts == MAX_INTERRUPTS) {
4575 event->hw.interrupts = 0;
4576 perf_log_throttle(event, 1);
4577 }
4578 event->pmu->stop(event, PERF_EF_UPDATE);
4579 }
4580
4581 local64_set(&event->hw.period_left, 0);
4582
4583 if (active) {
4584 event->pmu->start(event, PERF_EF_RELOAD);
4585 perf_pmu_enable(ctx->pmu);
4586 }
4587 }
4588
4589 static int perf_event_period(struct perf_event *event, u64 __user *arg)
4590 {
4591 u64 value;
4592
4593 if (!is_sampling_event(event))
4594 return -EINVAL;
4595
4596 if (copy_from_user(&value, arg, sizeof(value)))
4597 return -EFAULT;
4598
4599 if (!value)
4600 return -EINVAL;
4601
4602 if (event->attr.freq && value > sysctl_perf_event_sample_rate)
4603 return -EINVAL;
4604
4605 event_function_call(event, __perf_event_period, &value);
4606
4607 return 0;
4608 }
4609
4610 static const struct file_operations perf_fops;
4611
4612 static inline int perf_fget_light(int fd, struct fd *p)
4613 {
4614 struct fd f = fdget(fd);
4615 if (!f.file)
4616 return -EBADF;
4617
4618 if (f.file->f_op != &perf_fops) {
4619 fdput(f);
4620 return -EBADF;
4621 }
4622 *p = f;
4623 return 0;
4624 }
4625
4626 static int perf_event_set_output(struct perf_event *event,
4627 struct perf_event *output_event);
4628 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
4629 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd);
4630
4631 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
4632 {
4633 void (*func)(struct perf_event *);
4634 u32 flags = arg;
4635
4636 switch (cmd) {
4637 case PERF_EVENT_IOC_ENABLE:
4638 func = _perf_event_enable;
4639 break;
4640 case PERF_EVENT_IOC_DISABLE:
4641 func = _perf_event_disable;
4642 break;
4643 case PERF_EVENT_IOC_RESET:
4644 func = _perf_event_reset;
4645 break;
4646
4647 case PERF_EVENT_IOC_REFRESH:
4648 return _perf_event_refresh(event, arg);
4649
4650 case PERF_EVENT_IOC_PERIOD:
4651 return perf_event_period(event, (u64 __user *)arg);
4652
4653 case PERF_EVENT_IOC_ID:
4654 {
4655 u64 id = primary_event_id(event);
4656
4657 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
4658 return -EFAULT;
4659 return 0;
4660 }
4661
4662 case PERF_EVENT_IOC_SET_OUTPUT:
4663 {
4664 int ret;
4665 if (arg != -1) {
4666 struct perf_event *output_event;
4667 struct fd output;
4668 ret = perf_fget_light(arg, &output);
4669 if (ret)
4670 return ret;
4671 output_event = output.file->private_data;
4672 ret = perf_event_set_output(event, output_event);
4673 fdput(output);
4674 } else {
4675 ret = perf_event_set_output(event, NULL);
4676 }
4677 return ret;
4678 }
4679
4680 case PERF_EVENT_IOC_SET_FILTER:
4681 return perf_event_set_filter(event, (void __user *)arg);
4682
4683 case PERF_EVENT_IOC_SET_BPF:
4684 return perf_event_set_bpf_prog(event, arg);
4685
4686 case PERF_EVENT_IOC_PAUSE_OUTPUT: {
4687 struct ring_buffer *rb;
4688
4689 rcu_read_lock();
4690 rb = rcu_dereference(event->rb);
4691 if (!rb || !rb->nr_pages) {
4692 rcu_read_unlock();
4693 return -EINVAL;
4694 }
4695 rb_toggle_paused(rb, !!arg);
4696 rcu_read_unlock();
4697 return 0;
4698 }
4699 default:
4700 return -ENOTTY;
4701 }
4702
4703 if (flags & PERF_IOC_FLAG_GROUP)
4704 perf_event_for_each(event, func);
4705 else
4706 perf_event_for_each_child(event, func);
4707
4708 return 0;
4709 }
4710
4711 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
4712 {
4713 struct perf_event *event = file->private_data;
4714 struct perf_event_context *ctx;
4715 long ret;
4716
4717 ctx = perf_event_ctx_lock(event);
4718 ret = _perf_ioctl(event, cmd, arg);
4719 perf_event_ctx_unlock(event, ctx);
4720
4721 return ret;
4722 }
4723
4724 #ifdef CONFIG_COMPAT
4725 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
4726 unsigned long arg)
4727 {
4728 switch (_IOC_NR(cmd)) {
4729 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
4730 case _IOC_NR(PERF_EVENT_IOC_ID):
4731 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
4732 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
4733 cmd &= ~IOCSIZE_MASK;
4734 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
4735 }
4736 break;
4737 }
4738 return perf_ioctl(file, cmd, arg);
4739 }
4740 #else
4741 # define perf_compat_ioctl NULL
4742 #endif
4743
4744 int perf_event_task_enable(void)
4745 {
4746 struct perf_event_context *ctx;
4747 struct perf_event *event;
4748
4749 mutex_lock(&current->perf_event_mutex);
4750 list_for_each_entry(event, &current->perf_event_list, owner_entry) {
4751 ctx = perf_event_ctx_lock(event);
4752 perf_event_for_each_child(event, _perf_event_enable);
4753 perf_event_ctx_unlock(event, ctx);
4754 }
4755 mutex_unlock(&current->perf_event_mutex);
4756
4757 return 0;
4758 }
4759
4760 int perf_event_task_disable(void)
4761 {
4762 struct perf_event_context *ctx;
4763 struct perf_event *event;
4764
4765 mutex_lock(&current->perf_event_mutex);
4766 list_for_each_entry(event, &current->perf_event_list, owner_entry) {
4767 ctx = perf_event_ctx_lock(event);
4768 perf_event_for_each_child(event, _perf_event_disable);
4769 perf_event_ctx_unlock(event, ctx);
4770 }
4771 mutex_unlock(&current->perf_event_mutex);
4772
4773 return 0;
4774 }
4775
4776 static int perf_event_index(struct perf_event *event)
4777 {
4778 if (event->hw.state & PERF_HES_STOPPED)
4779 return 0;
4780
4781 if (event->state != PERF_EVENT_STATE_ACTIVE)
4782 return 0;
4783
4784 return event->pmu->event_idx(event);
4785 }
4786
4787 static void calc_timer_values(struct perf_event *event,
4788 u64 *now,
4789 u64 *enabled,
4790 u64 *running)
4791 {
4792 u64 ctx_time;
4793
4794 *now = perf_clock();
4795 ctx_time = event->shadow_ctx_time + *now;
4796 *enabled = ctx_time - event->tstamp_enabled;
4797 *running = ctx_time - event->tstamp_running;
4798 }
4799
4800 static void perf_event_init_userpage(struct perf_event *event)
4801 {
4802 struct perf_event_mmap_page *userpg;
4803 struct ring_buffer *rb;
4804
4805 rcu_read_lock();
4806 rb = rcu_dereference(event->rb);
4807 if (!rb)
4808 goto unlock;
4809
4810 userpg = rb->user_page;
4811
4812 /* Allow new userspace to detect that bit 0 is deprecated */
4813 userpg->cap_bit0_is_deprecated = 1;
4814 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
4815 userpg->data_offset = PAGE_SIZE;
4816 userpg->data_size = perf_data_size(rb);
4817
4818 unlock:
4819 rcu_read_unlock();
4820 }
4821
4822 void __weak arch_perf_update_userpage(
4823 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
4824 {
4825 }
4826
4827 /*
4828 * Callers need to ensure there can be no nesting of this function, otherwise
4829 * the seqlock logic goes bad. We can not serialize this because the arch
4830 * code calls this from NMI context.
4831 */
4832 void perf_event_update_userpage(struct perf_event *event)
4833 {
4834 struct perf_event_mmap_page *userpg;
4835 struct ring_buffer *rb;
4836 u64 enabled, running, now;
4837
4838 rcu_read_lock();
4839 rb = rcu_dereference(event->rb);
4840 if (!rb)
4841 goto unlock;
4842
4843 /*
4844 * compute total_time_enabled, total_time_running
4845 * based on snapshot values taken when the event
4846 * was last scheduled in.
4847 *
4848 * we cannot simply called update_context_time()
4849 * because of locking issue as we can be called in
4850 * NMI context
4851 */
4852 calc_timer_values(event, &now, &enabled, &running);
4853
4854 userpg = rb->user_page;
4855 /*
4856 * Disable preemption so as to not let the corresponding user-space
4857 * spin too long if we get preempted.
4858 */
4859 preempt_disable();
4860 ++userpg->lock;
4861 barrier();
4862 userpg->index = perf_event_index(event);
4863 userpg->offset = perf_event_count(event);
4864 if (userpg->index)
4865 userpg->offset -= local64_read(&event->hw.prev_count);
4866
4867 userpg->time_enabled = enabled +
4868 atomic64_read(&event->child_total_time_enabled);
4869
4870 userpg->time_running = running +
4871 atomic64_read(&event->child_total_time_running);
4872
4873 arch_perf_update_userpage(event, userpg, now);
4874
4875 barrier();
4876 ++userpg->lock;
4877 preempt_enable();
4878 unlock:
4879 rcu_read_unlock();
4880 }
4881
4882 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
4883 {
4884 struct perf_event *event = vma->vm_file->private_data;
4885 struct ring_buffer *rb;
4886 int ret = VM_FAULT_SIGBUS;
4887
4888 if (vmf->flags & FAULT_FLAG_MKWRITE) {
4889 if (vmf->pgoff == 0)
4890 ret = 0;
4891 return ret;
4892 }
4893
4894 rcu_read_lock();
4895 rb = rcu_dereference(event->rb);
4896 if (!rb)
4897 goto unlock;
4898
4899 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
4900 goto unlock;
4901
4902 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
4903 if (!vmf->page)
4904 goto unlock;
4905
4906 get_page(vmf->page);
4907 vmf->page->mapping = vma->vm_file->f_mapping;
4908 vmf->page->index = vmf->pgoff;
4909
4910 ret = 0;
4911 unlock:
4912 rcu_read_unlock();
4913
4914 return ret;
4915 }
4916
4917 static void ring_buffer_attach(struct perf_event *event,
4918 struct ring_buffer *rb)
4919 {
4920 struct ring_buffer *old_rb = NULL;
4921 unsigned long flags;
4922
4923 if (event->rb) {
4924 /*
4925 * Should be impossible, we set this when removing
4926 * event->rb_entry and wait/clear when adding event->rb_entry.
4927 */
4928 WARN_ON_ONCE(event->rcu_pending);
4929
4930 old_rb = event->rb;
4931 spin_lock_irqsave(&old_rb->event_lock, flags);
4932 list_del_rcu(&event->rb_entry);
4933 spin_unlock_irqrestore(&old_rb->event_lock, flags);
4934
4935 event->rcu_batches = get_state_synchronize_rcu();
4936 event->rcu_pending = 1;
4937 }
4938
4939 if (rb) {
4940 if (event->rcu_pending) {
4941 cond_synchronize_rcu(event->rcu_batches);
4942 event->rcu_pending = 0;
4943 }
4944
4945 spin_lock_irqsave(&rb->event_lock, flags);
4946 list_add_rcu(&event->rb_entry, &rb->event_list);
4947 spin_unlock_irqrestore(&rb->event_lock, flags);
4948 }
4949
4950 /*
4951 * Avoid racing with perf_mmap_close(AUX): stop the event
4952 * before swizzling the event::rb pointer; if it's getting
4953 * unmapped, its aux_mmap_count will be 0 and it won't
4954 * restart. See the comment in __perf_pmu_output_stop().
4955 *
4956 * Data will inevitably be lost when set_output is done in
4957 * mid-air, but then again, whoever does it like this is
4958 * not in for the data anyway.
4959 */
4960 if (has_aux(event))
4961 perf_event_stop(event, 0);
4962
4963 rcu_assign_pointer(event->rb, rb);
4964
4965 if (old_rb) {
4966 ring_buffer_put(old_rb);
4967 /*
4968 * Since we detached before setting the new rb, so that we
4969 * could attach the new rb, we could have missed a wakeup.
4970 * Provide it now.
4971 */
4972 wake_up_all(&event->waitq);
4973 }
4974 }
4975
4976 static void ring_buffer_wakeup(struct perf_event *event)
4977 {
4978 struct ring_buffer *rb;
4979
4980 rcu_read_lock();
4981 rb = rcu_dereference(event->rb);
4982 if (rb) {
4983 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
4984 wake_up_all(&event->waitq);
4985 }
4986 rcu_read_unlock();
4987 }
4988
4989 struct ring_buffer *ring_buffer_get(struct perf_event *event)
4990 {
4991 struct ring_buffer *rb;
4992
4993 rcu_read_lock();
4994 rb = rcu_dereference(event->rb);
4995 if (rb) {
4996 if (!atomic_inc_not_zero(&rb->refcount))
4997 rb = NULL;
4998 }
4999 rcu_read_unlock();
5000
5001 return rb;
5002 }
5003
5004 void ring_buffer_put(struct ring_buffer *rb)
5005 {
5006 if (!atomic_dec_and_test(&rb->refcount))
5007 return;
5008
5009 WARN_ON_ONCE(!list_empty(&rb->event_list));
5010
5011 call_rcu(&rb->rcu_head, rb_free_rcu);
5012 }
5013
5014 static void perf_mmap_open(struct vm_area_struct *vma)
5015 {
5016 struct perf_event *event = vma->vm_file->private_data;
5017
5018 atomic_inc(&event->mmap_count);
5019 atomic_inc(&event->rb->mmap_count);
5020
5021 if (vma->vm_pgoff)
5022 atomic_inc(&event->rb->aux_mmap_count);
5023
5024 if (event->pmu->event_mapped)
5025 event->pmu->event_mapped(event);
5026 }
5027
5028 static void perf_pmu_output_stop(struct perf_event *event);
5029
5030 /*
5031 * A buffer can be mmap()ed multiple times; either directly through the same
5032 * event, or through other events by use of perf_event_set_output().
5033 *
5034 * In order to undo the VM accounting done by perf_mmap() we need to destroy
5035 * the buffer here, where we still have a VM context. This means we need
5036 * to detach all events redirecting to us.
5037 */
5038 static void perf_mmap_close(struct vm_area_struct *vma)
5039 {
5040 struct perf_event *event = vma->vm_file->private_data;
5041
5042 struct ring_buffer *rb = ring_buffer_get(event);
5043 struct user_struct *mmap_user = rb->mmap_user;
5044 int mmap_locked = rb->mmap_locked;
5045 unsigned long size = perf_data_size(rb);
5046
5047 if (event->pmu->event_unmapped)
5048 event->pmu->event_unmapped(event);
5049
5050 /*
5051 * rb->aux_mmap_count will always drop before rb->mmap_count and
5052 * event->mmap_count, so it is ok to use event->mmap_mutex to
5053 * serialize with perf_mmap here.
5054 */
5055 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
5056 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
5057 /*
5058 * Stop all AUX events that are writing to this buffer,
5059 * so that we can free its AUX pages and corresponding PMU
5060 * data. Note that after rb::aux_mmap_count dropped to zero,
5061 * they won't start any more (see perf_aux_output_begin()).
5062 */
5063 perf_pmu_output_stop(event);
5064
5065 /* now it's safe to free the pages */
5066 atomic_long_sub(rb->aux_nr_pages, &mmap_user->locked_vm);
5067 vma->vm_mm->pinned_vm -= rb->aux_mmap_locked;
5068
5069 /* this has to be the last one */
5070 rb_free_aux(rb);
5071 WARN_ON_ONCE(atomic_read(&rb->aux_refcount));
5072
5073 mutex_unlock(&event->mmap_mutex);
5074 }
5075
5076 atomic_dec(&rb->mmap_count);
5077
5078 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
5079 goto out_put;
5080
5081 ring_buffer_attach(event, NULL);
5082 mutex_unlock(&event->mmap_mutex);
5083
5084 /* If there's still other mmap()s of this buffer, we're done. */
5085 if (atomic_read(&rb->mmap_count))
5086 goto out_put;
5087
5088 /*
5089 * No other mmap()s, detach from all other events that might redirect
5090 * into the now unreachable buffer. Somewhat complicated by the
5091 * fact that rb::event_lock otherwise nests inside mmap_mutex.
5092 */
5093 again:
5094 rcu_read_lock();
5095 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
5096 if (!atomic_long_inc_not_zero(&event->refcount)) {
5097 /*
5098 * This event is en-route to free_event() which will
5099 * detach it and remove it from the list.
5100 */
5101 continue;
5102 }
5103 rcu_read_unlock();
5104
5105 mutex_lock(&event->mmap_mutex);
5106 /*
5107 * Check we didn't race with perf_event_set_output() which can
5108 * swizzle the rb from under us while we were waiting to
5109 * acquire mmap_mutex.
5110 *
5111 * If we find a different rb; ignore this event, a next
5112 * iteration will no longer find it on the list. We have to
5113 * still restart the iteration to make sure we're not now
5114 * iterating the wrong list.
5115 */
5116 if (event->rb == rb)
5117 ring_buffer_attach(event, NULL);
5118
5119 mutex_unlock(&event->mmap_mutex);
5120 put_event(event);
5121
5122 /*
5123 * Restart the iteration; either we're on the wrong list or
5124 * destroyed its integrity by doing a deletion.
5125 */
5126 goto again;
5127 }
5128 rcu_read_unlock();
5129
5130 /*
5131 * It could be there's still a few 0-ref events on the list; they'll
5132 * get cleaned up by free_event() -- they'll also still have their
5133 * ref on the rb and will free it whenever they are done with it.
5134 *
5135 * Aside from that, this buffer is 'fully' detached and unmapped,
5136 * undo the VM accounting.
5137 */
5138
5139 atomic_long_sub((size >> PAGE_SHIFT) + 1, &mmap_user->locked_vm);
5140 vma->vm_mm->pinned_vm -= mmap_locked;
5141 free_uid(mmap_user);
5142
5143 out_put:
5144 ring_buffer_put(rb); /* could be last */
5145 }
5146
5147 static const struct vm_operations_struct perf_mmap_vmops = {
5148 .open = perf_mmap_open,
5149 .close = perf_mmap_close, /* non mergable */
5150 .fault = perf_mmap_fault,
5151 .page_mkwrite = perf_mmap_fault,
5152 };
5153
5154 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
5155 {
5156 struct perf_event *event = file->private_data;
5157 unsigned long user_locked, user_lock_limit;
5158 struct user_struct *user = current_user();
5159 unsigned long locked, lock_limit;
5160 struct ring_buffer *rb = NULL;
5161 unsigned long vma_size;
5162 unsigned long nr_pages;
5163 long user_extra = 0, extra = 0;
5164 int ret = 0, flags = 0;
5165
5166 /*
5167 * Don't allow mmap() of inherited per-task counters. This would
5168 * create a performance issue due to all children writing to the
5169 * same rb.
5170 */
5171 if (event->cpu == -1 && event->attr.inherit)
5172 return -EINVAL;
5173
5174 if (!(vma->vm_flags & VM_SHARED))
5175 return -EINVAL;
5176
5177 vma_size = vma->vm_end - vma->vm_start;
5178
5179 if (vma->vm_pgoff == 0) {
5180 nr_pages = (vma_size / PAGE_SIZE) - 1;
5181 } else {
5182 /*
5183 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
5184 * mapped, all subsequent mappings should have the same size
5185 * and offset. Must be above the normal perf buffer.
5186 */
5187 u64 aux_offset, aux_size;
5188
5189 if (!event->rb)
5190 return -EINVAL;
5191
5192 nr_pages = vma_size / PAGE_SIZE;
5193
5194 mutex_lock(&event->mmap_mutex);
5195 ret = -EINVAL;
5196
5197 rb = event->rb;
5198 if (!rb)
5199 goto aux_unlock;
5200
5201 aux_offset = ACCESS_ONCE(rb->user_page->aux_offset);
5202 aux_size = ACCESS_ONCE(rb->user_page->aux_size);
5203
5204 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
5205 goto aux_unlock;
5206
5207 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
5208 goto aux_unlock;
5209
5210 /* already mapped with a different offset */
5211 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
5212 goto aux_unlock;
5213
5214 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
5215 goto aux_unlock;
5216
5217 /* already mapped with a different size */
5218 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
5219 goto aux_unlock;
5220
5221 if (!is_power_of_2(nr_pages))
5222 goto aux_unlock;
5223
5224 if (!atomic_inc_not_zero(&rb->mmap_count))
5225 goto aux_unlock;
5226
5227 if (rb_has_aux(rb)) {
5228 atomic_inc(&rb->aux_mmap_count);
5229 ret = 0;
5230 goto unlock;
5231 }
5232
5233 atomic_set(&rb->aux_mmap_count, 1);
5234 user_extra = nr_pages;
5235
5236 goto accounting;
5237 }
5238
5239 /*
5240 * If we have rb pages ensure they're a power-of-two number, so we
5241 * can do bitmasks instead of modulo.
5242 */
5243 if (nr_pages != 0 && !is_power_of_2(nr_pages))
5244 return -EINVAL;
5245
5246 if (vma_size != PAGE_SIZE * (1 + nr_pages))
5247 return -EINVAL;
5248
5249 WARN_ON_ONCE(event->ctx->parent_ctx);
5250 again:
5251 mutex_lock(&event->mmap_mutex);
5252 if (event->rb) {
5253 if (event->rb->nr_pages != nr_pages) {
5254 ret = -EINVAL;
5255 goto unlock;
5256 }
5257
5258 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
5259 /*
5260 * Raced against perf_mmap_close() through
5261 * perf_event_set_output(). Try again, hope for better
5262 * luck.
5263 */
5264 mutex_unlock(&event->mmap_mutex);
5265 goto again;
5266 }
5267
5268 goto unlock;
5269 }
5270
5271 user_extra = nr_pages + 1;
5272
5273 accounting:
5274 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
5275
5276 /*
5277 * Increase the limit linearly with more CPUs:
5278 */
5279 user_lock_limit *= num_online_cpus();
5280
5281 user_locked = atomic_long_read(&user->locked_vm) + user_extra;
5282
5283 if (user_locked > user_lock_limit)
5284 extra = user_locked - user_lock_limit;
5285
5286 lock_limit = rlimit(RLIMIT_MEMLOCK);
5287 lock_limit >>= PAGE_SHIFT;
5288 locked = vma->vm_mm->pinned_vm + extra;
5289
5290 if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
5291 !capable(CAP_IPC_LOCK)) {
5292 ret = -EPERM;
5293 goto unlock;
5294 }
5295
5296 WARN_ON(!rb && event->rb);
5297
5298 if (vma->vm_flags & VM_WRITE)
5299 flags |= RING_BUFFER_WRITABLE;
5300
5301 if (!rb) {
5302 rb = rb_alloc(nr_pages,
5303 event->attr.watermark ? event->attr.wakeup_watermark : 0,
5304 event->cpu, flags);
5305
5306 if (!rb) {
5307 ret = -ENOMEM;
5308 goto unlock;
5309 }
5310
5311 atomic_set(&rb->mmap_count, 1);
5312 rb->mmap_user = get_current_user();
5313 rb->mmap_locked = extra;
5314
5315 ring_buffer_attach(event, rb);
5316
5317 perf_event_init_userpage(event);
5318 perf_event_update_userpage(event);
5319 } else {
5320 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
5321 event->attr.aux_watermark, flags);
5322 if (!ret)
5323 rb->aux_mmap_locked = extra;
5324 }
5325
5326 unlock:
5327 if (!ret) {
5328 atomic_long_add(user_extra, &user->locked_vm);
5329 vma->vm_mm->pinned_vm += extra;
5330
5331 atomic_inc(&event->mmap_count);
5332 } else if (rb) {
5333 atomic_dec(&rb->mmap_count);
5334 }
5335 aux_unlock:
5336 mutex_unlock(&event->mmap_mutex);
5337
5338 /*
5339 * Since pinned accounting is per vm we cannot allow fork() to copy our
5340 * vma.
5341 */
5342 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
5343 vma->vm_ops = &perf_mmap_vmops;
5344
5345 if (event->pmu->event_mapped)
5346 event->pmu->event_mapped(event);
5347
5348 return ret;
5349 }
5350
5351 static int perf_fasync(int fd, struct file *filp, int on)
5352 {
5353 struct inode *inode = file_inode(filp);
5354 struct perf_event *event = filp->private_data;
5355 int retval;
5356
5357 inode_lock(inode);
5358 retval = fasync_helper(fd, filp, on, &event->fasync);
5359 inode_unlock(inode);
5360
5361 if (retval < 0)
5362 return retval;
5363
5364 return 0;
5365 }
5366
5367 static const struct file_operations perf_fops = {
5368 .llseek = no_llseek,
5369 .release = perf_release,
5370 .read = perf_read,
5371 .poll = perf_poll,
5372 .unlocked_ioctl = perf_ioctl,
5373 .compat_ioctl = perf_compat_ioctl,
5374 .mmap = perf_mmap,
5375 .fasync = perf_fasync,
5376 };
5377
5378 /*
5379 * Perf event wakeup
5380 *
5381 * If there's data, ensure we set the poll() state and publish everything
5382 * to user-space before waking everybody up.
5383 */
5384
5385 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
5386 {
5387 /* only the parent has fasync state */
5388 if (event->parent)
5389 event = event->parent;
5390 return &event->fasync;
5391 }
5392
5393 void perf_event_wakeup(struct perf_event *event)
5394 {
5395 ring_buffer_wakeup(event);
5396
5397 if (event->pending_kill) {
5398 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
5399 event->pending_kill = 0;
5400 }
5401 }
5402
5403 static void perf_pending_event(struct irq_work *entry)
5404 {
5405 struct perf_event *event = container_of(entry,
5406 struct perf_event, pending);
5407 int rctx;
5408
5409 rctx = perf_swevent_get_recursion_context();
5410 /*
5411 * If we 'fail' here, that's OK, it means recursion is already disabled
5412 * and we won't recurse 'further'.
5413 */
5414
5415 if (event->pending_disable) {
5416 event->pending_disable = 0;
5417 perf_event_disable_local(event);
5418 }
5419
5420 if (event->pending_wakeup) {
5421 event->pending_wakeup = 0;
5422 perf_event_wakeup(event);
5423 }
5424
5425 if (rctx >= 0)
5426 perf_swevent_put_recursion_context(rctx);
5427 }
5428
5429 /*
5430 * We assume there is only KVM supporting the callbacks.
5431 * Later on, we might change it to a list if there is
5432 * another virtualization implementation supporting the callbacks.
5433 */
5434 struct perf_guest_info_callbacks *perf_guest_cbs;
5435
5436 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
5437 {
5438 perf_guest_cbs = cbs;
5439 return 0;
5440 }
5441 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
5442
5443 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
5444 {
5445 perf_guest_cbs = NULL;
5446 return 0;
5447 }
5448 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
5449
5450 static void
5451 perf_output_sample_regs(struct perf_output_handle *handle,
5452 struct pt_regs *regs, u64 mask)
5453 {
5454 int bit;
5455 DECLARE_BITMAP(_mask, 64);
5456
5457 bitmap_from_u64(_mask, mask);
5458 for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) {
5459 u64 val;
5460
5461 val = perf_reg_value(regs, bit);
5462 perf_output_put(handle, val);
5463 }
5464 }
5465
5466 static void perf_sample_regs_user(struct perf_regs *regs_user,
5467 struct pt_regs *regs,
5468 struct pt_regs *regs_user_copy)
5469 {
5470 if (user_mode(regs)) {
5471 regs_user->abi = perf_reg_abi(current);
5472 regs_user->regs = regs;
5473 } else if (current->mm) {
5474 perf_get_regs_user(regs_user, regs, regs_user_copy);
5475 } else {
5476 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
5477 regs_user->regs = NULL;
5478 }
5479 }
5480
5481 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
5482 struct pt_regs *regs)
5483 {
5484 regs_intr->regs = regs;
5485 regs_intr->abi = perf_reg_abi(current);
5486 }
5487
5488
5489 /*
5490 * Get remaining task size from user stack pointer.
5491 *
5492 * It'd be better to take stack vma map and limit this more
5493 * precisly, but there's no way to get it safely under interrupt,
5494 * so using TASK_SIZE as limit.
5495 */
5496 static u64 perf_ustack_task_size(struct pt_regs *regs)
5497 {
5498 unsigned long addr = perf_user_stack_pointer(regs);
5499
5500 if (!addr || addr >= TASK_SIZE)
5501 return 0;
5502
5503 return TASK_SIZE - addr;
5504 }
5505
5506 static u16
5507 perf_sample_ustack_size(u16 stack_size, u16 header_size,
5508 struct pt_regs *regs)
5509 {
5510 u64 task_size;
5511
5512 /* No regs, no stack pointer, no dump. */
5513 if (!regs)
5514 return 0;
5515
5516 /*
5517 * Check if we fit in with the requested stack size into the:
5518 * - TASK_SIZE
5519 * If we don't, we limit the size to the TASK_SIZE.
5520 *
5521 * - remaining sample size
5522 * If we don't, we customize the stack size to
5523 * fit in to the remaining sample size.
5524 */
5525
5526 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
5527 stack_size = min(stack_size, (u16) task_size);
5528
5529 /* Current header size plus static size and dynamic size. */
5530 header_size += 2 * sizeof(u64);
5531
5532 /* Do we fit in with the current stack dump size? */
5533 if ((u16) (header_size + stack_size) < header_size) {
5534 /*
5535 * If we overflow the maximum size for the sample,
5536 * we customize the stack dump size to fit in.
5537 */
5538 stack_size = USHRT_MAX - header_size - sizeof(u64);
5539 stack_size = round_up(stack_size, sizeof(u64));
5540 }
5541
5542 return stack_size;
5543 }
5544
5545 static void
5546 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
5547 struct pt_regs *regs)
5548 {
5549 /* Case of a kernel thread, nothing to dump */
5550 if (!regs) {
5551 u64 size = 0;
5552 perf_output_put(handle, size);
5553 } else {
5554 unsigned long sp;
5555 unsigned int rem;
5556 u64 dyn_size;
5557
5558 /*
5559 * We dump:
5560 * static size
5561 * - the size requested by user or the best one we can fit
5562 * in to the sample max size
5563 * data
5564 * - user stack dump data
5565 * dynamic size
5566 * - the actual dumped size
5567 */
5568
5569 /* Static size. */
5570 perf_output_put(handle, dump_size);
5571
5572 /* Data. */
5573 sp = perf_user_stack_pointer(regs);
5574 rem = __output_copy_user(handle, (void *) sp, dump_size);
5575 dyn_size = dump_size - rem;
5576
5577 perf_output_skip(handle, rem);
5578
5579 /* Dynamic size. */
5580 perf_output_put(handle, dyn_size);
5581 }
5582 }
5583
5584 static void __perf_event_header__init_id(struct perf_event_header *header,
5585 struct perf_sample_data *data,
5586 struct perf_event *event)
5587 {
5588 u64 sample_type = event->attr.sample_type;
5589
5590 data->type = sample_type;
5591 header->size += event->id_header_size;
5592
5593 if (sample_type & PERF_SAMPLE_TID) {
5594 /* namespace issues */
5595 data->tid_entry.pid = perf_event_pid(event, current);
5596 data->tid_entry.tid = perf_event_tid(event, current);
5597 }
5598
5599 if (sample_type & PERF_SAMPLE_TIME)
5600 data->time = perf_event_clock(event);
5601
5602 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
5603 data->id = primary_event_id(event);
5604
5605 if (sample_type & PERF_SAMPLE_STREAM_ID)
5606 data->stream_id = event->id;
5607
5608 if (sample_type & PERF_SAMPLE_CPU) {
5609 data->cpu_entry.cpu = raw_smp_processor_id();
5610 data->cpu_entry.reserved = 0;
5611 }
5612 }
5613
5614 void perf_event_header__init_id(struct perf_event_header *header,
5615 struct perf_sample_data *data,
5616 struct perf_event *event)
5617 {
5618 if (event->attr.sample_id_all)
5619 __perf_event_header__init_id(header, data, event);
5620 }
5621
5622 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
5623 struct perf_sample_data *data)
5624 {
5625 u64 sample_type = data->type;
5626
5627 if (sample_type & PERF_SAMPLE_TID)
5628 perf_output_put(handle, data->tid_entry);
5629
5630 if (sample_type & PERF_SAMPLE_TIME)
5631 perf_output_put(handle, data->time);
5632
5633 if (sample_type & PERF_SAMPLE_ID)
5634 perf_output_put(handle, data->id);
5635
5636 if (sample_type & PERF_SAMPLE_STREAM_ID)
5637 perf_output_put(handle, data->stream_id);
5638
5639 if (sample_type & PERF_SAMPLE_CPU)
5640 perf_output_put(handle, data->cpu_entry);
5641
5642 if (sample_type & PERF_SAMPLE_IDENTIFIER)
5643 perf_output_put(handle, data->id);
5644 }
5645
5646 void perf_event__output_id_sample(struct perf_event *event,
5647 struct perf_output_handle *handle,
5648 struct perf_sample_data *sample)
5649 {
5650 if (event->attr.sample_id_all)
5651 __perf_event__output_id_sample(handle, sample);
5652 }
5653
5654 static void perf_output_read_one(struct perf_output_handle *handle,
5655 struct perf_event *event,
5656 u64 enabled, u64 running)
5657 {
5658 u64 read_format = event->attr.read_format;
5659 u64 values[4];
5660 int n = 0;
5661
5662 values[n++] = perf_event_count(event);
5663 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5664 values[n++] = enabled +
5665 atomic64_read(&event->child_total_time_enabled);
5666 }
5667 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5668 values[n++] = running +
5669 atomic64_read(&event->child_total_time_running);
5670 }
5671 if (read_format & PERF_FORMAT_ID)
5672 values[n++] = primary_event_id(event);
5673
5674 __output_copy(handle, values, n * sizeof(u64));
5675 }
5676
5677 /*
5678 * XXX PERF_FORMAT_GROUP vs inherited events seems difficult.
5679 */
5680 static void perf_output_read_group(struct perf_output_handle *handle,
5681 struct perf_event *event,
5682 u64 enabled, u64 running)
5683 {
5684 struct perf_event *leader = event->group_leader, *sub;
5685 u64 read_format = event->attr.read_format;
5686 u64 values[5];
5687 int n = 0;
5688
5689 values[n++] = 1 + leader->nr_siblings;
5690
5691 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
5692 values[n++] = enabled;
5693
5694 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
5695 values[n++] = running;
5696
5697 if (leader != event)
5698 leader->pmu->read(leader);
5699
5700 values[n++] = perf_event_count(leader);
5701 if (read_format & PERF_FORMAT_ID)
5702 values[n++] = primary_event_id(leader);
5703
5704 __output_copy(handle, values, n * sizeof(u64));
5705
5706 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
5707 n = 0;
5708
5709 if ((sub != event) &&
5710 (sub->state == PERF_EVENT_STATE_ACTIVE))
5711 sub->pmu->read(sub);
5712
5713 values[n++] = perf_event_count(sub);
5714 if (read_format & PERF_FORMAT_ID)
5715 values[n++] = primary_event_id(sub);
5716
5717 __output_copy(handle, values, n * sizeof(u64));
5718 }
5719 }
5720
5721 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
5722 PERF_FORMAT_TOTAL_TIME_RUNNING)
5723
5724 static void perf_output_read(struct perf_output_handle *handle,
5725 struct perf_event *event)
5726 {
5727 u64 enabled = 0, running = 0, now;
5728 u64 read_format = event->attr.read_format;
5729
5730 /*
5731 * compute total_time_enabled, total_time_running
5732 * based on snapshot values taken when the event
5733 * was last scheduled in.
5734 *
5735 * we cannot simply called update_context_time()
5736 * because of locking issue as we are called in
5737 * NMI context
5738 */
5739 if (read_format & PERF_FORMAT_TOTAL_TIMES)
5740 calc_timer_values(event, &now, &enabled, &running);
5741
5742 if (event->attr.read_format & PERF_FORMAT_GROUP)
5743 perf_output_read_group(handle, event, enabled, running);
5744 else
5745 perf_output_read_one(handle, event, enabled, running);
5746 }
5747
5748 void perf_output_sample(struct perf_output_handle *handle,
5749 struct perf_event_header *header,
5750 struct perf_sample_data *data,
5751 struct perf_event *event)
5752 {
5753 u64 sample_type = data->type;
5754
5755 perf_output_put(handle, *header);
5756
5757 if (sample_type & PERF_SAMPLE_IDENTIFIER)
5758 perf_output_put(handle, data->id);
5759
5760 if (sample_type & PERF_SAMPLE_IP)
5761 perf_output_put(handle, data->ip);
5762
5763 if (sample_type & PERF_SAMPLE_TID)
5764 perf_output_put(handle, data->tid_entry);
5765
5766 if (sample_type & PERF_SAMPLE_TIME)
5767 perf_output_put(handle, data->time);
5768
5769 if (sample_type & PERF_SAMPLE_ADDR)
5770 perf_output_put(handle, data->addr);
5771
5772 if (sample_type & PERF_SAMPLE_ID)
5773 perf_output_put(handle, data->id);
5774
5775 if (sample_type & PERF_SAMPLE_STREAM_ID)
5776 perf_output_put(handle, data->stream_id);
5777
5778 if (sample_type & PERF_SAMPLE_CPU)
5779 perf_output_put(handle, data->cpu_entry);
5780
5781 if (sample_type & PERF_SAMPLE_PERIOD)
5782 perf_output_put(handle, data->period);
5783
5784 if (sample_type & PERF_SAMPLE_READ)
5785 perf_output_read(handle, event);
5786
5787 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
5788 if (data->callchain) {
5789 int size = 1;
5790
5791 if (data->callchain)
5792 size += data->callchain->nr;
5793
5794 size *= sizeof(u64);
5795
5796 __output_copy(handle, data->callchain, size);
5797 } else {
5798 u64 nr = 0;
5799 perf_output_put(handle, nr);
5800 }
5801 }
5802
5803 if (sample_type & PERF_SAMPLE_RAW) {
5804 struct perf_raw_record *raw = data->raw;
5805
5806 if (raw) {
5807 struct perf_raw_frag *frag = &raw->frag;
5808
5809 perf_output_put(handle, raw->size);
5810 do {
5811 if (frag->copy) {
5812 __output_custom(handle, frag->copy,
5813 frag->data, frag->size);
5814 } else {
5815 __output_copy(handle, frag->data,
5816 frag->size);
5817 }
5818 if (perf_raw_frag_last(frag))
5819 break;
5820 frag = frag->next;
5821 } while (1);
5822 if (frag->pad)
5823 __output_skip(handle, NULL, frag->pad);
5824 } else {
5825 struct {
5826 u32 size;
5827 u32 data;
5828 } raw = {
5829 .size = sizeof(u32),
5830 .data = 0,
5831 };
5832 perf_output_put(handle, raw);
5833 }
5834 }
5835
5836 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
5837 if (data->br_stack) {
5838 size_t size;
5839
5840 size = data->br_stack->nr
5841 * sizeof(struct perf_branch_entry);
5842
5843 perf_output_put(handle, data->br_stack->nr);
5844 perf_output_copy(handle, data->br_stack->entries, size);
5845 } else {
5846 /*
5847 * we always store at least the value of nr
5848 */
5849 u64 nr = 0;
5850 perf_output_put(handle, nr);
5851 }
5852 }
5853
5854 if (sample_type & PERF_SAMPLE_REGS_USER) {
5855 u64 abi = data->regs_user.abi;
5856
5857 /*
5858 * If there are no regs to dump, notice it through
5859 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
5860 */
5861 perf_output_put(handle, abi);
5862
5863 if (abi) {
5864 u64 mask = event->attr.sample_regs_user;
5865 perf_output_sample_regs(handle,
5866 data->regs_user.regs,
5867 mask);
5868 }
5869 }
5870
5871 if (sample_type & PERF_SAMPLE_STACK_USER) {
5872 perf_output_sample_ustack(handle,
5873 data->stack_user_size,
5874 data->regs_user.regs);
5875 }
5876
5877 if (sample_type & PERF_SAMPLE_WEIGHT)
5878 perf_output_put(handle, data->weight);
5879
5880 if (sample_type & PERF_SAMPLE_DATA_SRC)
5881 perf_output_put(handle, data->data_src.val);
5882
5883 if (sample_type & PERF_SAMPLE_TRANSACTION)
5884 perf_output_put(handle, data->txn);
5885
5886 if (sample_type & PERF_SAMPLE_REGS_INTR) {
5887 u64 abi = data->regs_intr.abi;
5888 /*
5889 * If there are no regs to dump, notice it through
5890 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
5891 */
5892 perf_output_put(handle, abi);
5893
5894 if (abi) {
5895 u64 mask = event->attr.sample_regs_intr;
5896
5897 perf_output_sample_regs(handle,
5898 data->regs_intr.regs,
5899 mask);
5900 }
5901 }
5902
5903 if (!event->attr.watermark) {
5904 int wakeup_events = event->attr.wakeup_events;
5905
5906 if (wakeup_events) {
5907 struct ring_buffer *rb = handle->rb;
5908 int events = local_inc_return(&rb->events);
5909
5910 if (events >= wakeup_events) {
5911 local_sub(wakeup_events, &rb->events);
5912 local_inc(&rb->wakeup);
5913 }
5914 }
5915 }
5916 }
5917
5918 void perf_prepare_sample(struct perf_event_header *header,
5919 struct perf_sample_data *data,
5920 struct perf_event *event,
5921 struct pt_regs *regs)
5922 {
5923 u64 sample_type = event->attr.sample_type;
5924
5925 header->type = PERF_RECORD_SAMPLE;
5926 header->size = sizeof(*header) + event->header_size;
5927
5928 header->misc = 0;
5929 header->misc |= perf_misc_flags(regs);
5930
5931 __perf_event_header__init_id(header, data, event);
5932
5933 if (sample_type & PERF_SAMPLE_IP)
5934 data->ip = perf_instruction_pointer(regs);
5935
5936 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
5937 int size = 1;
5938
5939 data->callchain = perf_callchain(event, regs);
5940
5941 if (data->callchain)
5942 size += data->callchain->nr;
5943
5944 header->size += size * sizeof(u64);
5945 }
5946
5947 if (sample_type & PERF_SAMPLE_RAW) {
5948 struct perf_raw_record *raw = data->raw;
5949 int size;
5950
5951 if (raw) {
5952 struct perf_raw_frag *frag = &raw->frag;
5953 u32 sum = 0;
5954
5955 do {
5956 sum += frag->size;
5957 if (perf_raw_frag_last(frag))
5958 break;
5959 frag = frag->next;
5960 } while (1);
5961
5962 size = round_up(sum + sizeof(u32), sizeof(u64));
5963 raw->size = size - sizeof(u32);
5964 frag->pad = raw->size - sum;
5965 } else {
5966 size = sizeof(u64);
5967 }
5968
5969 header->size += size;
5970 }
5971
5972 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
5973 int size = sizeof(u64); /* nr */
5974 if (data->br_stack) {
5975 size += data->br_stack->nr
5976 * sizeof(struct perf_branch_entry);
5977 }
5978 header->size += size;
5979 }
5980
5981 if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
5982 perf_sample_regs_user(&data->regs_user, regs,
5983 &data->regs_user_copy);
5984
5985 if (sample_type & PERF_SAMPLE_REGS_USER) {
5986 /* regs dump ABI info */
5987 int size = sizeof(u64);
5988
5989 if (data->regs_user.regs) {
5990 u64 mask = event->attr.sample_regs_user;
5991 size += hweight64(mask) * sizeof(u64);
5992 }
5993
5994 header->size += size;
5995 }
5996
5997 if (sample_type & PERF_SAMPLE_STACK_USER) {
5998 /*
5999 * Either we need PERF_SAMPLE_STACK_USER bit to be allways
6000 * processed as the last one or have additional check added
6001 * in case new sample type is added, because we could eat
6002 * up the rest of the sample size.
6003 */
6004 u16 stack_size = event->attr.sample_stack_user;
6005 u16 size = sizeof(u64);
6006
6007 stack_size = perf_sample_ustack_size(stack_size, header->size,
6008 data->regs_user.regs);
6009
6010 /*
6011 * If there is something to dump, add space for the dump
6012 * itself and for the field that tells the dynamic size,
6013 * which is how many have been actually dumped.
6014 */
6015 if (stack_size)
6016 size += sizeof(u64) + stack_size;
6017
6018 data->stack_user_size = stack_size;
6019 header->size += size;
6020 }
6021
6022 if (sample_type & PERF_SAMPLE_REGS_INTR) {
6023 /* regs dump ABI info */
6024 int size = sizeof(u64);
6025
6026 perf_sample_regs_intr(&data->regs_intr, regs);
6027
6028 if (data->regs_intr.regs) {
6029 u64 mask = event->attr.sample_regs_intr;
6030
6031 size += hweight64(mask) * sizeof(u64);
6032 }
6033
6034 header->size += size;
6035 }
6036 }
6037
6038 static void __always_inline
6039 __perf_event_output(struct perf_event *event,
6040 struct perf_sample_data *data,
6041 struct pt_regs *regs,
6042 int (*output_begin)(struct perf_output_handle *,
6043 struct perf_event *,
6044 unsigned int))
6045 {
6046 struct perf_output_handle handle;
6047 struct perf_event_header header;
6048
6049 /* protect the callchain buffers */
6050 rcu_read_lock();
6051
6052 perf_prepare_sample(&header, data, event, regs);
6053
6054 if (output_begin(&handle, event, header.size))
6055 goto exit;
6056
6057 perf_output_sample(&handle, &header, data, event);
6058
6059 perf_output_end(&handle);
6060
6061 exit:
6062 rcu_read_unlock();
6063 }
6064
6065 void
6066 perf_event_output_forward(struct perf_event *event,
6067 struct perf_sample_data *data,
6068 struct pt_regs *regs)
6069 {
6070 __perf_event_output(event, data, regs, perf_output_begin_forward);
6071 }
6072
6073 void
6074 perf_event_output_backward(struct perf_event *event,
6075 struct perf_sample_data *data,
6076 struct pt_regs *regs)
6077 {
6078 __perf_event_output(event, data, regs, perf_output_begin_backward);
6079 }
6080
6081 void
6082 perf_event_output(struct perf_event *event,
6083 struct perf_sample_data *data,
6084 struct pt_regs *regs)
6085 {
6086 __perf_event_output(event, data, regs, perf_output_begin);
6087 }
6088
6089 /*
6090 * read event_id
6091 */
6092
6093 struct perf_read_event {
6094 struct perf_event_header header;
6095
6096 u32 pid;
6097 u32 tid;
6098 };
6099
6100 static void
6101 perf_event_read_event(struct perf_event *event,
6102 struct task_struct *task)
6103 {
6104 struct perf_output_handle handle;
6105 struct perf_sample_data sample;
6106 struct perf_read_event read_event = {
6107 .header = {
6108 .type = PERF_RECORD_READ,
6109 .misc = 0,
6110 .size = sizeof(read_event) + event->read_size,
6111 },
6112 .pid = perf_event_pid(event, task),
6113 .tid = perf_event_tid(event, task),
6114 };
6115 int ret;
6116
6117 perf_event_header__init_id(&read_event.header, &sample, event);
6118 ret = perf_output_begin(&handle, event, read_event.header.size);
6119 if (ret)
6120 return;
6121
6122 perf_output_put(&handle, read_event);
6123 perf_output_read(&handle, event);
6124 perf_event__output_id_sample(event, &handle, &sample);
6125
6126 perf_output_end(&handle);
6127 }
6128
6129 typedef void (perf_iterate_f)(struct perf_event *event, void *data);
6130
6131 static void
6132 perf_iterate_ctx(struct perf_event_context *ctx,
6133 perf_iterate_f output,
6134 void *data, bool all)
6135 {
6136 struct perf_event *event;
6137
6138 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
6139 if (!all) {
6140 if (event->state < PERF_EVENT_STATE_INACTIVE)
6141 continue;
6142 if (!event_filter_match(event))
6143 continue;
6144 }
6145
6146 output(event, data);
6147 }
6148 }
6149
6150 static void perf_iterate_sb_cpu(perf_iterate_f output, void *data)
6151 {
6152 struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events);
6153 struct perf_event *event;
6154
6155 list_for_each_entry_rcu(event, &pel->list, sb_list) {
6156 /*
6157 * Skip events that are not fully formed yet; ensure that
6158 * if we observe event->ctx, both event and ctx will be
6159 * complete enough. See perf_install_in_context().
6160 */
6161 if (!smp_load_acquire(&event->ctx))
6162 continue;
6163
6164 if (event->state < PERF_EVENT_STATE_INACTIVE)
6165 continue;
6166 if (!event_filter_match(event))
6167 continue;
6168 output(event, data);
6169 }
6170 }
6171
6172 /*
6173 * Iterate all events that need to receive side-band events.
6174 *
6175 * For new callers; ensure that account_pmu_sb_event() includes
6176 * your event, otherwise it might not get delivered.
6177 */
6178 static void
6179 perf_iterate_sb(perf_iterate_f output, void *data,
6180 struct perf_event_context *task_ctx)
6181 {
6182 struct perf_event_context *ctx;
6183 int ctxn;
6184
6185 rcu_read_lock();
6186 preempt_disable();
6187
6188 /*
6189 * If we have task_ctx != NULL we only notify the task context itself.
6190 * The task_ctx is set only for EXIT events before releasing task
6191 * context.
6192 */
6193 if (task_ctx) {
6194 perf_iterate_ctx(task_ctx, output, data, false);
6195 goto done;
6196 }
6197
6198 perf_iterate_sb_cpu(output, data);
6199
6200 for_each_task_context_nr(ctxn) {
6201 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
6202 if (ctx)
6203 perf_iterate_ctx(ctx, output, data, false);
6204 }
6205 done:
6206 preempt_enable();
6207 rcu_read_unlock();
6208 }
6209
6210 /*
6211 * Clear all file-based filters at exec, they'll have to be
6212 * re-instated when/if these objects are mmapped again.
6213 */
6214 static void perf_event_addr_filters_exec(struct perf_event *event, void *data)
6215 {
6216 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
6217 struct perf_addr_filter *filter;
6218 unsigned int restart = 0, count = 0;
6219 unsigned long flags;
6220
6221 if (!has_addr_filter(event))
6222 return;
6223
6224 raw_spin_lock_irqsave(&ifh->lock, flags);
6225 list_for_each_entry(filter, &ifh->list, entry) {
6226 if (filter->inode) {
6227 event->addr_filters_offs[count] = 0;
6228 restart++;
6229 }
6230
6231 count++;
6232 }
6233
6234 if (restart)
6235 event->addr_filters_gen++;
6236 raw_spin_unlock_irqrestore(&ifh->lock, flags);
6237
6238 if (restart)
6239 perf_event_stop(event, 1);
6240 }
6241
6242 void perf_event_exec(void)
6243 {
6244 struct perf_event_context *ctx;
6245 int ctxn;
6246
6247 rcu_read_lock();
6248 for_each_task_context_nr(ctxn) {
6249 ctx = current->perf_event_ctxp[ctxn];
6250 if (!ctx)
6251 continue;
6252
6253 perf_event_enable_on_exec(ctxn);
6254
6255 perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL,
6256 true);
6257 }
6258 rcu_read_unlock();
6259 }
6260
6261 struct remote_output {
6262 struct ring_buffer *rb;
6263 int err;
6264 };
6265
6266 static void __perf_event_output_stop(struct perf_event *event, void *data)
6267 {
6268 struct perf_event *parent = event->parent;
6269 struct remote_output *ro = data;
6270 struct ring_buffer *rb = ro->rb;
6271 struct stop_event_data sd = {
6272 .event = event,
6273 };
6274
6275 if (!has_aux(event))
6276 return;
6277
6278 if (!parent)
6279 parent = event;
6280
6281 /*
6282 * In case of inheritance, it will be the parent that links to the
6283 * ring-buffer, but it will be the child that's actually using it.
6284 *
6285 * We are using event::rb to determine if the event should be stopped,
6286 * however this may race with ring_buffer_attach() (through set_output),
6287 * which will make us skip the event that actually needs to be stopped.
6288 * So ring_buffer_attach() has to stop an aux event before re-assigning
6289 * its rb pointer.
6290 */
6291 if (rcu_dereference(parent->rb) == rb)
6292 ro->err = __perf_event_stop(&sd);
6293 }
6294
6295 static int __perf_pmu_output_stop(void *info)
6296 {
6297 struct perf_event *event = info;
6298 struct pmu *pmu = event->pmu;
6299 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
6300 struct remote_output ro = {
6301 .rb = event->rb,
6302 };
6303
6304 rcu_read_lock();
6305 perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false);
6306 if (cpuctx->task_ctx)
6307 perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop,
6308 &ro, false);
6309 rcu_read_unlock();
6310
6311 return ro.err;
6312 }
6313
6314 static void perf_pmu_output_stop(struct perf_event *event)
6315 {
6316 struct perf_event *iter;
6317 int err, cpu;
6318
6319 restart:
6320 rcu_read_lock();
6321 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
6322 /*
6323 * For per-CPU events, we need to make sure that neither they
6324 * nor their children are running; for cpu==-1 events it's
6325 * sufficient to stop the event itself if it's active, since
6326 * it can't have children.
6327 */
6328 cpu = iter->cpu;
6329 if (cpu == -1)
6330 cpu = READ_ONCE(iter->oncpu);
6331
6332 if (cpu == -1)
6333 continue;
6334
6335 err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
6336 if (err == -EAGAIN) {
6337 rcu_read_unlock();
6338 goto restart;
6339 }
6340 }
6341 rcu_read_unlock();
6342 }
6343
6344 /*
6345 * task tracking -- fork/exit
6346 *
6347 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
6348 */
6349
6350 struct perf_task_event {
6351 struct task_struct *task;
6352 struct perf_event_context *task_ctx;
6353
6354 struct {
6355 struct perf_event_header header;
6356
6357 u32 pid;
6358 u32 ppid;
6359 u32 tid;
6360 u32 ptid;
6361 u64 time;
6362 } event_id;
6363 };
6364
6365 static int perf_event_task_match(struct perf_event *event)
6366 {
6367 return event->attr.comm || event->attr.mmap ||
6368 event->attr.mmap2 || event->attr.mmap_data ||
6369 event->attr.task;
6370 }
6371
6372 static void perf_event_task_output(struct perf_event *event,
6373 void *data)
6374 {
6375 struct perf_task_event *task_event = data;
6376 struct perf_output_handle handle;
6377 struct perf_sample_data sample;
6378 struct task_struct *task = task_event->task;
6379 int ret, size = task_event->event_id.header.size;
6380
6381 if (!perf_event_task_match(event))
6382 return;
6383
6384 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
6385
6386 ret = perf_output_begin(&handle, event,
6387 task_event->event_id.header.size);
6388 if (ret)
6389 goto out;
6390
6391 task_event->event_id.pid = perf_event_pid(event, task);
6392 task_event->event_id.ppid = perf_event_pid(event, current);
6393
6394 task_event->event_id.tid = perf_event_tid(event, task);
6395 task_event->event_id.ptid = perf_event_tid(event, current);
6396
6397 task_event->event_id.time = perf_event_clock(event);
6398
6399 perf_output_put(&handle, task_event->event_id);
6400
6401 perf_event__output_id_sample(event, &handle, &sample);
6402
6403 perf_output_end(&handle);
6404 out:
6405 task_event->event_id.header.size = size;
6406 }
6407
6408 static void perf_event_task(struct task_struct *task,
6409 struct perf_event_context *task_ctx,
6410 int new)
6411 {
6412 struct perf_task_event task_event;
6413
6414 if (!atomic_read(&nr_comm_events) &&
6415 !atomic_read(&nr_mmap_events) &&
6416 !atomic_read(&nr_task_events))
6417 return;
6418
6419 task_event = (struct perf_task_event){
6420 .task = task,
6421 .task_ctx = task_ctx,
6422 .event_id = {
6423 .header = {
6424 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
6425 .misc = 0,
6426 .size = sizeof(task_event.event_id),
6427 },
6428 /* .pid */
6429 /* .ppid */
6430 /* .tid */
6431 /* .ptid */
6432 /* .time */
6433 },
6434 };
6435
6436 perf_iterate_sb(perf_event_task_output,
6437 &task_event,
6438 task_ctx);
6439 }
6440
6441 void perf_event_fork(struct task_struct *task)
6442 {
6443 perf_event_task(task, NULL, 1);
6444 }
6445
6446 /*
6447 * comm tracking
6448 */
6449
6450 struct perf_comm_event {
6451 struct task_struct *task;
6452 char *comm;
6453 int comm_size;
6454
6455 struct {
6456 struct perf_event_header header;
6457
6458 u32 pid;
6459 u32 tid;
6460 } event_id;
6461 };
6462
6463 static int perf_event_comm_match(struct perf_event *event)
6464 {
6465 return event->attr.comm;
6466 }
6467
6468 static void perf_event_comm_output(struct perf_event *event,
6469 void *data)
6470 {
6471 struct perf_comm_event *comm_event = data;
6472 struct perf_output_handle handle;
6473 struct perf_sample_data sample;
6474 int size = comm_event->event_id.header.size;
6475 int ret;
6476
6477 if (!perf_event_comm_match(event))
6478 return;
6479
6480 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
6481 ret = perf_output_begin(&handle, event,
6482 comm_event->event_id.header.size);
6483
6484 if (ret)
6485 goto out;
6486
6487 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
6488 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
6489
6490 perf_output_put(&handle, comm_event->event_id);
6491 __output_copy(&handle, comm_event->comm,
6492 comm_event->comm_size);
6493
6494 perf_event__output_id_sample(event, &handle, &sample);
6495
6496 perf_output_end(&handle);
6497 out:
6498 comm_event->event_id.header.size = size;
6499 }
6500
6501 static void perf_event_comm_event(struct perf_comm_event *comm_event)
6502 {
6503 char comm[TASK_COMM_LEN];
6504 unsigned int size;
6505
6506 memset(comm, 0, sizeof(comm));
6507 strlcpy(comm, comm_event->task->comm, sizeof(comm));
6508 size = ALIGN(strlen(comm)+1, sizeof(u64));
6509
6510 comm_event->comm = comm;
6511 comm_event->comm_size = size;
6512
6513 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
6514
6515 perf_iterate_sb(perf_event_comm_output,
6516 comm_event,
6517 NULL);
6518 }
6519
6520 void perf_event_comm(struct task_struct *task, bool exec)
6521 {
6522 struct perf_comm_event comm_event;
6523
6524 if (!atomic_read(&nr_comm_events))
6525 return;
6526
6527 comm_event = (struct perf_comm_event){
6528 .task = task,
6529 /* .comm */
6530 /* .comm_size */
6531 .event_id = {
6532 .header = {
6533 .type = PERF_RECORD_COMM,
6534 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
6535 /* .size */
6536 },
6537 /* .pid */
6538 /* .tid */
6539 },
6540 };
6541
6542 perf_event_comm_event(&comm_event);
6543 }
6544
6545 /*
6546 * mmap tracking
6547 */
6548
6549 struct perf_mmap_event {
6550 struct vm_area_struct *vma;
6551
6552 const char *file_name;
6553 int file_size;
6554 int maj, min;
6555 u64 ino;
6556 u64 ino_generation;
6557 u32 prot, flags;
6558
6559 struct {
6560 struct perf_event_header header;
6561
6562 u32 pid;
6563 u32 tid;
6564 u64 start;
6565 u64 len;
6566 u64 pgoff;
6567 } event_id;
6568 };
6569
6570 static int perf_event_mmap_match(struct perf_event *event,
6571 void *data)
6572 {
6573 struct perf_mmap_event *mmap_event = data;
6574 struct vm_area_struct *vma = mmap_event->vma;
6575 int executable = vma->vm_flags & VM_EXEC;
6576
6577 return (!executable && event->attr.mmap_data) ||
6578 (executable && (event->attr.mmap || event->attr.mmap2));
6579 }
6580
6581 static void perf_event_mmap_output(struct perf_event *event,
6582 void *data)
6583 {
6584 struct perf_mmap_event *mmap_event = data;
6585 struct perf_output_handle handle;
6586 struct perf_sample_data sample;
6587 int size = mmap_event->event_id.header.size;
6588 int ret;
6589
6590 if (!perf_event_mmap_match(event, data))
6591 return;
6592
6593 if (event->attr.mmap2) {
6594 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
6595 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
6596 mmap_event->event_id.header.size += sizeof(mmap_event->min);
6597 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
6598 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
6599 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
6600 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
6601 }
6602
6603 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
6604 ret = perf_output_begin(&handle, event,
6605 mmap_event->event_id.header.size);
6606 if (ret)
6607 goto out;
6608
6609 mmap_event->event_id.pid = perf_event_pid(event, current);
6610 mmap_event->event_id.tid = perf_event_tid(event, current);
6611
6612 perf_output_put(&handle, mmap_event->event_id);
6613
6614 if (event->attr.mmap2) {
6615 perf_output_put(&handle, mmap_event->maj);
6616 perf_output_put(&handle, mmap_event->min);
6617 perf_output_put(&handle, mmap_event->ino);
6618 perf_output_put(&handle, mmap_event->ino_generation);
6619 perf_output_put(&handle, mmap_event->prot);
6620 perf_output_put(&handle, mmap_event->flags);
6621 }
6622
6623 __output_copy(&handle, mmap_event->file_name,
6624 mmap_event->file_size);
6625
6626 perf_event__output_id_sample(event, &handle, &sample);
6627
6628 perf_output_end(&handle);
6629 out:
6630 mmap_event->event_id.header.size = size;
6631 }
6632
6633 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
6634 {
6635 struct vm_area_struct *vma = mmap_event->vma;
6636 struct file *file = vma->vm_file;
6637 int maj = 0, min = 0;
6638 u64 ino = 0, gen = 0;
6639 u32 prot = 0, flags = 0;
6640 unsigned int size;
6641 char tmp[16];
6642 char *buf = NULL;
6643 char *name;
6644
6645 if (vma->vm_flags & VM_READ)
6646 prot |= PROT_READ;
6647 if (vma->vm_flags & VM_WRITE)
6648 prot |= PROT_WRITE;
6649 if (vma->vm_flags & VM_EXEC)
6650 prot |= PROT_EXEC;
6651
6652 if (vma->vm_flags & VM_MAYSHARE)
6653 flags = MAP_SHARED;
6654 else
6655 flags = MAP_PRIVATE;
6656
6657 if (vma->vm_flags & VM_DENYWRITE)
6658 flags |= MAP_DENYWRITE;
6659 if (vma->vm_flags & VM_MAYEXEC)
6660 flags |= MAP_EXECUTABLE;
6661 if (vma->vm_flags & VM_LOCKED)
6662 flags |= MAP_LOCKED;
6663 if (vma->vm_flags & VM_HUGETLB)
6664 flags |= MAP_HUGETLB;
6665
6666 if (file) {
6667 struct inode *inode;
6668 dev_t dev;
6669
6670 buf = kmalloc(PATH_MAX, GFP_KERNEL);
6671 if (!buf) {
6672 name = "//enomem";
6673 goto cpy_name;
6674 }
6675 /*
6676 * d_path() works from the end of the rb backwards, so we
6677 * need to add enough zero bytes after the string to handle
6678 * the 64bit alignment we do later.
6679 */
6680 name = file_path(file, buf, PATH_MAX - sizeof(u64));
6681 if (IS_ERR(name)) {
6682 name = "//toolong";
6683 goto cpy_name;
6684 }
6685 inode = file_inode(vma->vm_file);
6686 dev = inode->i_sb->s_dev;
6687 ino = inode->i_ino;
6688 gen = inode->i_generation;
6689 maj = MAJOR(dev);
6690 min = MINOR(dev);
6691
6692 goto got_name;
6693 } else {
6694 if (vma->vm_ops && vma->vm_ops->name) {
6695 name = (char *) vma->vm_ops->name(vma);
6696 if (name)
6697 goto cpy_name;
6698 }
6699
6700 name = (char *)arch_vma_name(vma);
6701 if (name)
6702 goto cpy_name;
6703
6704 if (vma->vm_start <= vma->vm_mm->start_brk &&
6705 vma->vm_end >= vma->vm_mm->brk) {
6706 name = "[heap]";
6707 goto cpy_name;
6708 }
6709 if (vma->vm_start <= vma->vm_mm->start_stack &&
6710 vma->vm_end >= vma->vm_mm->start_stack) {
6711 name = "[stack]";
6712 goto cpy_name;
6713 }
6714
6715 name = "//anon";
6716 goto cpy_name;
6717 }
6718
6719 cpy_name:
6720 strlcpy(tmp, name, sizeof(tmp));
6721 name = tmp;
6722 got_name:
6723 /*
6724 * Since our buffer works in 8 byte units we need to align our string
6725 * size to a multiple of 8. However, we must guarantee the tail end is
6726 * zero'd out to avoid leaking random bits to userspace.
6727 */
6728 size = strlen(name)+1;
6729 while (!IS_ALIGNED(size, sizeof(u64)))
6730 name[size++] = '\0';
6731
6732 mmap_event->file_name = name;
6733 mmap_event->file_size = size;
6734 mmap_event->maj = maj;
6735 mmap_event->min = min;
6736 mmap_event->ino = ino;
6737 mmap_event->ino_generation = gen;
6738 mmap_event->prot = prot;
6739 mmap_event->flags = flags;
6740
6741 if (!(vma->vm_flags & VM_EXEC))
6742 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
6743
6744 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
6745
6746 perf_iterate_sb(perf_event_mmap_output,
6747 mmap_event,
6748 NULL);
6749
6750 kfree(buf);
6751 }
6752
6753 /*
6754 * Check whether inode and address range match filter criteria.
6755 */
6756 static bool perf_addr_filter_match(struct perf_addr_filter *filter,
6757 struct file *file, unsigned long offset,
6758 unsigned long size)
6759 {
6760 if (filter->inode != file_inode(file))
6761 return false;
6762
6763 if (filter->offset > offset + size)
6764 return false;
6765
6766 if (filter->offset + filter->size < offset)
6767 return false;
6768
6769 return true;
6770 }
6771
6772 static void __perf_addr_filters_adjust(struct perf_event *event, void *data)
6773 {
6774 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
6775 struct vm_area_struct *vma = data;
6776 unsigned long off = vma->vm_pgoff << PAGE_SHIFT, flags;
6777 struct file *file = vma->vm_file;
6778 struct perf_addr_filter *filter;
6779 unsigned int restart = 0, count = 0;
6780
6781 if (!has_addr_filter(event))
6782 return;
6783
6784 if (!file)
6785 return;
6786
6787 raw_spin_lock_irqsave(&ifh->lock, flags);
6788 list_for_each_entry(filter, &ifh->list, entry) {
6789 if (perf_addr_filter_match(filter, file, off,
6790 vma->vm_end - vma->vm_start)) {
6791 event->addr_filters_offs[count] = vma->vm_start;
6792 restart++;
6793 }
6794
6795 count++;
6796 }
6797
6798 if (restart)
6799 event->addr_filters_gen++;
6800 raw_spin_unlock_irqrestore(&ifh->lock, flags);
6801
6802 if (restart)
6803 perf_event_stop(event, 1);
6804 }
6805
6806 /*
6807 * Adjust all task's events' filters to the new vma
6808 */
6809 static void perf_addr_filters_adjust(struct vm_area_struct *vma)
6810 {
6811 struct perf_event_context *ctx;
6812 int ctxn;
6813
6814 /*
6815 * Data tracing isn't supported yet and as such there is no need
6816 * to keep track of anything that isn't related to executable code:
6817 */
6818 if (!(vma->vm_flags & VM_EXEC))
6819 return;
6820
6821 rcu_read_lock();
6822 for_each_task_context_nr(ctxn) {
6823 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
6824 if (!ctx)
6825 continue;
6826
6827 perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true);
6828 }
6829 rcu_read_unlock();
6830 }
6831
6832 void perf_event_mmap(struct vm_area_struct *vma)
6833 {
6834 struct perf_mmap_event mmap_event;
6835
6836 if (!atomic_read(&nr_mmap_events))
6837 return;
6838
6839 mmap_event = (struct perf_mmap_event){
6840 .vma = vma,
6841 /* .file_name */
6842 /* .file_size */
6843 .event_id = {
6844 .header = {
6845 .type = PERF_RECORD_MMAP,
6846 .misc = PERF_RECORD_MISC_USER,
6847 /* .size */
6848 },
6849 /* .pid */
6850 /* .tid */
6851 .start = vma->vm_start,
6852 .len = vma->vm_end - vma->vm_start,
6853 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
6854 },
6855 /* .maj (attr_mmap2 only) */
6856 /* .min (attr_mmap2 only) */
6857 /* .ino (attr_mmap2 only) */
6858 /* .ino_generation (attr_mmap2 only) */
6859 /* .prot (attr_mmap2 only) */
6860 /* .flags (attr_mmap2 only) */
6861 };
6862
6863 perf_addr_filters_adjust(vma);
6864 perf_event_mmap_event(&mmap_event);
6865 }
6866
6867 void perf_event_aux_event(struct perf_event *event, unsigned long head,
6868 unsigned long size, u64 flags)
6869 {
6870 struct perf_output_handle handle;
6871 struct perf_sample_data sample;
6872 struct perf_aux_event {
6873 struct perf_event_header header;
6874 u64 offset;
6875 u64 size;
6876 u64 flags;
6877 } rec = {
6878 .header = {
6879 .type = PERF_RECORD_AUX,
6880 .misc = 0,
6881 .size = sizeof(rec),
6882 },
6883 .offset = head,
6884 .size = size,
6885 .flags = flags,
6886 };
6887 int ret;
6888
6889 perf_event_header__init_id(&rec.header, &sample, event);
6890 ret = perf_output_begin(&handle, event, rec.header.size);
6891
6892 if (ret)
6893 return;
6894
6895 perf_output_put(&handle, rec);
6896 perf_event__output_id_sample(event, &handle, &sample);
6897
6898 perf_output_end(&handle);
6899 }
6900
6901 /*
6902 * Lost/dropped samples logging
6903 */
6904 void perf_log_lost_samples(struct perf_event *event, u64 lost)
6905 {
6906 struct perf_output_handle handle;
6907 struct perf_sample_data sample;
6908 int ret;
6909
6910 struct {
6911 struct perf_event_header header;
6912 u64 lost;
6913 } lost_samples_event = {
6914 .header = {
6915 .type = PERF_RECORD_LOST_SAMPLES,
6916 .misc = 0,
6917 .size = sizeof(lost_samples_event),
6918 },
6919 .lost = lost,
6920 };
6921
6922 perf_event_header__init_id(&lost_samples_event.header, &sample, event);
6923
6924 ret = perf_output_begin(&handle, event,
6925 lost_samples_event.header.size);
6926 if (ret)
6927 return;
6928
6929 perf_output_put(&handle, lost_samples_event);
6930 perf_event__output_id_sample(event, &handle, &sample);
6931 perf_output_end(&handle);
6932 }
6933
6934 /*
6935 * context_switch tracking
6936 */
6937
6938 struct perf_switch_event {
6939 struct task_struct *task;
6940 struct task_struct *next_prev;
6941
6942 struct {
6943 struct perf_event_header header;
6944 u32 next_prev_pid;
6945 u32 next_prev_tid;
6946 } event_id;
6947 };
6948
6949 static int perf_event_switch_match(struct perf_event *event)
6950 {
6951 return event->attr.context_switch;
6952 }
6953
6954 static void perf_event_switch_output(struct perf_event *event, void *data)
6955 {
6956 struct perf_switch_event *se = data;
6957 struct perf_output_handle handle;
6958 struct perf_sample_data sample;
6959 int ret;
6960
6961 if (!perf_event_switch_match(event))
6962 return;
6963
6964 /* Only CPU-wide events are allowed to see next/prev pid/tid */
6965 if (event->ctx->task) {
6966 se->event_id.header.type = PERF_RECORD_SWITCH;
6967 se->event_id.header.size = sizeof(se->event_id.header);
6968 } else {
6969 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
6970 se->event_id.header.size = sizeof(se->event_id);
6971 se->event_id.next_prev_pid =
6972 perf_event_pid(event, se->next_prev);
6973 se->event_id.next_prev_tid =
6974 perf_event_tid(event, se->next_prev);
6975 }
6976
6977 perf_event_header__init_id(&se->event_id.header, &sample, event);
6978
6979 ret = perf_output_begin(&handle, event, se->event_id.header.size);
6980 if (ret)
6981 return;
6982
6983 if (event->ctx->task)
6984 perf_output_put(&handle, se->event_id.header);
6985 else
6986 perf_output_put(&handle, se->event_id);
6987
6988 perf_event__output_id_sample(event, &handle, &sample);
6989
6990 perf_output_end(&handle);
6991 }
6992
6993 static void perf_event_switch(struct task_struct *task,
6994 struct task_struct *next_prev, bool sched_in)
6995 {
6996 struct perf_switch_event switch_event;
6997
6998 /* N.B. caller checks nr_switch_events != 0 */
6999
7000 switch_event = (struct perf_switch_event){
7001 .task = task,
7002 .next_prev = next_prev,
7003 .event_id = {
7004 .header = {
7005 /* .type */
7006 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
7007 /* .size */
7008 },
7009 /* .next_prev_pid */
7010 /* .next_prev_tid */
7011 },
7012 };
7013
7014 perf_iterate_sb(perf_event_switch_output,
7015 &switch_event,
7016 NULL);
7017 }
7018
7019 /*
7020 * IRQ throttle logging
7021 */
7022
7023 static void perf_log_throttle(struct perf_event *event, int enable)
7024 {
7025 struct perf_output_handle handle;
7026 struct perf_sample_data sample;
7027 int ret;
7028
7029 struct {
7030 struct perf_event_header header;
7031 u64 time;
7032 u64 id;
7033 u64 stream_id;
7034 } throttle_event = {
7035 .header = {
7036 .type = PERF_RECORD_THROTTLE,
7037 .misc = 0,
7038 .size = sizeof(throttle_event),
7039 },
7040 .time = perf_event_clock(event),
7041 .id = primary_event_id(event),
7042 .stream_id = event->id,
7043 };
7044
7045 if (enable)
7046 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
7047
7048 perf_event_header__init_id(&throttle_event.header, &sample, event);
7049
7050 ret = perf_output_begin(&handle, event,
7051 throttle_event.header.size);
7052 if (ret)
7053 return;
7054
7055 perf_output_put(&handle, throttle_event);
7056 perf_event__output_id_sample(event, &handle, &sample);
7057 perf_output_end(&handle);
7058 }
7059
7060 static void perf_log_itrace_start(struct perf_event *event)
7061 {
7062 struct perf_output_handle handle;
7063 struct perf_sample_data sample;
7064 struct perf_aux_event {
7065 struct perf_event_header header;
7066 u32 pid;
7067 u32 tid;
7068 } rec;
7069 int ret;
7070
7071 if (event->parent)
7072 event = event->parent;
7073
7074 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
7075 event->hw.itrace_started)
7076 return;
7077
7078 rec.header.type = PERF_RECORD_ITRACE_START;
7079 rec.header.misc = 0;
7080 rec.header.size = sizeof(rec);
7081 rec.pid = perf_event_pid(event, current);
7082 rec.tid = perf_event_tid(event, current);
7083
7084 perf_event_header__init_id(&rec.header, &sample, event);
7085 ret = perf_output_begin(&handle, event, rec.header.size);
7086
7087 if (ret)
7088 return;
7089
7090 perf_output_put(&handle, rec);
7091 perf_event__output_id_sample(event, &handle, &sample);
7092
7093 perf_output_end(&handle);
7094 }
7095
7096 static int
7097 __perf_event_account_interrupt(struct perf_event *event, int throttle)
7098 {
7099 struct hw_perf_event *hwc = &event->hw;
7100 int ret = 0;
7101 u64 seq;
7102
7103 seq = __this_cpu_read(perf_throttled_seq);
7104 if (seq != hwc->interrupts_seq) {
7105 hwc->interrupts_seq = seq;
7106 hwc->interrupts = 1;
7107 } else {
7108 hwc->interrupts++;
7109 if (unlikely(throttle
7110 && hwc->interrupts >= max_samples_per_tick)) {
7111 __this_cpu_inc(perf_throttled_count);
7112 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
7113 hwc->interrupts = MAX_INTERRUPTS;
7114 perf_log_throttle(event, 0);
7115 ret = 1;
7116 }
7117 }
7118
7119 if (event->attr.freq) {
7120 u64 now = perf_clock();
7121 s64 delta = now - hwc->freq_time_stamp;
7122
7123 hwc->freq_time_stamp = now;
7124
7125 if (delta > 0 && delta < 2*TICK_NSEC)
7126 perf_adjust_period(event, delta, hwc->last_period, true);
7127 }
7128
7129 return ret;
7130 }
7131
7132 int perf_event_account_interrupt(struct perf_event *event)
7133 {
7134 return __perf_event_account_interrupt(event, 1);
7135 }
7136
7137 /*
7138 * Generic event overflow handling, sampling.
7139 */
7140
7141 static int __perf_event_overflow(struct perf_event *event,
7142 int throttle, struct perf_sample_data *data,
7143 struct pt_regs *regs)
7144 {
7145 int events = atomic_read(&event->event_limit);
7146 int ret = 0;
7147
7148 /*
7149 * Non-sampling counters might still use the PMI to fold short
7150 * hardware counters, ignore those.
7151 */
7152 if (unlikely(!is_sampling_event(event)))
7153 return 0;
7154
7155 ret = __perf_event_account_interrupt(event, throttle);
7156
7157 /*
7158 * XXX event_limit might not quite work as expected on inherited
7159 * events
7160 */
7161
7162 event->pending_kill = POLL_IN;
7163 if (events && atomic_dec_and_test(&event->event_limit)) {
7164 ret = 1;
7165 event->pending_kill = POLL_HUP;
7166
7167 perf_event_disable_inatomic(event);
7168 }
7169
7170 READ_ONCE(event->overflow_handler)(event, data, regs);
7171
7172 if (*perf_event_fasync(event) && event->pending_kill) {
7173 event->pending_wakeup = 1;
7174 irq_work_queue(&event->pending);
7175 }
7176
7177 return ret;
7178 }
7179
7180 int perf_event_overflow(struct perf_event *event,
7181 struct perf_sample_data *data,
7182 struct pt_regs *regs)
7183 {
7184 return __perf_event_overflow(event, 1, data, regs);
7185 }
7186
7187 /*
7188 * Generic software event infrastructure
7189 */
7190
7191 struct swevent_htable {
7192 struct swevent_hlist *swevent_hlist;
7193 struct mutex hlist_mutex;
7194 int hlist_refcount;
7195
7196 /* Recursion avoidance in each contexts */
7197 int recursion[PERF_NR_CONTEXTS];
7198 };
7199
7200 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
7201
7202 /*
7203 * We directly increment event->count and keep a second value in
7204 * event->hw.period_left to count intervals. This period event
7205 * is kept in the range [-sample_period, 0] so that we can use the
7206 * sign as trigger.
7207 */
7208
7209 u64 perf_swevent_set_period(struct perf_event *event)
7210 {
7211 struct hw_perf_event *hwc = &event->hw;
7212 u64 period = hwc->last_period;
7213 u64 nr, offset;
7214 s64 old, val;
7215
7216 hwc->last_period = hwc->sample_period;
7217
7218 again:
7219 old = val = local64_read(&hwc->period_left);
7220 if (val < 0)
7221 return 0;
7222
7223 nr = div64_u64(period + val, period);
7224 offset = nr * period;
7225 val -= offset;
7226 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
7227 goto again;
7228
7229 return nr;
7230 }
7231
7232 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
7233 struct perf_sample_data *data,
7234 struct pt_regs *regs)
7235 {
7236 struct hw_perf_event *hwc = &event->hw;
7237 int throttle = 0;
7238
7239 if (!overflow)
7240 overflow = perf_swevent_set_period(event);
7241
7242 if (hwc->interrupts == MAX_INTERRUPTS)
7243 return;
7244
7245 for (; overflow; overflow--) {
7246 if (__perf_event_overflow(event, throttle,
7247 data, regs)) {
7248 /*
7249 * We inhibit the overflow from happening when
7250 * hwc->interrupts == MAX_INTERRUPTS.
7251 */
7252 break;
7253 }
7254 throttle = 1;
7255 }
7256 }
7257
7258 static void perf_swevent_event(struct perf_event *event, u64 nr,
7259 struct perf_sample_data *data,
7260 struct pt_regs *regs)
7261 {
7262 struct hw_perf_event *hwc = &event->hw;
7263
7264 local64_add(nr, &event->count);
7265
7266 if (!regs)
7267 return;
7268
7269 if (!is_sampling_event(event))
7270 return;
7271
7272 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
7273 data->period = nr;
7274 return perf_swevent_overflow(event, 1, data, regs);
7275 } else
7276 data->period = event->hw.last_period;
7277
7278 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
7279 return perf_swevent_overflow(event, 1, data, regs);
7280
7281 if (local64_add_negative(nr, &hwc->period_left))
7282 return;
7283
7284 perf_swevent_overflow(event, 0, data, regs);
7285 }
7286
7287 static int perf_exclude_event(struct perf_event *event,
7288 struct pt_regs *regs)
7289 {
7290 if (event->hw.state & PERF_HES_STOPPED)
7291 return 1;
7292
7293 if (regs) {
7294 if (event->attr.exclude_user && user_mode(regs))
7295 return 1;
7296
7297 if (event->attr.exclude_kernel && !user_mode(regs))
7298 return 1;
7299 }
7300
7301 return 0;
7302 }
7303
7304 static int perf_swevent_match(struct perf_event *event,
7305 enum perf_type_id type,
7306 u32 event_id,
7307 struct perf_sample_data *data,
7308 struct pt_regs *regs)
7309 {
7310 if (event->attr.type != type)
7311 return 0;
7312
7313 if (event->attr.config != event_id)
7314 return 0;
7315
7316 if (perf_exclude_event(event, regs))
7317 return 0;
7318
7319 return 1;
7320 }
7321
7322 static inline u64 swevent_hash(u64 type, u32 event_id)
7323 {
7324 u64 val = event_id | (type << 32);
7325
7326 return hash_64(val, SWEVENT_HLIST_BITS);
7327 }
7328
7329 static inline struct hlist_head *
7330 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
7331 {
7332 u64 hash = swevent_hash(type, event_id);
7333
7334 return &hlist->heads[hash];
7335 }
7336
7337 /* For the read side: events when they trigger */
7338 static inline struct hlist_head *
7339 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
7340 {
7341 struct swevent_hlist *hlist;
7342
7343 hlist = rcu_dereference(swhash->swevent_hlist);
7344 if (!hlist)
7345 return NULL;
7346
7347 return __find_swevent_head(hlist, type, event_id);
7348 }
7349
7350 /* For the event head insertion and removal in the hlist */
7351 static inline struct hlist_head *
7352 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
7353 {
7354 struct swevent_hlist *hlist;
7355 u32 event_id = event->attr.config;
7356 u64 type = event->attr.type;
7357
7358 /*
7359 * Event scheduling is always serialized against hlist allocation
7360 * and release. Which makes the protected version suitable here.
7361 * The context lock guarantees that.
7362 */
7363 hlist = rcu_dereference_protected(swhash->swevent_hlist,
7364 lockdep_is_held(&event->ctx->lock));
7365 if (!hlist)
7366 return NULL;
7367
7368 return __find_swevent_head(hlist, type, event_id);
7369 }
7370
7371 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
7372 u64 nr,
7373 struct perf_sample_data *data,
7374 struct pt_regs *regs)
7375 {
7376 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
7377 struct perf_event *event;
7378 struct hlist_head *head;
7379
7380 rcu_read_lock();
7381 head = find_swevent_head_rcu(swhash, type, event_id);
7382 if (!head)
7383 goto end;
7384
7385 hlist_for_each_entry_rcu(event, head, hlist_entry) {
7386 if (perf_swevent_match(event, type, event_id, data, regs))
7387 perf_swevent_event(event, nr, data, regs);
7388 }
7389 end:
7390 rcu_read_unlock();
7391 }
7392
7393 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
7394
7395 int perf_swevent_get_recursion_context(void)
7396 {
7397 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
7398
7399 return get_recursion_context(swhash->recursion);
7400 }
7401 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
7402
7403 void perf_swevent_put_recursion_context(int rctx)
7404 {
7405 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
7406
7407 put_recursion_context(swhash->recursion, rctx);
7408 }
7409
7410 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
7411 {
7412 struct perf_sample_data data;
7413
7414 if (WARN_ON_ONCE(!regs))
7415 return;
7416
7417 perf_sample_data_init(&data, addr, 0);
7418 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
7419 }
7420
7421 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
7422 {
7423 int rctx;
7424
7425 preempt_disable_notrace();
7426 rctx = perf_swevent_get_recursion_context();
7427 if (unlikely(rctx < 0))
7428 goto fail;
7429
7430 ___perf_sw_event(event_id, nr, regs, addr);
7431
7432 perf_swevent_put_recursion_context(rctx);
7433 fail:
7434 preempt_enable_notrace();
7435 }
7436
7437 static void perf_swevent_read(struct perf_event *event)
7438 {
7439 }
7440
7441 static int perf_swevent_add(struct perf_event *event, int flags)
7442 {
7443 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
7444 struct hw_perf_event *hwc = &event->hw;
7445 struct hlist_head *head;
7446
7447 if (is_sampling_event(event)) {
7448 hwc->last_period = hwc->sample_period;
7449 perf_swevent_set_period(event);
7450 }
7451
7452 hwc->state = !(flags & PERF_EF_START);
7453
7454 head = find_swevent_head(swhash, event);
7455 if (WARN_ON_ONCE(!head))
7456 return -EINVAL;
7457
7458 hlist_add_head_rcu(&event->hlist_entry, head);
7459 perf_event_update_userpage(event);
7460
7461 return 0;
7462 }
7463
7464 static void perf_swevent_del(struct perf_event *event, int flags)
7465 {
7466 hlist_del_rcu(&event->hlist_entry);
7467 }
7468
7469 static void perf_swevent_start(struct perf_event *event, int flags)
7470 {
7471 event->hw.state = 0;
7472 }
7473
7474 static void perf_swevent_stop(struct perf_event *event, int flags)
7475 {
7476 event->hw.state = PERF_HES_STOPPED;
7477 }
7478
7479 /* Deref the hlist from the update side */
7480 static inline struct swevent_hlist *
7481 swevent_hlist_deref(struct swevent_htable *swhash)
7482 {
7483 return rcu_dereference_protected(swhash->swevent_hlist,
7484 lockdep_is_held(&swhash->hlist_mutex));
7485 }
7486
7487 static void swevent_hlist_release(struct swevent_htable *swhash)
7488 {
7489 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
7490
7491 if (!hlist)
7492 return;
7493
7494 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
7495 kfree_rcu(hlist, rcu_head);
7496 }
7497
7498 static void swevent_hlist_put_cpu(int cpu)
7499 {
7500 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
7501
7502 mutex_lock(&swhash->hlist_mutex);
7503
7504 if (!--swhash->hlist_refcount)
7505 swevent_hlist_release(swhash);
7506
7507 mutex_unlock(&swhash->hlist_mutex);
7508 }
7509
7510 static void swevent_hlist_put(void)
7511 {
7512 int cpu;
7513
7514 for_each_possible_cpu(cpu)
7515 swevent_hlist_put_cpu(cpu);
7516 }
7517
7518 static int swevent_hlist_get_cpu(int cpu)
7519 {
7520 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
7521 int err = 0;
7522
7523 mutex_lock(&swhash->hlist_mutex);
7524 if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
7525 struct swevent_hlist *hlist;
7526
7527 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
7528 if (!hlist) {
7529 err = -ENOMEM;
7530 goto exit;
7531 }
7532 rcu_assign_pointer(swhash->swevent_hlist, hlist);
7533 }
7534 swhash->hlist_refcount++;
7535 exit:
7536 mutex_unlock(&swhash->hlist_mutex);
7537
7538 return err;
7539 }
7540
7541 static int swevent_hlist_get(void)
7542 {
7543 int err, cpu, failed_cpu;
7544
7545 get_online_cpus();
7546 for_each_possible_cpu(cpu) {
7547 err = swevent_hlist_get_cpu(cpu);
7548 if (err) {
7549 failed_cpu = cpu;
7550 goto fail;
7551 }
7552 }
7553 put_online_cpus();
7554
7555 return 0;
7556 fail:
7557 for_each_possible_cpu(cpu) {
7558 if (cpu == failed_cpu)
7559 break;
7560 swevent_hlist_put_cpu(cpu);
7561 }
7562
7563 put_online_cpus();
7564 return err;
7565 }
7566
7567 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
7568
7569 static void sw_perf_event_destroy(struct perf_event *event)
7570 {
7571 u64 event_id = event->attr.config;
7572
7573 WARN_ON(event->parent);
7574
7575 static_key_slow_dec(&perf_swevent_enabled[event_id]);
7576 swevent_hlist_put();
7577 }
7578
7579 static int perf_swevent_init(struct perf_event *event)
7580 {
7581 u64 event_id = event->attr.config;
7582
7583 if (event->attr.type != PERF_TYPE_SOFTWARE)
7584 return -ENOENT;
7585
7586 /*
7587 * no branch sampling for software events
7588 */
7589 if (has_branch_stack(event))
7590 return -EOPNOTSUPP;
7591
7592 switch (event_id) {
7593 case PERF_COUNT_SW_CPU_CLOCK:
7594 case PERF_COUNT_SW_TASK_CLOCK:
7595 return -ENOENT;
7596
7597 default:
7598 break;
7599 }
7600
7601 if (event_id >= PERF_COUNT_SW_MAX)
7602 return -ENOENT;
7603
7604 if (!event->parent) {
7605 int err;
7606
7607 err = swevent_hlist_get();
7608 if (err)
7609 return err;
7610
7611 static_key_slow_inc(&perf_swevent_enabled[event_id]);
7612 event->destroy = sw_perf_event_destroy;
7613 }
7614
7615 return 0;
7616 }
7617
7618 static struct pmu perf_swevent = {
7619 .task_ctx_nr = perf_sw_context,
7620
7621 .capabilities = PERF_PMU_CAP_NO_NMI,
7622
7623 .event_init = perf_swevent_init,
7624 .add = perf_swevent_add,
7625 .del = perf_swevent_del,
7626 .start = perf_swevent_start,
7627 .stop = perf_swevent_stop,
7628 .read = perf_swevent_read,
7629 };
7630
7631 #ifdef CONFIG_EVENT_TRACING
7632
7633 static int perf_tp_filter_match(struct perf_event *event,
7634 struct perf_sample_data *data)
7635 {
7636 void *record = data->raw->frag.data;
7637
7638 /* only top level events have filters set */
7639 if (event->parent)
7640 event = event->parent;
7641
7642 if (likely(!event->filter) || filter_match_preds(event->filter, record))
7643 return 1;
7644 return 0;
7645 }
7646
7647 static int perf_tp_event_match(struct perf_event *event,
7648 struct perf_sample_data *data,
7649 struct pt_regs *regs)
7650 {
7651 if (event->hw.state & PERF_HES_STOPPED)
7652 return 0;
7653 /*
7654 * All tracepoints are from kernel-space.
7655 */
7656 if (event->attr.exclude_kernel)
7657 return 0;
7658
7659 if (!perf_tp_filter_match(event, data))
7660 return 0;
7661
7662 return 1;
7663 }
7664
7665 void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx,
7666 struct trace_event_call *call, u64 count,
7667 struct pt_regs *regs, struct hlist_head *head,
7668 struct task_struct *task)
7669 {
7670 struct bpf_prog *prog = call->prog;
7671
7672 if (prog) {
7673 *(struct pt_regs **)raw_data = regs;
7674 if (!trace_call_bpf(prog, raw_data) || hlist_empty(head)) {
7675 perf_swevent_put_recursion_context(rctx);
7676 return;
7677 }
7678 }
7679 perf_tp_event(call->event.type, count, raw_data, size, regs, head,
7680 rctx, task);
7681 }
7682 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit);
7683
7684 void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size,
7685 struct pt_regs *regs, struct hlist_head *head, int rctx,
7686 struct task_struct *task)
7687 {
7688 struct perf_sample_data data;
7689 struct perf_event *event;
7690
7691 struct perf_raw_record raw = {
7692 .frag = {
7693 .size = entry_size,
7694 .data = record,
7695 },
7696 };
7697
7698 perf_sample_data_init(&data, 0, 0);
7699 data.raw = &raw;
7700
7701 perf_trace_buf_update(record, event_type);
7702
7703 hlist_for_each_entry_rcu(event, head, hlist_entry) {
7704 if (perf_tp_event_match(event, &data, regs))
7705 perf_swevent_event(event, count, &data, regs);
7706 }
7707
7708 /*
7709 * If we got specified a target task, also iterate its context and
7710 * deliver this event there too.
7711 */
7712 if (task && task != current) {
7713 struct perf_event_context *ctx;
7714 struct trace_entry *entry = record;
7715
7716 rcu_read_lock();
7717 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
7718 if (!ctx)
7719 goto unlock;
7720
7721 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
7722 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7723 continue;
7724 if (event->attr.config != entry->type)
7725 continue;
7726 if (perf_tp_event_match(event, &data, regs))
7727 perf_swevent_event(event, count, &data, regs);
7728 }
7729 unlock:
7730 rcu_read_unlock();
7731 }
7732
7733 perf_swevent_put_recursion_context(rctx);
7734 }
7735 EXPORT_SYMBOL_GPL(perf_tp_event);
7736
7737 static void tp_perf_event_destroy(struct perf_event *event)
7738 {
7739 perf_trace_destroy(event);
7740 }
7741
7742 static int perf_tp_event_init(struct perf_event *event)
7743 {
7744 int err;
7745
7746 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7747 return -ENOENT;
7748
7749 /*
7750 * no branch sampling for tracepoint events
7751 */
7752 if (has_branch_stack(event))
7753 return -EOPNOTSUPP;
7754
7755 err = perf_trace_init(event);
7756 if (err)
7757 return err;
7758
7759 event->destroy = tp_perf_event_destroy;
7760
7761 return 0;
7762 }
7763
7764 static struct pmu perf_tracepoint = {
7765 .task_ctx_nr = perf_sw_context,
7766
7767 .event_init = perf_tp_event_init,
7768 .add = perf_trace_add,
7769 .del = perf_trace_del,
7770 .start = perf_swevent_start,
7771 .stop = perf_swevent_stop,
7772 .read = perf_swevent_read,
7773 };
7774
7775 static inline void perf_tp_register(void)
7776 {
7777 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
7778 }
7779
7780 static void perf_event_free_filter(struct perf_event *event)
7781 {
7782 ftrace_profile_free_filter(event);
7783 }
7784
7785 #ifdef CONFIG_BPF_SYSCALL
7786 static void bpf_overflow_handler(struct perf_event *event,
7787 struct perf_sample_data *data,
7788 struct pt_regs *regs)
7789 {
7790 struct bpf_perf_event_data_kern ctx = {
7791 .data = data,
7792 .regs = regs,
7793 };
7794 int ret = 0;
7795
7796 preempt_disable();
7797 if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1))
7798 goto out;
7799 rcu_read_lock();
7800 ret = BPF_PROG_RUN(event->prog, &ctx);
7801 rcu_read_unlock();
7802 out:
7803 __this_cpu_dec(bpf_prog_active);
7804 preempt_enable();
7805 if (!ret)
7806 return;
7807
7808 event->orig_overflow_handler(event, data, regs);
7809 }
7810
7811 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
7812 {
7813 struct bpf_prog *prog;
7814
7815 if (event->overflow_handler_context)
7816 /* hw breakpoint or kernel counter */
7817 return -EINVAL;
7818
7819 if (event->prog)
7820 return -EEXIST;
7821
7822 prog = bpf_prog_get_type(prog_fd, BPF_PROG_TYPE_PERF_EVENT);
7823 if (IS_ERR(prog))
7824 return PTR_ERR(prog);
7825
7826 event->prog = prog;
7827 event->orig_overflow_handler = READ_ONCE(event->overflow_handler);
7828 WRITE_ONCE(event->overflow_handler, bpf_overflow_handler);
7829 return 0;
7830 }
7831
7832 static void perf_event_free_bpf_handler(struct perf_event *event)
7833 {
7834 struct bpf_prog *prog = event->prog;
7835
7836 if (!prog)
7837 return;
7838
7839 WRITE_ONCE(event->overflow_handler, event->orig_overflow_handler);
7840 event->prog = NULL;
7841 bpf_prog_put(prog);
7842 }
7843 #else
7844 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
7845 {
7846 return -EOPNOTSUPP;
7847 }
7848 static void perf_event_free_bpf_handler(struct perf_event *event)
7849 {
7850 }
7851 #endif
7852
7853 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
7854 {
7855 bool is_kprobe, is_tracepoint;
7856 struct bpf_prog *prog;
7857
7858 if (event->attr.type == PERF_TYPE_HARDWARE ||
7859 event->attr.type == PERF_TYPE_SOFTWARE)
7860 return perf_event_set_bpf_handler(event, prog_fd);
7861
7862 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7863 return -EINVAL;
7864
7865 if (event->tp_event->prog)
7866 return -EEXIST;
7867
7868 is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_UKPROBE;
7869 is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT;
7870 if (!is_kprobe && !is_tracepoint)
7871 /* bpf programs can only be attached to u/kprobe or tracepoint */
7872 return -EINVAL;
7873
7874 prog = bpf_prog_get(prog_fd);
7875 if (IS_ERR(prog))
7876 return PTR_ERR(prog);
7877
7878 if ((is_kprobe && prog->type != BPF_PROG_TYPE_KPROBE) ||
7879 (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT)) {
7880 /* valid fd, but invalid bpf program type */
7881 bpf_prog_put(prog);
7882 return -EINVAL;
7883 }
7884
7885 if (is_tracepoint) {
7886 int off = trace_event_get_offsets(event->tp_event);
7887
7888 if (prog->aux->max_ctx_offset > off) {
7889 bpf_prog_put(prog);
7890 return -EACCES;
7891 }
7892 }
7893 event->tp_event->prog = prog;
7894
7895 return 0;
7896 }
7897
7898 static void perf_event_free_bpf_prog(struct perf_event *event)
7899 {
7900 struct bpf_prog *prog;
7901
7902 perf_event_free_bpf_handler(event);
7903
7904 if (!event->tp_event)
7905 return;
7906
7907 prog = event->tp_event->prog;
7908 if (prog) {
7909 event->tp_event->prog = NULL;
7910 bpf_prog_put(prog);
7911 }
7912 }
7913
7914 #else
7915
7916 static inline void perf_tp_register(void)
7917 {
7918 }
7919
7920 static void perf_event_free_filter(struct perf_event *event)
7921 {
7922 }
7923
7924 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
7925 {
7926 return -ENOENT;
7927 }
7928
7929 static void perf_event_free_bpf_prog(struct perf_event *event)
7930 {
7931 }
7932 #endif /* CONFIG_EVENT_TRACING */
7933
7934 #ifdef CONFIG_HAVE_HW_BREAKPOINT
7935 void perf_bp_event(struct perf_event *bp, void *data)
7936 {
7937 struct perf_sample_data sample;
7938 struct pt_regs *regs = data;
7939
7940 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
7941
7942 if (!bp->hw.state && !perf_exclude_event(bp, regs))
7943 perf_swevent_event(bp, 1, &sample, regs);
7944 }
7945 #endif
7946
7947 /*
7948 * Allocate a new address filter
7949 */
7950 static struct perf_addr_filter *
7951 perf_addr_filter_new(struct perf_event *event, struct list_head *filters)
7952 {
7953 int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu);
7954 struct perf_addr_filter *filter;
7955
7956 filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node);
7957 if (!filter)
7958 return NULL;
7959
7960 INIT_LIST_HEAD(&filter->entry);
7961 list_add_tail(&filter->entry, filters);
7962
7963 return filter;
7964 }
7965
7966 static void free_filters_list(struct list_head *filters)
7967 {
7968 struct perf_addr_filter *filter, *iter;
7969
7970 list_for_each_entry_safe(filter, iter, filters, entry) {
7971 if (filter->inode)
7972 iput(filter->inode);
7973 list_del(&filter->entry);
7974 kfree(filter);
7975 }
7976 }
7977
7978 /*
7979 * Free existing address filters and optionally install new ones
7980 */
7981 static void perf_addr_filters_splice(struct perf_event *event,
7982 struct list_head *head)
7983 {
7984 unsigned long flags;
7985 LIST_HEAD(list);
7986
7987 if (!has_addr_filter(event))
7988 return;
7989
7990 /* don't bother with children, they don't have their own filters */
7991 if (event->parent)
7992 return;
7993
7994 raw_spin_lock_irqsave(&event->addr_filters.lock, flags);
7995
7996 list_splice_init(&event->addr_filters.list, &list);
7997 if (head)
7998 list_splice(head, &event->addr_filters.list);
7999
8000 raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags);
8001
8002 free_filters_list(&list);
8003 }
8004
8005 /*
8006 * Scan through mm's vmas and see if one of them matches the
8007 * @filter; if so, adjust filter's address range.
8008 * Called with mm::mmap_sem down for reading.
8009 */
8010 static unsigned long perf_addr_filter_apply(struct perf_addr_filter *filter,
8011 struct mm_struct *mm)
8012 {
8013 struct vm_area_struct *vma;
8014
8015 for (vma = mm->mmap; vma; vma = vma->vm_next) {
8016 struct file *file = vma->vm_file;
8017 unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
8018 unsigned long vma_size = vma->vm_end - vma->vm_start;
8019
8020 if (!file)
8021 continue;
8022
8023 if (!perf_addr_filter_match(filter, file, off, vma_size))
8024 continue;
8025
8026 return vma->vm_start;
8027 }
8028
8029 return 0;
8030 }
8031
8032 /*
8033 * Update event's address range filters based on the
8034 * task's existing mappings, if any.
8035 */
8036 static void perf_event_addr_filters_apply(struct perf_event *event)
8037 {
8038 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
8039 struct task_struct *task = READ_ONCE(event->ctx->task);
8040 struct perf_addr_filter *filter;
8041 struct mm_struct *mm = NULL;
8042 unsigned int count = 0;
8043 unsigned long flags;
8044
8045 /*
8046 * We may observe TASK_TOMBSTONE, which means that the event tear-down
8047 * will stop on the parent's child_mutex that our caller is also holding
8048 */
8049 if (task == TASK_TOMBSTONE)
8050 return;
8051
8052 mm = get_task_mm(event->ctx->task);
8053 if (!mm)
8054 goto restart;
8055
8056 down_read(&mm->mmap_sem);
8057
8058 raw_spin_lock_irqsave(&ifh->lock, flags);
8059 list_for_each_entry(filter, &ifh->list, entry) {
8060 event->addr_filters_offs[count] = 0;
8061
8062 /*
8063 * Adjust base offset if the filter is associated to a binary
8064 * that needs to be mapped:
8065 */
8066 if (filter->inode)
8067 event->addr_filters_offs[count] =
8068 perf_addr_filter_apply(filter, mm);
8069
8070 count++;
8071 }
8072
8073 event->addr_filters_gen++;
8074 raw_spin_unlock_irqrestore(&ifh->lock, flags);
8075
8076 up_read(&mm->mmap_sem);
8077
8078 mmput(mm);
8079
8080 restart:
8081 perf_event_stop(event, 1);
8082 }
8083
8084 /*
8085 * Address range filtering: limiting the data to certain
8086 * instruction address ranges. Filters are ioctl()ed to us from
8087 * userspace as ascii strings.
8088 *
8089 * Filter string format:
8090 *
8091 * ACTION RANGE_SPEC
8092 * where ACTION is one of the
8093 * * "filter": limit the trace to this region
8094 * * "start": start tracing from this address
8095 * * "stop": stop tracing at this address/region;
8096 * RANGE_SPEC is
8097 * * for kernel addresses: <start address>[/<size>]
8098 * * for object files: <start address>[/<size>]@</path/to/object/file>
8099 *
8100 * if <size> is not specified, the range is treated as a single address.
8101 */
8102 enum {
8103 IF_ACT_NONE = -1,
8104 IF_ACT_FILTER,
8105 IF_ACT_START,
8106 IF_ACT_STOP,
8107 IF_SRC_FILE,
8108 IF_SRC_KERNEL,
8109 IF_SRC_FILEADDR,
8110 IF_SRC_KERNELADDR,
8111 };
8112
8113 enum {
8114 IF_STATE_ACTION = 0,
8115 IF_STATE_SOURCE,
8116 IF_STATE_END,
8117 };
8118
8119 static const match_table_t if_tokens = {
8120 { IF_ACT_FILTER, "filter" },
8121 { IF_ACT_START, "start" },
8122 { IF_ACT_STOP, "stop" },
8123 { IF_SRC_FILE, "%u/%u@%s" },
8124 { IF_SRC_KERNEL, "%u/%u" },
8125 { IF_SRC_FILEADDR, "%u@%s" },
8126 { IF_SRC_KERNELADDR, "%u" },
8127 { IF_ACT_NONE, NULL },
8128 };
8129
8130 /*
8131 * Address filter string parser
8132 */
8133 static int
8134 perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
8135 struct list_head *filters)
8136 {
8137 struct perf_addr_filter *filter = NULL;
8138 char *start, *orig, *filename = NULL;
8139 struct path path;
8140 substring_t args[MAX_OPT_ARGS];
8141 int state = IF_STATE_ACTION, token;
8142 unsigned int kernel = 0;
8143 int ret = -EINVAL;
8144
8145 orig = fstr = kstrdup(fstr, GFP_KERNEL);
8146 if (!fstr)
8147 return -ENOMEM;
8148
8149 while ((start = strsep(&fstr, " ,\n")) != NULL) {
8150 ret = -EINVAL;
8151
8152 if (!*start)
8153 continue;
8154
8155 /* filter definition begins */
8156 if (state == IF_STATE_ACTION) {
8157 filter = perf_addr_filter_new(event, filters);
8158 if (!filter)
8159 goto fail;
8160 }
8161
8162 token = match_token(start, if_tokens, args);
8163 switch (token) {
8164 case IF_ACT_FILTER:
8165 case IF_ACT_START:
8166 filter->filter = 1;
8167
8168 case IF_ACT_STOP:
8169 if (state != IF_STATE_ACTION)
8170 goto fail;
8171
8172 state = IF_STATE_SOURCE;
8173 break;
8174
8175 case IF_SRC_KERNELADDR:
8176 case IF_SRC_KERNEL:
8177 kernel = 1;
8178
8179 case IF_SRC_FILEADDR:
8180 case IF_SRC_FILE:
8181 if (state != IF_STATE_SOURCE)
8182 goto fail;
8183
8184 if (token == IF_SRC_FILE || token == IF_SRC_KERNEL)
8185 filter->range = 1;
8186
8187 *args[0].to = 0;
8188 ret = kstrtoul(args[0].from, 0, &filter->offset);
8189 if (ret)
8190 goto fail;
8191
8192 if (filter->range) {
8193 *args[1].to = 0;
8194 ret = kstrtoul(args[1].from, 0, &filter->size);
8195 if (ret)
8196 goto fail;
8197 }
8198
8199 if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) {
8200 int fpos = filter->range ? 2 : 1;
8201
8202 filename = match_strdup(&args[fpos]);
8203 if (!filename) {
8204 ret = -ENOMEM;
8205 goto fail;
8206 }
8207 }
8208
8209 state = IF_STATE_END;
8210 break;
8211
8212 default:
8213 goto fail;
8214 }
8215
8216 /*
8217 * Filter definition is fully parsed, validate and install it.
8218 * Make sure that it doesn't contradict itself or the event's
8219 * attribute.
8220 */
8221 if (state == IF_STATE_END) {
8222 if (kernel && event->attr.exclude_kernel)
8223 goto fail;
8224
8225 if (!kernel) {
8226 if (!filename)
8227 goto fail;
8228
8229 /* look up the path and grab its inode */
8230 ret = kern_path(filename, LOOKUP_FOLLOW, &path);
8231 if (ret)
8232 goto fail_free_name;
8233
8234 filter->inode = igrab(d_inode(path.dentry));
8235 path_put(&path);
8236 kfree(filename);
8237 filename = NULL;
8238
8239 ret = -EINVAL;
8240 if (!filter->inode ||
8241 !S_ISREG(filter->inode->i_mode))
8242 /* free_filters_list() will iput() */
8243 goto fail;
8244 }
8245
8246 /* ready to consume more filters */
8247 state = IF_STATE_ACTION;
8248 filter = NULL;
8249 }
8250 }
8251
8252 if (state != IF_STATE_ACTION)
8253 goto fail;
8254
8255 kfree(orig);
8256
8257 return 0;
8258
8259 fail_free_name:
8260 kfree(filename);
8261 fail:
8262 free_filters_list(filters);
8263 kfree(orig);
8264
8265 return ret;
8266 }
8267
8268 static int
8269 perf_event_set_addr_filter(struct perf_event *event, char *filter_str)
8270 {
8271 LIST_HEAD(filters);
8272 int ret;
8273
8274 /*
8275 * Since this is called in perf_ioctl() path, we're already holding
8276 * ctx::mutex.
8277 */
8278 lockdep_assert_held(&event->ctx->mutex);
8279
8280 if (WARN_ON_ONCE(event->parent))
8281 return -EINVAL;
8282
8283 /*
8284 * For now, we only support filtering in per-task events; doing so
8285 * for CPU-wide events requires additional context switching trickery,
8286 * since same object code will be mapped at different virtual
8287 * addresses in different processes.
8288 */
8289 if (!event->ctx->task)
8290 return -EOPNOTSUPP;
8291
8292 ret = perf_event_parse_addr_filter(event, filter_str, &filters);
8293 if (ret)
8294 return ret;
8295
8296 ret = event->pmu->addr_filters_validate(&filters);
8297 if (ret) {
8298 free_filters_list(&filters);
8299 return ret;
8300 }
8301
8302 /* remove existing filters, if any */
8303 perf_addr_filters_splice(event, &filters);
8304
8305 /* install new filters */
8306 perf_event_for_each_child(event, perf_event_addr_filters_apply);
8307
8308 return ret;
8309 }
8310
8311 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
8312 {
8313 char *filter_str;
8314 int ret = -EINVAL;
8315
8316 if ((event->attr.type != PERF_TYPE_TRACEPOINT ||
8317 !IS_ENABLED(CONFIG_EVENT_TRACING)) &&
8318 !has_addr_filter(event))
8319 return -EINVAL;
8320
8321 filter_str = strndup_user(arg, PAGE_SIZE);
8322 if (IS_ERR(filter_str))
8323 return PTR_ERR(filter_str);
8324
8325 if (IS_ENABLED(CONFIG_EVENT_TRACING) &&
8326 event->attr.type == PERF_TYPE_TRACEPOINT)
8327 ret = ftrace_profile_set_filter(event, event->attr.config,
8328 filter_str);
8329 else if (has_addr_filter(event))
8330 ret = perf_event_set_addr_filter(event, filter_str);
8331
8332 kfree(filter_str);
8333 return ret;
8334 }
8335
8336 /*
8337 * hrtimer based swevent callback
8338 */
8339
8340 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
8341 {
8342 enum hrtimer_restart ret = HRTIMER_RESTART;
8343 struct perf_sample_data data;
8344 struct pt_regs *regs;
8345 struct perf_event *event;
8346 u64 period;
8347
8348 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
8349
8350 if (event->state != PERF_EVENT_STATE_ACTIVE)
8351 return HRTIMER_NORESTART;
8352
8353 event->pmu->read(event);
8354
8355 perf_sample_data_init(&data, 0, event->hw.last_period);
8356 regs = get_irq_regs();
8357
8358 if (regs && !perf_exclude_event(event, regs)) {
8359 if (!(event->attr.exclude_idle && is_idle_task(current)))
8360 if (__perf_event_overflow(event, 1, &data, regs))
8361 ret = HRTIMER_NORESTART;
8362 }
8363
8364 period = max_t(u64, 10000, event->hw.sample_period);
8365 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
8366
8367 return ret;
8368 }
8369
8370 static void perf_swevent_start_hrtimer(struct perf_event *event)
8371 {
8372 struct hw_perf_event *hwc = &event->hw;
8373 s64 period;
8374
8375 if (!is_sampling_event(event))
8376 return;
8377
8378 period = local64_read(&hwc->period_left);
8379 if (period) {
8380 if (period < 0)
8381 period = 10000;
8382
8383 local64_set(&hwc->period_left, 0);
8384 } else {
8385 period = max_t(u64, 10000, hwc->sample_period);
8386 }
8387 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
8388 HRTIMER_MODE_REL_PINNED);
8389 }
8390
8391 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
8392 {
8393 struct hw_perf_event *hwc = &event->hw;
8394
8395 if (is_sampling_event(event)) {
8396 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
8397 local64_set(&hwc->period_left, ktime_to_ns(remaining));
8398
8399 hrtimer_cancel(&hwc->hrtimer);
8400 }
8401 }
8402
8403 static void perf_swevent_init_hrtimer(struct perf_event *event)
8404 {
8405 struct hw_perf_event *hwc = &event->hw;
8406
8407 if (!is_sampling_event(event))
8408 return;
8409
8410 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
8411 hwc->hrtimer.function = perf_swevent_hrtimer;
8412
8413 /*
8414 * Since hrtimers have a fixed rate, we can do a static freq->period
8415 * mapping and avoid the whole period adjust feedback stuff.
8416 */
8417 if (event->attr.freq) {
8418 long freq = event->attr.sample_freq;
8419
8420 event->attr.sample_period = NSEC_PER_SEC / freq;
8421 hwc->sample_period = event->attr.sample_period;
8422 local64_set(&hwc->period_left, hwc->sample_period);
8423 hwc->last_period = hwc->sample_period;
8424 event->attr.freq = 0;
8425 }
8426 }
8427
8428 /*
8429 * Software event: cpu wall time clock
8430 */
8431
8432 static void cpu_clock_event_update(struct perf_event *event)
8433 {
8434 s64 prev;
8435 u64 now;
8436
8437 now = local_clock();
8438 prev = local64_xchg(&event->hw.prev_count, now);
8439 local64_add(now - prev, &event->count);
8440 }
8441
8442 static void cpu_clock_event_start(struct perf_event *event, int flags)
8443 {
8444 local64_set(&event->hw.prev_count, local_clock());
8445 perf_swevent_start_hrtimer(event);
8446 }
8447
8448 static void cpu_clock_event_stop(struct perf_event *event, int flags)
8449 {
8450 perf_swevent_cancel_hrtimer(event);
8451 cpu_clock_event_update(event);
8452 }
8453
8454 static int cpu_clock_event_add(struct perf_event *event, int flags)
8455 {
8456 if (flags & PERF_EF_START)
8457 cpu_clock_event_start(event, flags);
8458 perf_event_update_userpage(event);
8459
8460 return 0;
8461 }
8462
8463 static void cpu_clock_event_del(struct perf_event *event, int flags)
8464 {
8465 cpu_clock_event_stop(event, flags);
8466 }
8467
8468 static void cpu_clock_event_read(struct perf_event *event)
8469 {
8470 cpu_clock_event_update(event);
8471 }
8472
8473 static int cpu_clock_event_init(struct perf_event *event)
8474 {
8475 if (event->attr.type != PERF_TYPE_SOFTWARE)
8476 return -ENOENT;
8477
8478 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
8479 return -ENOENT;
8480
8481 /*
8482 * no branch sampling for software events
8483 */
8484 if (has_branch_stack(event))
8485 return -EOPNOTSUPP;
8486
8487 perf_swevent_init_hrtimer(event);
8488
8489 return 0;
8490 }
8491
8492 static struct pmu perf_cpu_clock = {
8493 .task_ctx_nr = perf_sw_context,
8494
8495 .capabilities = PERF_PMU_CAP_NO_NMI,
8496
8497 .event_init = cpu_clock_event_init,
8498 .add = cpu_clock_event_add,
8499 .del = cpu_clock_event_del,
8500 .start = cpu_clock_event_start,
8501 .stop = cpu_clock_event_stop,
8502 .read = cpu_clock_event_read,
8503 };
8504
8505 /*
8506 * Software event: task time clock
8507 */
8508
8509 static void task_clock_event_update(struct perf_event *event, u64 now)
8510 {
8511 u64 prev;
8512 s64 delta;
8513
8514 prev = local64_xchg(&event->hw.prev_count, now);
8515 delta = now - prev;
8516 local64_add(delta, &event->count);
8517 }
8518
8519 static void task_clock_event_start(struct perf_event *event, int flags)
8520 {
8521 local64_set(&event->hw.prev_count, event->ctx->time);
8522 perf_swevent_start_hrtimer(event);
8523 }
8524
8525 static void task_clock_event_stop(struct perf_event *event, int flags)
8526 {
8527 perf_swevent_cancel_hrtimer(event);
8528 task_clock_event_update(event, event->ctx->time);
8529 }
8530
8531 static int task_clock_event_add(struct perf_event *event, int flags)
8532 {
8533 if (flags & PERF_EF_START)
8534 task_clock_event_start(event, flags);
8535 perf_event_update_userpage(event);
8536
8537 return 0;
8538 }
8539
8540 static void task_clock_event_del(struct perf_event *event, int flags)
8541 {
8542 task_clock_event_stop(event, PERF_EF_UPDATE);
8543 }
8544
8545 static void task_clock_event_read(struct perf_event *event)
8546 {
8547 u64 now = perf_clock();
8548 u64 delta = now - event->ctx->timestamp;
8549 u64 time = event->ctx->time + delta;
8550
8551 task_clock_event_update(event, time);
8552 }
8553
8554 static int task_clock_event_init(struct perf_event *event)
8555 {
8556 if (event->attr.type != PERF_TYPE_SOFTWARE)
8557 return -ENOENT;
8558
8559 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
8560 return -ENOENT;
8561
8562 /*
8563 * no branch sampling for software events
8564 */
8565 if (has_branch_stack(event))
8566 return -EOPNOTSUPP;
8567
8568 perf_swevent_init_hrtimer(event);
8569
8570 return 0;
8571 }
8572
8573 static struct pmu perf_task_clock = {
8574 .task_ctx_nr = perf_sw_context,
8575
8576 .capabilities = PERF_PMU_CAP_NO_NMI,
8577
8578 .event_init = task_clock_event_init,
8579 .add = task_clock_event_add,
8580 .del = task_clock_event_del,
8581 .start = task_clock_event_start,
8582 .stop = task_clock_event_stop,
8583 .read = task_clock_event_read,
8584 };
8585
8586 static void perf_pmu_nop_void(struct pmu *pmu)
8587 {
8588 }
8589
8590 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
8591 {
8592 }
8593
8594 static int perf_pmu_nop_int(struct pmu *pmu)
8595 {
8596 return 0;
8597 }
8598
8599 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
8600
8601 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
8602 {
8603 __this_cpu_write(nop_txn_flags, flags);
8604
8605 if (flags & ~PERF_PMU_TXN_ADD)
8606 return;
8607
8608 perf_pmu_disable(pmu);
8609 }
8610
8611 static int perf_pmu_commit_txn(struct pmu *pmu)
8612 {
8613 unsigned int flags = __this_cpu_read(nop_txn_flags);
8614
8615 __this_cpu_write(nop_txn_flags, 0);
8616
8617 if (flags & ~PERF_PMU_TXN_ADD)
8618 return 0;
8619
8620 perf_pmu_enable(pmu);
8621 return 0;
8622 }
8623
8624 static void perf_pmu_cancel_txn(struct pmu *pmu)
8625 {
8626 unsigned int flags = __this_cpu_read(nop_txn_flags);
8627
8628 __this_cpu_write(nop_txn_flags, 0);
8629
8630 if (flags & ~PERF_PMU_TXN_ADD)
8631 return;
8632
8633 perf_pmu_enable(pmu);
8634 }
8635
8636 static int perf_event_idx_default(struct perf_event *event)
8637 {
8638 return 0;
8639 }
8640
8641 /*
8642 * Ensures all contexts with the same task_ctx_nr have the same
8643 * pmu_cpu_context too.
8644 */
8645 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
8646 {
8647 struct pmu *pmu;
8648
8649 if (ctxn < 0)
8650 return NULL;
8651
8652 list_for_each_entry(pmu, &pmus, entry) {
8653 if (pmu->task_ctx_nr == ctxn)
8654 return pmu->pmu_cpu_context;
8655 }
8656
8657 return NULL;
8658 }
8659
8660 static void update_pmu_context(struct pmu *pmu, struct pmu *old_pmu)
8661 {
8662 int cpu;
8663
8664 for_each_possible_cpu(cpu) {
8665 struct perf_cpu_context *cpuctx;
8666
8667 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
8668
8669 if (cpuctx->unique_pmu == old_pmu)
8670 cpuctx->unique_pmu = pmu;
8671 }
8672 }
8673
8674 static void free_pmu_context(struct pmu *pmu)
8675 {
8676 struct pmu *i;
8677
8678 mutex_lock(&pmus_lock);
8679 /*
8680 * Like a real lame refcount.
8681 */
8682 list_for_each_entry(i, &pmus, entry) {
8683 if (i->pmu_cpu_context == pmu->pmu_cpu_context) {
8684 update_pmu_context(i, pmu);
8685 goto out;
8686 }
8687 }
8688
8689 free_percpu(pmu->pmu_cpu_context);
8690 out:
8691 mutex_unlock(&pmus_lock);
8692 }
8693
8694 /*
8695 * Let userspace know that this PMU supports address range filtering:
8696 */
8697 static ssize_t nr_addr_filters_show(struct device *dev,
8698 struct device_attribute *attr,
8699 char *page)
8700 {
8701 struct pmu *pmu = dev_get_drvdata(dev);
8702
8703 return snprintf(page, PAGE_SIZE - 1, "%d\n", pmu->nr_addr_filters);
8704 }
8705 DEVICE_ATTR_RO(nr_addr_filters);
8706
8707 static struct idr pmu_idr;
8708
8709 static ssize_t
8710 type_show(struct device *dev, struct device_attribute *attr, char *page)
8711 {
8712 struct pmu *pmu = dev_get_drvdata(dev);
8713
8714 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
8715 }
8716 static DEVICE_ATTR_RO(type);
8717
8718 static ssize_t
8719 perf_event_mux_interval_ms_show(struct device *dev,
8720 struct device_attribute *attr,
8721 char *page)
8722 {
8723 struct pmu *pmu = dev_get_drvdata(dev);
8724
8725 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
8726 }
8727
8728 static DEFINE_MUTEX(mux_interval_mutex);
8729
8730 static ssize_t
8731 perf_event_mux_interval_ms_store(struct device *dev,
8732 struct device_attribute *attr,
8733 const char *buf, size_t count)
8734 {
8735 struct pmu *pmu = dev_get_drvdata(dev);
8736 int timer, cpu, ret;
8737
8738 ret = kstrtoint(buf, 0, &timer);
8739 if (ret)
8740 return ret;
8741
8742 if (timer < 1)
8743 return -EINVAL;
8744
8745 /* same value, noting to do */
8746 if (timer == pmu->hrtimer_interval_ms)
8747 return count;
8748
8749 mutex_lock(&mux_interval_mutex);
8750 pmu->hrtimer_interval_ms = timer;
8751
8752 /* update all cpuctx for this PMU */
8753 get_online_cpus();
8754 for_each_online_cpu(cpu) {
8755 struct perf_cpu_context *cpuctx;
8756 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
8757 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
8758
8759 cpu_function_call(cpu,
8760 (remote_function_f)perf_mux_hrtimer_restart, cpuctx);
8761 }
8762 put_online_cpus();
8763 mutex_unlock(&mux_interval_mutex);
8764
8765 return count;
8766 }
8767 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
8768
8769 static struct attribute *pmu_dev_attrs[] = {
8770 &dev_attr_type.attr,
8771 &dev_attr_perf_event_mux_interval_ms.attr,
8772 NULL,
8773 };
8774 ATTRIBUTE_GROUPS(pmu_dev);
8775
8776 static int pmu_bus_running;
8777 static struct bus_type pmu_bus = {
8778 .name = "event_source",
8779 .dev_groups = pmu_dev_groups,
8780 };
8781
8782 static void pmu_dev_release(struct device *dev)
8783 {
8784 kfree(dev);
8785 }
8786
8787 static int pmu_dev_alloc(struct pmu *pmu)
8788 {
8789 int ret = -ENOMEM;
8790
8791 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
8792 if (!pmu->dev)
8793 goto out;
8794
8795 pmu->dev->groups = pmu->attr_groups;
8796 device_initialize(pmu->dev);
8797 ret = dev_set_name(pmu->dev, "%s", pmu->name);
8798 if (ret)
8799 goto free_dev;
8800
8801 dev_set_drvdata(pmu->dev, pmu);
8802 pmu->dev->bus = &pmu_bus;
8803 pmu->dev->release = pmu_dev_release;
8804 ret = device_add(pmu->dev);
8805 if (ret)
8806 goto free_dev;
8807
8808 /* For PMUs with address filters, throw in an extra attribute: */
8809 if (pmu->nr_addr_filters)
8810 ret = device_create_file(pmu->dev, &dev_attr_nr_addr_filters);
8811
8812 if (ret)
8813 goto del_dev;
8814
8815 out:
8816 return ret;
8817
8818 del_dev:
8819 device_del(pmu->dev);
8820
8821 free_dev:
8822 put_device(pmu->dev);
8823 goto out;
8824 }
8825
8826 static struct lock_class_key cpuctx_mutex;
8827 static struct lock_class_key cpuctx_lock;
8828
8829 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
8830 {
8831 int cpu, ret;
8832
8833 mutex_lock(&pmus_lock);
8834 ret = -ENOMEM;
8835 pmu->pmu_disable_count = alloc_percpu(int);
8836 if (!pmu->pmu_disable_count)
8837 goto unlock;
8838
8839 pmu->type = -1;
8840 if (!name)
8841 goto skip_type;
8842 pmu->name = name;
8843
8844 if (type < 0) {
8845 type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
8846 if (type < 0) {
8847 ret = type;
8848 goto free_pdc;
8849 }
8850 }
8851 pmu->type = type;
8852
8853 if (pmu_bus_running) {
8854 ret = pmu_dev_alloc(pmu);
8855 if (ret)
8856 goto free_idr;
8857 }
8858
8859 skip_type:
8860 if (pmu->task_ctx_nr == perf_hw_context) {
8861 static int hw_context_taken = 0;
8862
8863 /*
8864 * Other than systems with heterogeneous CPUs, it never makes
8865 * sense for two PMUs to share perf_hw_context. PMUs which are
8866 * uncore must use perf_invalid_context.
8867 */
8868 if (WARN_ON_ONCE(hw_context_taken &&
8869 !(pmu->capabilities & PERF_PMU_CAP_HETEROGENEOUS_CPUS)))
8870 pmu->task_ctx_nr = perf_invalid_context;
8871
8872 hw_context_taken = 1;
8873 }
8874
8875 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
8876 if (pmu->pmu_cpu_context)
8877 goto got_cpu_context;
8878
8879 ret = -ENOMEM;
8880 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
8881 if (!pmu->pmu_cpu_context)
8882 goto free_dev;
8883
8884 for_each_possible_cpu(cpu) {
8885 struct perf_cpu_context *cpuctx;
8886
8887 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
8888 __perf_event_init_context(&cpuctx->ctx);
8889 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
8890 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
8891 cpuctx->ctx.pmu = pmu;
8892
8893 __perf_mux_hrtimer_init(cpuctx, cpu);
8894
8895 cpuctx->unique_pmu = pmu;
8896 }
8897
8898 got_cpu_context:
8899 if (!pmu->start_txn) {
8900 if (pmu->pmu_enable) {
8901 /*
8902 * If we have pmu_enable/pmu_disable calls, install
8903 * transaction stubs that use that to try and batch
8904 * hardware accesses.
8905 */
8906 pmu->start_txn = perf_pmu_start_txn;
8907 pmu->commit_txn = perf_pmu_commit_txn;
8908 pmu->cancel_txn = perf_pmu_cancel_txn;
8909 } else {
8910 pmu->start_txn = perf_pmu_nop_txn;
8911 pmu->commit_txn = perf_pmu_nop_int;
8912 pmu->cancel_txn = perf_pmu_nop_void;
8913 }
8914 }
8915
8916 if (!pmu->pmu_enable) {
8917 pmu->pmu_enable = perf_pmu_nop_void;
8918 pmu->pmu_disable = perf_pmu_nop_void;
8919 }
8920
8921 if (!pmu->event_idx)
8922 pmu->event_idx = perf_event_idx_default;
8923
8924 list_add_rcu(&pmu->entry, &pmus);
8925 atomic_set(&pmu->exclusive_cnt, 0);
8926 ret = 0;
8927 unlock:
8928 mutex_unlock(&pmus_lock);
8929
8930 return ret;
8931
8932 free_dev:
8933 device_del(pmu->dev);
8934 put_device(pmu->dev);
8935
8936 free_idr:
8937 if (pmu->type >= PERF_TYPE_MAX)
8938 idr_remove(&pmu_idr, pmu->type);
8939
8940 free_pdc:
8941 free_percpu(pmu->pmu_disable_count);
8942 goto unlock;
8943 }
8944 EXPORT_SYMBOL_GPL(perf_pmu_register);
8945
8946 void perf_pmu_unregister(struct pmu *pmu)
8947 {
8948 int remove_device;
8949
8950 mutex_lock(&pmus_lock);
8951 remove_device = pmu_bus_running;
8952 list_del_rcu(&pmu->entry);
8953 mutex_unlock(&pmus_lock);
8954
8955 /*
8956 * We dereference the pmu list under both SRCU and regular RCU, so
8957 * synchronize against both of those.
8958 */
8959 synchronize_srcu(&pmus_srcu);
8960 synchronize_rcu();
8961
8962 free_percpu(pmu->pmu_disable_count);
8963 if (pmu->type >= PERF_TYPE_MAX)
8964 idr_remove(&pmu_idr, pmu->type);
8965 if (remove_device) {
8966 if (pmu->nr_addr_filters)
8967 device_remove_file(pmu->dev, &dev_attr_nr_addr_filters);
8968 device_del(pmu->dev);
8969 put_device(pmu->dev);
8970 }
8971 free_pmu_context(pmu);
8972 }
8973 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
8974
8975 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
8976 {
8977 struct perf_event_context *ctx = NULL;
8978 int ret;
8979
8980 if (!try_module_get(pmu->module))
8981 return -ENODEV;
8982
8983 if (event->group_leader != event) {
8984 /*
8985 * This ctx->mutex can nest when we're called through
8986 * inheritance. See the perf_event_ctx_lock_nested() comment.
8987 */
8988 ctx = perf_event_ctx_lock_nested(event->group_leader,
8989 SINGLE_DEPTH_NESTING);
8990 BUG_ON(!ctx);
8991 }
8992
8993 event->pmu = pmu;
8994 ret = pmu->event_init(event);
8995
8996 if (ctx)
8997 perf_event_ctx_unlock(event->group_leader, ctx);
8998
8999 if (ret)
9000 module_put(pmu->module);
9001
9002 return ret;
9003 }
9004
9005 static struct pmu *perf_init_event(struct perf_event *event)
9006 {
9007 struct pmu *pmu = NULL;
9008 int idx;
9009 int ret;
9010
9011 idx = srcu_read_lock(&pmus_srcu);
9012
9013 rcu_read_lock();
9014 pmu = idr_find(&pmu_idr, event->attr.type);
9015 rcu_read_unlock();
9016 if (pmu) {
9017 ret = perf_try_init_event(pmu, event);
9018 if (ret)
9019 pmu = ERR_PTR(ret);
9020 goto unlock;
9021 }
9022
9023 list_for_each_entry_rcu(pmu, &pmus, entry) {
9024 ret = perf_try_init_event(pmu, event);
9025 if (!ret)
9026 goto unlock;
9027
9028 if (ret != -ENOENT) {
9029 pmu = ERR_PTR(ret);
9030 goto unlock;
9031 }
9032 }
9033 pmu = ERR_PTR(-ENOENT);
9034 unlock:
9035 srcu_read_unlock(&pmus_srcu, idx);
9036
9037 return pmu;
9038 }
9039
9040 static void attach_sb_event(struct perf_event *event)
9041 {
9042 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
9043
9044 raw_spin_lock(&pel->lock);
9045 list_add_rcu(&event->sb_list, &pel->list);
9046 raw_spin_unlock(&pel->lock);
9047 }
9048
9049 /*
9050 * We keep a list of all !task (and therefore per-cpu) events
9051 * that need to receive side-band records.
9052 *
9053 * This avoids having to scan all the various PMU per-cpu contexts
9054 * looking for them.
9055 */
9056 static void account_pmu_sb_event(struct perf_event *event)
9057 {
9058 if (is_sb_event(event))
9059 attach_sb_event(event);
9060 }
9061
9062 static void account_event_cpu(struct perf_event *event, int cpu)
9063 {
9064 if (event->parent)
9065 return;
9066
9067 if (is_cgroup_event(event))
9068 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
9069 }
9070
9071 /* Freq events need the tick to stay alive (see perf_event_task_tick). */
9072 static void account_freq_event_nohz(void)
9073 {
9074 #ifdef CONFIG_NO_HZ_FULL
9075 /* Lock so we don't race with concurrent unaccount */
9076 spin_lock(&nr_freq_lock);
9077 if (atomic_inc_return(&nr_freq_events) == 1)
9078 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS);
9079 spin_unlock(&nr_freq_lock);
9080 #endif
9081 }
9082
9083 static void account_freq_event(void)
9084 {
9085 if (tick_nohz_full_enabled())
9086 account_freq_event_nohz();
9087 else
9088 atomic_inc(&nr_freq_events);
9089 }
9090
9091
9092 static void account_event(struct perf_event *event)
9093 {
9094 bool inc = false;
9095
9096 if (event->parent)
9097 return;
9098
9099 if (event->attach_state & PERF_ATTACH_TASK)
9100 inc = true;
9101 if (event->attr.mmap || event->attr.mmap_data)
9102 atomic_inc(&nr_mmap_events);
9103 if (event->attr.comm)
9104 atomic_inc(&nr_comm_events);
9105 if (event->attr.task)
9106 atomic_inc(&nr_task_events);
9107 if (event->attr.freq)
9108 account_freq_event();
9109 if (event->attr.context_switch) {
9110 atomic_inc(&nr_switch_events);
9111 inc = true;
9112 }
9113 if (has_branch_stack(event))
9114 inc = true;
9115 if (is_cgroup_event(event))
9116 inc = true;
9117
9118 if (inc) {
9119 if (atomic_inc_not_zero(&perf_sched_count))
9120 goto enabled;
9121
9122 mutex_lock(&perf_sched_mutex);
9123 if (!atomic_read(&perf_sched_count)) {
9124 static_branch_enable(&perf_sched_events);
9125 /*
9126 * Guarantee that all CPUs observe they key change and
9127 * call the perf scheduling hooks before proceeding to
9128 * install events that need them.
9129 */
9130 synchronize_sched();
9131 }
9132 /*
9133 * Now that we have waited for the sync_sched(), allow further
9134 * increments to by-pass the mutex.
9135 */
9136 atomic_inc(&perf_sched_count);
9137 mutex_unlock(&perf_sched_mutex);
9138 }
9139 enabled:
9140
9141 account_event_cpu(event, event->cpu);
9142
9143 account_pmu_sb_event(event);
9144 }
9145
9146 /*
9147 * Allocate and initialize a event structure
9148 */
9149 static struct perf_event *
9150 perf_event_alloc(struct perf_event_attr *attr, int cpu,
9151 struct task_struct *task,
9152 struct perf_event *group_leader,
9153 struct perf_event *parent_event,
9154 perf_overflow_handler_t overflow_handler,
9155 void *context, int cgroup_fd)
9156 {
9157 struct pmu *pmu;
9158 struct perf_event *event;
9159 struct hw_perf_event *hwc;
9160 long err = -EINVAL;
9161
9162 if ((unsigned)cpu >= nr_cpu_ids) {
9163 if (!task || cpu != -1)
9164 return ERR_PTR(-EINVAL);
9165 }
9166
9167 event = kzalloc(sizeof(*event), GFP_KERNEL);
9168 if (!event)
9169 return ERR_PTR(-ENOMEM);
9170
9171 /*
9172 * Single events are their own group leaders, with an
9173 * empty sibling list:
9174 */
9175 if (!group_leader)
9176 group_leader = event;
9177
9178 mutex_init(&event->child_mutex);
9179 INIT_LIST_HEAD(&event->child_list);
9180
9181 INIT_LIST_HEAD(&event->group_entry);
9182 INIT_LIST_HEAD(&event->event_entry);
9183 INIT_LIST_HEAD(&event->sibling_list);
9184 INIT_LIST_HEAD(&event->rb_entry);
9185 INIT_LIST_HEAD(&event->active_entry);
9186 INIT_LIST_HEAD(&event->addr_filters.list);
9187 INIT_HLIST_NODE(&event->hlist_entry);
9188
9189
9190 init_waitqueue_head(&event->waitq);
9191 init_irq_work(&event->pending, perf_pending_event);
9192
9193 mutex_init(&event->mmap_mutex);
9194 raw_spin_lock_init(&event->addr_filters.lock);
9195
9196 atomic_long_set(&event->refcount, 1);
9197 event->cpu = cpu;
9198 event->attr = *attr;
9199 event->group_leader = group_leader;
9200 event->pmu = NULL;
9201 event->oncpu = -1;
9202
9203 event->parent = parent_event;
9204
9205 event->ns = get_pid_ns(task_active_pid_ns(current));
9206 event->id = atomic64_inc_return(&perf_event_id);
9207
9208 event->state = PERF_EVENT_STATE_INACTIVE;
9209
9210 if (task) {
9211 event->attach_state = PERF_ATTACH_TASK;
9212 /*
9213 * XXX pmu::event_init needs to know what task to account to
9214 * and we cannot use the ctx information because we need the
9215 * pmu before we get a ctx.
9216 */
9217 event->hw.target = task;
9218 }
9219
9220 event->clock = &local_clock;
9221 if (parent_event)
9222 event->clock = parent_event->clock;
9223
9224 if (!overflow_handler && parent_event) {
9225 overflow_handler = parent_event->overflow_handler;
9226 context = parent_event->overflow_handler_context;
9227 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING)
9228 if (overflow_handler == bpf_overflow_handler) {
9229 struct bpf_prog *prog = bpf_prog_inc(parent_event->prog);
9230
9231 if (IS_ERR(prog)) {
9232 err = PTR_ERR(prog);
9233 goto err_ns;
9234 }
9235 event->prog = prog;
9236 event->orig_overflow_handler =
9237 parent_event->orig_overflow_handler;
9238 }
9239 #endif
9240 }
9241
9242 if (overflow_handler) {
9243 event->overflow_handler = overflow_handler;
9244 event->overflow_handler_context = context;
9245 } else if (is_write_backward(event)){
9246 event->overflow_handler = perf_event_output_backward;
9247 event->overflow_handler_context = NULL;
9248 } else {
9249 event->overflow_handler = perf_event_output_forward;
9250 event->overflow_handler_context = NULL;
9251 }
9252
9253 perf_event__state_init(event);
9254
9255 pmu = NULL;
9256
9257 hwc = &event->hw;
9258 hwc->sample_period = attr->sample_period;
9259 if (attr->freq && attr->sample_freq)
9260 hwc->sample_period = 1;
9261 hwc->last_period = hwc->sample_period;
9262
9263 local64_set(&hwc->period_left, hwc->sample_period);
9264
9265 /*
9266 * we currently do not support PERF_FORMAT_GROUP on inherited events
9267 */
9268 if (attr->inherit && (attr->read_format & PERF_FORMAT_GROUP))
9269 goto err_ns;
9270
9271 if (!has_branch_stack(event))
9272 event->attr.branch_sample_type = 0;
9273
9274 if (cgroup_fd != -1) {
9275 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
9276 if (err)
9277 goto err_ns;
9278 }
9279
9280 pmu = perf_init_event(event);
9281 if (!pmu)
9282 goto err_ns;
9283 else if (IS_ERR(pmu)) {
9284 err = PTR_ERR(pmu);
9285 goto err_ns;
9286 }
9287
9288 err = exclusive_event_init(event);
9289 if (err)
9290 goto err_pmu;
9291
9292 if (has_addr_filter(event)) {
9293 event->addr_filters_offs = kcalloc(pmu->nr_addr_filters,
9294 sizeof(unsigned long),
9295 GFP_KERNEL);
9296 if (!event->addr_filters_offs)
9297 goto err_per_task;
9298
9299 /* force hw sync on the address filters */
9300 event->addr_filters_gen = 1;
9301 }
9302
9303 if (!event->parent) {
9304 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
9305 err = get_callchain_buffers(attr->sample_max_stack);
9306 if (err)
9307 goto err_addr_filters;
9308 }
9309 }
9310
9311 /* symmetric to unaccount_event() in _free_event() */
9312 account_event(event);
9313
9314 return event;
9315
9316 err_addr_filters:
9317 kfree(event->addr_filters_offs);
9318
9319 err_per_task:
9320 exclusive_event_destroy(event);
9321
9322 err_pmu:
9323 if (event->destroy)
9324 event->destroy(event);
9325 module_put(pmu->module);
9326 err_ns:
9327 if (is_cgroup_event(event))
9328 perf_detach_cgroup(event);
9329 if (event->ns)
9330 put_pid_ns(event->ns);
9331 kfree(event);
9332
9333 return ERR_PTR(err);
9334 }
9335
9336 static int perf_copy_attr(struct perf_event_attr __user *uattr,
9337 struct perf_event_attr *attr)
9338 {
9339 u32 size;
9340 int ret;
9341
9342 if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
9343 return -EFAULT;
9344
9345 /*
9346 * zero the full structure, so that a short copy will be nice.
9347 */
9348 memset(attr, 0, sizeof(*attr));
9349
9350 ret = get_user(size, &uattr->size);
9351 if (ret)
9352 return ret;
9353
9354 if (size > PAGE_SIZE) /* silly large */
9355 goto err_size;
9356
9357 if (!size) /* abi compat */
9358 size = PERF_ATTR_SIZE_VER0;
9359
9360 if (size < PERF_ATTR_SIZE_VER0)
9361 goto err_size;
9362
9363 /*
9364 * If we're handed a bigger struct than we know of,
9365 * ensure all the unknown bits are 0 - i.e. new
9366 * user-space does not rely on any kernel feature
9367 * extensions we dont know about yet.
9368 */
9369 if (size > sizeof(*attr)) {
9370 unsigned char __user *addr;
9371 unsigned char __user *end;
9372 unsigned char val;
9373
9374 addr = (void __user *)uattr + sizeof(*attr);
9375 end = (void __user *)uattr + size;
9376
9377 for (; addr < end; addr++) {
9378 ret = get_user(val, addr);
9379 if (ret)
9380 return ret;
9381 if (val)
9382 goto err_size;
9383 }
9384 size = sizeof(*attr);
9385 }
9386
9387 ret = copy_from_user(attr, uattr, size);
9388 if (ret)
9389 return -EFAULT;
9390
9391 if (attr->__reserved_1)
9392 return -EINVAL;
9393
9394 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
9395 return -EINVAL;
9396
9397 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
9398 return -EINVAL;
9399
9400 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
9401 u64 mask = attr->branch_sample_type;
9402
9403 /* only using defined bits */
9404 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
9405 return -EINVAL;
9406
9407 /* at least one branch bit must be set */
9408 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
9409 return -EINVAL;
9410
9411 /* propagate priv level, when not set for branch */
9412 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
9413
9414 /* exclude_kernel checked on syscall entry */
9415 if (!attr->exclude_kernel)
9416 mask |= PERF_SAMPLE_BRANCH_KERNEL;
9417
9418 if (!attr->exclude_user)
9419 mask |= PERF_SAMPLE_BRANCH_USER;
9420
9421 if (!attr->exclude_hv)
9422 mask |= PERF_SAMPLE_BRANCH_HV;
9423 /*
9424 * adjust user setting (for HW filter setup)
9425 */
9426 attr->branch_sample_type = mask;
9427 }
9428 /* privileged levels capture (kernel, hv): check permissions */
9429 if ((mask & PERF_SAMPLE_BRANCH_PERM_PLM)
9430 && perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
9431 return -EACCES;
9432 }
9433
9434 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
9435 ret = perf_reg_validate(attr->sample_regs_user);
9436 if (ret)
9437 return ret;
9438 }
9439
9440 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
9441 if (!arch_perf_have_user_stack_dump())
9442 return -ENOSYS;
9443
9444 /*
9445 * We have __u32 type for the size, but so far
9446 * we can only use __u16 as maximum due to the
9447 * __u16 sample size limit.
9448 */
9449 if (attr->sample_stack_user >= USHRT_MAX)
9450 ret = -EINVAL;
9451 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
9452 ret = -EINVAL;
9453 }
9454
9455 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
9456 ret = perf_reg_validate(attr->sample_regs_intr);
9457 out:
9458 return ret;
9459
9460 err_size:
9461 put_user(sizeof(*attr), &uattr->size);
9462 ret = -E2BIG;
9463 goto out;
9464 }
9465
9466 static int
9467 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
9468 {
9469 struct ring_buffer *rb = NULL;
9470 int ret = -EINVAL;
9471
9472 if (!output_event)
9473 goto set;
9474
9475 /* don't allow circular references */
9476 if (event == output_event)
9477 goto out;
9478
9479 /*
9480 * Don't allow cross-cpu buffers
9481 */
9482 if (output_event->cpu != event->cpu)
9483 goto out;
9484
9485 /*
9486 * If its not a per-cpu rb, it must be the same task.
9487 */
9488 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
9489 goto out;
9490
9491 /*
9492 * Mixing clocks in the same buffer is trouble you don't need.
9493 */
9494 if (output_event->clock != event->clock)
9495 goto out;
9496
9497 /*
9498 * Either writing ring buffer from beginning or from end.
9499 * Mixing is not allowed.
9500 */
9501 if (is_write_backward(output_event) != is_write_backward(event))
9502 goto out;
9503
9504 /*
9505 * If both events generate aux data, they must be on the same PMU
9506 */
9507 if (has_aux(event) && has_aux(output_event) &&
9508 event->pmu != output_event->pmu)
9509 goto out;
9510
9511 set:
9512 mutex_lock(&event->mmap_mutex);
9513 /* Can't redirect output if we've got an active mmap() */
9514 if (atomic_read(&event->mmap_count))
9515 goto unlock;
9516
9517 if (output_event) {
9518 /* get the rb we want to redirect to */
9519 rb = ring_buffer_get(output_event);
9520 if (!rb)
9521 goto unlock;
9522 }
9523
9524 ring_buffer_attach(event, rb);
9525
9526 ret = 0;
9527 unlock:
9528 mutex_unlock(&event->mmap_mutex);
9529
9530 out:
9531 return ret;
9532 }
9533
9534 static void mutex_lock_double(struct mutex *a, struct mutex *b)
9535 {
9536 if (b < a)
9537 swap(a, b);
9538
9539 mutex_lock(a);
9540 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
9541 }
9542
9543 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
9544 {
9545 bool nmi_safe = false;
9546
9547 switch (clk_id) {
9548 case CLOCK_MONOTONIC:
9549 event->clock = &ktime_get_mono_fast_ns;
9550 nmi_safe = true;
9551 break;
9552
9553 case CLOCK_MONOTONIC_RAW:
9554 event->clock = &ktime_get_raw_fast_ns;
9555 nmi_safe = true;
9556 break;
9557
9558 case CLOCK_REALTIME:
9559 event->clock = &ktime_get_real_ns;
9560 break;
9561
9562 case CLOCK_BOOTTIME:
9563 event->clock = &ktime_get_boot_ns;
9564 break;
9565
9566 case CLOCK_TAI:
9567 event->clock = &ktime_get_tai_ns;
9568 break;
9569
9570 default:
9571 return -EINVAL;
9572 }
9573
9574 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
9575 return -EINVAL;
9576
9577 return 0;
9578 }
9579
9580 /*
9581 * Variation on perf_event_ctx_lock_nested(), except we take two context
9582 * mutexes.
9583 */
9584 static struct perf_event_context *
9585 __perf_event_ctx_lock_double(struct perf_event *group_leader,
9586 struct perf_event_context *ctx)
9587 {
9588 struct perf_event_context *gctx;
9589
9590 again:
9591 rcu_read_lock();
9592 gctx = READ_ONCE(group_leader->ctx);
9593 if (!atomic_inc_not_zero(&gctx->refcount)) {
9594 rcu_read_unlock();
9595 goto again;
9596 }
9597 rcu_read_unlock();
9598
9599 mutex_lock_double(&gctx->mutex, &ctx->mutex);
9600
9601 if (group_leader->ctx != gctx) {
9602 mutex_unlock(&ctx->mutex);
9603 mutex_unlock(&gctx->mutex);
9604 put_ctx(gctx);
9605 goto again;
9606 }
9607
9608 return gctx;
9609 }
9610
9611 /**
9612 * sys_perf_event_open - open a performance event, associate it to a task/cpu
9613 *
9614 * @attr_uptr: event_id type attributes for monitoring/sampling
9615 * @pid: target pid
9616 * @cpu: target cpu
9617 * @group_fd: group leader event fd
9618 */
9619 SYSCALL_DEFINE5(perf_event_open,
9620 struct perf_event_attr __user *, attr_uptr,
9621 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
9622 {
9623 struct perf_event *group_leader = NULL, *output_event = NULL;
9624 struct perf_event *event, *sibling;
9625 struct perf_event_attr attr;
9626 struct perf_event_context *ctx, *uninitialized_var(gctx);
9627 struct file *event_file = NULL;
9628 struct fd group = {NULL, 0};
9629 struct task_struct *task = NULL;
9630 struct pmu *pmu;
9631 int event_fd;
9632 int move_group = 0;
9633 int err;
9634 int f_flags = O_RDWR;
9635 int cgroup_fd = -1;
9636
9637 /* for future expandability... */
9638 if (flags & ~PERF_FLAG_ALL)
9639 return -EINVAL;
9640
9641 if (perf_paranoid_any() && !capable(CAP_SYS_ADMIN))
9642 return -EACCES;
9643
9644 err = perf_copy_attr(attr_uptr, &attr);
9645 if (err)
9646 return err;
9647
9648 if (!attr.exclude_kernel) {
9649 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
9650 return -EACCES;
9651 }
9652
9653 if (attr.freq) {
9654 if (attr.sample_freq > sysctl_perf_event_sample_rate)
9655 return -EINVAL;
9656 } else {
9657 if (attr.sample_period & (1ULL << 63))
9658 return -EINVAL;
9659 }
9660
9661 if (!attr.sample_max_stack)
9662 attr.sample_max_stack = sysctl_perf_event_max_stack;
9663
9664 /*
9665 * In cgroup mode, the pid argument is used to pass the fd
9666 * opened to the cgroup directory in cgroupfs. The cpu argument
9667 * designates the cpu on which to monitor threads from that
9668 * cgroup.
9669 */
9670 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
9671 return -EINVAL;
9672
9673 if (flags & PERF_FLAG_FD_CLOEXEC)
9674 f_flags |= O_CLOEXEC;
9675
9676 event_fd = get_unused_fd_flags(f_flags);
9677 if (event_fd < 0)
9678 return event_fd;
9679
9680 if (group_fd != -1) {
9681 err = perf_fget_light(group_fd, &group);
9682 if (err)
9683 goto err_fd;
9684 group_leader = group.file->private_data;
9685 if (flags & PERF_FLAG_FD_OUTPUT)
9686 output_event = group_leader;
9687 if (flags & PERF_FLAG_FD_NO_GROUP)
9688 group_leader = NULL;
9689 }
9690
9691 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
9692 task = find_lively_task_by_vpid(pid);
9693 if (IS_ERR(task)) {
9694 err = PTR_ERR(task);
9695 goto err_group_fd;
9696 }
9697 }
9698
9699 if (task && group_leader &&
9700 group_leader->attr.inherit != attr.inherit) {
9701 err = -EINVAL;
9702 goto err_task;
9703 }
9704
9705 get_online_cpus();
9706
9707 if (task) {
9708 err = mutex_lock_interruptible(&task->signal->cred_guard_mutex);
9709 if (err)
9710 goto err_cpus;
9711
9712 /*
9713 * Reuse ptrace permission checks for now.
9714 *
9715 * We must hold cred_guard_mutex across this and any potential
9716 * perf_install_in_context() call for this new event to
9717 * serialize against exec() altering our credentials (and the
9718 * perf_event_exit_task() that could imply).
9719 */
9720 err = -EACCES;
9721 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS))
9722 goto err_cred;
9723 }
9724
9725 if (flags & PERF_FLAG_PID_CGROUP)
9726 cgroup_fd = pid;
9727
9728 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
9729 NULL, NULL, cgroup_fd);
9730 if (IS_ERR(event)) {
9731 err = PTR_ERR(event);
9732 goto err_cred;
9733 }
9734
9735 if (is_sampling_event(event)) {
9736 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
9737 err = -EOPNOTSUPP;
9738 goto err_alloc;
9739 }
9740 }
9741
9742 /*
9743 * Special case software events and allow them to be part of
9744 * any hardware group.
9745 */
9746 pmu = event->pmu;
9747
9748 if (attr.use_clockid) {
9749 err = perf_event_set_clock(event, attr.clockid);
9750 if (err)
9751 goto err_alloc;
9752 }
9753
9754 if (pmu->task_ctx_nr == perf_sw_context)
9755 event->event_caps |= PERF_EV_CAP_SOFTWARE;
9756
9757 if (group_leader &&
9758 (is_software_event(event) != is_software_event(group_leader))) {
9759 if (is_software_event(event)) {
9760 /*
9761 * If event and group_leader are not both a software
9762 * event, and event is, then group leader is not.
9763 *
9764 * Allow the addition of software events to !software
9765 * groups, this is safe because software events never
9766 * fail to schedule.
9767 */
9768 pmu = group_leader->pmu;
9769 } else if (is_software_event(group_leader) &&
9770 (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
9771 /*
9772 * In case the group is a pure software group, and we
9773 * try to add a hardware event, move the whole group to
9774 * the hardware context.
9775 */
9776 move_group = 1;
9777 }
9778 }
9779
9780 /*
9781 * Get the target context (task or percpu):
9782 */
9783 ctx = find_get_context(pmu, task, event);
9784 if (IS_ERR(ctx)) {
9785 err = PTR_ERR(ctx);
9786 goto err_alloc;
9787 }
9788
9789 if ((pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) && group_leader) {
9790 err = -EBUSY;
9791 goto err_context;
9792 }
9793
9794 /*
9795 * Look up the group leader (we will attach this event to it):
9796 */
9797 if (group_leader) {
9798 err = -EINVAL;
9799
9800 /*
9801 * Do not allow a recursive hierarchy (this new sibling
9802 * becoming part of another group-sibling):
9803 */
9804 if (group_leader->group_leader != group_leader)
9805 goto err_context;
9806
9807 /* All events in a group should have the same clock */
9808 if (group_leader->clock != event->clock)
9809 goto err_context;
9810
9811 /*
9812 * Do not allow to attach to a group in a different
9813 * task or CPU context:
9814 */
9815 if (move_group) {
9816 /*
9817 * Make sure we're both on the same task, or both
9818 * per-cpu events.
9819 */
9820 if (group_leader->ctx->task != ctx->task)
9821 goto err_context;
9822
9823 /*
9824 * Make sure we're both events for the same CPU;
9825 * grouping events for different CPUs is broken; since
9826 * you can never concurrently schedule them anyhow.
9827 */
9828 if (group_leader->cpu != event->cpu)
9829 goto err_context;
9830 } else {
9831 if (group_leader->ctx != ctx)
9832 goto err_context;
9833 }
9834
9835 /*
9836 * Only a group leader can be exclusive or pinned
9837 */
9838 if (attr.exclusive || attr.pinned)
9839 goto err_context;
9840 }
9841
9842 if (output_event) {
9843 err = perf_event_set_output(event, output_event);
9844 if (err)
9845 goto err_context;
9846 }
9847
9848 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
9849 f_flags);
9850 if (IS_ERR(event_file)) {
9851 err = PTR_ERR(event_file);
9852 event_file = NULL;
9853 goto err_context;
9854 }
9855
9856 if (move_group) {
9857 gctx = __perf_event_ctx_lock_double(group_leader, ctx);
9858
9859 if (gctx->task == TASK_TOMBSTONE) {
9860 err = -ESRCH;
9861 goto err_locked;
9862 }
9863
9864 /*
9865 * Check if we raced against another sys_perf_event_open() call
9866 * moving the software group underneath us.
9867 */
9868 if (!(group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
9869 /*
9870 * If someone moved the group out from under us, check
9871 * if this new event wound up on the same ctx, if so
9872 * its the regular !move_group case, otherwise fail.
9873 */
9874 if (gctx != ctx) {
9875 err = -EINVAL;
9876 goto err_locked;
9877 } else {
9878 perf_event_ctx_unlock(group_leader, gctx);
9879 move_group = 0;
9880 }
9881 }
9882 } else {
9883 mutex_lock(&ctx->mutex);
9884 }
9885
9886 if (ctx->task == TASK_TOMBSTONE) {
9887 err = -ESRCH;
9888 goto err_locked;
9889 }
9890
9891 if (!perf_event_validate_size(event)) {
9892 err = -E2BIG;
9893 goto err_locked;
9894 }
9895
9896 /*
9897 * Must be under the same ctx::mutex as perf_install_in_context(),
9898 * because we need to serialize with concurrent event creation.
9899 */
9900 if (!exclusive_event_installable(event, ctx)) {
9901 /* exclusive and group stuff are assumed mutually exclusive */
9902 WARN_ON_ONCE(move_group);
9903
9904 err = -EBUSY;
9905 goto err_locked;
9906 }
9907
9908 WARN_ON_ONCE(ctx->parent_ctx);
9909
9910 /*
9911 * This is the point on no return; we cannot fail hereafter. This is
9912 * where we start modifying current state.
9913 */
9914
9915 if (move_group) {
9916 /*
9917 * See perf_event_ctx_lock() for comments on the details
9918 * of swizzling perf_event::ctx.
9919 */
9920 perf_remove_from_context(group_leader, 0);
9921
9922 list_for_each_entry(sibling, &group_leader->sibling_list,
9923 group_entry) {
9924 perf_remove_from_context(sibling, 0);
9925 put_ctx(gctx);
9926 }
9927
9928 /*
9929 * Wait for everybody to stop referencing the events through
9930 * the old lists, before installing it on new lists.
9931 */
9932 synchronize_rcu();
9933
9934 /*
9935 * Install the group siblings before the group leader.
9936 *
9937 * Because a group leader will try and install the entire group
9938 * (through the sibling list, which is still in-tact), we can
9939 * end up with siblings installed in the wrong context.
9940 *
9941 * By installing siblings first we NO-OP because they're not
9942 * reachable through the group lists.
9943 */
9944 list_for_each_entry(sibling, &group_leader->sibling_list,
9945 group_entry) {
9946 perf_event__state_init(sibling);
9947 perf_install_in_context(ctx, sibling, sibling->cpu);
9948 get_ctx(ctx);
9949 }
9950
9951 /*
9952 * Removing from the context ends up with disabled
9953 * event. What we want here is event in the initial
9954 * startup state, ready to be add into new context.
9955 */
9956 perf_event__state_init(group_leader);
9957 perf_install_in_context(ctx, group_leader, group_leader->cpu);
9958 get_ctx(ctx);
9959
9960 /*
9961 * Now that all events are installed in @ctx, nothing
9962 * references @gctx anymore, so drop the last reference we have
9963 * on it.
9964 */
9965 put_ctx(gctx);
9966 }
9967
9968 /*
9969 * Precalculate sample_data sizes; do while holding ctx::mutex such
9970 * that we're serialized against further additions and before
9971 * perf_install_in_context() which is the point the event is active and
9972 * can use these values.
9973 */
9974 perf_event__header_size(event);
9975 perf_event__id_header_size(event);
9976
9977 event->owner = current;
9978
9979 perf_install_in_context(ctx, event, event->cpu);
9980 perf_unpin_context(ctx);
9981
9982 if (move_group)
9983 perf_event_ctx_unlock(group_leader, gctx);
9984 mutex_unlock(&ctx->mutex);
9985
9986 if (task) {
9987 mutex_unlock(&task->signal->cred_guard_mutex);
9988 put_task_struct(task);
9989 }
9990
9991 put_online_cpus();
9992
9993 mutex_lock(&current->perf_event_mutex);
9994 list_add_tail(&event->owner_entry, &current->perf_event_list);
9995 mutex_unlock(&current->perf_event_mutex);
9996
9997 /*
9998 * Drop the reference on the group_event after placing the
9999 * new event on the sibling_list. This ensures destruction
10000 * of the group leader will find the pointer to itself in
10001 * perf_group_detach().
10002 */
10003 fdput(group);
10004 fd_install(event_fd, event_file);
10005 return event_fd;
10006
10007 err_locked:
10008 if (move_group)
10009 perf_event_ctx_unlock(group_leader, gctx);
10010 mutex_unlock(&ctx->mutex);
10011 /* err_file: */
10012 fput(event_file);
10013 err_context:
10014 perf_unpin_context(ctx);
10015 put_ctx(ctx);
10016 err_alloc:
10017 /*
10018 * If event_file is set, the fput() above will have called ->release()
10019 * and that will take care of freeing the event.
10020 */
10021 if (!event_file)
10022 free_event(event);
10023 err_cred:
10024 if (task)
10025 mutex_unlock(&task->signal->cred_guard_mutex);
10026 err_cpus:
10027 put_online_cpus();
10028 err_task:
10029 if (task)
10030 put_task_struct(task);
10031 err_group_fd:
10032 fdput(group);
10033 err_fd:
10034 put_unused_fd(event_fd);
10035 return err;
10036 }
10037
10038 /**
10039 * perf_event_create_kernel_counter
10040 *
10041 * @attr: attributes of the counter to create
10042 * @cpu: cpu in which the counter is bound
10043 * @task: task to profile (NULL for percpu)
10044 */
10045 struct perf_event *
10046 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
10047 struct task_struct *task,
10048 perf_overflow_handler_t overflow_handler,
10049 void *context)
10050 {
10051 struct perf_event_context *ctx;
10052 struct perf_event *event;
10053 int err;
10054
10055 /*
10056 * Get the target context (task or percpu):
10057 */
10058
10059 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
10060 overflow_handler, context, -1);
10061 if (IS_ERR(event)) {
10062 err = PTR_ERR(event);
10063 goto err;
10064 }
10065
10066 /* Mark owner so we could distinguish it from user events. */
10067 event->owner = TASK_TOMBSTONE;
10068
10069 ctx = find_get_context(event->pmu, task, event);
10070 if (IS_ERR(ctx)) {
10071 err = PTR_ERR(ctx);
10072 goto err_free;
10073 }
10074
10075 WARN_ON_ONCE(ctx->parent_ctx);
10076 mutex_lock(&ctx->mutex);
10077 if (ctx->task == TASK_TOMBSTONE) {
10078 err = -ESRCH;
10079 goto err_unlock;
10080 }
10081
10082 if (!exclusive_event_installable(event, ctx)) {
10083 err = -EBUSY;
10084 goto err_unlock;
10085 }
10086
10087 perf_install_in_context(ctx, event, cpu);
10088 perf_unpin_context(ctx);
10089 mutex_unlock(&ctx->mutex);
10090
10091 return event;
10092
10093 err_unlock:
10094 mutex_unlock(&ctx->mutex);
10095 perf_unpin_context(ctx);
10096 put_ctx(ctx);
10097 err_free:
10098 free_event(event);
10099 err:
10100 return ERR_PTR(err);
10101 }
10102 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
10103
10104 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
10105 {
10106 struct perf_event_context *src_ctx;
10107 struct perf_event_context *dst_ctx;
10108 struct perf_event *event, *tmp;
10109 LIST_HEAD(events);
10110
10111 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
10112 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
10113
10114 /*
10115 * See perf_event_ctx_lock() for comments on the details
10116 * of swizzling perf_event::ctx.
10117 */
10118 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
10119 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
10120 event_entry) {
10121 perf_remove_from_context(event, 0);
10122 unaccount_event_cpu(event, src_cpu);
10123 put_ctx(src_ctx);
10124 list_add(&event->migrate_entry, &events);
10125 }
10126
10127 /*
10128 * Wait for the events to quiesce before re-instating them.
10129 */
10130 synchronize_rcu();
10131
10132 /*
10133 * Re-instate events in 2 passes.
10134 *
10135 * Skip over group leaders and only install siblings on this first
10136 * pass, siblings will not get enabled without a leader, however a
10137 * leader will enable its siblings, even if those are still on the old
10138 * context.
10139 */
10140 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
10141 if (event->group_leader == event)
10142 continue;
10143
10144 list_del(&event->migrate_entry);
10145 if (event->state >= PERF_EVENT_STATE_OFF)
10146 event->state = PERF_EVENT_STATE_INACTIVE;
10147 account_event_cpu(event, dst_cpu);
10148 perf_install_in_context(dst_ctx, event, dst_cpu);
10149 get_ctx(dst_ctx);
10150 }
10151
10152 /*
10153 * Once all the siblings are setup properly, install the group leaders
10154 * to make it go.
10155 */
10156 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
10157 list_del(&event->migrate_entry);
10158 if (event->state >= PERF_EVENT_STATE_OFF)
10159 event->state = PERF_EVENT_STATE_INACTIVE;
10160 account_event_cpu(event, dst_cpu);
10161 perf_install_in_context(dst_ctx, event, dst_cpu);
10162 get_ctx(dst_ctx);
10163 }
10164 mutex_unlock(&dst_ctx->mutex);
10165 mutex_unlock(&src_ctx->mutex);
10166 }
10167 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
10168
10169 static void sync_child_event(struct perf_event *child_event,
10170 struct task_struct *child)
10171 {
10172 struct perf_event *parent_event = child_event->parent;
10173 u64 child_val;
10174
10175 if (child_event->attr.inherit_stat)
10176 perf_event_read_event(child_event, child);
10177
10178 child_val = perf_event_count(child_event);
10179
10180 /*
10181 * Add back the child's count to the parent's count:
10182 */
10183 atomic64_add(child_val, &parent_event->child_count);
10184 atomic64_add(child_event->total_time_enabled,
10185 &parent_event->child_total_time_enabled);
10186 atomic64_add(child_event->total_time_running,
10187 &parent_event->child_total_time_running);
10188 }
10189
10190 static void
10191 perf_event_exit_event(struct perf_event *child_event,
10192 struct perf_event_context *child_ctx,
10193 struct task_struct *child)
10194 {
10195 struct perf_event *parent_event = child_event->parent;
10196
10197 /*
10198 * Do not destroy the 'original' grouping; because of the context
10199 * switch optimization the original events could've ended up in a
10200 * random child task.
10201 *
10202 * If we were to destroy the original group, all group related
10203 * operations would cease to function properly after this random
10204 * child dies.
10205 *
10206 * Do destroy all inherited groups, we don't care about those
10207 * and being thorough is better.
10208 */
10209 raw_spin_lock_irq(&child_ctx->lock);
10210 WARN_ON_ONCE(child_ctx->is_active);
10211
10212 if (parent_event)
10213 perf_group_detach(child_event);
10214 list_del_event(child_event, child_ctx);
10215 child_event->state = PERF_EVENT_STATE_EXIT; /* is_event_hup() */
10216 raw_spin_unlock_irq(&child_ctx->lock);
10217
10218 /*
10219 * Parent events are governed by their filedesc, retain them.
10220 */
10221 if (!parent_event) {
10222 perf_event_wakeup(child_event);
10223 return;
10224 }
10225 /*
10226 * Child events can be cleaned up.
10227 */
10228
10229 sync_child_event(child_event, child);
10230
10231 /*
10232 * Remove this event from the parent's list
10233 */
10234 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
10235 mutex_lock(&parent_event->child_mutex);
10236 list_del_init(&child_event->child_list);
10237 mutex_unlock(&parent_event->child_mutex);
10238
10239 /*
10240 * Kick perf_poll() for is_event_hup().
10241 */
10242 perf_event_wakeup(parent_event);
10243 free_event(child_event);
10244 put_event(parent_event);
10245 }
10246
10247 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
10248 {
10249 struct perf_event_context *child_ctx, *clone_ctx = NULL;
10250 struct perf_event *child_event, *next;
10251
10252 WARN_ON_ONCE(child != current);
10253
10254 child_ctx = perf_pin_task_context(child, ctxn);
10255 if (!child_ctx)
10256 return;
10257
10258 /*
10259 * In order to reduce the amount of tricky in ctx tear-down, we hold
10260 * ctx::mutex over the entire thing. This serializes against almost
10261 * everything that wants to access the ctx.
10262 *
10263 * The exception is sys_perf_event_open() /
10264 * perf_event_create_kernel_count() which does find_get_context()
10265 * without ctx::mutex (it cannot because of the move_group double mutex
10266 * lock thing). See the comments in perf_install_in_context().
10267 */
10268 mutex_lock(&child_ctx->mutex);
10269
10270 /*
10271 * In a single ctx::lock section, de-schedule the events and detach the
10272 * context from the task such that we cannot ever get it scheduled back
10273 * in.
10274 */
10275 raw_spin_lock_irq(&child_ctx->lock);
10276 task_ctx_sched_out(__get_cpu_context(child_ctx), child_ctx);
10277
10278 /*
10279 * Now that the context is inactive, destroy the task <-> ctx relation
10280 * and mark the context dead.
10281 */
10282 RCU_INIT_POINTER(child->perf_event_ctxp[ctxn], NULL);
10283 put_ctx(child_ctx); /* cannot be last */
10284 WRITE_ONCE(child_ctx->task, TASK_TOMBSTONE);
10285 put_task_struct(current); /* cannot be last */
10286
10287 clone_ctx = unclone_ctx(child_ctx);
10288 raw_spin_unlock_irq(&child_ctx->lock);
10289
10290 if (clone_ctx)
10291 put_ctx(clone_ctx);
10292
10293 /*
10294 * Report the task dead after unscheduling the events so that we
10295 * won't get any samples after PERF_RECORD_EXIT. We can however still
10296 * get a few PERF_RECORD_READ events.
10297 */
10298 perf_event_task(child, child_ctx, 0);
10299
10300 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
10301 perf_event_exit_event(child_event, child_ctx, child);
10302
10303 mutex_unlock(&child_ctx->mutex);
10304
10305 put_ctx(child_ctx);
10306 }
10307
10308 /*
10309 * When a child task exits, feed back event values to parent events.
10310 *
10311 * Can be called with cred_guard_mutex held when called from
10312 * install_exec_creds().
10313 */
10314 void perf_event_exit_task(struct task_struct *child)
10315 {
10316 struct perf_event *event, *tmp;
10317 int ctxn;
10318
10319 mutex_lock(&child->perf_event_mutex);
10320 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
10321 owner_entry) {
10322 list_del_init(&event->owner_entry);
10323
10324 /*
10325 * Ensure the list deletion is visible before we clear
10326 * the owner, closes a race against perf_release() where
10327 * we need to serialize on the owner->perf_event_mutex.
10328 */
10329 smp_store_release(&event->owner, NULL);
10330 }
10331 mutex_unlock(&child->perf_event_mutex);
10332
10333 for_each_task_context_nr(ctxn)
10334 perf_event_exit_task_context(child, ctxn);
10335
10336 /*
10337 * The perf_event_exit_task_context calls perf_event_task
10338 * with child's task_ctx, which generates EXIT events for
10339 * child contexts and sets child->perf_event_ctxp[] to NULL.
10340 * At this point we need to send EXIT events to cpu contexts.
10341 */
10342 perf_event_task(child, NULL, 0);
10343 }
10344
10345 static void perf_free_event(struct perf_event *event,
10346 struct perf_event_context *ctx)
10347 {
10348 struct perf_event *parent = event->parent;
10349
10350 if (WARN_ON_ONCE(!parent))
10351 return;
10352
10353 mutex_lock(&parent->child_mutex);
10354 list_del_init(&event->child_list);
10355 mutex_unlock(&parent->child_mutex);
10356
10357 put_event(parent);
10358
10359 raw_spin_lock_irq(&ctx->lock);
10360 perf_group_detach(event);
10361 list_del_event(event, ctx);
10362 raw_spin_unlock_irq(&ctx->lock);
10363 free_event(event);
10364 }
10365
10366 /*
10367 * Free an unexposed, unused context as created by inheritance by
10368 * perf_event_init_task below, used by fork() in case of fail.
10369 *
10370 * Not all locks are strictly required, but take them anyway to be nice and
10371 * help out with the lockdep assertions.
10372 */
10373 void perf_event_free_task(struct task_struct *task)
10374 {
10375 struct perf_event_context *ctx;
10376 struct perf_event *event, *tmp;
10377 int ctxn;
10378
10379 for_each_task_context_nr(ctxn) {
10380 ctx = task->perf_event_ctxp[ctxn];
10381 if (!ctx)
10382 continue;
10383
10384 mutex_lock(&ctx->mutex);
10385 raw_spin_lock_irq(&ctx->lock);
10386 /*
10387 * Destroy the task <-> ctx relation and mark the context dead.
10388 *
10389 * This is important because even though the task hasn't been
10390 * exposed yet the context has been (through child_list).
10391 */
10392 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], NULL);
10393 WRITE_ONCE(ctx->task, TASK_TOMBSTONE);
10394 put_task_struct(task); /* cannot be last */
10395 raw_spin_unlock_irq(&ctx->lock);
10396 again:
10397 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups,
10398 group_entry)
10399 perf_free_event(event, ctx);
10400
10401 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
10402 group_entry)
10403 perf_free_event(event, ctx);
10404
10405 if (!list_empty(&ctx->pinned_groups) ||
10406 !list_empty(&ctx->flexible_groups))
10407 goto again;
10408
10409 mutex_unlock(&ctx->mutex);
10410
10411 put_ctx(ctx);
10412 }
10413 }
10414
10415 void perf_event_delayed_put(struct task_struct *task)
10416 {
10417 int ctxn;
10418
10419 for_each_task_context_nr(ctxn)
10420 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
10421 }
10422
10423 struct file *perf_event_get(unsigned int fd)
10424 {
10425 struct file *file;
10426
10427 file = fget_raw(fd);
10428 if (!file)
10429 return ERR_PTR(-EBADF);
10430
10431 if (file->f_op != &perf_fops) {
10432 fput(file);
10433 return ERR_PTR(-EBADF);
10434 }
10435
10436 return file;
10437 }
10438
10439 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
10440 {
10441 if (!event)
10442 return ERR_PTR(-EINVAL);
10443
10444 return &event->attr;
10445 }
10446
10447 /*
10448 * inherit a event from parent task to child task:
10449 */
10450 static struct perf_event *
10451 inherit_event(struct perf_event *parent_event,
10452 struct task_struct *parent,
10453 struct perf_event_context *parent_ctx,
10454 struct task_struct *child,
10455 struct perf_event *group_leader,
10456 struct perf_event_context *child_ctx)
10457 {
10458 enum perf_event_active_state parent_state = parent_event->state;
10459 struct perf_event *child_event;
10460 unsigned long flags;
10461
10462 /*
10463 * Instead of creating recursive hierarchies of events,
10464 * we link inherited events back to the original parent,
10465 * which has a filp for sure, which we use as the reference
10466 * count:
10467 */
10468 if (parent_event->parent)
10469 parent_event = parent_event->parent;
10470
10471 child_event = perf_event_alloc(&parent_event->attr,
10472 parent_event->cpu,
10473 child,
10474 group_leader, parent_event,
10475 NULL, NULL, -1);
10476 if (IS_ERR(child_event))
10477 return child_event;
10478
10479 /*
10480 * is_orphaned_event() and list_add_tail(&parent_event->child_list)
10481 * must be under the same lock in order to serialize against
10482 * perf_event_release_kernel(), such that either we must observe
10483 * is_orphaned_event() or they will observe us on the child_list.
10484 */
10485 mutex_lock(&parent_event->child_mutex);
10486 if (is_orphaned_event(parent_event) ||
10487 !atomic_long_inc_not_zero(&parent_event->refcount)) {
10488 mutex_unlock(&parent_event->child_mutex);
10489 free_event(child_event);
10490 return NULL;
10491 }
10492
10493 get_ctx(child_ctx);
10494
10495 /*
10496 * Make the child state follow the state of the parent event,
10497 * not its attr.disabled bit. We hold the parent's mutex,
10498 * so we won't race with perf_event_{en, dis}able_family.
10499 */
10500 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
10501 child_event->state = PERF_EVENT_STATE_INACTIVE;
10502 else
10503 child_event->state = PERF_EVENT_STATE_OFF;
10504
10505 if (parent_event->attr.freq) {
10506 u64 sample_period = parent_event->hw.sample_period;
10507 struct hw_perf_event *hwc = &child_event->hw;
10508
10509 hwc->sample_period = sample_period;
10510 hwc->last_period = sample_period;
10511
10512 local64_set(&hwc->period_left, sample_period);
10513 }
10514
10515 child_event->ctx = child_ctx;
10516 child_event->overflow_handler = parent_event->overflow_handler;
10517 child_event->overflow_handler_context
10518 = parent_event->overflow_handler_context;
10519
10520 /*
10521 * Precalculate sample_data sizes
10522 */
10523 perf_event__header_size(child_event);
10524 perf_event__id_header_size(child_event);
10525
10526 /*
10527 * Link it up in the child's context:
10528 */
10529 raw_spin_lock_irqsave(&child_ctx->lock, flags);
10530 add_event_to_ctx(child_event, child_ctx);
10531 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
10532
10533 /*
10534 * Link this into the parent event's child list
10535 */
10536 list_add_tail(&child_event->child_list, &parent_event->child_list);
10537 mutex_unlock(&parent_event->child_mutex);
10538
10539 return child_event;
10540 }
10541
10542 static int inherit_group(struct perf_event *parent_event,
10543 struct task_struct *parent,
10544 struct perf_event_context *parent_ctx,
10545 struct task_struct *child,
10546 struct perf_event_context *child_ctx)
10547 {
10548 struct perf_event *leader;
10549 struct perf_event *sub;
10550 struct perf_event *child_ctr;
10551
10552 leader = inherit_event(parent_event, parent, parent_ctx,
10553 child, NULL, child_ctx);
10554 if (IS_ERR(leader))
10555 return PTR_ERR(leader);
10556 list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
10557 child_ctr = inherit_event(sub, parent, parent_ctx,
10558 child, leader, child_ctx);
10559 if (IS_ERR(child_ctr))
10560 return PTR_ERR(child_ctr);
10561 }
10562 return 0;
10563 }
10564
10565 static int
10566 inherit_task_group(struct perf_event *event, struct task_struct *parent,
10567 struct perf_event_context *parent_ctx,
10568 struct task_struct *child, int ctxn,
10569 int *inherited_all)
10570 {
10571 int ret;
10572 struct perf_event_context *child_ctx;
10573
10574 if (!event->attr.inherit) {
10575 *inherited_all = 0;
10576 return 0;
10577 }
10578
10579 child_ctx = child->perf_event_ctxp[ctxn];
10580 if (!child_ctx) {
10581 /*
10582 * This is executed from the parent task context, so
10583 * inherit events that have been marked for cloning.
10584 * First allocate and initialize a context for the
10585 * child.
10586 */
10587
10588 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
10589 if (!child_ctx)
10590 return -ENOMEM;
10591
10592 child->perf_event_ctxp[ctxn] = child_ctx;
10593 }
10594
10595 ret = inherit_group(event, parent, parent_ctx,
10596 child, child_ctx);
10597
10598 if (ret)
10599 *inherited_all = 0;
10600
10601 return ret;
10602 }
10603
10604 /*
10605 * Initialize the perf_event context in task_struct
10606 */
10607 static int perf_event_init_context(struct task_struct *child, int ctxn)
10608 {
10609 struct perf_event_context *child_ctx, *parent_ctx;
10610 struct perf_event_context *cloned_ctx;
10611 struct perf_event *event;
10612 struct task_struct *parent = current;
10613 int inherited_all = 1;
10614 unsigned long flags;
10615 int ret = 0;
10616
10617 if (likely(!parent->perf_event_ctxp[ctxn]))
10618 return 0;
10619
10620 /*
10621 * If the parent's context is a clone, pin it so it won't get
10622 * swapped under us.
10623 */
10624 parent_ctx = perf_pin_task_context(parent, ctxn);
10625 if (!parent_ctx)
10626 return 0;
10627
10628 /*
10629 * No need to check if parent_ctx != NULL here; since we saw
10630 * it non-NULL earlier, the only reason for it to become NULL
10631 * is if we exit, and since we're currently in the middle of
10632 * a fork we can't be exiting at the same time.
10633 */
10634
10635 /*
10636 * Lock the parent list. No need to lock the child - not PID
10637 * hashed yet and not running, so nobody can access it.
10638 */
10639 mutex_lock(&parent_ctx->mutex);
10640
10641 /*
10642 * We dont have to disable NMIs - we are only looking at
10643 * the list, not manipulating it:
10644 */
10645 list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
10646 ret = inherit_task_group(event, parent, parent_ctx,
10647 child, ctxn, &inherited_all);
10648 if (ret)
10649 break;
10650 }
10651
10652 /*
10653 * We can't hold ctx->lock when iterating the ->flexible_group list due
10654 * to allocations, but we need to prevent rotation because
10655 * rotate_ctx() will change the list from interrupt context.
10656 */
10657 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
10658 parent_ctx->rotate_disable = 1;
10659 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
10660
10661 list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
10662 ret = inherit_task_group(event, parent, parent_ctx,
10663 child, ctxn, &inherited_all);
10664 if (ret)
10665 break;
10666 }
10667
10668 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
10669 parent_ctx->rotate_disable = 0;
10670
10671 child_ctx = child->perf_event_ctxp[ctxn];
10672
10673 if (child_ctx && inherited_all) {
10674 /*
10675 * Mark the child context as a clone of the parent
10676 * context, or of whatever the parent is a clone of.
10677 *
10678 * Note that if the parent is a clone, the holding of
10679 * parent_ctx->lock avoids it from being uncloned.
10680 */
10681 cloned_ctx = parent_ctx->parent_ctx;
10682 if (cloned_ctx) {
10683 child_ctx->parent_ctx = cloned_ctx;
10684 child_ctx->parent_gen = parent_ctx->parent_gen;
10685 } else {
10686 child_ctx->parent_ctx = parent_ctx;
10687 child_ctx->parent_gen = parent_ctx->generation;
10688 }
10689 get_ctx(child_ctx->parent_ctx);
10690 }
10691
10692 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
10693 mutex_unlock(&parent_ctx->mutex);
10694
10695 perf_unpin_context(parent_ctx);
10696 put_ctx(parent_ctx);
10697
10698 return ret;
10699 }
10700
10701 /*
10702 * Initialize the perf_event context in task_struct
10703 */
10704 int perf_event_init_task(struct task_struct *child)
10705 {
10706 int ctxn, ret;
10707
10708 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
10709 mutex_init(&child->perf_event_mutex);
10710 INIT_LIST_HEAD(&child->perf_event_list);
10711
10712 for_each_task_context_nr(ctxn) {
10713 ret = perf_event_init_context(child, ctxn);
10714 if (ret) {
10715 perf_event_free_task(child);
10716 return ret;
10717 }
10718 }
10719
10720 return 0;
10721 }
10722
10723 static void __init perf_event_init_all_cpus(void)
10724 {
10725 struct swevent_htable *swhash;
10726 int cpu;
10727
10728 for_each_possible_cpu(cpu) {
10729 swhash = &per_cpu(swevent_htable, cpu);
10730 mutex_init(&swhash->hlist_mutex);
10731 INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
10732
10733 INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu));
10734 raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu));
10735
10736 INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu));
10737 }
10738 }
10739
10740 int perf_event_init_cpu(unsigned int cpu)
10741 {
10742 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
10743
10744 mutex_lock(&swhash->hlist_mutex);
10745 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
10746 struct swevent_hlist *hlist;
10747
10748 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
10749 WARN_ON(!hlist);
10750 rcu_assign_pointer(swhash->swevent_hlist, hlist);
10751 }
10752 mutex_unlock(&swhash->hlist_mutex);
10753 return 0;
10754 }
10755
10756 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
10757 static void __perf_event_exit_context(void *__info)
10758 {
10759 struct perf_event_context *ctx = __info;
10760 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
10761 struct perf_event *event;
10762
10763 raw_spin_lock(&ctx->lock);
10764 list_for_each_entry(event, &ctx->event_list, event_entry)
10765 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
10766 raw_spin_unlock(&ctx->lock);
10767 }
10768
10769 static void perf_event_exit_cpu_context(int cpu)
10770 {
10771 struct perf_event_context *ctx;
10772 struct pmu *pmu;
10773 int idx;
10774
10775 idx = srcu_read_lock(&pmus_srcu);
10776 list_for_each_entry_rcu(pmu, &pmus, entry) {
10777 ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx;
10778
10779 mutex_lock(&ctx->mutex);
10780 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
10781 mutex_unlock(&ctx->mutex);
10782 }
10783 srcu_read_unlock(&pmus_srcu, idx);
10784 }
10785 #else
10786
10787 static void perf_event_exit_cpu_context(int cpu) { }
10788
10789 #endif
10790
10791 int perf_event_exit_cpu(unsigned int cpu)
10792 {
10793 perf_event_exit_cpu_context(cpu);
10794 return 0;
10795 }
10796
10797 static int
10798 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
10799 {
10800 int cpu;
10801
10802 for_each_online_cpu(cpu)
10803 perf_event_exit_cpu(cpu);
10804
10805 return NOTIFY_OK;
10806 }
10807
10808 /*
10809 * Run the perf reboot notifier at the very last possible moment so that
10810 * the generic watchdog code runs as long as possible.
10811 */
10812 static struct notifier_block perf_reboot_notifier = {
10813 .notifier_call = perf_reboot,
10814 .priority = INT_MIN,
10815 };
10816
10817 void __init perf_event_init(void)
10818 {
10819 int ret;
10820
10821 idr_init(&pmu_idr);
10822
10823 perf_event_init_all_cpus();
10824 init_srcu_struct(&pmus_srcu);
10825 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
10826 perf_pmu_register(&perf_cpu_clock, NULL, -1);
10827 perf_pmu_register(&perf_task_clock, NULL, -1);
10828 perf_tp_register();
10829 perf_event_init_cpu(smp_processor_id());
10830 register_reboot_notifier(&perf_reboot_notifier);
10831
10832 ret = init_hw_breakpoint();
10833 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
10834
10835 /*
10836 * Build time assertion that we keep the data_head at the intended
10837 * location. IOW, validation we got the __reserved[] size right.
10838 */
10839 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
10840 != 1024);
10841 }
10842
10843 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
10844 char *page)
10845 {
10846 struct perf_pmu_events_attr *pmu_attr =
10847 container_of(attr, struct perf_pmu_events_attr, attr);
10848
10849 if (pmu_attr->event_str)
10850 return sprintf(page, "%s\n", pmu_attr->event_str);
10851
10852 return 0;
10853 }
10854 EXPORT_SYMBOL_GPL(perf_event_sysfs_show);
10855
10856 static int __init perf_event_sysfs_init(void)
10857 {
10858 struct pmu *pmu;
10859 int ret;
10860
10861 mutex_lock(&pmus_lock);
10862
10863 ret = bus_register(&pmu_bus);
10864 if (ret)
10865 goto unlock;
10866
10867 list_for_each_entry(pmu, &pmus, entry) {
10868 if (!pmu->name || pmu->type < 0)
10869 continue;
10870
10871 ret = pmu_dev_alloc(pmu);
10872 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
10873 }
10874 pmu_bus_running = 1;
10875 ret = 0;
10876
10877 unlock:
10878 mutex_unlock(&pmus_lock);
10879
10880 return ret;
10881 }
10882 device_initcall(perf_event_sysfs_init);
10883
10884 #ifdef CONFIG_CGROUP_PERF
10885 static struct cgroup_subsys_state *
10886 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
10887 {
10888 struct perf_cgroup *jc;
10889
10890 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
10891 if (!jc)
10892 return ERR_PTR(-ENOMEM);
10893
10894 jc->info = alloc_percpu(struct perf_cgroup_info);
10895 if (!jc->info) {
10896 kfree(jc);
10897 return ERR_PTR(-ENOMEM);
10898 }
10899
10900 return &jc->css;
10901 }
10902
10903 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
10904 {
10905 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
10906
10907 free_percpu(jc->info);
10908 kfree(jc);
10909 }
10910
10911 static int __perf_cgroup_move(void *info)
10912 {
10913 struct task_struct *task = info;
10914 rcu_read_lock();
10915 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
10916 rcu_read_unlock();
10917 return 0;
10918 }
10919
10920 static void perf_cgroup_attach(struct cgroup_taskset *tset)
10921 {
10922 struct task_struct *task;
10923 struct cgroup_subsys_state *css;
10924
10925 cgroup_taskset_for_each(task, css, tset)
10926 task_function_call(task, __perf_cgroup_move, task);
10927 }
10928
10929 struct cgroup_subsys perf_event_cgrp_subsys = {
10930 .css_alloc = perf_cgroup_css_alloc,
10931 .css_free = perf_cgroup_css_free,
10932 .attach = perf_cgroup_attach,
10933 };
10934 #endif /* CONFIG_CGROUP_PERF */