1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * Performance events core code:
4 *
5 * Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
6 * Copyright (C) 2008-2011 Red Hat, Inc., Ingo Molnar
7 * Copyright (C) 2008-2011 Red Hat, Inc., Peter Zijlstra
8 * Copyright © 2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
9 */
10
11 #include <linux/fs.h>
12 #include <linux/mm.h>
13 #include <linux/cpu.h>
14 #include <linux/smp.h>
15 #include <linux/idr.h>
16 #include <linux/file.h>
17 #include <linux/poll.h>
18 #include <linux/slab.h>
19 #include <linux/hash.h>
20 #include <linux/tick.h>
21 #include <linux/sysfs.h>
22 #include <linux/dcache.h>
23 #include <linux/percpu.h>
24 #include <linux/ptrace.h>
25 #include <linux/reboot.h>
26 #include <linux/vmstat.h>
27 #include <linux/device.h>
28 #include <linux/export.h>
29 #include <linux/vmalloc.h>
30 #include <linux/hardirq.h>
31 #include <linux/hugetlb.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 #include <linux/page_size_compat.h>
50 #include <linux/sched/clock.h>
51 #include <linux/sched/mm.h>
52 #include <linux/proc_ns.h>
53 #include <linux/mount.h>
54 #include <linux/min_heap.h>
55 #include <linux/highmem.h>
56 #include <linux/pgtable.h>
57 #include <linux/buildid.h>
58 #include <linux/task_work.h>
59
60 #include "internal.h"
61
62 #include <asm/irq_regs.h>
63
64 typedef int (*remote_function_f)(void *);
65
66 struct remote_function_call {
67 struct task_struct *p;
68 remote_function_f func;
69 void *info;
70 int ret;
71 };
72
remote_function(void * data)73 static void remote_function(void *data)
74 {
75 struct remote_function_call *tfc = data;
76 struct task_struct *p = tfc->p;
77
78 if (p) {
79 /* -EAGAIN */
80 if (task_cpu(p) != smp_processor_id())
81 return;
82
83 /*
84 * Now that we're on right CPU with IRQs disabled, we can test
85 * if we hit the right task without races.
86 */
87
88 tfc->ret = -ESRCH; /* No such (running) process */
89 if (p != current)
90 return;
91 }
92
93 tfc->ret = tfc->func(tfc->info);
94 }
95
96 /**
97 * task_function_call - call a function on the cpu on which a task runs
98 * @p: the task to evaluate
99 * @func: the function to be called
100 * @info: the function call argument
101 *
102 * Calls the function @func when the task is currently running. This might
103 * be on the current CPU, which just calls the function directly. This will
104 * retry due to any failures in smp_call_function_single(), such as if the
105 * task_cpu() goes offline concurrently.
106 *
107 * returns @func return value or -ESRCH or -ENXIO when the process isn't running
108 */
109 static int
task_function_call(struct task_struct * p,remote_function_f func,void * info)110 task_function_call(struct task_struct *p, remote_function_f func, void *info)
111 {
112 struct remote_function_call data = {
113 .p = p,
114 .func = func,
115 .info = info,
116 .ret = -EAGAIN,
117 };
118 int ret;
119
120 for (;;) {
121 ret = smp_call_function_single(task_cpu(p), remote_function,
122 &data, 1);
123 if (!ret)
124 ret = data.ret;
125
126 if (ret != -EAGAIN)
127 break;
128
129 cond_resched();
130 }
131
132 return ret;
133 }
134
135 /**
136 * cpu_function_call - call a function on the cpu
137 * @cpu: target cpu to queue this function
138 * @func: the function to be called
139 * @info: the function call argument
140 *
141 * Calls the function @func on the remote cpu.
142 *
143 * returns: @func return value or -ENXIO when the cpu is offline
144 */
cpu_function_call(int cpu,remote_function_f func,void * info)145 static int cpu_function_call(int cpu, remote_function_f func, void *info)
146 {
147 struct remote_function_call data = {
148 .p = NULL,
149 .func = func,
150 .info = info,
151 .ret = -ENXIO, /* No such CPU */
152 };
153
154 smp_call_function_single(cpu, remote_function, &data, 1);
155
156 return data.ret;
157 }
158
159 enum event_type_t {
160 EVENT_FLEXIBLE = 0x01,
161 EVENT_PINNED = 0x02,
162 EVENT_TIME = 0x04,
163 EVENT_FROZEN = 0x08,
164 /* see ctx_resched() for details */
165 EVENT_CPU = 0x10,
166 EVENT_CGROUP = 0x20,
167
168 /* compound helpers */
169 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
170 EVENT_TIME_FROZEN = EVENT_TIME | EVENT_FROZEN,
171 };
172
__perf_ctx_lock(struct perf_event_context * ctx)173 static inline void __perf_ctx_lock(struct perf_event_context *ctx)
174 {
175 raw_spin_lock(&ctx->lock);
176 WARN_ON_ONCE(ctx->is_active & EVENT_FROZEN);
177 }
178
perf_ctx_lock(struct perf_cpu_context * cpuctx,struct perf_event_context * ctx)179 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
180 struct perf_event_context *ctx)
181 {
182 __perf_ctx_lock(&cpuctx->ctx);
183 if (ctx)
184 __perf_ctx_lock(ctx);
185 }
186
__perf_ctx_unlock(struct perf_event_context * ctx)187 static inline void __perf_ctx_unlock(struct perf_event_context *ctx)
188 {
189 /*
190 * If ctx_sched_in() didn't again set any ALL flags, clean up
191 * after ctx_sched_out() by clearing is_active.
192 */
193 if (ctx->is_active & EVENT_FROZEN) {
194 if (!(ctx->is_active & EVENT_ALL))
195 ctx->is_active = 0;
196 else
197 ctx->is_active &= ~EVENT_FROZEN;
198 }
199 raw_spin_unlock(&ctx->lock);
200 }
201
perf_ctx_unlock(struct perf_cpu_context * cpuctx,struct perf_event_context * ctx)202 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
203 struct perf_event_context *ctx)
204 {
205 if (ctx)
206 __perf_ctx_unlock(ctx);
207 __perf_ctx_unlock(&cpuctx->ctx);
208 }
209
210 typedef struct {
211 struct perf_cpu_context *cpuctx;
212 struct perf_event_context *ctx;
213 } class_perf_ctx_lock_t;
214
class_perf_ctx_lock_destructor(class_perf_ctx_lock_t * _T)215 static inline void class_perf_ctx_lock_destructor(class_perf_ctx_lock_t *_T)
216 { perf_ctx_unlock(_T->cpuctx, _T->ctx); }
217
218 static inline class_perf_ctx_lock_t
class_perf_ctx_lock_constructor(struct perf_cpu_context * cpuctx,struct perf_event_context * ctx)219 class_perf_ctx_lock_constructor(struct perf_cpu_context *cpuctx,
220 struct perf_event_context *ctx)
221 { perf_ctx_lock(cpuctx, ctx); return (class_perf_ctx_lock_t){ cpuctx, ctx }; }
222
223 #define TASK_TOMBSTONE ((void *)-1L)
224
is_kernel_event(struct perf_event * event)225 static bool is_kernel_event(struct perf_event *event)
226 {
227 return READ_ONCE(event->owner) == TASK_TOMBSTONE;
228 }
229
230 static DEFINE_PER_CPU(struct perf_cpu_context, perf_cpu_context);
231
perf_cpu_task_ctx(void)232 struct perf_event_context *perf_cpu_task_ctx(void)
233 {
234 lockdep_assert_irqs_disabled();
235 return this_cpu_ptr(&perf_cpu_context)->task_ctx;
236 }
237
238 /*
239 * On task ctx scheduling...
240 *
241 * When !ctx->nr_events a task context will not be scheduled. This means
242 * we can disable the scheduler hooks (for performance) without leaving
243 * pending task ctx state.
244 *
245 * This however results in two special cases:
246 *
247 * - removing the last event from a task ctx; this is relatively straight
248 * forward and is done in __perf_remove_from_context.
249 *
250 * - adding the first event to a task ctx; this is tricky because we cannot
251 * rely on ctx->is_active and therefore cannot use event_function_call().
252 * See perf_install_in_context().
253 *
254 * If ctx->nr_events, then ctx->is_active and cpuctx->task_ctx are set.
255 */
256
257 typedef void (*event_f)(struct perf_event *, struct perf_cpu_context *,
258 struct perf_event_context *, void *);
259
260 struct event_function_struct {
261 struct perf_event *event;
262 event_f func;
263 void *data;
264 };
265
event_function(void * info)266 static int event_function(void *info)
267 {
268 struct event_function_struct *efs = info;
269 struct perf_event *event = efs->event;
270 struct perf_event_context *ctx = event->ctx;
271 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
272 struct perf_event_context *task_ctx = cpuctx->task_ctx;
273 int ret = 0;
274
275 lockdep_assert_irqs_disabled();
276
277 perf_ctx_lock(cpuctx, task_ctx);
278 /*
279 * Since we do the IPI call without holding ctx->lock things can have
280 * changed, double check we hit the task we set out to hit.
281 */
282 if (ctx->task) {
283 if (ctx->task != current) {
284 ret = -ESRCH;
285 goto unlock;
286 }
287
288 /*
289 * We only use event_function_call() on established contexts,
290 * and event_function() is only ever called when active (or
291 * rather, we'll have bailed in task_function_call() or the
292 * above ctx->task != current test), therefore we must have
293 * ctx->is_active here.
294 */
295 WARN_ON_ONCE(!ctx->is_active);
296 /*
297 * And since we have ctx->is_active, cpuctx->task_ctx must
298 * match.
299 */
300 WARN_ON_ONCE(task_ctx != ctx);
301 } else {
302 WARN_ON_ONCE(&cpuctx->ctx != ctx);
303 }
304
305 efs->func(event, cpuctx, ctx, efs->data);
306 unlock:
307 perf_ctx_unlock(cpuctx, task_ctx);
308
309 return ret;
310 }
311
event_function_call(struct perf_event * event,event_f func,void * data)312 static void event_function_call(struct perf_event *event, event_f func, void *data)
313 {
314 struct perf_event_context *ctx = event->ctx;
315 struct task_struct *task = READ_ONCE(ctx->task); /* verified in event_function */
316 struct perf_cpu_context *cpuctx;
317 struct event_function_struct efs = {
318 .event = event,
319 .func = func,
320 .data = data,
321 };
322
323 if (!event->parent) {
324 /*
325 * If this is a !child event, we must hold ctx::mutex to
326 * stabilize the event->ctx relation. See
327 * perf_event_ctx_lock().
328 */
329 lockdep_assert_held(&ctx->mutex);
330 }
331
332 if (!task) {
333 cpu_function_call(event->cpu, event_function, &efs);
334 return;
335 }
336
337 if (task == TASK_TOMBSTONE)
338 return;
339
340 again:
341 if (!task_function_call(task, event_function, &efs))
342 return;
343
344 local_irq_disable();
345 cpuctx = this_cpu_ptr(&perf_cpu_context);
346 perf_ctx_lock(cpuctx, ctx);
347 /*
348 * Reload the task pointer, it might have been changed by
349 * a concurrent perf_event_context_sched_out().
350 */
351 task = ctx->task;
352 if (task == TASK_TOMBSTONE)
353 goto unlock;
354 if (ctx->is_active) {
355 perf_ctx_unlock(cpuctx, ctx);
356 local_irq_enable();
357 goto again;
358 }
359 func(event, NULL, ctx, data);
360 unlock:
361 perf_ctx_unlock(cpuctx, ctx);
362 local_irq_enable();
363 }
364
365 /*
366 * Similar to event_function_call() + event_function(), but hard assumes IRQs
367 * are already disabled and we're on the right CPU.
368 */
event_function_local(struct perf_event * event,event_f func,void * data)369 static void event_function_local(struct perf_event *event, event_f func, void *data)
370 {
371 struct perf_event_context *ctx = event->ctx;
372 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
373 struct task_struct *task = READ_ONCE(ctx->task);
374 struct perf_event_context *task_ctx = NULL;
375
376 lockdep_assert_irqs_disabled();
377
378 if (task) {
379 if (task == TASK_TOMBSTONE)
380 return;
381
382 task_ctx = ctx;
383 }
384
385 perf_ctx_lock(cpuctx, task_ctx);
386
387 task = ctx->task;
388 if (task == TASK_TOMBSTONE)
389 goto unlock;
390
391 if (task) {
392 /*
393 * We must be either inactive or active and the right task,
394 * otherwise we're screwed, since we cannot IPI to somewhere
395 * else.
396 */
397 if (ctx->is_active) {
398 if (WARN_ON_ONCE(task != current))
399 goto unlock;
400
401 if (WARN_ON_ONCE(cpuctx->task_ctx != ctx))
402 goto unlock;
403 }
404 } else {
405 WARN_ON_ONCE(&cpuctx->ctx != ctx);
406 }
407
408 func(event, cpuctx, ctx, data);
409 unlock:
410 perf_ctx_unlock(cpuctx, task_ctx);
411 }
412
413 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
414 PERF_FLAG_FD_OUTPUT |\
415 PERF_FLAG_PID_CGROUP |\
416 PERF_FLAG_FD_CLOEXEC)
417
418 /*
419 * branch priv levels that need permission checks
420 */
421 #define PERF_SAMPLE_BRANCH_PERM_PLM \
422 (PERF_SAMPLE_BRANCH_KERNEL |\
423 PERF_SAMPLE_BRANCH_HV)
424
425 /*
426 * perf_sched_events : >0 events exist
427 */
428
429 static void perf_sched_delayed(struct work_struct *work);
430 DEFINE_STATIC_KEY_FALSE(perf_sched_events);
431 static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed);
432 static DEFINE_MUTEX(perf_sched_mutex);
433 static atomic_t perf_sched_count;
434
435 static DEFINE_PER_CPU(struct pmu_event_list, pmu_sb_events);
436
437 static atomic_t nr_mmap_events __read_mostly;
438 static atomic_t nr_comm_events __read_mostly;
439 static atomic_t nr_namespaces_events __read_mostly;
440 static atomic_t nr_task_events __read_mostly;
441 static atomic_t nr_freq_events __read_mostly;
442 static atomic_t nr_switch_events __read_mostly;
443 static atomic_t nr_ksymbol_events __read_mostly;
444 static atomic_t nr_bpf_events __read_mostly;
445 static atomic_t nr_cgroup_events __read_mostly;
446 static atomic_t nr_text_poke_events __read_mostly;
447 static atomic_t nr_build_id_events __read_mostly;
448
449 static LIST_HEAD(pmus);
450 static DEFINE_MUTEX(pmus_lock);
451 static struct srcu_struct pmus_srcu;
452 static cpumask_var_t perf_online_mask;
453 static cpumask_var_t perf_online_core_mask;
454 static cpumask_var_t perf_online_die_mask;
455 static cpumask_var_t perf_online_cluster_mask;
456 static cpumask_var_t perf_online_pkg_mask;
457 static cpumask_var_t perf_online_sys_mask;
458 static struct kmem_cache *perf_event_cache;
459
460 /*
461 * perf event paranoia level:
462 * -1 - not paranoid at all
463 * 0 - disallow raw tracepoint access for unpriv
464 * 1 - disallow cpu events for unpriv
465 * 2 - disallow kernel profiling for unpriv
466 */
467 int sysctl_perf_event_paranoid __read_mostly = 2;
468
469 /* Minimum for 512 kiB + 1 user control page */
470 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
471
472 /*
473 * max perf event sample rate
474 */
475 #define DEFAULT_MAX_SAMPLE_RATE 100000
476 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
477 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
478
479 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
480
481 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
482 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
483
484 static int perf_sample_allowed_ns __read_mostly =
485 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
486
update_perf_cpu_limits(void)487 static void update_perf_cpu_limits(void)
488 {
489 u64 tmp = perf_sample_period_ns;
490
491 tmp *= sysctl_perf_cpu_time_max_percent;
492 tmp = div_u64(tmp, 100);
493 if (!tmp)
494 tmp = 1;
495
496 WRITE_ONCE(perf_sample_allowed_ns, tmp);
497 }
498
499 static bool perf_rotate_context(struct perf_cpu_pmu_context *cpc);
500
perf_event_max_sample_rate_handler(const struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)501 int perf_event_max_sample_rate_handler(const struct ctl_table *table, int write,
502 void *buffer, size_t *lenp, loff_t *ppos)
503 {
504 int ret;
505 int perf_cpu = sysctl_perf_cpu_time_max_percent;
506 /*
507 * If throttling is disabled don't allow the write:
508 */
509 if (write && (perf_cpu == 100 || perf_cpu == 0))
510 return -EINVAL;
511
512 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
513 if (ret || !write)
514 return ret;
515
516 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
517 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
518 update_perf_cpu_limits();
519
520 return 0;
521 }
522
523 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
524
perf_cpu_time_max_percent_handler(const struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)525 int perf_cpu_time_max_percent_handler(const struct ctl_table *table, int write,
526 void *buffer, size_t *lenp, loff_t *ppos)
527 {
528 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
529
530 if (ret || !write)
531 return ret;
532
533 if (sysctl_perf_cpu_time_max_percent == 100 ||
534 sysctl_perf_cpu_time_max_percent == 0) {
535 printk(KERN_WARNING
536 "perf: Dynamic interrupt throttling disabled, can hang your system!\n");
537 WRITE_ONCE(perf_sample_allowed_ns, 0);
538 } else {
539 update_perf_cpu_limits();
540 }
541
542 return 0;
543 }
544
545 /*
546 * perf samples are done in some very critical code paths (NMIs).
547 * If they take too much CPU time, the system can lock up and not
548 * get any real work done. This will drop the sample rate when
549 * we detect that events are taking too long.
550 */
551 #define NR_ACCUMULATED_SAMPLES 128
552 static DEFINE_PER_CPU(u64, running_sample_length);
553
554 static u64 __report_avg;
555 static u64 __report_allowed;
556
perf_duration_warn(struct irq_work * w)557 static void perf_duration_warn(struct irq_work *w)
558 {
559 printk_ratelimited(KERN_INFO
560 "perf: interrupt took too long (%lld > %lld), lowering "
561 "kernel.perf_event_max_sample_rate to %d\n",
562 __report_avg, __report_allowed,
563 sysctl_perf_event_sample_rate);
564 }
565
566 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
567
perf_sample_event_took(u64 sample_len_ns)568 void perf_sample_event_took(u64 sample_len_ns)
569 {
570 u64 max_len = READ_ONCE(perf_sample_allowed_ns);
571 u64 running_len;
572 u64 avg_len;
573 u32 max;
574
575 if (max_len == 0)
576 return;
577
578 /* Decay the counter by 1 average sample. */
579 running_len = __this_cpu_read(running_sample_length);
580 running_len -= running_len/NR_ACCUMULATED_SAMPLES;
581 running_len += sample_len_ns;
582 __this_cpu_write(running_sample_length, running_len);
583
584 /*
585 * Note: this will be biased artificially low until we have
586 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
587 * from having to maintain a count.
588 */
589 avg_len = running_len/NR_ACCUMULATED_SAMPLES;
590 if (avg_len <= max_len)
591 return;
592
593 __report_avg = avg_len;
594 __report_allowed = max_len;
595
596 /*
597 * Compute a throttle threshold 25% below the current duration.
598 */
599 avg_len += avg_len / 4;
600 max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent;
601 if (avg_len < max)
602 max /= (u32)avg_len;
603 else
604 max = 1;
605
606 WRITE_ONCE(perf_sample_allowed_ns, avg_len);
607 WRITE_ONCE(max_samples_per_tick, max);
608
609 sysctl_perf_event_sample_rate = max * HZ;
610 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
611
612 if (!irq_work_queue(&perf_duration_work)) {
613 early_printk("perf: interrupt took too long (%lld > %lld), lowering "
614 "kernel.perf_event_max_sample_rate to %d\n",
615 __report_avg, __report_allowed,
616 sysctl_perf_event_sample_rate);
617 }
618 }
619
620 static atomic64_t perf_event_id;
621
622 static void update_context_time(struct perf_event_context *ctx);
623 static u64 perf_event_time(struct perf_event *event);
624
perf_event_print_debug(void)625 void __weak perf_event_print_debug(void) { }
626
perf_clock(void)627 static inline u64 perf_clock(void)
628 {
629 return local_clock();
630 }
631
perf_event_clock(struct perf_event * event)632 static inline u64 perf_event_clock(struct perf_event *event)
633 {
634 return event->clock();
635 }
636
637 /*
638 * State based event timekeeping...
639 *
640 * The basic idea is to use event->state to determine which (if any) time
641 * fields to increment with the current delta. This means we only need to
642 * update timestamps when we change state or when they are explicitly requested
643 * (read).
644 *
645 * Event groups make things a little more complicated, but not terribly so. The
646 * rules for a group are that if the group leader is OFF the entire group is
647 * OFF, irrespective of what the group member states are. This results in
648 * __perf_effective_state().
649 *
650 * A further ramification is that when a group leader flips between OFF and
651 * !OFF, we need to update all group member times.
652 *
653 *
654 * NOTE: perf_event_time() is based on the (cgroup) context time, and thus we
655 * need to make sure the relevant context time is updated before we try and
656 * update our timestamps.
657 */
658
659 static __always_inline enum perf_event_state
__perf_effective_state(struct perf_event * event)660 __perf_effective_state(struct perf_event *event)
661 {
662 struct perf_event *leader = event->group_leader;
663
664 if (leader->state <= PERF_EVENT_STATE_OFF)
665 return leader->state;
666
667 return event->state;
668 }
669
670 static __always_inline void
__perf_update_times(struct perf_event * event,u64 now,u64 * enabled,u64 * running)671 __perf_update_times(struct perf_event *event, u64 now, u64 *enabled, u64 *running)
672 {
673 enum perf_event_state state = __perf_effective_state(event);
674 u64 delta = now - event->tstamp;
675
676 *enabled = event->total_time_enabled;
677 if (state >= PERF_EVENT_STATE_INACTIVE)
678 *enabled += delta;
679
680 *running = event->total_time_running;
681 if (state >= PERF_EVENT_STATE_ACTIVE)
682 *running += delta;
683 }
684
perf_event_update_time(struct perf_event * event)685 static void perf_event_update_time(struct perf_event *event)
686 {
687 u64 now = perf_event_time(event);
688
689 __perf_update_times(event, now, &event->total_time_enabled,
690 &event->total_time_running);
691 event->tstamp = now;
692 }
693
perf_event_update_sibling_time(struct perf_event * leader)694 static void perf_event_update_sibling_time(struct perf_event *leader)
695 {
696 struct perf_event *sibling;
697
698 for_each_sibling_event(sibling, leader)
699 perf_event_update_time(sibling);
700 }
701
702 static void
perf_event_set_state(struct perf_event * event,enum perf_event_state state)703 perf_event_set_state(struct perf_event *event, enum perf_event_state state)
704 {
705 if (event->state == state)
706 return;
707
708 perf_event_update_time(event);
709 /*
710 * If a group leader gets enabled/disabled all its siblings
711 * are affected too.
712 */
713 if ((event->state < 0) ^ (state < 0))
714 perf_event_update_sibling_time(event);
715
716 WRITE_ONCE(event->state, state);
717 }
718
719 /*
720 * UP store-release, load-acquire
721 */
722
723 #define __store_release(ptr, val) \
724 do { \
725 barrier(); \
726 WRITE_ONCE(*(ptr), (val)); \
727 } while (0)
728
729 #define __load_acquire(ptr) \
730 ({ \
731 __unqual_scalar_typeof(*(ptr)) ___p = READ_ONCE(*(ptr)); \
732 barrier(); \
733 ___p; \
734 })
735
736 #define for_each_epc(_epc, _ctx, _pmu, _cgroup) \
737 list_for_each_entry(_epc, &((_ctx)->pmu_ctx_list), pmu_ctx_entry) \
738 if (_cgroup && !_epc->nr_cgroups) \
739 continue; \
740 else if (_pmu && _epc->pmu != _pmu) \
741 continue; \
742 else
743
perf_ctx_disable(struct perf_event_context * ctx,bool cgroup)744 static void perf_ctx_disable(struct perf_event_context *ctx, bool cgroup)
745 {
746 struct perf_event_pmu_context *pmu_ctx;
747
748 for_each_epc(pmu_ctx, ctx, NULL, cgroup)
749 perf_pmu_disable(pmu_ctx->pmu);
750 }
751
perf_ctx_enable(struct perf_event_context * ctx,bool cgroup)752 static void perf_ctx_enable(struct perf_event_context *ctx, bool cgroup)
753 {
754 struct perf_event_pmu_context *pmu_ctx;
755
756 for_each_epc(pmu_ctx, ctx, NULL, cgroup)
757 perf_pmu_enable(pmu_ctx->pmu);
758 }
759
760 static void ctx_sched_out(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type);
761 static void ctx_sched_in(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type);
762
763 #ifdef CONFIG_CGROUP_PERF
764
765 static inline bool
perf_cgroup_match(struct perf_event * event)766 perf_cgroup_match(struct perf_event *event)
767 {
768 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
769
770 /* @event doesn't care about cgroup */
771 if (!event->cgrp)
772 return true;
773
774 /* wants specific cgroup scope but @cpuctx isn't associated with any */
775 if (!cpuctx->cgrp)
776 return false;
777
778 /*
779 * Cgroup scoping is recursive. An event enabled for a cgroup is
780 * also enabled for all its descendant cgroups. If @cpuctx's
781 * cgroup is a descendant of @event's (the test covers identity
782 * case), it's a match.
783 */
784 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
785 event->cgrp->css.cgroup);
786 }
787
perf_detach_cgroup(struct perf_event * event)788 static inline void perf_detach_cgroup(struct perf_event *event)
789 {
790 css_put(&event->cgrp->css);
791 event->cgrp = NULL;
792 }
793
is_cgroup_event(struct perf_event * event)794 static inline int is_cgroup_event(struct perf_event *event)
795 {
796 return event->cgrp != NULL;
797 }
798
perf_cgroup_event_time(struct perf_event * event)799 static inline u64 perf_cgroup_event_time(struct perf_event *event)
800 {
801 struct perf_cgroup_info *t;
802
803 t = per_cpu_ptr(event->cgrp->info, event->cpu);
804 return t->time;
805 }
806
perf_cgroup_event_time_now(struct perf_event * event,u64 now)807 static inline u64 perf_cgroup_event_time_now(struct perf_event *event, u64 now)
808 {
809 struct perf_cgroup_info *t;
810
811 t = per_cpu_ptr(event->cgrp->info, event->cpu);
812 if (!__load_acquire(&t->active))
813 return t->time;
814 now += READ_ONCE(t->timeoffset);
815 return now;
816 }
817
__update_cgrp_time(struct perf_cgroup_info * info,u64 now,bool adv)818 static inline void __update_cgrp_time(struct perf_cgroup_info *info, u64 now, bool adv)
819 {
820 if (adv)
821 info->time += now - info->timestamp;
822 info->timestamp = now;
823 /*
824 * see update_context_time()
825 */
826 WRITE_ONCE(info->timeoffset, info->time - info->timestamp);
827 }
828
update_cgrp_time_from_cpuctx(struct perf_cpu_context * cpuctx,bool final)829 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx, bool final)
830 {
831 struct perf_cgroup *cgrp = cpuctx->cgrp;
832 struct cgroup_subsys_state *css;
833 struct perf_cgroup_info *info;
834
835 if (cgrp) {
836 u64 now = perf_clock();
837
838 for (css = &cgrp->css; css; css = css->parent) {
839 cgrp = container_of(css, struct perf_cgroup, css);
840 info = this_cpu_ptr(cgrp->info);
841
842 __update_cgrp_time(info, now, true);
843 if (final)
844 __store_release(&info->active, 0);
845 }
846 }
847 }
848
update_cgrp_time_from_event(struct perf_event * event)849 static inline void update_cgrp_time_from_event(struct perf_event *event)
850 {
851 struct perf_cgroup_info *info;
852
853 /*
854 * ensure we access cgroup data only when needed and
855 * when we know the cgroup is pinned (css_get)
856 */
857 if (!is_cgroup_event(event))
858 return;
859
860 info = this_cpu_ptr(event->cgrp->info);
861 /*
862 * Do not update time when cgroup is not active
863 */
864 if (info->active)
865 __update_cgrp_time(info, perf_clock(), true);
866 }
867
868 static inline void
perf_cgroup_set_timestamp(struct perf_cpu_context * cpuctx)869 perf_cgroup_set_timestamp(struct perf_cpu_context *cpuctx)
870 {
871 struct perf_event_context *ctx = &cpuctx->ctx;
872 struct perf_cgroup *cgrp = cpuctx->cgrp;
873 struct perf_cgroup_info *info;
874 struct cgroup_subsys_state *css;
875
876 /*
877 * ctx->lock held by caller
878 * ensure we do not access cgroup data
879 * unless we have the cgroup pinned (css_get)
880 */
881 if (!cgrp)
882 return;
883
884 WARN_ON_ONCE(!ctx->nr_cgroups);
885
886 for (css = &cgrp->css; css; css = css->parent) {
887 cgrp = container_of(css, struct perf_cgroup, css);
888 info = this_cpu_ptr(cgrp->info);
889 __update_cgrp_time(info, ctx->timestamp, false);
890 __store_release(&info->active, 1);
891 }
892 }
893
894 /*
895 * reschedule events based on the cgroup constraint of task.
896 */
perf_cgroup_switch(struct task_struct * task)897 static void perf_cgroup_switch(struct task_struct *task)
898 {
899 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
900 struct perf_cgroup *cgrp;
901
902 /*
903 * cpuctx->cgrp is set when the first cgroup event enabled,
904 * and is cleared when the last cgroup event disabled.
905 */
906 if (READ_ONCE(cpuctx->cgrp) == NULL)
907 return;
908
909 cgrp = perf_cgroup_from_task(task, NULL);
910 if (READ_ONCE(cpuctx->cgrp) == cgrp)
911 return;
912
913 guard(perf_ctx_lock)(cpuctx, cpuctx->task_ctx);
914 /*
915 * Re-check, could've raced vs perf_remove_from_context().
916 */
917 if (READ_ONCE(cpuctx->cgrp) == NULL)
918 return;
919
920 WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0);
921
922 perf_ctx_disable(&cpuctx->ctx, true);
923
924 ctx_sched_out(&cpuctx->ctx, NULL, EVENT_ALL|EVENT_CGROUP);
925 /*
926 * must not be done before ctxswout due
927 * to update_cgrp_time_from_cpuctx() in
928 * ctx_sched_out()
929 */
930 cpuctx->cgrp = cgrp;
931 /*
932 * set cgrp before ctxsw in to allow
933 * perf_cgroup_set_timestamp() in ctx_sched_in()
934 * to not have to pass task around
935 */
936 ctx_sched_in(&cpuctx->ctx, NULL, EVENT_ALL|EVENT_CGROUP);
937
938 perf_ctx_enable(&cpuctx->ctx, true);
939 }
940
perf_cgroup_ensure_storage(struct perf_event * event,struct cgroup_subsys_state * css)941 static int perf_cgroup_ensure_storage(struct perf_event *event,
942 struct cgroup_subsys_state *css)
943 {
944 struct perf_cpu_context *cpuctx;
945 struct perf_event **storage;
946 int cpu, heap_size, ret = 0;
947
948 /*
949 * Allow storage to have sufficient space for an iterator for each
950 * possibly nested cgroup plus an iterator for events with no cgroup.
951 */
952 for (heap_size = 1; css; css = css->parent)
953 heap_size++;
954
955 for_each_possible_cpu(cpu) {
956 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
957 if (heap_size <= cpuctx->heap_size)
958 continue;
959
960 storage = kmalloc_node(heap_size * sizeof(struct perf_event *),
961 GFP_KERNEL, cpu_to_node(cpu));
962 if (!storage) {
963 ret = -ENOMEM;
964 break;
965 }
966
967 raw_spin_lock_irq(&cpuctx->ctx.lock);
968 if (cpuctx->heap_size < heap_size) {
969 swap(cpuctx->heap, storage);
970 if (storage == cpuctx->heap_default)
971 storage = NULL;
972 cpuctx->heap_size = heap_size;
973 }
974 raw_spin_unlock_irq(&cpuctx->ctx.lock);
975
976 kfree(storage);
977 }
978
979 return ret;
980 }
981
perf_cgroup_connect(int fd,struct perf_event * event,struct perf_event_attr * attr,struct perf_event * group_leader)982 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
983 struct perf_event_attr *attr,
984 struct perf_event *group_leader)
985 {
986 struct perf_cgroup *cgrp;
987 struct cgroup_subsys_state *css;
988 struct fd f = fdget(fd);
989 int ret = 0;
990
991 if (!fd_file(f))
992 return -EBADF;
993
994 css = css_tryget_online_from_dir(fd_file(f)->f_path.dentry,
995 &perf_event_cgrp_subsys);
996 if (IS_ERR(css)) {
997 ret = PTR_ERR(css);
998 goto out;
999 }
1000
1001 ret = perf_cgroup_ensure_storage(event, css);
1002 if (ret)
1003 goto out;
1004
1005 cgrp = container_of(css, struct perf_cgroup, css);
1006 event->cgrp = cgrp;
1007
1008 /*
1009 * all events in a group must monitor
1010 * the same cgroup because a task belongs
1011 * to only one perf cgroup at a time
1012 */
1013 if (group_leader && group_leader->cgrp != cgrp) {
1014 perf_detach_cgroup(event);
1015 ret = -EINVAL;
1016 }
1017 out:
1018 fdput(f);
1019 return ret;
1020 }
1021
1022 static inline void
perf_cgroup_event_enable(struct perf_event * event,struct perf_event_context * ctx)1023 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
1024 {
1025 struct perf_cpu_context *cpuctx;
1026
1027 if (!is_cgroup_event(event))
1028 return;
1029
1030 event->pmu_ctx->nr_cgroups++;
1031
1032 /*
1033 * Because cgroup events are always per-cpu events,
1034 * @ctx == &cpuctx->ctx.
1035 */
1036 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
1037
1038 if (ctx->nr_cgroups++)
1039 return;
1040
1041 cpuctx->cgrp = perf_cgroup_from_task(current, ctx);
1042 }
1043
1044 static inline void
perf_cgroup_event_disable(struct perf_event * event,struct perf_event_context * ctx)1045 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1046 {
1047 struct perf_cpu_context *cpuctx;
1048
1049 if (!is_cgroup_event(event))
1050 return;
1051
1052 event->pmu_ctx->nr_cgroups--;
1053
1054 /*
1055 * Because cgroup events are always per-cpu events,
1056 * @ctx == &cpuctx->ctx.
1057 */
1058 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
1059
1060 if (--ctx->nr_cgroups)
1061 return;
1062
1063 cpuctx->cgrp = NULL;
1064 }
1065
1066 #else /* !CONFIG_CGROUP_PERF */
1067
1068 static inline bool
perf_cgroup_match(struct perf_event * event)1069 perf_cgroup_match(struct perf_event *event)
1070 {
1071 return true;
1072 }
1073
perf_detach_cgroup(struct perf_event * event)1074 static inline void perf_detach_cgroup(struct perf_event *event)
1075 {}
1076
is_cgroup_event(struct perf_event * event)1077 static inline int is_cgroup_event(struct perf_event *event)
1078 {
1079 return 0;
1080 }
1081
update_cgrp_time_from_event(struct perf_event * event)1082 static inline void update_cgrp_time_from_event(struct perf_event *event)
1083 {
1084 }
1085
update_cgrp_time_from_cpuctx(struct perf_cpu_context * cpuctx,bool final)1086 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx,
1087 bool final)
1088 {
1089 }
1090
perf_cgroup_connect(pid_t pid,struct perf_event * event,struct perf_event_attr * attr,struct perf_event * group_leader)1091 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
1092 struct perf_event_attr *attr,
1093 struct perf_event *group_leader)
1094 {
1095 return -EINVAL;
1096 }
1097
1098 static inline void
perf_cgroup_set_timestamp(struct perf_cpu_context * cpuctx)1099 perf_cgroup_set_timestamp(struct perf_cpu_context *cpuctx)
1100 {
1101 }
1102
perf_cgroup_event_time(struct perf_event * event)1103 static inline u64 perf_cgroup_event_time(struct perf_event *event)
1104 {
1105 return 0;
1106 }
1107
perf_cgroup_event_time_now(struct perf_event * event,u64 now)1108 static inline u64 perf_cgroup_event_time_now(struct perf_event *event, u64 now)
1109 {
1110 return 0;
1111 }
1112
1113 static inline void
perf_cgroup_event_enable(struct perf_event * event,struct perf_event_context * ctx)1114 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
1115 {
1116 }
1117
1118 static inline void
perf_cgroup_event_disable(struct perf_event * event,struct perf_event_context * ctx)1119 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1120 {
1121 }
1122
perf_cgroup_switch(struct task_struct * task)1123 static void perf_cgroup_switch(struct task_struct *task)
1124 {
1125 }
1126 #endif
1127
1128 /*
1129 * set default to be dependent on timer tick just
1130 * like original code
1131 */
1132 #define PERF_CPU_HRTIMER (1000 / HZ)
1133 /*
1134 * function must be called with interrupts disabled
1135 */
perf_mux_hrtimer_handler(struct hrtimer * hr)1136 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
1137 {
1138 struct perf_cpu_pmu_context *cpc;
1139 bool rotations;
1140
1141 lockdep_assert_irqs_disabled();
1142
1143 cpc = container_of(hr, struct perf_cpu_pmu_context, hrtimer);
1144 rotations = perf_rotate_context(cpc);
1145
1146 raw_spin_lock(&cpc->hrtimer_lock);
1147 if (rotations)
1148 hrtimer_forward_now(hr, cpc->hrtimer_interval);
1149 else
1150 cpc->hrtimer_active = 0;
1151 raw_spin_unlock(&cpc->hrtimer_lock);
1152
1153 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
1154 }
1155
__perf_mux_hrtimer_init(struct perf_cpu_pmu_context * cpc,int cpu)1156 static void __perf_mux_hrtimer_init(struct perf_cpu_pmu_context *cpc, int cpu)
1157 {
1158 struct hrtimer *timer = &cpc->hrtimer;
1159 struct pmu *pmu = cpc->epc.pmu;
1160 u64 interval;
1161
1162 /*
1163 * check default is sane, if not set then force to
1164 * default interval (1/tick)
1165 */
1166 interval = pmu->hrtimer_interval_ms;
1167 if (interval < 1)
1168 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
1169
1170 cpc->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
1171
1172 raw_spin_lock_init(&cpc->hrtimer_lock);
1173 hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED_HARD);
1174 timer->function = perf_mux_hrtimer_handler;
1175 }
1176
perf_mux_hrtimer_restart(struct perf_cpu_pmu_context * cpc)1177 static int perf_mux_hrtimer_restart(struct perf_cpu_pmu_context *cpc)
1178 {
1179 struct hrtimer *timer = &cpc->hrtimer;
1180 unsigned long flags;
1181
1182 raw_spin_lock_irqsave(&cpc->hrtimer_lock, flags);
1183 if (!cpc->hrtimer_active) {
1184 cpc->hrtimer_active = 1;
1185 hrtimer_forward_now(timer, cpc->hrtimer_interval);
1186 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED_HARD);
1187 }
1188 raw_spin_unlock_irqrestore(&cpc->hrtimer_lock, flags);
1189
1190 return 0;
1191 }
1192
perf_mux_hrtimer_restart_ipi(void * arg)1193 static int perf_mux_hrtimer_restart_ipi(void *arg)
1194 {
1195 return perf_mux_hrtimer_restart(arg);
1196 }
1197
perf_pmu_disable(struct pmu * pmu)1198 void perf_pmu_disable(struct pmu *pmu)
1199 {
1200 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1201 if (!(*count)++)
1202 pmu->pmu_disable(pmu);
1203 }
1204
perf_pmu_enable(struct pmu * pmu)1205 void perf_pmu_enable(struct pmu *pmu)
1206 {
1207 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1208 if (!--(*count))
1209 pmu->pmu_enable(pmu);
1210 }
1211
perf_assert_pmu_disabled(struct pmu * pmu)1212 static void perf_assert_pmu_disabled(struct pmu *pmu)
1213 {
1214 WARN_ON_ONCE(*this_cpu_ptr(pmu->pmu_disable_count) == 0);
1215 }
1216
get_ctx(struct perf_event_context * ctx)1217 static void get_ctx(struct perf_event_context *ctx)
1218 {
1219 refcount_inc(&ctx->refcount);
1220 }
1221
alloc_task_ctx_data(struct pmu * pmu)1222 static void *alloc_task_ctx_data(struct pmu *pmu)
1223 {
1224 if (pmu->task_ctx_cache)
1225 return kmem_cache_zalloc(pmu->task_ctx_cache, GFP_KERNEL);
1226
1227 return NULL;
1228 }
1229
free_task_ctx_data(struct pmu * pmu,void * task_ctx_data)1230 static void free_task_ctx_data(struct pmu *pmu, void *task_ctx_data)
1231 {
1232 if (pmu->task_ctx_cache && task_ctx_data)
1233 kmem_cache_free(pmu->task_ctx_cache, task_ctx_data);
1234 }
1235
free_ctx(struct rcu_head * head)1236 static void free_ctx(struct rcu_head *head)
1237 {
1238 struct perf_event_context *ctx;
1239
1240 ctx = container_of(head, struct perf_event_context, rcu_head);
1241 kfree(ctx);
1242 }
1243
put_ctx(struct perf_event_context * ctx)1244 static void put_ctx(struct perf_event_context *ctx)
1245 {
1246 if (refcount_dec_and_test(&ctx->refcount)) {
1247 if (ctx->parent_ctx)
1248 put_ctx(ctx->parent_ctx);
1249 if (ctx->task && ctx->task != TASK_TOMBSTONE)
1250 put_task_struct(ctx->task);
1251 call_rcu(&ctx->rcu_head, free_ctx);
1252 }
1253 }
1254
1255 /*
1256 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
1257 * perf_pmu_migrate_context() we need some magic.
1258 *
1259 * Those places that change perf_event::ctx will hold both
1260 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
1261 *
1262 * Lock ordering is by mutex address. There are two other sites where
1263 * perf_event_context::mutex nests and those are:
1264 *
1265 * - perf_event_exit_task_context() [ child , 0 ]
1266 * perf_event_exit_event()
1267 * put_event() [ parent, 1 ]
1268 *
1269 * - perf_event_init_context() [ parent, 0 ]
1270 * inherit_task_group()
1271 * inherit_group()
1272 * inherit_event()
1273 * perf_event_alloc()
1274 * perf_init_event()
1275 * perf_try_init_event() [ child , 1 ]
1276 *
1277 * While it appears there is an obvious deadlock here -- the parent and child
1278 * nesting levels are inverted between the two. This is in fact safe because
1279 * life-time rules separate them. That is an exiting task cannot fork, and a
1280 * spawning task cannot (yet) exit.
1281 *
1282 * But remember that these are parent<->child context relations, and
1283 * migration does not affect children, therefore these two orderings should not
1284 * interact.
1285 *
1286 * The change in perf_event::ctx does not affect children (as claimed above)
1287 * because the sys_perf_event_open() case will install a new event and break
1288 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
1289 * concerned with cpuctx and that doesn't have children.
1290 *
1291 * The places that change perf_event::ctx will issue:
1292 *
1293 * perf_remove_from_context();
1294 * synchronize_rcu();
1295 * perf_install_in_context();
1296 *
1297 * to affect the change. The remove_from_context() + synchronize_rcu() should
1298 * quiesce the event, after which we can install it in the new location. This
1299 * means that only external vectors (perf_fops, prctl) can perturb the event
1300 * while in transit. Therefore all such accessors should also acquire
1301 * perf_event_context::mutex to serialize against this.
1302 *
1303 * However; because event->ctx can change while we're waiting to acquire
1304 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
1305 * function.
1306 *
1307 * Lock order:
1308 * exec_update_lock
1309 * task_struct::perf_event_mutex
1310 * perf_event_context::mutex
1311 * perf_event::child_mutex;
1312 * perf_event_context::lock
1313 * mmap_lock
1314 * perf_event::mmap_mutex
1315 * perf_buffer::aux_mutex
1316 * perf_addr_filters_head::lock
1317 *
1318 * cpu_hotplug_lock
1319 * pmus_lock
1320 * cpuctx->mutex / perf_event_context::mutex
1321 */
1322 static struct perf_event_context *
perf_event_ctx_lock_nested(struct perf_event * event,int nesting)1323 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
1324 {
1325 struct perf_event_context *ctx;
1326
1327 again:
1328 rcu_read_lock();
1329 ctx = READ_ONCE(event->ctx);
1330 if (!refcount_inc_not_zero(&ctx->refcount)) {
1331 rcu_read_unlock();
1332 goto again;
1333 }
1334 rcu_read_unlock();
1335
1336 mutex_lock_nested(&ctx->mutex, nesting);
1337 if (event->ctx != ctx) {
1338 mutex_unlock(&ctx->mutex);
1339 put_ctx(ctx);
1340 goto again;
1341 }
1342
1343 return ctx;
1344 }
1345
1346 static inline struct perf_event_context *
perf_event_ctx_lock(struct perf_event * event)1347 perf_event_ctx_lock(struct perf_event *event)
1348 {
1349 return perf_event_ctx_lock_nested(event, 0);
1350 }
1351
perf_event_ctx_unlock(struct perf_event * event,struct perf_event_context * ctx)1352 static void perf_event_ctx_unlock(struct perf_event *event,
1353 struct perf_event_context *ctx)
1354 {
1355 mutex_unlock(&ctx->mutex);
1356 put_ctx(ctx);
1357 }
1358
1359 /*
1360 * This must be done under the ctx->lock, such as to serialize against
1361 * context_equiv(), therefore we cannot call put_ctx() since that might end up
1362 * calling scheduler related locks and ctx->lock nests inside those.
1363 */
1364 static __must_check struct perf_event_context *
unclone_ctx(struct perf_event_context * ctx)1365 unclone_ctx(struct perf_event_context *ctx)
1366 {
1367 struct perf_event_context *parent_ctx = ctx->parent_ctx;
1368
1369 lockdep_assert_held(&ctx->lock);
1370
1371 if (parent_ctx)
1372 ctx->parent_ctx = NULL;
1373 ctx->generation++;
1374
1375 return parent_ctx;
1376 }
1377
perf_event_pid_type(struct perf_event * event,struct task_struct * p,enum pid_type type)1378 static u32 perf_event_pid_type(struct perf_event *event, struct task_struct *p,
1379 enum pid_type type)
1380 {
1381 u32 nr;
1382 /*
1383 * only top level events have the pid namespace they were created in
1384 */
1385 if (event->parent)
1386 event = event->parent;
1387
1388 nr = __task_pid_nr_ns(p, type, event->ns);
1389 /* avoid -1 if it is idle thread or runs in another ns */
1390 if (!nr && !pid_alive(p))
1391 nr = -1;
1392 return nr;
1393 }
1394
perf_event_pid(struct perf_event * event,struct task_struct * p)1395 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1396 {
1397 return perf_event_pid_type(event, p, PIDTYPE_TGID);
1398 }
1399
perf_event_tid(struct perf_event * event,struct task_struct * p)1400 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1401 {
1402 return perf_event_pid_type(event, p, PIDTYPE_PID);
1403 }
1404
1405 /*
1406 * If we inherit events we want to return the parent event id
1407 * to userspace.
1408 */
primary_event_id(struct perf_event * event)1409 static u64 primary_event_id(struct perf_event *event)
1410 {
1411 u64 id = event->id;
1412
1413 if (event->parent)
1414 id = event->parent->id;
1415
1416 return id;
1417 }
1418
1419 /*
1420 * Get the perf_event_context for a task and lock it.
1421 *
1422 * This has to cope with the fact that until it is locked,
1423 * the context could get moved to another task.
1424 */
1425 static struct perf_event_context *
perf_lock_task_context(struct task_struct * task,unsigned long * flags)1426 perf_lock_task_context(struct task_struct *task, unsigned long *flags)
1427 {
1428 struct perf_event_context *ctx;
1429
1430 retry:
1431 /*
1432 * One of the few rules of preemptible RCU is that one cannot do
1433 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1434 * part of the read side critical section was irqs-enabled -- see
1435 * rcu_read_unlock_special().
1436 *
1437 * Since ctx->lock nests under rq->lock we must ensure the entire read
1438 * side critical section has interrupts disabled.
1439 */
1440 local_irq_save(*flags);
1441 rcu_read_lock();
1442 ctx = rcu_dereference(task->perf_event_ctxp);
1443 if (ctx) {
1444 /*
1445 * If this context is a clone of another, it might
1446 * get swapped for another underneath us by
1447 * perf_event_task_sched_out, though the
1448 * rcu_read_lock() protects us from any context
1449 * getting freed. Lock the context and check if it
1450 * got swapped before we could get the lock, and retry
1451 * if so. If we locked the right context, then it
1452 * can't get swapped on us any more.
1453 */
1454 raw_spin_lock(&ctx->lock);
1455 if (ctx != rcu_dereference(task->perf_event_ctxp)) {
1456 raw_spin_unlock(&ctx->lock);
1457 rcu_read_unlock();
1458 local_irq_restore(*flags);
1459 goto retry;
1460 }
1461
1462 if (ctx->task == TASK_TOMBSTONE ||
1463 !refcount_inc_not_zero(&ctx->refcount)) {
1464 raw_spin_unlock(&ctx->lock);
1465 ctx = NULL;
1466 } else {
1467 WARN_ON_ONCE(ctx->task != task);
1468 }
1469 }
1470 rcu_read_unlock();
1471 if (!ctx)
1472 local_irq_restore(*flags);
1473 return ctx;
1474 }
1475
1476 /*
1477 * Get the context for a task and increment its pin_count so it
1478 * can't get swapped to another task. This also increments its
1479 * reference count so that the context can't get freed.
1480 */
1481 static struct perf_event_context *
perf_pin_task_context(struct task_struct * task)1482 perf_pin_task_context(struct task_struct *task)
1483 {
1484 struct perf_event_context *ctx;
1485 unsigned long flags;
1486
1487 ctx = perf_lock_task_context(task, &flags);
1488 if (ctx) {
1489 ++ctx->pin_count;
1490 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1491 }
1492 return ctx;
1493 }
1494
perf_unpin_context(struct perf_event_context * ctx)1495 static void perf_unpin_context(struct perf_event_context *ctx)
1496 {
1497 unsigned long flags;
1498
1499 raw_spin_lock_irqsave(&ctx->lock, flags);
1500 --ctx->pin_count;
1501 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1502 }
1503
1504 /*
1505 * Update the record of the current time in a context.
1506 */
__update_context_time(struct perf_event_context * ctx,bool adv)1507 static void __update_context_time(struct perf_event_context *ctx, bool adv)
1508 {
1509 u64 now = perf_clock();
1510
1511 lockdep_assert_held(&ctx->lock);
1512
1513 if (adv)
1514 ctx->time += now - ctx->timestamp;
1515 ctx->timestamp = now;
1516
1517 /*
1518 * The above: time' = time + (now - timestamp), can be re-arranged
1519 * into: time` = now + (time - timestamp), which gives a single value
1520 * offset to compute future time without locks on.
1521 *
1522 * See perf_event_time_now(), which can be used from NMI context where
1523 * it's (obviously) not possible to acquire ctx->lock in order to read
1524 * both the above values in a consistent manner.
1525 */
1526 WRITE_ONCE(ctx->timeoffset, ctx->time - ctx->timestamp);
1527 }
1528
update_context_time(struct perf_event_context * ctx)1529 static void update_context_time(struct perf_event_context *ctx)
1530 {
1531 __update_context_time(ctx, true);
1532 }
1533
perf_event_time(struct perf_event * event)1534 static u64 perf_event_time(struct perf_event *event)
1535 {
1536 struct perf_event_context *ctx = event->ctx;
1537
1538 if (unlikely(!ctx))
1539 return 0;
1540
1541 if (is_cgroup_event(event))
1542 return perf_cgroup_event_time(event);
1543
1544 return ctx->time;
1545 }
1546
perf_event_time_now(struct perf_event * event,u64 now)1547 static u64 perf_event_time_now(struct perf_event *event, u64 now)
1548 {
1549 struct perf_event_context *ctx = event->ctx;
1550
1551 if (unlikely(!ctx))
1552 return 0;
1553
1554 if (is_cgroup_event(event))
1555 return perf_cgroup_event_time_now(event, now);
1556
1557 if (!(__load_acquire(&ctx->is_active) & EVENT_TIME))
1558 return ctx->time;
1559
1560 now += READ_ONCE(ctx->timeoffset);
1561 return now;
1562 }
1563
get_event_type(struct perf_event * event)1564 static enum event_type_t get_event_type(struct perf_event *event)
1565 {
1566 struct perf_event_context *ctx = event->ctx;
1567 enum event_type_t event_type;
1568
1569 lockdep_assert_held(&ctx->lock);
1570
1571 /*
1572 * It's 'group type', really, because if our group leader is
1573 * pinned, so are we.
1574 */
1575 if (event->group_leader != event)
1576 event = event->group_leader;
1577
1578 event_type = event->attr.pinned ? EVENT_PINNED : EVENT_FLEXIBLE;
1579 if (!ctx->task)
1580 event_type |= EVENT_CPU;
1581
1582 return event_type;
1583 }
1584
1585 /*
1586 * Helper function to initialize event group nodes.
1587 */
init_event_group(struct perf_event * event)1588 static void init_event_group(struct perf_event *event)
1589 {
1590 RB_CLEAR_NODE(&event->group_node);
1591 event->group_index = 0;
1592 }
1593
1594 /*
1595 * Extract pinned or flexible groups from the context
1596 * based on event attrs bits.
1597 */
1598 static struct perf_event_groups *
get_event_groups(struct perf_event * event,struct perf_event_context * ctx)1599 get_event_groups(struct perf_event *event, struct perf_event_context *ctx)
1600 {
1601 if (event->attr.pinned)
1602 return &ctx->pinned_groups;
1603 else
1604 return &ctx->flexible_groups;
1605 }
1606
1607 /*
1608 * Helper function to initializes perf_event_group trees.
1609 */
perf_event_groups_init(struct perf_event_groups * groups)1610 static void perf_event_groups_init(struct perf_event_groups *groups)
1611 {
1612 groups->tree = RB_ROOT;
1613 groups->index = 0;
1614 }
1615
event_cgroup(const struct perf_event * event)1616 static inline struct cgroup *event_cgroup(const struct perf_event *event)
1617 {
1618 struct cgroup *cgroup = NULL;
1619
1620 #ifdef CONFIG_CGROUP_PERF
1621 if (event->cgrp)
1622 cgroup = event->cgrp->css.cgroup;
1623 #endif
1624
1625 return cgroup;
1626 }
1627
1628 /*
1629 * Compare function for event groups;
1630 *
1631 * Implements complex key that first sorts by CPU and then by virtual index
1632 * which provides ordering when rotating groups for the same CPU.
1633 */
1634 static __always_inline int
perf_event_groups_cmp(const int left_cpu,const struct pmu * left_pmu,const struct cgroup * left_cgroup,const u64 left_group_index,const struct perf_event * right)1635 perf_event_groups_cmp(const int left_cpu, const struct pmu *left_pmu,
1636 const struct cgroup *left_cgroup, const u64 left_group_index,
1637 const struct perf_event *right)
1638 {
1639 if (left_cpu < right->cpu)
1640 return -1;
1641 if (left_cpu > right->cpu)
1642 return 1;
1643
1644 if (left_pmu) {
1645 if (left_pmu < right->pmu_ctx->pmu)
1646 return -1;
1647 if (left_pmu > right->pmu_ctx->pmu)
1648 return 1;
1649 }
1650
1651 #ifdef CONFIG_CGROUP_PERF
1652 {
1653 const struct cgroup *right_cgroup = event_cgroup(right);
1654
1655 if (left_cgroup != right_cgroup) {
1656 if (!left_cgroup) {
1657 /*
1658 * Left has no cgroup but right does, no
1659 * cgroups come first.
1660 */
1661 return -1;
1662 }
1663 if (!right_cgroup) {
1664 /*
1665 * Right has no cgroup but left does, no
1666 * cgroups come first.
1667 */
1668 return 1;
1669 }
1670 /* Two dissimilar cgroups, order by id. */
1671 if (cgroup_id(left_cgroup) < cgroup_id(right_cgroup))
1672 return -1;
1673
1674 return 1;
1675 }
1676 }
1677 #endif
1678
1679 if (left_group_index < right->group_index)
1680 return -1;
1681 if (left_group_index > right->group_index)
1682 return 1;
1683
1684 return 0;
1685 }
1686
1687 #define __node_2_pe(node) \
1688 rb_entry((node), struct perf_event, group_node)
1689
__group_less(struct rb_node * a,const struct rb_node * b)1690 static inline bool __group_less(struct rb_node *a, const struct rb_node *b)
1691 {
1692 struct perf_event *e = __node_2_pe(a);
1693 return perf_event_groups_cmp(e->cpu, e->pmu_ctx->pmu, event_cgroup(e),
1694 e->group_index, __node_2_pe(b)) < 0;
1695 }
1696
1697 struct __group_key {
1698 int cpu;
1699 struct pmu *pmu;
1700 struct cgroup *cgroup;
1701 };
1702
__group_cmp(const void * key,const struct rb_node * node)1703 static inline int __group_cmp(const void *key, const struct rb_node *node)
1704 {
1705 const struct __group_key *a = key;
1706 const struct perf_event *b = __node_2_pe(node);
1707
1708 /* partial/subtree match: @cpu, @pmu, @cgroup; ignore: @group_index */
1709 return perf_event_groups_cmp(a->cpu, a->pmu, a->cgroup, b->group_index, b);
1710 }
1711
1712 static inline int
__group_cmp_ignore_cgroup(const void * key,const struct rb_node * node)1713 __group_cmp_ignore_cgroup(const void *key, const struct rb_node *node)
1714 {
1715 const struct __group_key *a = key;
1716 const struct perf_event *b = __node_2_pe(node);
1717
1718 /* partial/subtree match: @cpu, @pmu, ignore: @cgroup, @group_index */
1719 return perf_event_groups_cmp(a->cpu, a->pmu, event_cgroup(b),
1720 b->group_index, b);
1721 }
1722
1723 /*
1724 * Insert @event into @groups' tree; using
1725 * {@event->cpu, @event->pmu_ctx->pmu, event_cgroup(@event), ++@groups->index}
1726 * as key. This places it last inside the {cpu,pmu,cgroup} subtree.
1727 */
1728 static void
perf_event_groups_insert(struct perf_event_groups * groups,struct perf_event * event)1729 perf_event_groups_insert(struct perf_event_groups *groups,
1730 struct perf_event *event)
1731 {
1732 event->group_index = ++groups->index;
1733
1734 rb_add(&event->group_node, &groups->tree, __group_less);
1735 }
1736
1737 /*
1738 * Helper function to insert event into the pinned or flexible groups.
1739 */
1740 static void
add_event_to_groups(struct perf_event * event,struct perf_event_context * ctx)1741 add_event_to_groups(struct perf_event *event, struct perf_event_context *ctx)
1742 {
1743 struct perf_event_groups *groups;
1744
1745 groups = get_event_groups(event, ctx);
1746 perf_event_groups_insert(groups, event);
1747 }
1748
1749 /*
1750 * Delete a group from a tree.
1751 */
1752 static void
perf_event_groups_delete(struct perf_event_groups * groups,struct perf_event * event)1753 perf_event_groups_delete(struct perf_event_groups *groups,
1754 struct perf_event *event)
1755 {
1756 WARN_ON_ONCE(RB_EMPTY_NODE(&event->group_node) ||
1757 RB_EMPTY_ROOT(&groups->tree));
1758
1759 rb_erase(&event->group_node, &groups->tree);
1760 init_event_group(event);
1761 }
1762
1763 /*
1764 * Helper function to delete event from its groups.
1765 */
1766 static void
del_event_from_groups(struct perf_event * event,struct perf_event_context * ctx)1767 del_event_from_groups(struct perf_event *event, struct perf_event_context *ctx)
1768 {
1769 struct perf_event_groups *groups;
1770
1771 groups = get_event_groups(event, ctx);
1772 perf_event_groups_delete(groups, event);
1773 }
1774
1775 /*
1776 * Get the leftmost event in the {cpu,pmu,cgroup} subtree.
1777 */
1778 static struct perf_event *
perf_event_groups_first(struct perf_event_groups * groups,int cpu,struct pmu * pmu,struct cgroup * cgrp)1779 perf_event_groups_first(struct perf_event_groups *groups, int cpu,
1780 struct pmu *pmu, struct cgroup *cgrp)
1781 {
1782 struct __group_key key = {
1783 .cpu = cpu,
1784 .pmu = pmu,
1785 .cgroup = cgrp,
1786 };
1787 struct rb_node *node;
1788
1789 node = rb_find_first(&key, &groups->tree, __group_cmp);
1790 if (node)
1791 return __node_2_pe(node);
1792
1793 return NULL;
1794 }
1795
1796 static struct perf_event *
perf_event_groups_next(struct perf_event * event,struct pmu * pmu)1797 perf_event_groups_next(struct perf_event *event, struct pmu *pmu)
1798 {
1799 struct __group_key key = {
1800 .cpu = event->cpu,
1801 .pmu = pmu,
1802 .cgroup = event_cgroup(event),
1803 };
1804 struct rb_node *next;
1805
1806 next = rb_next_match(&key, &event->group_node, __group_cmp);
1807 if (next)
1808 return __node_2_pe(next);
1809
1810 return NULL;
1811 }
1812
1813 #define perf_event_groups_for_cpu_pmu(event, groups, cpu, pmu) \
1814 for (event = perf_event_groups_first(groups, cpu, pmu, NULL); \
1815 event; event = perf_event_groups_next(event, pmu))
1816
1817 /*
1818 * Iterate through the whole groups tree.
1819 */
1820 #define perf_event_groups_for_each(event, groups) \
1821 for (event = rb_entry_safe(rb_first(&((groups)->tree)), \
1822 typeof(*event), group_node); event; \
1823 event = rb_entry_safe(rb_next(&event->group_node), \
1824 typeof(*event), group_node))
1825
1826 /*
1827 * Does the event attribute request inherit with PERF_SAMPLE_READ
1828 */
has_inherit_and_sample_read(struct perf_event_attr * attr)1829 static inline bool has_inherit_and_sample_read(struct perf_event_attr *attr)
1830 {
1831 return attr->inherit && (attr->sample_type & PERF_SAMPLE_READ);
1832 }
1833
1834 /*
1835 * Add an event from the lists for its context.
1836 * Must be called with ctx->mutex and ctx->lock held.
1837 */
1838 static void
list_add_event(struct perf_event * event,struct perf_event_context * ctx)1839 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1840 {
1841 lockdep_assert_held(&ctx->lock);
1842
1843 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1844 event->attach_state |= PERF_ATTACH_CONTEXT;
1845
1846 event->tstamp = perf_event_time(event);
1847
1848 /*
1849 * If we're a stand alone event or group leader, we go to the context
1850 * list, group events are kept attached to the group so that
1851 * perf_group_detach can, at all times, locate all siblings.
1852 */
1853 if (event->group_leader == event) {
1854 event->group_caps = event->event_caps;
1855 add_event_to_groups(event, ctx);
1856 }
1857
1858 list_add_rcu(&event->event_entry, &ctx->event_list);
1859 ctx->nr_events++;
1860 if (event->hw.flags & PERF_EVENT_FLAG_USER_READ_CNT)
1861 ctx->nr_user++;
1862 if (event->attr.inherit_stat)
1863 ctx->nr_stat++;
1864 if (has_inherit_and_sample_read(&event->attr))
1865 local_inc(&ctx->nr_no_switch_fast);
1866
1867 if (event->state > PERF_EVENT_STATE_OFF)
1868 perf_cgroup_event_enable(event, ctx);
1869
1870 ctx->generation++;
1871 event->pmu_ctx->nr_events++;
1872 }
1873
1874 /*
1875 * Initialize event state based on the perf_event_attr::disabled.
1876 */
perf_event__state_init(struct perf_event * event)1877 static inline void perf_event__state_init(struct perf_event *event)
1878 {
1879 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1880 PERF_EVENT_STATE_INACTIVE;
1881 }
1882
__perf_event_read_size(u64 read_format,int nr_siblings)1883 static int __perf_event_read_size(u64 read_format, int nr_siblings)
1884 {
1885 int entry = sizeof(u64); /* value */
1886 int size = 0;
1887 int nr = 1;
1888
1889 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1890 size += sizeof(u64);
1891
1892 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1893 size += sizeof(u64);
1894
1895 if (read_format & PERF_FORMAT_ID)
1896 entry += sizeof(u64);
1897
1898 if (read_format & PERF_FORMAT_LOST)
1899 entry += sizeof(u64);
1900
1901 if (read_format & PERF_FORMAT_GROUP) {
1902 nr += nr_siblings;
1903 size += sizeof(u64);
1904 }
1905
1906 /*
1907 * Since perf_event_validate_size() limits this to 16k and inhibits
1908 * adding more siblings, this will never overflow.
1909 */
1910 return size + nr * entry;
1911 }
1912
__perf_event_header_size(struct perf_event * event,u64 sample_type)1913 static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
1914 {
1915 struct perf_sample_data *data;
1916 u16 size = 0;
1917
1918 if (sample_type & PERF_SAMPLE_IP)
1919 size += sizeof(data->ip);
1920
1921 if (sample_type & PERF_SAMPLE_ADDR)
1922 size += sizeof(data->addr);
1923
1924 if (sample_type & PERF_SAMPLE_PERIOD)
1925 size += sizeof(data->period);
1926
1927 if (sample_type & PERF_SAMPLE_WEIGHT_TYPE)
1928 size += sizeof(data->weight.full);
1929
1930 if (sample_type & PERF_SAMPLE_READ)
1931 size += event->read_size;
1932
1933 if (sample_type & PERF_SAMPLE_DATA_SRC)
1934 size += sizeof(data->data_src.val);
1935
1936 if (sample_type & PERF_SAMPLE_TRANSACTION)
1937 size += sizeof(data->txn);
1938
1939 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
1940 size += sizeof(data->phys_addr);
1941
1942 if (sample_type & PERF_SAMPLE_CGROUP)
1943 size += sizeof(data->cgroup);
1944
1945 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
1946 size += sizeof(data->data_page_size);
1947
1948 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
1949 size += sizeof(data->code_page_size);
1950
1951 event->header_size = size;
1952 }
1953
1954 /*
1955 * Called at perf_event creation and when events are attached/detached from a
1956 * group.
1957 */
perf_event__header_size(struct perf_event * event)1958 static void perf_event__header_size(struct perf_event *event)
1959 {
1960 event->read_size =
1961 __perf_event_read_size(event->attr.read_format,
1962 event->group_leader->nr_siblings);
1963 __perf_event_header_size(event, event->attr.sample_type);
1964 }
1965
perf_event__id_header_size(struct perf_event * event)1966 static void perf_event__id_header_size(struct perf_event *event)
1967 {
1968 struct perf_sample_data *data;
1969 u64 sample_type = event->attr.sample_type;
1970 u16 size = 0;
1971
1972 if (sample_type & PERF_SAMPLE_TID)
1973 size += sizeof(data->tid_entry);
1974
1975 if (sample_type & PERF_SAMPLE_TIME)
1976 size += sizeof(data->time);
1977
1978 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1979 size += sizeof(data->id);
1980
1981 if (sample_type & PERF_SAMPLE_ID)
1982 size += sizeof(data->id);
1983
1984 if (sample_type & PERF_SAMPLE_STREAM_ID)
1985 size += sizeof(data->stream_id);
1986
1987 if (sample_type & PERF_SAMPLE_CPU)
1988 size += sizeof(data->cpu_entry);
1989
1990 event->id_header_size = size;
1991 }
1992
1993 /*
1994 * Check that adding an event to the group does not result in anybody
1995 * overflowing the 64k event limit imposed by the output buffer.
1996 *
1997 * Specifically, check that the read_size for the event does not exceed 16k,
1998 * read_size being the one term that grows with groups size. Since read_size
1999 * depends on per-event read_format, also (re)check the existing events.
2000 *
2001 * This leaves 48k for the constant size fields and things like callchains,
2002 * branch stacks and register sets.
2003 */
perf_event_validate_size(struct perf_event * event)2004 static bool perf_event_validate_size(struct perf_event *event)
2005 {
2006 struct perf_event *sibling, *group_leader = event->group_leader;
2007
2008 if (__perf_event_read_size(event->attr.read_format,
2009 group_leader->nr_siblings + 1) > 16*1024)
2010 return false;
2011
2012 if (__perf_event_read_size(group_leader->attr.read_format,
2013 group_leader->nr_siblings + 1) > 16*1024)
2014 return false;
2015
2016 /*
2017 * When creating a new group leader, group_leader->ctx is initialized
2018 * after the size has been validated, but we cannot safely use
2019 * for_each_sibling_event() until group_leader->ctx is set. A new group
2020 * leader cannot have any siblings yet, so we can safely skip checking
2021 * the non-existent siblings.
2022 */
2023 if (event == group_leader)
2024 return true;
2025
2026 for_each_sibling_event(sibling, group_leader) {
2027 if (__perf_event_read_size(sibling->attr.read_format,
2028 group_leader->nr_siblings + 1) > 16*1024)
2029 return false;
2030 }
2031
2032 return true;
2033 }
2034
perf_group_attach(struct perf_event * event)2035 static void perf_group_attach(struct perf_event *event)
2036 {
2037 struct perf_event *group_leader = event->group_leader, *pos;
2038
2039 lockdep_assert_held(&event->ctx->lock);
2040
2041 /*
2042 * We can have double attach due to group movement (move_group) in
2043 * perf_event_open().
2044 */
2045 if (event->attach_state & PERF_ATTACH_GROUP)
2046 return;
2047
2048 event->attach_state |= PERF_ATTACH_GROUP;
2049
2050 if (group_leader == event)
2051 return;
2052
2053 WARN_ON_ONCE(group_leader->ctx != event->ctx);
2054
2055 group_leader->group_caps &= event->event_caps;
2056
2057 list_add_tail(&event->sibling_list, &group_leader->sibling_list);
2058 group_leader->nr_siblings++;
2059 group_leader->group_generation++;
2060
2061 perf_event__header_size(group_leader);
2062
2063 for_each_sibling_event(pos, group_leader)
2064 perf_event__header_size(pos);
2065 }
2066
2067 /*
2068 * Remove an event from the lists for its context.
2069 * Must be called with ctx->mutex and ctx->lock held.
2070 */
2071 static void
list_del_event(struct perf_event * event,struct perf_event_context * ctx)2072 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
2073 {
2074 WARN_ON_ONCE(event->ctx != ctx);
2075 lockdep_assert_held(&ctx->lock);
2076
2077 /*
2078 * We can have double detach due to exit/hot-unplug + close.
2079 */
2080 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
2081 return;
2082
2083 event->attach_state &= ~PERF_ATTACH_CONTEXT;
2084
2085 ctx->nr_events--;
2086 if (event->hw.flags & PERF_EVENT_FLAG_USER_READ_CNT)
2087 ctx->nr_user--;
2088 if (event->attr.inherit_stat)
2089 ctx->nr_stat--;
2090 if (has_inherit_and_sample_read(&event->attr))
2091 local_dec(&ctx->nr_no_switch_fast);
2092
2093 list_del_rcu(&event->event_entry);
2094
2095 if (event->group_leader == event)
2096 del_event_from_groups(event, ctx);
2097
2098 /*
2099 * If event was in error state, then keep it
2100 * that way, otherwise bogus counts will be
2101 * returned on read(). The only way to get out
2102 * of error state is by explicit re-enabling
2103 * of the event
2104 */
2105 if (event->state > PERF_EVENT_STATE_OFF) {
2106 perf_cgroup_event_disable(event, ctx);
2107 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2108 }
2109
2110 ctx->generation++;
2111 event->pmu_ctx->nr_events--;
2112 }
2113
2114 static int
perf_aux_output_match(struct perf_event * event,struct perf_event * aux_event)2115 perf_aux_output_match(struct perf_event *event, struct perf_event *aux_event)
2116 {
2117 if (!has_aux(aux_event))
2118 return 0;
2119
2120 if (!event->pmu->aux_output_match)
2121 return 0;
2122
2123 return event->pmu->aux_output_match(aux_event);
2124 }
2125
2126 static void put_event(struct perf_event *event);
2127 static void __event_disable(struct perf_event *event,
2128 struct perf_event_context *ctx,
2129 enum perf_event_state state);
2130
perf_put_aux_event(struct perf_event * event)2131 static void perf_put_aux_event(struct perf_event *event)
2132 {
2133 struct perf_event_context *ctx = event->ctx;
2134 struct perf_event *iter;
2135
2136 /*
2137 * If event uses aux_event tear down the link
2138 */
2139 if (event->aux_event) {
2140 iter = event->aux_event;
2141 event->aux_event = NULL;
2142 put_event(iter);
2143 return;
2144 }
2145
2146 /*
2147 * If the event is an aux_event, tear down all links to
2148 * it from other events.
2149 */
2150 for_each_sibling_event(iter, event->group_leader) {
2151 if (iter->aux_event != event)
2152 continue;
2153
2154 iter->aux_event = NULL;
2155 put_event(event);
2156
2157 /*
2158 * If it's ACTIVE, schedule it out and put it into ERROR
2159 * state so that we don't try to schedule it again. Note
2160 * that perf_event_enable() will clear the ERROR status.
2161 */
2162 __event_disable(iter, ctx, PERF_EVENT_STATE_ERROR);
2163 }
2164 }
2165
perf_need_aux_event(struct perf_event * event)2166 static bool perf_need_aux_event(struct perf_event *event)
2167 {
2168 return event->attr.aux_output || has_aux_action(event);
2169 }
2170
perf_get_aux_event(struct perf_event * event,struct perf_event * group_leader)2171 static int perf_get_aux_event(struct perf_event *event,
2172 struct perf_event *group_leader)
2173 {
2174 /*
2175 * Our group leader must be an aux event if we want to be
2176 * an aux_output. This way, the aux event will precede its
2177 * aux_output events in the group, and therefore will always
2178 * schedule first.
2179 */
2180 if (!group_leader)
2181 return 0;
2182
2183 /*
2184 * aux_output and aux_sample_size are mutually exclusive.
2185 */
2186 if (event->attr.aux_output && event->attr.aux_sample_size)
2187 return 0;
2188
2189 if (event->attr.aux_output &&
2190 !perf_aux_output_match(event, group_leader))
2191 return 0;
2192
2193 if ((event->attr.aux_pause || event->attr.aux_resume) &&
2194 !(group_leader->pmu->capabilities & PERF_PMU_CAP_AUX_PAUSE))
2195 return 0;
2196
2197 if (event->attr.aux_sample_size && !group_leader->pmu->snapshot_aux)
2198 return 0;
2199
2200 if (!atomic_long_inc_not_zero(&group_leader->refcount))
2201 return 0;
2202
2203 /*
2204 * Link aux_outputs to their aux event; this is undone in
2205 * perf_group_detach() by perf_put_aux_event(). When the
2206 * group in torn down, the aux_output events loose their
2207 * link to the aux_event and can't schedule any more.
2208 */
2209 event->aux_event = group_leader;
2210
2211 return 1;
2212 }
2213
get_event_list(struct perf_event * event)2214 static inline struct list_head *get_event_list(struct perf_event *event)
2215 {
2216 return event->attr.pinned ? &event->pmu_ctx->pinned_active :
2217 &event->pmu_ctx->flexible_active;
2218 }
2219
perf_group_detach(struct perf_event * event)2220 static void perf_group_detach(struct perf_event *event)
2221 {
2222 struct perf_event *leader = event->group_leader;
2223 struct perf_event *sibling, *tmp;
2224 struct perf_event_context *ctx = event->ctx;
2225
2226 lockdep_assert_held(&ctx->lock);
2227
2228 /*
2229 * We can have double detach due to exit/hot-unplug + close.
2230 */
2231 if (!(event->attach_state & PERF_ATTACH_GROUP))
2232 return;
2233
2234 event->attach_state &= ~PERF_ATTACH_GROUP;
2235
2236 perf_put_aux_event(event);
2237
2238 /*
2239 * If this is a sibling, remove it from its group.
2240 */
2241 if (leader != event) {
2242 list_del_init(&event->sibling_list);
2243 event->group_leader->nr_siblings--;
2244 event->group_leader->group_generation++;
2245 goto out;
2246 }
2247
2248 /*
2249 * If this was a group event with sibling events then
2250 * upgrade the siblings to singleton events by adding them
2251 * to whatever list we are on.
2252 */
2253 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, sibling_list) {
2254
2255 /*
2256 * Events that have PERF_EV_CAP_SIBLING require being part of
2257 * a group and cannot exist on their own, schedule them out
2258 * and move them into the ERROR state. Also see
2259 * _perf_event_enable(), it will not be able to recover this
2260 * ERROR state.
2261 */
2262 if (sibling->event_caps & PERF_EV_CAP_SIBLING)
2263 __event_disable(sibling, ctx, PERF_EVENT_STATE_ERROR);
2264
2265 sibling->group_leader = sibling;
2266 list_del_init(&sibling->sibling_list);
2267
2268 /* Inherit group flags from the previous leader */
2269 sibling->group_caps = event->group_caps;
2270
2271 if (sibling->attach_state & PERF_ATTACH_CONTEXT) {
2272 add_event_to_groups(sibling, event->ctx);
2273
2274 if (sibling->state == PERF_EVENT_STATE_ACTIVE)
2275 list_add_tail(&sibling->active_list, get_event_list(sibling));
2276 }
2277
2278 WARN_ON_ONCE(sibling->ctx != event->ctx);
2279 }
2280
2281 out:
2282 for_each_sibling_event(tmp, leader)
2283 perf_event__header_size(tmp);
2284
2285 perf_event__header_size(leader);
2286 }
2287
2288 static void sync_child_event(struct perf_event *child_event);
2289
perf_child_detach(struct perf_event * event)2290 static void perf_child_detach(struct perf_event *event)
2291 {
2292 struct perf_event *parent_event = event->parent;
2293
2294 if (!(event->attach_state & PERF_ATTACH_CHILD))
2295 return;
2296
2297 event->attach_state &= ~PERF_ATTACH_CHILD;
2298
2299 if (WARN_ON_ONCE(!parent_event))
2300 return;
2301
2302 lockdep_assert_held(&parent_event->child_mutex);
2303
2304 sync_child_event(event);
2305 list_del_init(&event->child_list);
2306 }
2307
is_orphaned_event(struct perf_event * event)2308 static bool is_orphaned_event(struct perf_event *event)
2309 {
2310 return event->state == PERF_EVENT_STATE_DEAD;
2311 }
2312
2313 static inline int
event_filter_match(struct perf_event * event)2314 event_filter_match(struct perf_event *event)
2315 {
2316 return (event->cpu == -1 || event->cpu == smp_processor_id()) &&
2317 perf_cgroup_match(event);
2318 }
2319
2320 static void
event_sched_out(struct perf_event * event,struct perf_event_context * ctx)2321 event_sched_out(struct perf_event *event, struct perf_event_context *ctx)
2322 {
2323 struct perf_event_pmu_context *epc = event->pmu_ctx;
2324 struct perf_cpu_pmu_context *cpc = this_cpu_ptr(epc->pmu->cpu_pmu_context);
2325 enum perf_event_state state = PERF_EVENT_STATE_INACTIVE;
2326
2327 // XXX cpc serialization, probably per-cpu IRQ disabled
2328
2329 WARN_ON_ONCE(event->ctx != ctx);
2330 lockdep_assert_held(&ctx->lock);
2331
2332 if (event->state != PERF_EVENT_STATE_ACTIVE)
2333 return;
2334
2335 /*
2336 * Asymmetry; we only schedule events _IN_ through ctx_sched_in(), but
2337 * we can schedule events _OUT_ individually through things like
2338 * __perf_remove_from_context().
2339 */
2340 list_del_init(&event->active_list);
2341
2342 perf_pmu_disable(event->pmu);
2343
2344 event->pmu->del(event, 0);
2345 event->oncpu = -1;
2346
2347 if (event->pending_disable) {
2348 event->pending_disable = 0;
2349 perf_cgroup_event_disable(event, ctx);
2350 state = PERF_EVENT_STATE_OFF;
2351 }
2352
2353 perf_event_set_state(event, state);
2354
2355 if (!is_software_event(event))
2356 cpc->active_oncpu--;
2357 if (event->attr.freq && event->attr.sample_freq) {
2358 ctx->nr_freq--;
2359 epc->nr_freq--;
2360 }
2361 if (event->attr.exclusive || !cpc->active_oncpu)
2362 cpc->exclusive = 0;
2363
2364 perf_pmu_enable(event->pmu);
2365 }
2366
2367 static void
group_sched_out(struct perf_event * group_event,struct perf_event_context * ctx)2368 group_sched_out(struct perf_event *group_event, struct perf_event_context *ctx)
2369 {
2370 struct perf_event *event;
2371
2372 if (group_event->state != PERF_EVENT_STATE_ACTIVE)
2373 return;
2374
2375 perf_assert_pmu_disabled(group_event->pmu_ctx->pmu);
2376
2377 event_sched_out(group_event, ctx);
2378
2379 /*
2380 * Schedule out siblings (if any):
2381 */
2382 for_each_sibling_event(event, group_event)
2383 event_sched_out(event, ctx);
2384 }
2385
2386 static inline void
__ctx_time_update(struct perf_cpu_context * cpuctx,struct perf_event_context * ctx,bool final)2387 __ctx_time_update(struct perf_cpu_context *cpuctx, struct perf_event_context *ctx, bool final)
2388 {
2389 if (ctx->is_active & EVENT_TIME) {
2390 if (ctx->is_active & EVENT_FROZEN)
2391 return;
2392 update_context_time(ctx);
2393 update_cgrp_time_from_cpuctx(cpuctx, final);
2394 }
2395 }
2396
2397 static inline void
ctx_time_update(struct perf_cpu_context * cpuctx,struct perf_event_context * ctx)2398 ctx_time_update(struct perf_cpu_context *cpuctx, struct perf_event_context *ctx)
2399 {
2400 __ctx_time_update(cpuctx, ctx, false);
2401 }
2402
2403 /*
2404 * To be used inside perf_ctx_lock() / perf_ctx_unlock(). Lasts until perf_ctx_unlock().
2405 */
2406 static inline void
ctx_time_freeze(struct perf_cpu_context * cpuctx,struct perf_event_context * ctx)2407 ctx_time_freeze(struct perf_cpu_context *cpuctx, struct perf_event_context *ctx)
2408 {
2409 ctx_time_update(cpuctx, ctx);
2410 if (ctx->is_active & EVENT_TIME)
2411 ctx->is_active |= EVENT_FROZEN;
2412 }
2413
2414 static inline void
ctx_time_update_event(struct perf_event_context * ctx,struct perf_event * event)2415 ctx_time_update_event(struct perf_event_context *ctx, struct perf_event *event)
2416 {
2417 if (ctx->is_active & EVENT_TIME) {
2418 if (ctx->is_active & EVENT_FROZEN)
2419 return;
2420 update_context_time(ctx);
2421 update_cgrp_time_from_event(event);
2422 }
2423 }
2424
2425 #define DETACH_GROUP 0x01UL
2426 #define DETACH_CHILD 0x02UL
2427 #define DETACH_DEAD 0x04UL
2428 #define DETACH_EXIT 0x08UL
2429
2430 /*
2431 * Cross CPU call to remove a performance event
2432 *
2433 * We disable the event on the hardware level first. After that we
2434 * remove it from the context list.
2435 */
2436 static void
__perf_remove_from_context(struct perf_event * event,struct perf_cpu_context * cpuctx,struct perf_event_context * ctx,void * info)2437 __perf_remove_from_context(struct perf_event *event,
2438 struct perf_cpu_context *cpuctx,
2439 struct perf_event_context *ctx,
2440 void *info)
2441 {
2442 struct perf_event_pmu_context *pmu_ctx = event->pmu_ctx;
2443 enum perf_event_state state = PERF_EVENT_STATE_OFF;
2444 unsigned long flags = (unsigned long)info;
2445
2446 ctx_time_update(cpuctx, ctx);
2447
2448 /*
2449 * Ensure event_sched_out() switches to OFF, at the very least
2450 * this avoids raising perf_pending_task() at this time.
2451 */
2452 if (flags & DETACH_EXIT)
2453 state = PERF_EVENT_STATE_EXIT;
2454 if (flags & DETACH_DEAD) {
2455 event->pending_disable = 1;
2456 state = PERF_EVENT_STATE_DEAD;
2457 }
2458 event_sched_out(event, ctx);
2459 perf_event_set_state(event, min(event->state, state));
2460 if (flags & DETACH_GROUP)
2461 perf_group_detach(event);
2462 if (flags & DETACH_CHILD)
2463 perf_child_detach(event);
2464 list_del_event(event, ctx);
2465
2466 if (!pmu_ctx->nr_events) {
2467 pmu_ctx->rotate_necessary = 0;
2468
2469 if (ctx->task && ctx->is_active) {
2470 struct perf_cpu_pmu_context *cpc;
2471
2472 cpc = this_cpu_ptr(pmu_ctx->pmu->cpu_pmu_context);
2473 WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx);
2474 cpc->task_epc = NULL;
2475 }
2476 }
2477
2478 if (!ctx->nr_events && ctx->is_active) {
2479 if (ctx == &cpuctx->ctx)
2480 update_cgrp_time_from_cpuctx(cpuctx, true);
2481
2482 ctx->is_active = 0;
2483 if (ctx->task) {
2484 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2485 cpuctx->task_ctx = NULL;
2486 }
2487 }
2488 }
2489
2490 /*
2491 * Remove the event from a task's (or a CPU's) list of events.
2492 *
2493 * If event->ctx is a cloned context, callers must make sure that
2494 * every task struct that event->ctx->task could possibly point to
2495 * remains valid. This is OK when called from perf_release since
2496 * that only calls us on the top-level context, which can't be a clone.
2497 * When called from perf_event_exit_task, it's OK because the
2498 * context has been detached from its task.
2499 */
perf_remove_from_context(struct perf_event * event,unsigned long flags)2500 static void perf_remove_from_context(struct perf_event *event, unsigned long flags)
2501 {
2502 struct perf_event_context *ctx = event->ctx;
2503
2504 lockdep_assert_held(&ctx->mutex);
2505
2506 /*
2507 * Because of perf_event_exit_task(), perf_remove_from_context() ought
2508 * to work in the face of TASK_TOMBSTONE, unlike every other
2509 * event_function_call() user.
2510 */
2511 raw_spin_lock_irq(&ctx->lock);
2512 if (!ctx->is_active) {
2513 __perf_remove_from_context(event, this_cpu_ptr(&perf_cpu_context),
2514 ctx, (void *)flags);
2515 raw_spin_unlock_irq(&ctx->lock);
2516 return;
2517 }
2518 raw_spin_unlock_irq(&ctx->lock);
2519
2520 event_function_call(event, __perf_remove_from_context, (void *)flags);
2521 }
2522
__event_disable(struct perf_event * event,struct perf_event_context * ctx,enum perf_event_state state)2523 static void __event_disable(struct perf_event *event,
2524 struct perf_event_context *ctx,
2525 enum perf_event_state state)
2526 {
2527 event_sched_out(event, ctx);
2528 perf_cgroup_event_disable(event, ctx);
2529 perf_event_set_state(event, state);
2530 }
2531
2532 /*
2533 * Cross CPU call to disable a performance event
2534 */
__perf_event_disable(struct perf_event * event,struct perf_cpu_context * cpuctx,struct perf_event_context * ctx,void * info)2535 static void __perf_event_disable(struct perf_event *event,
2536 struct perf_cpu_context *cpuctx,
2537 struct perf_event_context *ctx,
2538 void *info)
2539 {
2540 if (event->state < PERF_EVENT_STATE_INACTIVE)
2541 return;
2542
2543 perf_pmu_disable(event->pmu_ctx->pmu);
2544 ctx_time_update_event(ctx, event);
2545
2546 /*
2547 * When disabling a group leader, the whole group becomes ineligible
2548 * to run, so schedule out the full group.
2549 */
2550 if (event == event->group_leader)
2551 group_sched_out(event, ctx);
2552
2553 /*
2554 * But only mark the leader OFF; the siblings will remain
2555 * INACTIVE.
2556 */
2557 __event_disable(event, ctx, PERF_EVENT_STATE_OFF);
2558
2559 perf_pmu_enable(event->pmu_ctx->pmu);
2560 }
2561
2562 /*
2563 * Disable an event.
2564 *
2565 * If event->ctx is a cloned context, callers must make sure that
2566 * every task struct that event->ctx->task could possibly point to
2567 * remains valid. This condition is satisfied when called through
2568 * perf_event_for_each_child or perf_event_for_each because they
2569 * hold the top-level event's child_mutex, so any descendant that
2570 * goes to exit will block in perf_event_exit_event().
2571 *
2572 * When called from perf_pending_disable it's OK because event->ctx
2573 * is the current context on this CPU and preemption is disabled,
2574 * hence we can't get into perf_event_task_sched_out for this context.
2575 */
_perf_event_disable(struct perf_event * event)2576 static void _perf_event_disable(struct perf_event *event)
2577 {
2578 struct perf_event_context *ctx = event->ctx;
2579
2580 raw_spin_lock_irq(&ctx->lock);
2581 if (event->state <= PERF_EVENT_STATE_OFF) {
2582 raw_spin_unlock_irq(&ctx->lock);
2583 return;
2584 }
2585 raw_spin_unlock_irq(&ctx->lock);
2586
2587 event_function_call(event, __perf_event_disable, NULL);
2588 }
2589
perf_event_disable_local(struct perf_event * event)2590 void perf_event_disable_local(struct perf_event *event)
2591 {
2592 event_function_local(event, __perf_event_disable, NULL);
2593 }
2594
2595 /*
2596 * Strictly speaking kernel users cannot create groups and therefore this
2597 * interface does not need the perf_event_ctx_lock() magic.
2598 */
perf_event_disable(struct perf_event * event)2599 void perf_event_disable(struct perf_event *event)
2600 {
2601 struct perf_event_context *ctx;
2602
2603 ctx = perf_event_ctx_lock(event);
2604 _perf_event_disable(event);
2605 perf_event_ctx_unlock(event, ctx);
2606 }
2607 EXPORT_SYMBOL_GPL(perf_event_disable);
2608
perf_event_disable_inatomic(struct perf_event * event)2609 void perf_event_disable_inatomic(struct perf_event *event)
2610 {
2611 event->pending_disable = 1;
2612 irq_work_queue(&event->pending_disable_irq);
2613 }
2614
2615 #define MAX_INTERRUPTS (~0ULL)
2616
2617 static void perf_log_throttle(struct perf_event *event, int enable);
2618 static void perf_log_itrace_start(struct perf_event *event);
2619
2620 static int
event_sched_in(struct perf_event * event,struct perf_event_context * ctx)2621 event_sched_in(struct perf_event *event, struct perf_event_context *ctx)
2622 {
2623 struct perf_event_pmu_context *epc = event->pmu_ctx;
2624 struct perf_cpu_pmu_context *cpc = this_cpu_ptr(epc->pmu->cpu_pmu_context);
2625 int ret = 0;
2626
2627 WARN_ON_ONCE(event->ctx != ctx);
2628
2629 lockdep_assert_held(&ctx->lock);
2630
2631 if (event->state <= PERF_EVENT_STATE_OFF)
2632 return 0;
2633
2634 WRITE_ONCE(event->oncpu, smp_processor_id());
2635 /*
2636 * Order event::oncpu write to happen before the ACTIVE state is
2637 * visible. This allows perf_event_{stop,read}() to observe the correct
2638 * ->oncpu if it sees ACTIVE.
2639 */
2640 smp_wmb();
2641 perf_event_set_state(event, PERF_EVENT_STATE_ACTIVE);
2642
2643 /*
2644 * Unthrottle events, since we scheduled we might have missed several
2645 * ticks already, also for a heavily scheduling task there is little
2646 * guarantee it'll get a tick in a timely manner.
2647 */
2648 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
2649 perf_log_throttle(event, 1);
2650 event->hw.interrupts = 0;
2651 }
2652
2653 perf_pmu_disable(event->pmu);
2654
2655 perf_log_itrace_start(event);
2656
2657 if (event->pmu->add(event, PERF_EF_START)) {
2658 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2659 event->oncpu = -1;
2660 ret = -EAGAIN;
2661 goto out;
2662 }
2663
2664 if (!is_software_event(event))
2665 cpc->active_oncpu++;
2666 if (event->attr.freq && event->attr.sample_freq) {
2667 ctx->nr_freq++;
2668 epc->nr_freq++;
2669 }
2670 if (event->attr.exclusive)
2671 cpc->exclusive = 1;
2672
2673 out:
2674 perf_pmu_enable(event->pmu);
2675
2676 return ret;
2677 }
2678
2679 static int
group_sched_in(struct perf_event * group_event,struct perf_event_context * ctx)2680 group_sched_in(struct perf_event *group_event, struct perf_event_context *ctx)
2681 {
2682 struct perf_event *event, *partial_group = NULL;
2683 struct pmu *pmu = group_event->pmu_ctx->pmu;
2684
2685 if (group_event->state == PERF_EVENT_STATE_OFF)
2686 return 0;
2687
2688 pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
2689
2690 if (event_sched_in(group_event, ctx))
2691 goto error;
2692
2693 /*
2694 * Schedule in siblings as one group (if any):
2695 */
2696 for_each_sibling_event(event, group_event) {
2697 if (event_sched_in(event, ctx)) {
2698 partial_group = event;
2699 goto group_error;
2700 }
2701 }
2702
2703 if (!pmu->commit_txn(pmu))
2704 return 0;
2705
2706 group_error:
2707 /*
2708 * Groups can be scheduled in as one unit only, so undo any
2709 * partial group before returning:
2710 * The events up to the failed event are scheduled out normally.
2711 */
2712 for_each_sibling_event(event, group_event) {
2713 if (event == partial_group)
2714 break;
2715
2716 event_sched_out(event, ctx);
2717 }
2718 event_sched_out(group_event, ctx);
2719
2720 error:
2721 pmu->cancel_txn(pmu);
2722 return -EAGAIN;
2723 }
2724
2725 /*
2726 * Work out whether we can put this event group on the CPU now.
2727 */
group_can_go_on(struct perf_event * event,int can_add_hw)2728 static int group_can_go_on(struct perf_event *event, int can_add_hw)
2729 {
2730 struct perf_event_pmu_context *epc = event->pmu_ctx;
2731 struct perf_cpu_pmu_context *cpc = this_cpu_ptr(epc->pmu->cpu_pmu_context);
2732
2733 /*
2734 * Groups consisting entirely of software events can always go on.
2735 */
2736 if (event->group_caps & PERF_EV_CAP_SOFTWARE)
2737 return 1;
2738 /*
2739 * If an exclusive group is already on, no other hardware
2740 * events can go on.
2741 */
2742 if (cpc->exclusive)
2743 return 0;
2744 /*
2745 * If this group is exclusive and there are already
2746 * events on the CPU, it can't go on.
2747 */
2748 if (event->attr.exclusive && !list_empty(get_event_list(event)))
2749 return 0;
2750 /*
2751 * Otherwise, try to add it if all previous groups were able
2752 * to go on.
2753 */
2754 return can_add_hw;
2755 }
2756
add_event_to_ctx(struct perf_event * event,struct perf_event_context * ctx)2757 static void add_event_to_ctx(struct perf_event *event,
2758 struct perf_event_context *ctx)
2759 {
2760 list_add_event(event, ctx);
2761 perf_group_attach(event);
2762 }
2763
task_ctx_sched_out(struct perf_event_context * ctx,struct pmu * pmu,enum event_type_t event_type)2764 static void task_ctx_sched_out(struct perf_event_context *ctx,
2765 struct pmu *pmu,
2766 enum event_type_t event_type)
2767 {
2768 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
2769
2770 if (!cpuctx->task_ctx)
2771 return;
2772
2773 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2774 return;
2775
2776 ctx_sched_out(ctx, pmu, event_type);
2777 }
2778
perf_event_sched_in(struct perf_cpu_context * cpuctx,struct perf_event_context * ctx,struct pmu * pmu)2779 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2780 struct perf_event_context *ctx,
2781 struct pmu *pmu)
2782 {
2783 ctx_sched_in(&cpuctx->ctx, pmu, EVENT_PINNED);
2784 if (ctx)
2785 ctx_sched_in(ctx, pmu, EVENT_PINNED);
2786 ctx_sched_in(&cpuctx->ctx, pmu, EVENT_FLEXIBLE);
2787 if (ctx)
2788 ctx_sched_in(ctx, pmu, EVENT_FLEXIBLE);
2789 }
2790
2791 /*
2792 * We want to maintain the following priority of scheduling:
2793 * - CPU pinned (EVENT_CPU | EVENT_PINNED)
2794 * - task pinned (EVENT_PINNED)
2795 * - CPU flexible (EVENT_CPU | EVENT_FLEXIBLE)
2796 * - task flexible (EVENT_FLEXIBLE).
2797 *
2798 * In order to avoid unscheduling and scheduling back in everything every
2799 * time an event is added, only do it for the groups of equal priority and
2800 * below.
2801 *
2802 * This can be called after a batch operation on task events, in which case
2803 * event_type is a bit mask of the types of events involved. For CPU events,
2804 * event_type is only either EVENT_PINNED or EVENT_FLEXIBLE.
2805 */
ctx_resched(struct perf_cpu_context * cpuctx,struct perf_event_context * task_ctx,struct pmu * pmu,enum event_type_t event_type)2806 static void ctx_resched(struct perf_cpu_context *cpuctx,
2807 struct perf_event_context *task_ctx,
2808 struct pmu *pmu, enum event_type_t event_type)
2809 {
2810 bool cpu_event = !!(event_type & EVENT_CPU);
2811 struct perf_event_pmu_context *epc;
2812
2813 /*
2814 * If pinned groups are involved, flexible groups also need to be
2815 * scheduled out.
2816 */
2817 if (event_type & EVENT_PINNED)
2818 event_type |= EVENT_FLEXIBLE;
2819
2820 event_type &= EVENT_ALL;
2821
2822 for_each_epc(epc, &cpuctx->ctx, pmu, false)
2823 perf_pmu_disable(epc->pmu);
2824
2825 if (task_ctx) {
2826 for_each_epc(epc, task_ctx, pmu, false)
2827 perf_pmu_disable(epc->pmu);
2828
2829 task_ctx_sched_out(task_ctx, pmu, event_type);
2830 }
2831
2832 /*
2833 * Decide which cpu ctx groups to schedule out based on the types
2834 * of events that caused rescheduling:
2835 * - EVENT_CPU: schedule out corresponding groups;
2836 * - EVENT_PINNED task events: schedule out EVENT_FLEXIBLE groups;
2837 * - otherwise, do nothing more.
2838 */
2839 if (cpu_event)
2840 ctx_sched_out(&cpuctx->ctx, pmu, event_type);
2841 else if (event_type & EVENT_PINNED)
2842 ctx_sched_out(&cpuctx->ctx, pmu, EVENT_FLEXIBLE);
2843
2844 perf_event_sched_in(cpuctx, task_ctx, pmu);
2845
2846 for_each_epc(epc, &cpuctx->ctx, pmu, false)
2847 perf_pmu_enable(epc->pmu);
2848
2849 if (task_ctx) {
2850 for_each_epc(epc, task_ctx, pmu, false)
2851 perf_pmu_enable(epc->pmu);
2852 }
2853 }
2854
perf_pmu_resched(struct pmu * pmu)2855 void perf_pmu_resched(struct pmu *pmu)
2856 {
2857 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
2858 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2859
2860 perf_ctx_lock(cpuctx, task_ctx);
2861 ctx_resched(cpuctx, task_ctx, pmu, EVENT_ALL|EVENT_CPU);
2862 perf_ctx_unlock(cpuctx, task_ctx);
2863 }
2864
2865 /*
2866 * Cross CPU call to install and enable a performance event
2867 *
2868 * Very similar to remote_function() + event_function() but cannot assume that
2869 * things like ctx->is_active and cpuctx->task_ctx are set.
2870 */
__perf_install_in_context(void * info)2871 static int __perf_install_in_context(void *info)
2872 {
2873 struct perf_event *event = info;
2874 struct perf_event_context *ctx = event->ctx;
2875 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
2876 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2877 bool reprogram = true;
2878 int ret = 0;
2879
2880 raw_spin_lock(&cpuctx->ctx.lock);
2881 if (ctx->task) {
2882 raw_spin_lock(&ctx->lock);
2883 task_ctx = ctx;
2884
2885 reprogram = (ctx->task == current);
2886
2887 /*
2888 * If the task is running, it must be running on this CPU,
2889 * otherwise we cannot reprogram things.
2890 *
2891 * If its not running, we don't care, ctx->lock will
2892 * serialize against it becoming runnable.
2893 */
2894 if (task_curr(ctx->task) && !reprogram) {
2895 ret = -ESRCH;
2896 goto unlock;
2897 }
2898
2899 WARN_ON_ONCE(reprogram && cpuctx->task_ctx && cpuctx->task_ctx != ctx);
2900 } else if (task_ctx) {
2901 raw_spin_lock(&task_ctx->lock);
2902 }
2903
2904 #ifdef CONFIG_CGROUP_PERF
2905 if (event->state > PERF_EVENT_STATE_OFF && is_cgroup_event(event)) {
2906 /*
2907 * If the current cgroup doesn't match the event's
2908 * cgroup, we should not try to schedule it.
2909 */
2910 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
2911 reprogram = cgroup_is_descendant(cgrp->css.cgroup,
2912 event->cgrp->css.cgroup);
2913 }
2914 #endif
2915
2916 if (reprogram) {
2917 ctx_time_freeze(cpuctx, ctx);
2918 add_event_to_ctx(event, ctx);
2919 ctx_resched(cpuctx, task_ctx, event->pmu_ctx->pmu,
2920 get_event_type(event));
2921 } else {
2922 add_event_to_ctx(event, ctx);
2923 }
2924
2925 unlock:
2926 perf_ctx_unlock(cpuctx, task_ctx);
2927
2928 return ret;
2929 }
2930
2931 static bool exclusive_event_installable(struct perf_event *event,
2932 struct perf_event_context *ctx);
2933
2934 /*
2935 * Attach a performance event to a context.
2936 *
2937 * Very similar to event_function_call, see comment there.
2938 */
2939 static void
perf_install_in_context(struct perf_event_context * ctx,struct perf_event * event,int cpu)2940 perf_install_in_context(struct perf_event_context *ctx,
2941 struct perf_event *event,
2942 int cpu)
2943 {
2944 struct task_struct *task = READ_ONCE(ctx->task);
2945
2946 lockdep_assert_held(&ctx->mutex);
2947
2948 WARN_ON_ONCE(!exclusive_event_installable(event, ctx));
2949
2950 if (event->cpu != -1)
2951 WARN_ON_ONCE(event->cpu != cpu);
2952
2953 /*
2954 * Ensures that if we can observe event->ctx, both the event and ctx
2955 * will be 'complete'. See perf_iterate_sb_cpu().
2956 */
2957 smp_store_release(&event->ctx, ctx);
2958
2959 /*
2960 * perf_event_attr::disabled events will not run and can be initialized
2961 * without IPI. Except when this is the first event for the context, in
2962 * that case we need the magic of the IPI to set ctx->is_active.
2963 *
2964 * The IOC_ENABLE that is sure to follow the creation of a disabled
2965 * event will issue the IPI and reprogram the hardware.
2966 */
2967 if (__perf_effective_state(event) == PERF_EVENT_STATE_OFF &&
2968 ctx->nr_events && !is_cgroup_event(event)) {
2969 raw_spin_lock_irq(&ctx->lock);
2970 if (ctx->task == TASK_TOMBSTONE) {
2971 raw_spin_unlock_irq(&ctx->lock);
2972 return;
2973 }
2974 add_event_to_ctx(event, ctx);
2975 raw_spin_unlock_irq(&ctx->lock);
2976 return;
2977 }
2978
2979 if (!task) {
2980 cpu_function_call(cpu, __perf_install_in_context, event);
2981 return;
2982 }
2983
2984 /*
2985 * Should not happen, we validate the ctx is still alive before calling.
2986 */
2987 if (WARN_ON_ONCE(task == TASK_TOMBSTONE))
2988 return;
2989
2990 /*
2991 * Installing events is tricky because we cannot rely on ctx->is_active
2992 * to be set in case this is the nr_events 0 -> 1 transition.
2993 *
2994 * Instead we use task_curr(), which tells us if the task is running.
2995 * However, since we use task_curr() outside of rq::lock, we can race
2996 * against the actual state. This means the result can be wrong.
2997 *
2998 * If we get a false positive, we retry, this is harmless.
2999 *
3000 * If we get a false negative, things are complicated. If we are after
3001 * perf_event_context_sched_in() ctx::lock will serialize us, and the
3002 * value must be correct. If we're before, it doesn't matter since
3003 * perf_event_context_sched_in() will program the counter.
3004 *
3005 * However, this hinges on the remote context switch having observed
3006 * our task->perf_event_ctxp[] store, such that it will in fact take
3007 * ctx::lock in perf_event_context_sched_in().
3008 *
3009 * We do this by task_function_call(), if the IPI fails to hit the task
3010 * we know any future context switch of task must see the
3011 * perf_event_ctpx[] store.
3012 */
3013
3014 /*
3015 * This smp_mb() orders the task->perf_event_ctxp[] store with the
3016 * task_cpu() load, such that if the IPI then does not find the task
3017 * running, a future context switch of that task must observe the
3018 * store.
3019 */
3020 smp_mb();
3021 again:
3022 if (!task_function_call(task, __perf_install_in_context, event))
3023 return;
3024
3025 raw_spin_lock_irq(&ctx->lock);
3026 task = ctx->task;
3027 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) {
3028 /*
3029 * Cannot happen because we already checked above (which also
3030 * cannot happen), and we hold ctx->mutex, which serializes us
3031 * against perf_event_exit_task_context().
3032 */
3033 raw_spin_unlock_irq(&ctx->lock);
3034 return;
3035 }
3036 /*
3037 * If the task is not running, ctx->lock will avoid it becoming so,
3038 * thus we can safely install the event.
3039 */
3040 if (task_curr(task)) {
3041 raw_spin_unlock_irq(&ctx->lock);
3042 goto again;
3043 }
3044 add_event_to_ctx(event, ctx);
3045 raw_spin_unlock_irq(&ctx->lock);
3046 }
3047
3048 /*
3049 * Cross CPU call to enable a performance event
3050 */
__perf_event_enable(struct perf_event * event,struct perf_cpu_context * cpuctx,struct perf_event_context * ctx,void * info)3051 static void __perf_event_enable(struct perf_event *event,
3052 struct perf_cpu_context *cpuctx,
3053 struct perf_event_context *ctx,
3054 void *info)
3055 {
3056 struct perf_event *leader = event->group_leader;
3057 struct perf_event_context *task_ctx;
3058
3059 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
3060 event->state <= PERF_EVENT_STATE_ERROR)
3061 return;
3062
3063 ctx_time_freeze(cpuctx, ctx);
3064
3065 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
3066 perf_cgroup_event_enable(event, ctx);
3067
3068 if (!ctx->is_active)
3069 return;
3070
3071 if (!event_filter_match(event))
3072 return;
3073
3074 /*
3075 * If the event is in a group and isn't the group leader,
3076 * then don't put it on unless the group is on.
3077 */
3078 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
3079 return;
3080
3081 task_ctx = cpuctx->task_ctx;
3082 if (ctx->task)
3083 WARN_ON_ONCE(task_ctx != ctx);
3084
3085 ctx_resched(cpuctx, task_ctx, event->pmu_ctx->pmu, get_event_type(event));
3086 }
3087
3088 /*
3089 * Enable an event.
3090 *
3091 * If event->ctx is a cloned context, callers must make sure that
3092 * every task struct that event->ctx->task could possibly point to
3093 * remains valid. This condition is satisfied when called through
3094 * perf_event_for_each_child or perf_event_for_each as described
3095 * for perf_event_disable.
3096 */
_perf_event_enable(struct perf_event * event)3097 static void _perf_event_enable(struct perf_event *event)
3098 {
3099 struct perf_event_context *ctx = event->ctx;
3100
3101 raw_spin_lock_irq(&ctx->lock);
3102 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
3103 event->state < PERF_EVENT_STATE_ERROR) {
3104 out:
3105 raw_spin_unlock_irq(&ctx->lock);
3106 return;
3107 }
3108
3109 /*
3110 * If the event is in error state, clear that first.
3111 *
3112 * That way, if we see the event in error state below, we know that it
3113 * has gone back into error state, as distinct from the task having
3114 * been scheduled away before the cross-call arrived.
3115 */
3116 if (event->state == PERF_EVENT_STATE_ERROR) {
3117 /*
3118 * Detached SIBLING events cannot leave ERROR state.
3119 */
3120 if (event->event_caps & PERF_EV_CAP_SIBLING &&
3121 event->group_leader == event)
3122 goto out;
3123
3124 event->state = PERF_EVENT_STATE_OFF;
3125 }
3126 raw_spin_unlock_irq(&ctx->lock);
3127
3128 event_function_call(event, __perf_event_enable, NULL);
3129 }
3130
3131 /*
3132 * See perf_event_disable();
3133 */
perf_event_enable(struct perf_event * event)3134 void perf_event_enable(struct perf_event *event)
3135 {
3136 struct perf_event_context *ctx;
3137
3138 ctx = perf_event_ctx_lock(event);
3139 _perf_event_enable(event);
3140 perf_event_ctx_unlock(event, ctx);
3141 }
3142 EXPORT_SYMBOL_GPL(perf_event_enable);
3143
3144 struct stop_event_data {
3145 struct perf_event *event;
3146 unsigned int restart;
3147 };
3148
__perf_event_stop(void * info)3149 static int __perf_event_stop(void *info)
3150 {
3151 struct stop_event_data *sd = info;
3152 struct perf_event *event = sd->event;
3153
3154 /* if it's already INACTIVE, do nothing */
3155 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3156 return 0;
3157
3158 /* matches smp_wmb() in event_sched_in() */
3159 smp_rmb();
3160
3161 /*
3162 * There is a window with interrupts enabled before we get here,
3163 * so we need to check again lest we try to stop another CPU's event.
3164 */
3165 if (READ_ONCE(event->oncpu) != smp_processor_id())
3166 return -EAGAIN;
3167
3168 event->pmu->stop(event, PERF_EF_UPDATE);
3169
3170 /*
3171 * May race with the actual stop (through perf_pmu_output_stop()),
3172 * but it is only used for events with AUX ring buffer, and such
3173 * events will refuse to restart because of rb::aux_mmap_count==0,
3174 * see comments in perf_aux_output_begin().
3175 *
3176 * Since this is happening on an event-local CPU, no trace is lost
3177 * while restarting.
3178 */
3179 if (sd->restart)
3180 event->pmu->start(event, 0);
3181
3182 return 0;
3183 }
3184
perf_event_stop(struct perf_event * event,int restart)3185 static int perf_event_stop(struct perf_event *event, int restart)
3186 {
3187 struct stop_event_data sd = {
3188 .event = event,
3189 .restart = restart,
3190 };
3191 int ret = 0;
3192
3193 do {
3194 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3195 return 0;
3196
3197 /* matches smp_wmb() in event_sched_in() */
3198 smp_rmb();
3199
3200 /*
3201 * We only want to restart ACTIVE events, so if the event goes
3202 * inactive here (event->oncpu==-1), there's nothing more to do;
3203 * fall through with ret==-ENXIO.
3204 */
3205 ret = cpu_function_call(READ_ONCE(event->oncpu),
3206 __perf_event_stop, &sd);
3207 } while (ret == -EAGAIN);
3208
3209 return ret;
3210 }
3211
3212 /*
3213 * In order to contain the amount of racy and tricky in the address filter
3214 * configuration management, it is a two part process:
3215 *
3216 * (p1) when userspace mappings change as a result of (1) or (2) or (3) below,
3217 * we update the addresses of corresponding vmas in
3218 * event::addr_filter_ranges array and bump the event::addr_filters_gen;
3219 * (p2) when an event is scheduled in (pmu::add), it calls
3220 * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync()
3221 * if the generation has changed since the previous call.
3222 *
3223 * If (p1) happens while the event is active, we restart it to force (p2).
3224 *
3225 * (1) perf_addr_filters_apply(): adjusting filters' offsets based on
3226 * pre-existing mappings, called once when new filters arrive via SET_FILTER
3227 * ioctl;
3228 * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly
3229 * registered mapping, called for every new mmap(), with mm::mmap_lock down
3230 * for reading;
3231 * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process
3232 * of exec.
3233 */
perf_event_addr_filters_sync(struct perf_event * event)3234 void perf_event_addr_filters_sync(struct perf_event *event)
3235 {
3236 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
3237
3238 if (!has_addr_filter(event))
3239 return;
3240
3241 raw_spin_lock(&ifh->lock);
3242 if (event->addr_filters_gen != event->hw.addr_filters_gen) {
3243 event->pmu->addr_filters_sync(event);
3244 event->hw.addr_filters_gen = event->addr_filters_gen;
3245 }
3246 raw_spin_unlock(&ifh->lock);
3247 }
3248 EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync);
3249
_perf_event_refresh(struct perf_event * event,int refresh)3250 static int _perf_event_refresh(struct perf_event *event, int refresh)
3251 {
3252 /*
3253 * not supported on inherited events
3254 */
3255 if (event->attr.inherit || !is_sampling_event(event))
3256 return -EINVAL;
3257
3258 atomic_add(refresh, &event->event_limit);
3259 _perf_event_enable(event);
3260
3261 return 0;
3262 }
3263
3264 /*
3265 * See perf_event_disable()
3266 */
perf_event_refresh(struct perf_event * event,int refresh)3267 int perf_event_refresh(struct perf_event *event, int refresh)
3268 {
3269 struct perf_event_context *ctx;
3270 int ret;
3271
3272 ctx = perf_event_ctx_lock(event);
3273 ret = _perf_event_refresh(event, refresh);
3274 perf_event_ctx_unlock(event, ctx);
3275
3276 return ret;
3277 }
3278 EXPORT_SYMBOL_GPL(perf_event_refresh);
3279
perf_event_modify_breakpoint(struct perf_event * bp,struct perf_event_attr * attr)3280 static int perf_event_modify_breakpoint(struct perf_event *bp,
3281 struct perf_event_attr *attr)
3282 {
3283 int err;
3284
3285 _perf_event_disable(bp);
3286
3287 err = modify_user_hw_breakpoint_check(bp, attr, true);
3288
3289 if (!bp->attr.disabled)
3290 _perf_event_enable(bp);
3291
3292 return err;
3293 }
3294
3295 /*
3296 * Copy event-type-independent attributes that may be modified.
3297 */
perf_event_modify_copy_attr(struct perf_event_attr * to,const struct perf_event_attr * from)3298 static void perf_event_modify_copy_attr(struct perf_event_attr *to,
3299 const struct perf_event_attr *from)
3300 {
3301 to->sig_data = from->sig_data;
3302 }
3303
perf_event_modify_attr(struct perf_event * event,struct perf_event_attr * attr)3304 static int perf_event_modify_attr(struct perf_event *event,
3305 struct perf_event_attr *attr)
3306 {
3307 int (*func)(struct perf_event *, struct perf_event_attr *);
3308 struct perf_event *child;
3309 int err;
3310
3311 if (event->attr.type != attr->type)
3312 return -EINVAL;
3313
3314 switch (event->attr.type) {
3315 case PERF_TYPE_BREAKPOINT:
3316 func = perf_event_modify_breakpoint;
3317 break;
3318 default:
3319 /* Place holder for future additions. */
3320 return -EOPNOTSUPP;
3321 }
3322
3323 WARN_ON_ONCE(event->ctx->parent_ctx);
3324
3325 mutex_lock(&event->child_mutex);
3326 /*
3327 * Event-type-independent attributes must be copied before event-type
3328 * modification, which will validate that final attributes match the
3329 * source attributes after all relevant attributes have been copied.
3330 */
3331 perf_event_modify_copy_attr(&event->attr, attr);
3332 err = func(event, attr);
3333 if (err)
3334 goto out;
3335 list_for_each_entry(child, &event->child_list, child_list) {
3336 perf_event_modify_copy_attr(&child->attr, attr);
3337 err = func(child, attr);
3338 if (err)
3339 goto out;
3340 }
3341 out:
3342 mutex_unlock(&event->child_mutex);
3343 return err;
3344 }
3345
__pmu_ctx_sched_out(struct perf_event_pmu_context * pmu_ctx,enum event_type_t event_type)3346 static void __pmu_ctx_sched_out(struct perf_event_pmu_context *pmu_ctx,
3347 enum event_type_t event_type)
3348 {
3349 struct perf_event_context *ctx = pmu_ctx->ctx;
3350 struct perf_event *event, *tmp;
3351 struct pmu *pmu = pmu_ctx->pmu;
3352
3353 if (ctx->task && !(ctx->is_active & EVENT_ALL)) {
3354 struct perf_cpu_pmu_context *cpc;
3355
3356 cpc = this_cpu_ptr(pmu->cpu_pmu_context);
3357 WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx);
3358 cpc->task_epc = NULL;
3359 }
3360
3361 if (!(event_type & EVENT_ALL))
3362 return;
3363
3364 perf_pmu_disable(pmu);
3365 if (event_type & EVENT_PINNED) {
3366 list_for_each_entry_safe(event, tmp,
3367 &pmu_ctx->pinned_active,
3368 active_list)
3369 group_sched_out(event, ctx);
3370 }
3371
3372 if (event_type & EVENT_FLEXIBLE) {
3373 list_for_each_entry_safe(event, tmp,
3374 &pmu_ctx->flexible_active,
3375 active_list)
3376 group_sched_out(event, ctx);
3377 /*
3378 * Since we cleared EVENT_FLEXIBLE, also clear
3379 * rotate_necessary, is will be reset by
3380 * ctx_flexible_sched_in() when needed.
3381 */
3382 pmu_ctx->rotate_necessary = 0;
3383 }
3384 perf_pmu_enable(pmu);
3385 }
3386
3387 /*
3388 * Be very careful with the @pmu argument since this will change ctx state.
3389 * The @pmu argument works for ctx_resched(), because that is symmetric in
3390 * ctx_sched_out() / ctx_sched_in() usage and the ctx state ends up invariant.
3391 *
3392 * However, if you were to be asymmetrical, you could end up with messed up
3393 * state, eg. ctx->is_active cleared even though most EPCs would still actually
3394 * be active.
3395 */
3396 static void
ctx_sched_out(struct perf_event_context * ctx,struct pmu * pmu,enum event_type_t event_type)3397 ctx_sched_out(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type)
3398 {
3399 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3400 struct perf_event_pmu_context *pmu_ctx;
3401 int is_active = ctx->is_active;
3402 bool cgroup = event_type & EVENT_CGROUP;
3403
3404 event_type &= ~EVENT_CGROUP;
3405
3406 lockdep_assert_held(&ctx->lock);
3407
3408 if (likely(!ctx->nr_events)) {
3409 /*
3410 * See __perf_remove_from_context().
3411 */
3412 WARN_ON_ONCE(ctx->is_active);
3413 if (ctx->task)
3414 WARN_ON_ONCE(cpuctx->task_ctx);
3415 return;
3416 }
3417
3418 /*
3419 * Always update time if it was set; not only when it changes.
3420 * Otherwise we can 'forget' to update time for any but the last
3421 * context we sched out. For example:
3422 *
3423 * ctx_sched_out(.event_type = EVENT_FLEXIBLE)
3424 * ctx_sched_out(.event_type = EVENT_PINNED)
3425 *
3426 * would only update time for the pinned events.
3427 */
3428 __ctx_time_update(cpuctx, ctx, ctx == &cpuctx->ctx);
3429
3430 /*
3431 * CPU-release for the below ->is_active store,
3432 * see __load_acquire() in perf_event_time_now()
3433 */
3434 barrier();
3435 ctx->is_active &= ~event_type;
3436
3437 if (!(ctx->is_active & EVENT_ALL)) {
3438 /*
3439 * For FROZEN, preserve TIME|FROZEN such that perf_event_time_now()
3440 * does not observe a hole. perf_ctx_unlock() will clean up.
3441 */
3442 if (ctx->is_active & EVENT_FROZEN)
3443 ctx->is_active &= EVENT_TIME_FROZEN;
3444 else
3445 ctx->is_active = 0;
3446 }
3447
3448 if (ctx->task) {
3449 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3450 if (!(ctx->is_active & EVENT_ALL))
3451 cpuctx->task_ctx = NULL;
3452 }
3453
3454 is_active ^= ctx->is_active; /* changed bits */
3455
3456 for_each_epc(pmu_ctx, ctx, pmu, cgroup)
3457 __pmu_ctx_sched_out(pmu_ctx, is_active);
3458 }
3459
3460 /*
3461 * Test whether two contexts are equivalent, i.e. whether they have both been
3462 * cloned from the same version of the same context.
3463 *
3464 * Equivalence is measured using a generation number in the context that is
3465 * incremented on each modification to it; see unclone_ctx(), list_add_event()
3466 * and list_del_event().
3467 */
context_equiv(struct perf_event_context * ctx1,struct perf_event_context * ctx2)3468 static int context_equiv(struct perf_event_context *ctx1,
3469 struct perf_event_context *ctx2)
3470 {
3471 lockdep_assert_held(&ctx1->lock);
3472 lockdep_assert_held(&ctx2->lock);
3473
3474 /* Pinning disables the swap optimization */
3475 if (ctx1->pin_count || ctx2->pin_count)
3476 return 0;
3477
3478 /* If ctx1 is the parent of ctx2 */
3479 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
3480 return 1;
3481
3482 /* If ctx2 is the parent of ctx1 */
3483 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
3484 return 1;
3485
3486 /*
3487 * If ctx1 and ctx2 have the same parent; we flatten the parent
3488 * hierarchy, see perf_event_init_context().
3489 */
3490 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
3491 ctx1->parent_gen == ctx2->parent_gen)
3492 return 1;
3493
3494 /* Unmatched */
3495 return 0;
3496 }
3497
__perf_event_sync_stat(struct perf_event * event,struct perf_event * next_event)3498 static void __perf_event_sync_stat(struct perf_event *event,
3499 struct perf_event *next_event)
3500 {
3501 u64 value;
3502
3503 if (!event->attr.inherit_stat)
3504 return;
3505
3506 /*
3507 * Update the event value, we cannot use perf_event_read()
3508 * because we're in the middle of a context switch and have IRQs
3509 * disabled, which upsets smp_call_function_single(), however
3510 * we know the event must be on the current CPU, therefore we
3511 * don't need to use it.
3512 */
3513 if (event->state == PERF_EVENT_STATE_ACTIVE)
3514 event->pmu->read(event);
3515
3516 perf_event_update_time(event);
3517
3518 /*
3519 * In order to keep per-task stats reliable we need to flip the event
3520 * values when we flip the contexts.
3521 */
3522 value = local64_read(&next_event->count);
3523 value = local64_xchg(&event->count, value);
3524 local64_set(&next_event->count, value);
3525
3526 swap(event->total_time_enabled, next_event->total_time_enabled);
3527 swap(event->total_time_running, next_event->total_time_running);
3528
3529 /*
3530 * Since we swizzled the values, update the user visible data too.
3531 */
3532 perf_event_update_userpage(event);
3533 perf_event_update_userpage(next_event);
3534 }
3535
perf_event_sync_stat(struct perf_event_context * ctx,struct perf_event_context * next_ctx)3536 static void perf_event_sync_stat(struct perf_event_context *ctx,
3537 struct perf_event_context *next_ctx)
3538 {
3539 struct perf_event *event, *next_event;
3540
3541 if (!ctx->nr_stat)
3542 return;
3543
3544 update_context_time(ctx);
3545
3546 event = list_first_entry(&ctx->event_list,
3547 struct perf_event, event_entry);
3548
3549 next_event = list_first_entry(&next_ctx->event_list,
3550 struct perf_event, event_entry);
3551
3552 while (&event->event_entry != &ctx->event_list &&
3553 &next_event->event_entry != &next_ctx->event_list) {
3554
3555 __perf_event_sync_stat(event, next_event);
3556
3557 event = list_next_entry(event, event_entry);
3558 next_event = list_next_entry(next_event, event_entry);
3559 }
3560 }
3561
3562 #define double_list_for_each_entry(pos1, pos2, head1, head2, member) \
3563 for (pos1 = list_first_entry(head1, typeof(*pos1), member), \
3564 pos2 = list_first_entry(head2, typeof(*pos2), member); \
3565 !list_entry_is_head(pos1, head1, member) && \
3566 !list_entry_is_head(pos2, head2, member); \
3567 pos1 = list_next_entry(pos1, member), \
3568 pos2 = list_next_entry(pos2, member))
3569
perf_event_swap_task_ctx_data(struct perf_event_context * prev_ctx,struct perf_event_context * next_ctx)3570 static void perf_event_swap_task_ctx_data(struct perf_event_context *prev_ctx,
3571 struct perf_event_context *next_ctx)
3572 {
3573 struct perf_event_pmu_context *prev_epc, *next_epc;
3574
3575 if (!prev_ctx->nr_task_data)
3576 return;
3577
3578 double_list_for_each_entry(prev_epc, next_epc,
3579 &prev_ctx->pmu_ctx_list, &next_ctx->pmu_ctx_list,
3580 pmu_ctx_entry) {
3581
3582 if (WARN_ON_ONCE(prev_epc->pmu != next_epc->pmu))
3583 continue;
3584
3585 /*
3586 * PMU specific parts of task perf context can require
3587 * additional synchronization. As an example of such
3588 * synchronization see implementation details of Intel
3589 * LBR call stack data profiling;
3590 */
3591 if (prev_epc->pmu->swap_task_ctx)
3592 prev_epc->pmu->swap_task_ctx(prev_epc, next_epc);
3593 else
3594 swap(prev_epc->task_ctx_data, next_epc->task_ctx_data);
3595 }
3596 }
3597
perf_ctx_sched_task_cb(struct perf_event_context * ctx,bool sched_in)3598 static void perf_ctx_sched_task_cb(struct perf_event_context *ctx, bool sched_in)
3599 {
3600 struct perf_event_pmu_context *pmu_ctx;
3601 struct perf_cpu_pmu_context *cpc;
3602
3603 list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry) {
3604 cpc = this_cpu_ptr(pmu_ctx->pmu->cpu_pmu_context);
3605
3606 if (cpc->sched_cb_usage && pmu_ctx->pmu->sched_task)
3607 pmu_ctx->pmu->sched_task(pmu_ctx, sched_in);
3608 }
3609 }
3610
3611 static void
perf_event_context_sched_out(struct task_struct * task,struct task_struct * next)3612 perf_event_context_sched_out(struct task_struct *task, struct task_struct *next)
3613 {
3614 struct perf_event_context *ctx = task->perf_event_ctxp;
3615 struct perf_event_context *next_ctx;
3616 struct perf_event_context *parent, *next_parent;
3617 int do_switch = 1;
3618
3619 if (likely(!ctx))
3620 return;
3621
3622 rcu_read_lock();
3623 next_ctx = rcu_dereference(next->perf_event_ctxp);
3624 if (!next_ctx)
3625 goto unlock;
3626
3627 parent = rcu_dereference(ctx->parent_ctx);
3628 next_parent = rcu_dereference(next_ctx->parent_ctx);
3629
3630 /* If neither context have a parent context; they cannot be clones. */
3631 if (!parent && !next_parent)
3632 goto unlock;
3633
3634 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
3635 /*
3636 * Looks like the two contexts are clones, so we might be
3637 * able to optimize the context switch. We lock both
3638 * contexts and check that they are clones under the
3639 * lock (including re-checking that neither has been
3640 * uncloned in the meantime). It doesn't matter which
3641 * order we take the locks because no other cpu could
3642 * be trying to lock both of these tasks.
3643 */
3644 raw_spin_lock(&ctx->lock);
3645 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
3646 if (context_equiv(ctx, next_ctx)) {
3647
3648 perf_ctx_disable(ctx, false);
3649
3650 /* PMIs are disabled; ctx->nr_no_switch_fast is stable. */
3651 if (local_read(&ctx->nr_no_switch_fast) ||
3652 local_read(&next_ctx->nr_no_switch_fast)) {
3653 /*
3654 * Must not swap out ctx when there's pending
3655 * events that rely on the ctx->task relation.
3656 *
3657 * Likewise, when a context contains inherit +
3658 * SAMPLE_READ events they should be switched
3659 * out using the slow path so that they are
3660 * treated as if they were distinct contexts.
3661 */
3662 raw_spin_unlock(&next_ctx->lock);
3663 rcu_read_unlock();
3664 goto inside_switch;
3665 }
3666
3667 WRITE_ONCE(ctx->task, next);
3668 WRITE_ONCE(next_ctx->task, task);
3669
3670 perf_ctx_sched_task_cb(ctx, false);
3671 perf_event_swap_task_ctx_data(ctx, next_ctx);
3672
3673 perf_ctx_enable(ctx, false);
3674
3675 /*
3676 * RCU_INIT_POINTER here is safe because we've not
3677 * modified the ctx and the above modification of
3678 * ctx->task and ctx->task_ctx_data are immaterial
3679 * since those values are always verified under
3680 * ctx->lock which we're now holding.
3681 */
3682 RCU_INIT_POINTER(task->perf_event_ctxp, next_ctx);
3683 RCU_INIT_POINTER(next->perf_event_ctxp, ctx);
3684
3685 do_switch = 0;
3686
3687 perf_event_sync_stat(ctx, next_ctx);
3688 }
3689 raw_spin_unlock(&next_ctx->lock);
3690 raw_spin_unlock(&ctx->lock);
3691 }
3692 unlock:
3693 rcu_read_unlock();
3694
3695 if (do_switch) {
3696 raw_spin_lock(&ctx->lock);
3697 perf_ctx_disable(ctx, false);
3698
3699 inside_switch:
3700 perf_ctx_sched_task_cb(ctx, false);
3701 task_ctx_sched_out(ctx, NULL, EVENT_ALL);
3702
3703 perf_ctx_enable(ctx, false);
3704 raw_spin_unlock(&ctx->lock);
3705 }
3706 }
3707
3708 static DEFINE_PER_CPU(struct list_head, sched_cb_list);
3709 static DEFINE_PER_CPU(int, perf_sched_cb_usages);
3710
perf_sched_cb_dec(struct pmu * pmu)3711 void perf_sched_cb_dec(struct pmu *pmu)
3712 {
3713 struct perf_cpu_pmu_context *cpc = this_cpu_ptr(pmu->cpu_pmu_context);
3714
3715 this_cpu_dec(perf_sched_cb_usages);
3716 barrier();
3717
3718 if (!--cpc->sched_cb_usage)
3719 list_del(&cpc->sched_cb_entry);
3720 }
3721
3722
perf_sched_cb_inc(struct pmu * pmu)3723 void perf_sched_cb_inc(struct pmu *pmu)
3724 {
3725 struct perf_cpu_pmu_context *cpc = this_cpu_ptr(pmu->cpu_pmu_context);
3726
3727 if (!cpc->sched_cb_usage++)
3728 list_add(&cpc->sched_cb_entry, this_cpu_ptr(&sched_cb_list));
3729
3730 barrier();
3731 this_cpu_inc(perf_sched_cb_usages);
3732 }
3733
3734 /*
3735 * This function provides the context switch callback to the lower code
3736 * layer. It is invoked ONLY when the context switch callback is enabled.
3737 *
3738 * This callback is relevant even to per-cpu events; for example multi event
3739 * PEBS requires this to provide PID/TID information. This requires we flush
3740 * all queued PEBS records before we context switch to a new task.
3741 */
__perf_pmu_sched_task(struct perf_cpu_pmu_context * cpc,bool sched_in)3742 static void __perf_pmu_sched_task(struct perf_cpu_pmu_context *cpc, bool sched_in)
3743 {
3744 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3745 struct pmu *pmu;
3746
3747 pmu = cpc->epc.pmu;
3748
3749 /* software PMUs will not have sched_task */
3750 if (WARN_ON_ONCE(!pmu->sched_task))
3751 return;
3752
3753 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3754 perf_pmu_disable(pmu);
3755
3756 pmu->sched_task(cpc->task_epc, sched_in);
3757
3758 perf_pmu_enable(pmu);
3759 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3760 }
3761
perf_pmu_sched_task(struct task_struct * prev,struct task_struct * next,bool sched_in)3762 static void perf_pmu_sched_task(struct task_struct *prev,
3763 struct task_struct *next,
3764 bool sched_in)
3765 {
3766 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3767 struct perf_cpu_pmu_context *cpc;
3768
3769 /* cpuctx->task_ctx will be handled in perf_event_context_sched_in/out */
3770 if (prev == next || cpuctx->task_ctx)
3771 return;
3772
3773 list_for_each_entry(cpc, this_cpu_ptr(&sched_cb_list), sched_cb_entry)
3774 __perf_pmu_sched_task(cpc, sched_in);
3775 }
3776
3777 static void perf_event_switch(struct task_struct *task,
3778 struct task_struct *next_prev, bool sched_in);
3779
3780 /*
3781 * Called from scheduler to remove the events of the current task,
3782 * with interrupts disabled.
3783 *
3784 * We stop each event and update the event value in event->count.
3785 *
3786 * This does not protect us against NMI, but disable()
3787 * sets the disabled bit in the control field of event _before_
3788 * accessing the event control register. If a NMI hits, then it will
3789 * not restart the event.
3790 */
__perf_event_task_sched_out(struct task_struct * task,struct task_struct * next)3791 void __perf_event_task_sched_out(struct task_struct *task,
3792 struct task_struct *next)
3793 {
3794 if (__this_cpu_read(perf_sched_cb_usages))
3795 perf_pmu_sched_task(task, next, false);
3796
3797 if (atomic_read(&nr_switch_events))
3798 perf_event_switch(task, next, false);
3799
3800 perf_event_context_sched_out(task, next);
3801
3802 /*
3803 * if cgroup events exist on this CPU, then we need
3804 * to check if we have to switch out PMU state.
3805 * cgroup event are system-wide mode only
3806 */
3807 perf_cgroup_switch(next);
3808 }
3809
perf_less_group_idx(const void * l,const void * r,void __always_unused * args)3810 static bool perf_less_group_idx(const void *l, const void *r, void __always_unused *args)
3811 {
3812 const struct perf_event *le = *(const struct perf_event **)l;
3813 const struct perf_event *re = *(const struct perf_event **)r;
3814
3815 return le->group_index < re->group_index;
3816 }
3817
swap_ptr(void * l,void * r,void __always_unused * args)3818 static void swap_ptr(void *l, void *r, void __always_unused *args)
3819 {
3820 void **lp = l, **rp = r;
3821
3822 swap(*lp, *rp);
3823 }
3824
3825 DEFINE_MIN_HEAP(struct perf_event *, perf_event_min_heap);
3826
3827 static const struct min_heap_callbacks perf_min_heap = {
3828 .less = perf_less_group_idx,
3829 .swp = swap_ptr,
3830 };
3831
__heap_add(struct perf_event_min_heap * heap,struct perf_event * event)3832 static void __heap_add(struct perf_event_min_heap *heap, struct perf_event *event)
3833 {
3834 struct perf_event **itrs = heap->data;
3835
3836 if (event) {
3837 itrs[heap->nr] = event;
3838 heap->nr++;
3839 }
3840 }
3841
__link_epc(struct perf_event_pmu_context * pmu_ctx)3842 static void __link_epc(struct perf_event_pmu_context *pmu_ctx)
3843 {
3844 struct perf_cpu_pmu_context *cpc;
3845
3846 if (!pmu_ctx->ctx->task)
3847 return;
3848
3849 cpc = this_cpu_ptr(pmu_ctx->pmu->cpu_pmu_context);
3850 WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx);
3851 cpc->task_epc = pmu_ctx;
3852 }
3853
visit_groups_merge(struct perf_event_context * ctx,struct perf_event_groups * groups,int cpu,struct pmu * pmu,int (* func)(struct perf_event *,void *),void * data)3854 static noinline int visit_groups_merge(struct perf_event_context *ctx,
3855 struct perf_event_groups *groups, int cpu,
3856 struct pmu *pmu,
3857 int (*func)(struct perf_event *, void *),
3858 void *data)
3859 {
3860 #ifdef CONFIG_CGROUP_PERF
3861 struct cgroup_subsys_state *css = NULL;
3862 #endif
3863 struct perf_cpu_context *cpuctx = NULL;
3864 /* Space for per CPU and/or any CPU event iterators. */
3865 struct perf_event *itrs[2];
3866 struct perf_event_min_heap event_heap;
3867 struct perf_event **evt;
3868 int ret;
3869
3870 if (pmu->filter && pmu->filter(pmu, cpu))
3871 return 0;
3872
3873 if (!ctx->task) {
3874 cpuctx = this_cpu_ptr(&perf_cpu_context);
3875 event_heap = (struct perf_event_min_heap){
3876 .data = cpuctx->heap,
3877 .nr = 0,
3878 .size = cpuctx->heap_size,
3879 };
3880
3881 lockdep_assert_held(&cpuctx->ctx.lock);
3882
3883 #ifdef CONFIG_CGROUP_PERF
3884 if (cpuctx->cgrp)
3885 css = &cpuctx->cgrp->css;
3886 #endif
3887 } else {
3888 event_heap = (struct perf_event_min_heap){
3889 .data = itrs,
3890 .nr = 0,
3891 .size = ARRAY_SIZE(itrs),
3892 };
3893 /* Events not within a CPU context may be on any CPU. */
3894 __heap_add(&event_heap, perf_event_groups_first(groups, -1, pmu, NULL));
3895 }
3896 evt = event_heap.data;
3897
3898 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, pmu, NULL));
3899
3900 #ifdef CONFIG_CGROUP_PERF
3901 for (; css; css = css->parent)
3902 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, pmu, css->cgroup));
3903 #endif
3904
3905 if (event_heap.nr) {
3906 __link_epc((*evt)->pmu_ctx);
3907 perf_assert_pmu_disabled((*evt)->pmu_ctx->pmu);
3908 }
3909
3910 min_heapify_all(&event_heap, &perf_min_heap, NULL);
3911
3912 while (event_heap.nr) {
3913 ret = func(*evt, data);
3914 if (ret)
3915 return ret;
3916
3917 *evt = perf_event_groups_next(*evt, pmu);
3918 if (*evt)
3919 min_heap_sift_down(&event_heap, 0, &perf_min_heap, NULL);
3920 else
3921 min_heap_pop(&event_heap, &perf_min_heap, NULL);
3922 }
3923
3924 return 0;
3925 }
3926
3927 /*
3928 * Because the userpage is strictly per-event (there is no concept of context,
3929 * so there cannot be a context indirection), every userpage must be updated
3930 * when context time starts :-(
3931 *
3932 * IOW, we must not miss EVENT_TIME edges.
3933 */
event_update_userpage(struct perf_event * event)3934 static inline bool event_update_userpage(struct perf_event *event)
3935 {
3936 if (likely(!atomic_read(&event->mmap_count)))
3937 return false;
3938
3939 perf_event_update_time(event);
3940 perf_event_update_userpage(event);
3941
3942 return true;
3943 }
3944
group_update_userpage(struct perf_event * group_event)3945 static inline void group_update_userpage(struct perf_event *group_event)
3946 {
3947 struct perf_event *event;
3948
3949 if (!event_update_userpage(group_event))
3950 return;
3951
3952 for_each_sibling_event(event, group_event)
3953 event_update_userpage(event);
3954 }
3955
merge_sched_in(struct perf_event * event,void * data)3956 static int merge_sched_in(struct perf_event *event, void *data)
3957 {
3958 struct perf_event_context *ctx = event->ctx;
3959 int *can_add_hw = data;
3960
3961 if (event->state <= PERF_EVENT_STATE_OFF)
3962 return 0;
3963
3964 if (!event_filter_match(event))
3965 return 0;
3966
3967 if (group_can_go_on(event, *can_add_hw)) {
3968 if (!group_sched_in(event, ctx))
3969 list_add_tail(&event->active_list, get_event_list(event));
3970 }
3971
3972 if (event->state == PERF_EVENT_STATE_INACTIVE) {
3973 *can_add_hw = 0;
3974 if (event->attr.pinned) {
3975 perf_cgroup_event_disable(event, ctx);
3976 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
3977 } else {
3978 struct perf_cpu_pmu_context *cpc;
3979
3980 event->pmu_ctx->rotate_necessary = 1;
3981 cpc = this_cpu_ptr(event->pmu_ctx->pmu->cpu_pmu_context);
3982 perf_mux_hrtimer_restart(cpc);
3983 group_update_userpage(event);
3984 }
3985 }
3986
3987 return 0;
3988 }
3989
pmu_groups_sched_in(struct perf_event_context * ctx,struct perf_event_groups * groups,struct pmu * pmu)3990 static void pmu_groups_sched_in(struct perf_event_context *ctx,
3991 struct perf_event_groups *groups,
3992 struct pmu *pmu)
3993 {
3994 int can_add_hw = 1;
3995 visit_groups_merge(ctx, groups, smp_processor_id(), pmu,
3996 merge_sched_in, &can_add_hw);
3997 }
3998
__pmu_ctx_sched_in(struct perf_event_pmu_context * pmu_ctx,enum event_type_t event_type)3999 static void __pmu_ctx_sched_in(struct perf_event_pmu_context *pmu_ctx,
4000 enum event_type_t event_type)
4001 {
4002 struct perf_event_context *ctx = pmu_ctx->ctx;
4003
4004 if (event_type & EVENT_PINNED)
4005 pmu_groups_sched_in(ctx, &ctx->pinned_groups, pmu_ctx->pmu);
4006 if (event_type & EVENT_FLEXIBLE)
4007 pmu_groups_sched_in(ctx, &ctx->flexible_groups, pmu_ctx->pmu);
4008 }
4009
4010 static void
ctx_sched_in(struct perf_event_context * ctx,struct pmu * pmu,enum event_type_t event_type)4011 ctx_sched_in(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type)
4012 {
4013 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4014 struct perf_event_pmu_context *pmu_ctx;
4015 int is_active = ctx->is_active;
4016 bool cgroup = event_type & EVENT_CGROUP;
4017
4018 event_type &= ~EVENT_CGROUP;
4019
4020 lockdep_assert_held(&ctx->lock);
4021
4022 if (likely(!ctx->nr_events))
4023 return;
4024
4025 if (!(is_active & EVENT_TIME)) {
4026 /* start ctx time */
4027 __update_context_time(ctx, false);
4028 perf_cgroup_set_timestamp(cpuctx);
4029 /*
4030 * CPU-release for the below ->is_active store,
4031 * see __load_acquire() in perf_event_time_now()
4032 */
4033 barrier();
4034 }
4035
4036 ctx->is_active |= (event_type | EVENT_TIME);
4037 if (ctx->task) {
4038 if (!(is_active & EVENT_ALL))
4039 cpuctx->task_ctx = ctx;
4040 else
4041 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
4042 }
4043
4044 is_active ^= ctx->is_active; /* changed bits */
4045
4046 /*
4047 * First go through the list and put on any pinned groups
4048 * in order to give them the best chance of going on.
4049 */
4050 if (is_active & EVENT_PINNED) {
4051 for_each_epc(pmu_ctx, ctx, pmu, cgroup)
4052 __pmu_ctx_sched_in(pmu_ctx, EVENT_PINNED);
4053 }
4054
4055 /* Then walk through the lower prio flexible groups */
4056 if (is_active & EVENT_FLEXIBLE) {
4057 for_each_epc(pmu_ctx, ctx, pmu, cgroup)
4058 __pmu_ctx_sched_in(pmu_ctx, EVENT_FLEXIBLE);
4059 }
4060 }
4061
perf_event_context_sched_in(struct task_struct * task)4062 static void perf_event_context_sched_in(struct task_struct *task)
4063 {
4064 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4065 struct perf_event_context *ctx;
4066
4067 rcu_read_lock();
4068 ctx = rcu_dereference(task->perf_event_ctxp);
4069 if (!ctx)
4070 goto rcu_unlock;
4071
4072 if (cpuctx->task_ctx == ctx) {
4073 perf_ctx_lock(cpuctx, ctx);
4074 perf_ctx_disable(ctx, false);
4075
4076 perf_ctx_sched_task_cb(ctx, true);
4077
4078 perf_ctx_enable(ctx, false);
4079 perf_ctx_unlock(cpuctx, ctx);
4080 goto rcu_unlock;
4081 }
4082
4083 perf_ctx_lock(cpuctx, ctx);
4084 /*
4085 * We must check ctx->nr_events while holding ctx->lock, such
4086 * that we serialize against perf_install_in_context().
4087 */
4088 if (!ctx->nr_events)
4089 goto unlock;
4090
4091 perf_ctx_disable(ctx, false);
4092 /*
4093 * We want to keep the following priority order:
4094 * cpu pinned (that don't need to move), task pinned,
4095 * cpu flexible, task flexible.
4096 *
4097 * However, if task's ctx is not carrying any pinned
4098 * events, no need to flip the cpuctx's events around.
4099 */
4100 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree)) {
4101 perf_ctx_disable(&cpuctx->ctx, false);
4102 ctx_sched_out(&cpuctx->ctx, NULL, EVENT_FLEXIBLE);
4103 }
4104
4105 perf_event_sched_in(cpuctx, ctx, NULL);
4106
4107 perf_ctx_sched_task_cb(cpuctx->task_ctx, true);
4108
4109 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree))
4110 perf_ctx_enable(&cpuctx->ctx, false);
4111
4112 perf_ctx_enable(ctx, false);
4113
4114 unlock:
4115 perf_ctx_unlock(cpuctx, ctx);
4116 rcu_unlock:
4117 rcu_read_unlock();
4118 }
4119
4120 /*
4121 * Called from scheduler to add the events of the current task
4122 * with interrupts disabled.
4123 *
4124 * We restore the event value and then enable it.
4125 *
4126 * This does not protect us against NMI, but enable()
4127 * sets the enabled bit in the control field of event _before_
4128 * accessing the event control register. If a NMI hits, then it will
4129 * keep the event running.
4130 */
__perf_event_task_sched_in(struct task_struct * prev,struct task_struct * task)4131 void __perf_event_task_sched_in(struct task_struct *prev,
4132 struct task_struct *task)
4133 {
4134 perf_event_context_sched_in(task);
4135
4136 if (atomic_read(&nr_switch_events))
4137 perf_event_switch(task, prev, true);
4138
4139 if (__this_cpu_read(perf_sched_cb_usages))
4140 perf_pmu_sched_task(prev, task, true);
4141 }
4142
perf_calculate_period(struct perf_event * event,u64 nsec,u64 count)4143 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
4144 {
4145 u64 frequency = event->attr.sample_freq;
4146 u64 sec = NSEC_PER_SEC;
4147 u64 divisor, dividend;
4148
4149 int count_fls, nsec_fls, frequency_fls, sec_fls;
4150
4151 count_fls = fls64(count);
4152 nsec_fls = fls64(nsec);
4153 frequency_fls = fls64(frequency);
4154 sec_fls = 30;
4155
4156 /*
4157 * We got @count in @nsec, with a target of sample_freq HZ
4158 * the target period becomes:
4159 *
4160 * @count * 10^9
4161 * period = -------------------
4162 * @nsec * sample_freq
4163 *
4164 */
4165
4166 /*
4167 * Reduce accuracy by one bit such that @a and @b converge
4168 * to a similar magnitude.
4169 */
4170 #define REDUCE_FLS(a, b) \
4171 do { \
4172 if (a##_fls > b##_fls) { \
4173 a >>= 1; \
4174 a##_fls--; \
4175 } else { \
4176 b >>= 1; \
4177 b##_fls--; \
4178 } \
4179 } while (0)
4180
4181 /*
4182 * Reduce accuracy until either term fits in a u64, then proceed with
4183 * the other, so that finally we can do a u64/u64 division.
4184 */
4185 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
4186 REDUCE_FLS(nsec, frequency);
4187 REDUCE_FLS(sec, count);
4188 }
4189
4190 if (count_fls + sec_fls > 64) {
4191 divisor = nsec * frequency;
4192
4193 while (count_fls + sec_fls > 64) {
4194 REDUCE_FLS(count, sec);
4195 divisor >>= 1;
4196 }
4197
4198 dividend = count * sec;
4199 } else {
4200 dividend = count * sec;
4201
4202 while (nsec_fls + frequency_fls > 64) {
4203 REDUCE_FLS(nsec, frequency);
4204 dividend >>= 1;
4205 }
4206
4207 divisor = nsec * frequency;
4208 }
4209
4210 if (!divisor)
4211 return dividend;
4212
4213 return div64_u64(dividend, divisor);
4214 }
4215
4216 static DEFINE_PER_CPU(int, perf_throttled_count);
4217 static DEFINE_PER_CPU(u64, perf_throttled_seq);
4218
perf_adjust_period(struct perf_event * event,u64 nsec,u64 count,bool disable)4219 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
4220 {
4221 struct hw_perf_event *hwc = &event->hw;
4222 s64 period, sample_period;
4223 s64 delta;
4224
4225 period = perf_calculate_period(event, nsec, count);
4226
4227 delta = (s64)(period - hwc->sample_period);
4228 if (delta >= 0)
4229 delta += 7;
4230 else
4231 delta -= 7;
4232 delta /= 8; /* low pass filter */
4233
4234 sample_period = hwc->sample_period + delta;
4235
4236 if (!sample_period)
4237 sample_period = 1;
4238
4239 hwc->sample_period = sample_period;
4240
4241 if (local64_read(&hwc->period_left) > 8*sample_period) {
4242 if (disable)
4243 event->pmu->stop(event, PERF_EF_UPDATE);
4244
4245 local64_set(&hwc->period_left, 0);
4246
4247 if (disable)
4248 event->pmu->start(event, PERF_EF_RELOAD);
4249 }
4250 }
4251
perf_adjust_freq_unthr_events(struct list_head * event_list)4252 static void perf_adjust_freq_unthr_events(struct list_head *event_list)
4253 {
4254 struct perf_event *event;
4255 struct hw_perf_event *hwc;
4256 u64 now, period = TICK_NSEC;
4257 s64 delta;
4258
4259 list_for_each_entry(event, event_list, active_list) {
4260 if (event->state != PERF_EVENT_STATE_ACTIVE)
4261 continue;
4262
4263 // XXX use visit thingy to avoid the -1,cpu match
4264 if (!event_filter_match(event))
4265 continue;
4266
4267 hwc = &event->hw;
4268
4269 if (hwc->interrupts == MAX_INTERRUPTS) {
4270 hwc->interrupts = 0;
4271 perf_log_throttle(event, 1);
4272 if (!event->attr.freq || !event->attr.sample_freq)
4273 event->pmu->start(event, 0);
4274 }
4275
4276 if (!event->attr.freq || !event->attr.sample_freq)
4277 continue;
4278
4279 /*
4280 * stop the event and update event->count
4281 */
4282 event->pmu->stop(event, PERF_EF_UPDATE);
4283
4284 now = local64_read(&event->count);
4285 delta = now - hwc->freq_count_stamp;
4286 hwc->freq_count_stamp = now;
4287
4288 /*
4289 * restart the event
4290 * reload only if value has changed
4291 * we have stopped the event so tell that
4292 * to perf_adjust_period() to avoid stopping it
4293 * twice.
4294 */
4295 if (delta > 0)
4296 perf_adjust_period(event, period, delta, false);
4297
4298 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
4299 }
4300 }
4301
4302 /*
4303 * combine freq adjustment with unthrottling to avoid two passes over the
4304 * events. At the same time, make sure, having freq events does not change
4305 * the rate of unthrottling as that would introduce bias.
4306 */
4307 static void
perf_adjust_freq_unthr_context(struct perf_event_context * ctx,bool unthrottle)4308 perf_adjust_freq_unthr_context(struct perf_event_context *ctx, bool unthrottle)
4309 {
4310 struct perf_event_pmu_context *pmu_ctx;
4311
4312 /*
4313 * only need to iterate over all events iff:
4314 * - context have events in frequency mode (needs freq adjust)
4315 * - there are events to unthrottle on this cpu
4316 */
4317 if (!(ctx->nr_freq || unthrottle))
4318 return;
4319
4320 raw_spin_lock(&ctx->lock);
4321
4322 list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry) {
4323 if (!(pmu_ctx->nr_freq || unthrottle))
4324 continue;
4325 if (!perf_pmu_ctx_is_active(pmu_ctx))
4326 continue;
4327 if (pmu_ctx->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT)
4328 continue;
4329
4330 perf_pmu_disable(pmu_ctx->pmu);
4331 perf_adjust_freq_unthr_events(&pmu_ctx->pinned_active);
4332 perf_adjust_freq_unthr_events(&pmu_ctx->flexible_active);
4333 perf_pmu_enable(pmu_ctx->pmu);
4334 }
4335
4336 raw_spin_unlock(&ctx->lock);
4337 }
4338
4339 /*
4340 * Move @event to the tail of the @ctx's elegible events.
4341 */
rotate_ctx(struct perf_event_context * ctx,struct perf_event * event)4342 static void rotate_ctx(struct perf_event_context *ctx, struct perf_event *event)
4343 {
4344 /*
4345 * Rotate the first entry last of non-pinned groups. Rotation might be
4346 * disabled by the inheritance code.
4347 */
4348 if (ctx->rotate_disable)
4349 return;
4350
4351 perf_event_groups_delete(&ctx->flexible_groups, event);
4352 perf_event_groups_insert(&ctx->flexible_groups, event);
4353 }
4354
4355 /* pick an event from the flexible_groups to rotate */
4356 static inline struct perf_event *
ctx_event_to_rotate(struct perf_event_pmu_context * pmu_ctx)4357 ctx_event_to_rotate(struct perf_event_pmu_context *pmu_ctx)
4358 {
4359 struct perf_event *event;
4360 struct rb_node *node;
4361 struct rb_root *tree;
4362 struct __group_key key = {
4363 .pmu = pmu_ctx->pmu,
4364 };
4365
4366 /* pick the first active flexible event */
4367 event = list_first_entry_or_null(&pmu_ctx->flexible_active,
4368 struct perf_event, active_list);
4369 if (event)
4370 goto out;
4371
4372 /* if no active flexible event, pick the first event */
4373 tree = &pmu_ctx->ctx->flexible_groups.tree;
4374
4375 if (!pmu_ctx->ctx->task) {
4376 key.cpu = smp_processor_id();
4377
4378 node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup);
4379 if (node)
4380 event = __node_2_pe(node);
4381 goto out;
4382 }
4383
4384 key.cpu = -1;
4385 node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup);
4386 if (node) {
4387 event = __node_2_pe(node);
4388 goto out;
4389 }
4390
4391 key.cpu = smp_processor_id();
4392 node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup);
4393 if (node)
4394 event = __node_2_pe(node);
4395
4396 out:
4397 /*
4398 * Unconditionally clear rotate_necessary; if ctx_flexible_sched_in()
4399 * finds there are unschedulable events, it will set it again.
4400 */
4401 pmu_ctx->rotate_necessary = 0;
4402
4403 return event;
4404 }
4405
perf_rotate_context(struct perf_cpu_pmu_context * cpc)4406 static bool perf_rotate_context(struct perf_cpu_pmu_context *cpc)
4407 {
4408 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4409 struct perf_event_pmu_context *cpu_epc, *task_epc = NULL;
4410 struct perf_event *cpu_event = NULL, *task_event = NULL;
4411 int cpu_rotate, task_rotate;
4412 struct pmu *pmu;
4413
4414 /*
4415 * Since we run this from IRQ context, nobody can install new
4416 * events, thus the event count values are stable.
4417 */
4418
4419 cpu_epc = &cpc->epc;
4420 pmu = cpu_epc->pmu;
4421 task_epc = cpc->task_epc;
4422
4423 cpu_rotate = cpu_epc->rotate_necessary;
4424 task_rotate = task_epc ? task_epc->rotate_necessary : 0;
4425
4426 if (!(cpu_rotate || task_rotate))
4427 return false;
4428
4429 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
4430 perf_pmu_disable(pmu);
4431
4432 if (task_rotate)
4433 task_event = ctx_event_to_rotate(task_epc);
4434 if (cpu_rotate)
4435 cpu_event = ctx_event_to_rotate(cpu_epc);
4436
4437 /*
4438 * As per the order given at ctx_resched() first 'pop' task flexible
4439 * and then, if needed CPU flexible.
4440 */
4441 if (task_event || (task_epc && cpu_event)) {
4442 update_context_time(task_epc->ctx);
4443 __pmu_ctx_sched_out(task_epc, EVENT_FLEXIBLE);
4444 }
4445
4446 if (cpu_event) {
4447 update_context_time(&cpuctx->ctx);
4448 __pmu_ctx_sched_out(cpu_epc, EVENT_FLEXIBLE);
4449 rotate_ctx(&cpuctx->ctx, cpu_event);
4450 __pmu_ctx_sched_in(cpu_epc, EVENT_FLEXIBLE);
4451 }
4452
4453 if (task_event)
4454 rotate_ctx(task_epc->ctx, task_event);
4455
4456 if (task_event || (task_epc && cpu_event))
4457 __pmu_ctx_sched_in(task_epc, EVENT_FLEXIBLE);
4458
4459 perf_pmu_enable(pmu);
4460 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
4461
4462 return true;
4463 }
4464
perf_event_task_tick(void)4465 void perf_event_task_tick(void)
4466 {
4467 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4468 struct perf_event_context *ctx;
4469 int throttled;
4470
4471 lockdep_assert_irqs_disabled();
4472
4473 __this_cpu_inc(perf_throttled_seq);
4474 throttled = __this_cpu_xchg(perf_throttled_count, 0);
4475 tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
4476
4477 perf_adjust_freq_unthr_context(&cpuctx->ctx, !!throttled);
4478
4479 rcu_read_lock();
4480 ctx = rcu_dereference(current->perf_event_ctxp);
4481 if (ctx)
4482 perf_adjust_freq_unthr_context(ctx, !!throttled);
4483 rcu_read_unlock();
4484 }
4485
event_enable_on_exec(struct perf_event * event,struct perf_event_context * ctx)4486 static int event_enable_on_exec(struct perf_event *event,
4487 struct perf_event_context *ctx)
4488 {
4489 if (!event->attr.enable_on_exec)
4490 return 0;
4491
4492 event->attr.enable_on_exec = 0;
4493 if (event->state >= PERF_EVENT_STATE_INACTIVE)
4494 return 0;
4495
4496 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
4497
4498 return 1;
4499 }
4500
4501 /*
4502 * Enable all of a task's events that have been marked enable-on-exec.
4503 * This expects task == current.
4504 */
perf_event_enable_on_exec(struct perf_event_context * ctx)4505 static void perf_event_enable_on_exec(struct perf_event_context *ctx)
4506 {
4507 struct perf_event_context *clone_ctx = NULL;
4508 enum event_type_t event_type = 0;
4509 struct perf_cpu_context *cpuctx;
4510 struct perf_event *event;
4511 unsigned long flags;
4512 int enabled = 0;
4513
4514 local_irq_save(flags);
4515 if (WARN_ON_ONCE(current->perf_event_ctxp != ctx))
4516 goto out;
4517
4518 if (!ctx->nr_events)
4519 goto out;
4520
4521 cpuctx = this_cpu_ptr(&perf_cpu_context);
4522 perf_ctx_lock(cpuctx, ctx);
4523 ctx_time_freeze(cpuctx, ctx);
4524
4525 list_for_each_entry(event, &ctx->event_list, event_entry) {
4526 enabled |= event_enable_on_exec(event, ctx);
4527 event_type |= get_event_type(event);
4528 }
4529
4530 /*
4531 * Unclone and reschedule this context if we enabled any event.
4532 */
4533 if (enabled) {
4534 clone_ctx = unclone_ctx(ctx);
4535 ctx_resched(cpuctx, ctx, NULL, event_type);
4536 }
4537 perf_ctx_unlock(cpuctx, ctx);
4538
4539 out:
4540 local_irq_restore(flags);
4541
4542 if (clone_ctx)
4543 put_ctx(clone_ctx);
4544 }
4545
4546 static void perf_remove_from_owner(struct perf_event *event);
4547 static void perf_event_exit_event(struct perf_event *event,
4548 struct perf_event_context *ctx);
4549
4550 /*
4551 * Removes all events from the current task that have been marked
4552 * remove-on-exec, and feeds their values back to parent events.
4553 */
perf_event_remove_on_exec(struct perf_event_context * ctx)4554 static void perf_event_remove_on_exec(struct perf_event_context *ctx)
4555 {
4556 struct perf_event_context *clone_ctx = NULL;
4557 struct perf_event *event, *next;
4558 unsigned long flags;
4559 bool modified = false;
4560
4561 mutex_lock(&ctx->mutex);
4562
4563 if (WARN_ON_ONCE(ctx->task != current))
4564 goto unlock;
4565
4566 list_for_each_entry_safe(event, next, &ctx->event_list, event_entry) {
4567 if (!event->attr.remove_on_exec)
4568 continue;
4569
4570 if (!is_kernel_event(event))
4571 perf_remove_from_owner(event);
4572
4573 modified = true;
4574
4575 perf_event_exit_event(event, ctx);
4576 }
4577
4578 raw_spin_lock_irqsave(&ctx->lock, flags);
4579 if (modified)
4580 clone_ctx = unclone_ctx(ctx);
4581 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4582
4583 unlock:
4584 mutex_unlock(&ctx->mutex);
4585
4586 if (clone_ctx)
4587 put_ctx(clone_ctx);
4588 }
4589
4590 struct perf_read_data {
4591 struct perf_event *event;
4592 bool group;
4593 int ret;
4594 };
4595
4596 static inline const struct cpumask *perf_scope_cpu_topology_cpumask(unsigned int scope, int cpu);
4597
__perf_event_read_cpu(struct perf_event * event,int event_cpu)4598 static int __perf_event_read_cpu(struct perf_event *event, int event_cpu)
4599 {
4600 int local_cpu = smp_processor_id();
4601 u16 local_pkg, event_pkg;
4602
4603 if ((unsigned)event_cpu >= nr_cpu_ids)
4604 return event_cpu;
4605
4606 if (event->group_caps & PERF_EV_CAP_READ_SCOPE) {
4607 const struct cpumask *cpumask = perf_scope_cpu_topology_cpumask(event->pmu->scope, event_cpu);
4608
4609 if (cpumask && cpumask_test_cpu(local_cpu, cpumask))
4610 return local_cpu;
4611 }
4612
4613 if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) {
4614 event_pkg = topology_physical_package_id(event_cpu);
4615 local_pkg = topology_physical_package_id(local_cpu);
4616
4617 if (event_pkg == local_pkg)
4618 return local_cpu;
4619 }
4620
4621 return event_cpu;
4622 }
4623
4624 /*
4625 * Cross CPU call to read the hardware event
4626 */
__perf_event_read(void * info)4627 static void __perf_event_read(void *info)
4628 {
4629 struct perf_read_data *data = info;
4630 struct perf_event *sub, *event = data->event;
4631 struct perf_event_context *ctx = event->ctx;
4632 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4633 struct pmu *pmu = event->pmu;
4634
4635 /*
4636 * If this is a task context, we need to check whether it is
4637 * the current task context of this cpu. If not it has been
4638 * scheduled out before the smp call arrived. In that case
4639 * event->count would have been updated to a recent sample
4640 * when the event was scheduled out.
4641 */
4642 if (ctx->task && cpuctx->task_ctx != ctx)
4643 return;
4644
4645 raw_spin_lock(&ctx->lock);
4646 ctx_time_update_event(ctx, event);
4647
4648 perf_event_update_time(event);
4649 if (data->group)
4650 perf_event_update_sibling_time(event);
4651
4652 if (event->state != PERF_EVENT_STATE_ACTIVE)
4653 goto unlock;
4654
4655 if (!data->group) {
4656 pmu->read(event);
4657 data->ret = 0;
4658 goto unlock;
4659 }
4660
4661 pmu->start_txn(pmu, PERF_PMU_TXN_READ);
4662
4663 pmu->read(event);
4664
4665 for_each_sibling_event(sub, event) {
4666 if (sub->state == PERF_EVENT_STATE_ACTIVE) {
4667 /*
4668 * Use sibling's PMU rather than @event's since
4669 * sibling could be on different (eg: software) PMU.
4670 */
4671 sub->pmu->read(sub);
4672 }
4673 }
4674
4675 data->ret = pmu->commit_txn(pmu);
4676
4677 unlock:
4678 raw_spin_unlock(&ctx->lock);
4679 }
4680
perf_event_count(struct perf_event * event,bool self)4681 static inline u64 perf_event_count(struct perf_event *event, bool self)
4682 {
4683 if (self)
4684 return local64_read(&event->count);
4685
4686 return local64_read(&event->count) + atomic64_read(&event->child_count);
4687 }
4688
calc_timer_values(struct perf_event * event,u64 * now,u64 * enabled,u64 * running)4689 static void calc_timer_values(struct perf_event *event,
4690 u64 *now,
4691 u64 *enabled,
4692 u64 *running)
4693 {
4694 u64 ctx_time;
4695
4696 *now = perf_clock();
4697 ctx_time = perf_event_time_now(event, *now);
4698 __perf_update_times(event, ctx_time, enabled, running);
4699 }
4700
4701 /*
4702 * NMI-safe method to read a local event, that is an event that
4703 * is:
4704 * - either for the current task, or for this CPU
4705 * - does not have inherit set, for inherited task events
4706 * will not be local and we cannot read them atomically
4707 * - must not have a pmu::count method
4708 */
perf_event_read_local(struct perf_event * event,u64 * value,u64 * enabled,u64 * running)4709 int perf_event_read_local(struct perf_event *event, u64 *value,
4710 u64 *enabled, u64 *running)
4711 {
4712 unsigned long flags;
4713 int event_oncpu;
4714 int event_cpu;
4715 int ret = 0;
4716
4717 /*
4718 * Disabling interrupts avoids all counter scheduling (context
4719 * switches, timer based rotation and IPIs).
4720 */
4721 local_irq_save(flags);
4722
4723 /*
4724 * It must not be an event with inherit set, we cannot read
4725 * all child counters from atomic context.
4726 */
4727 if (event->attr.inherit) {
4728 ret = -EOPNOTSUPP;
4729 goto out;
4730 }
4731
4732 /* If this is a per-task event, it must be for current */
4733 if ((event->attach_state & PERF_ATTACH_TASK) &&
4734 event->hw.target != current) {
4735 ret = -EINVAL;
4736 goto out;
4737 }
4738
4739 /*
4740 * Get the event CPU numbers, and adjust them to local if the event is
4741 * a per-package event that can be read locally
4742 */
4743 event_oncpu = __perf_event_read_cpu(event, event->oncpu);
4744 event_cpu = __perf_event_read_cpu(event, event->cpu);
4745
4746 /* If this is a per-CPU event, it must be for this CPU */
4747 if (!(event->attach_state & PERF_ATTACH_TASK) &&
4748 event_cpu != smp_processor_id()) {
4749 ret = -EINVAL;
4750 goto out;
4751 }
4752
4753 /* If this is a pinned event it must be running on this CPU */
4754 if (event->attr.pinned && event_oncpu != smp_processor_id()) {
4755 ret = -EBUSY;
4756 goto out;
4757 }
4758
4759 /*
4760 * If the event is currently on this CPU, its either a per-task event,
4761 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
4762 * oncpu == -1).
4763 */
4764 if (event_oncpu == smp_processor_id())
4765 event->pmu->read(event);
4766
4767 *value = local64_read(&event->count);
4768 if (enabled || running) {
4769 u64 __enabled, __running, __now;
4770
4771 calc_timer_values(event, &__now, &__enabled, &__running);
4772 if (enabled)
4773 *enabled = __enabled;
4774 if (running)
4775 *running = __running;
4776 }
4777 out:
4778 local_irq_restore(flags);
4779
4780 return ret;
4781 }
4782 EXPORT_SYMBOL_GPL(perf_event_read_local);
4783
perf_event_read(struct perf_event * event,bool group)4784 static int perf_event_read(struct perf_event *event, bool group)
4785 {
4786 enum perf_event_state state = READ_ONCE(event->state);
4787 int event_cpu, ret = 0;
4788
4789 /*
4790 * If event is enabled and currently active on a CPU, update the
4791 * value in the event structure:
4792 */
4793 again:
4794 if (state == PERF_EVENT_STATE_ACTIVE) {
4795 struct perf_read_data data;
4796
4797 /*
4798 * Orders the ->state and ->oncpu loads such that if we see
4799 * ACTIVE we must also see the right ->oncpu.
4800 *
4801 * Matches the smp_wmb() from event_sched_in().
4802 */
4803 smp_rmb();
4804
4805 event_cpu = READ_ONCE(event->oncpu);
4806 if ((unsigned)event_cpu >= nr_cpu_ids)
4807 return 0;
4808
4809 data = (struct perf_read_data){
4810 .event = event,
4811 .group = group,
4812 .ret = 0,
4813 };
4814
4815 preempt_disable();
4816 event_cpu = __perf_event_read_cpu(event, event_cpu);
4817
4818 /*
4819 * Purposely ignore the smp_call_function_single() return
4820 * value.
4821 *
4822 * If event_cpu isn't a valid CPU it means the event got
4823 * scheduled out and that will have updated the event count.
4824 *
4825 * Therefore, either way, we'll have an up-to-date event count
4826 * after this.
4827 */
4828 (void)smp_call_function_single(event_cpu, __perf_event_read, &data, 1);
4829 preempt_enable();
4830 ret = data.ret;
4831
4832 } else if (state == PERF_EVENT_STATE_INACTIVE) {
4833 struct perf_event_context *ctx = event->ctx;
4834 unsigned long flags;
4835
4836 raw_spin_lock_irqsave(&ctx->lock, flags);
4837 state = event->state;
4838 if (state != PERF_EVENT_STATE_INACTIVE) {
4839 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4840 goto again;
4841 }
4842
4843 /*
4844 * May read while context is not active (e.g., thread is
4845 * blocked), in that case we cannot update context time
4846 */
4847 ctx_time_update_event(ctx, event);
4848
4849 perf_event_update_time(event);
4850 if (group)
4851 perf_event_update_sibling_time(event);
4852 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4853 }
4854
4855 return ret;
4856 }
4857
4858 /*
4859 * Initialize the perf_event context in a task_struct:
4860 */
__perf_event_init_context(struct perf_event_context * ctx)4861 static void __perf_event_init_context(struct perf_event_context *ctx)
4862 {
4863 raw_spin_lock_init(&ctx->lock);
4864 mutex_init(&ctx->mutex);
4865 INIT_LIST_HEAD(&ctx->pmu_ctx_list);
4866 perf_event_groups_init(&ctx->pinned_groups);
4867 perf_event_groups_init(&ctx->flexible_groups);
4868 INIT_LIST_HEAD(&ctx->event_list);
4869 refcount_set(&ctx->refcount, 1);
4870 }
4871
4872 static void
__perf_init_event_pmu_context(struct perf_event_pmu_context * epc,struct pmu * pmu)4873 __perf_init_event_pmu_context(struct perf_event_pmu_context *epc, struct pmu *pmu)
4874 {
4875 epc->pmu = pmu;
4876 INIT_LIST_HEAD(&epc->pmu_ctx_entry);
4877 INIT_LIST_HEAD(&epc->pinned_active);
4878 INIT_LIST_HEAD(&epc->flexible_active);
4879 atomic_set(&epc->refcount, 1);
4880 }
4881
4882 static struct perf_event_context *
alloc_perf_context(struct task_struct * task)4883 alloc_perf_context(struct task_struct *task)
4884 {
4885 struct perf_event_context *ctx;
4886
4887 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
4888 if (!ctx)
4889 return NULL;
4890
4891 __perf_event_init_context(ctx);
4892 if (task)
4893 ctx->task = get_task_struct(task);
4894
4895 return ctx;
4896 }
4897
4898 static struct task_struct *
find_lively_task_by_vpid(pid_t vpid)4899 find_lively_task_by_vpid(pid_t vpid)
4900 {
4901 struct task_struct *task;
4902
4903 rcu_read_lock();
4904 if (!vpid)
4905 task = current;
4906 else
4907 task = find_task_by_vpid(vpid);
4908 if (task)
4909 get_task_struct(task);
4910 rcu_read_unlock();
4911
4912 if (!task)
4913 return ERR_PTR(-ESRCH);
4914
4915 return task;
4916 }
4917
4918 /*
4919 * Returns a matching context with refcount and pincount.
4920 */
4921 static struct perf_event_context *
find_get_context(struct task_struct * task,struct perf_event * event)4922 find_get_context(struct task_struct *task, struct perf_event *event)
4923 {
4924 struct perf_event_context *ctx, *clone_ctx = NULL;
4925 struct perf_cpu_context *cpuctx;
4926 unsigned long flags;
4927 int err;
4928
4929 if (!task) {
4930 /* Must be root to operate on a CPU event: */
4931 err = perf_allow_cpu(&event->attr);
4932 if (err)
4933 return ERR_PTR(err);
4934
4935 cpuctx = per_cpu_ptr(&perf_cpu_context, event->cpu);
4936 ctx = &cpuctx->ctx;
4937 get_ctx(ctx);
4938 raw_spin_lock_irqsave(&ctx->lock, flags);
4939 ++ctx->pin_count;
4940 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4941
4942 return ctx;
4943 }
4944
4945 err = -EINVAL;
4946 retry:
4947 ctx = perf_lock_task_context(task, &flags);
4948 if (ctx) {
4949 clone_ctx = unclone_ctx(ctx);
4950 ++ctx->pin_count;
4951
4952 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4953
4954 if (clone_ctx)
4955 put_ctx(clone_ctx);
4956 } else {
4957 ctx = alloc_perf_context(task);
4958 err = -ENOMEM;
4959 if (!ctx)
4960 goto errout;
4961
4962 err = 0;
4963 mutex_lock(&task->perf_event_mutex);
4964 /*
4965 * If it has already passed perf_event_exit_task().
4966 * we must see PF_EXITING, it takes this mutex too.
4967 */
4968 if (task->flags & PF_EXITING)
4969 err = -ESRCH;
4970 else if (task->perf_event_ctxp)
4971 err = -EAGAIN;
4972 else {
4973 get_ctx(ctx);
4974 ++ctx->pin_count;
4975 rcu_assign_pointer(task->perf_event_ctxp, ctx);
4976 }
4977 mutex_unlock(&task->perf_event_mutex);
4978
4979 if (unlikely(err)) {
4980 put_ctx(ctx);
4981
4982 if (err == -EAGAIN)
4983 goto retry;
4984 goto errout;
4985 }
4986 }
4987
4988 return ctx;
4989
4990 errout:
4991 return ERR_PTR(err);
4992 }
4993
4994 static struct perf_event_pmu_context *
find_get_pmu_context(struct pmu * pmu,struct perf_event_context * ctx,struct perf_event * event)4995 find_get_pmu_context(struct pmu *pmu, struct perf_event_context *ctx,
4996 struct perf_event *event)
4997 {
4998 struct perf_event_pmu_context *new = NULL, *pos = NULL, *epc;
4999 void *task_ctx_data = NULL;
5000
5001 if (!ctx->task) {
5002 /*
5003 * perf_pmu_migrate_context() / __perf_pmu_install_event()
5004 * relies on the fact that find_get_pmu_context() cannot fail
5005 * for CPU contexts.
5006 */
5007 struct perf_cpu_pmu_context *cpc;
5008
5009 cpc = per_cpu_ptr(pmu->cpu_pmu_context, event->cpu);
5010 epc = &cpc->epc;
5011 raw_spin_lock_irq(&ctx->lock);
5012 if (!epc->ctx) {
5013 atomic_set(&epc->refcount, 1);
5014 epc->embedded = 1;
5015 list_add(&epc->pmu_ctx_entry, &ctx->pmu_ctx_list);
5016 epc->ctx = ctx;
5017 } else {
5018 WARN_ON_ONCE(epc->ctx != ctx);
5019 atomic_inc(&epc->refcount);
5020 }
5021 raw_spin_unlock_irq(&ctx->lock);
5022 return epc;
5023 }
5024
5025 new = kzalloc(sizeof(*epc), GFP_KERNEL);
5026 if (!new)
5027 return ERR_PTR(-ENOMEM);
5028
5029 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
5030 task_ctx_data = alloc_task_ctx_data(pmu);
5031 if (!task_ctx_data) {
5032 kfree(new);
5033 return ERR_PTR(-ENOMEM);
5034 }
5035 }
5036
5037 __perf_init_event_pmu_context(new, pmu);
5038
5039 /*
5040 * XXX
5041 *
5042 * lockdep_assert_held(&ctx->mutex);
5043 *
5044 * can't because perf_event_init_task() doesn't actually hold the
5045 * child_ctx->mutex.
5046 */
5047
5048 raw_spin_lock_irq(&ctx->lock);
5049 list_for_each_entry(epc, &ctx->pmu_ctx_list, pmu_ctx_entry) {
5050 if (epc->pmu == pmu) {
5051 WARN_ON_ONCE(epc->ctx != ctx);
5052 atomic_inc(&epc->refcount);
5053 goto found_epc;
5054 }
5055 /* Make sure the pmu_ctx_list is sorted by PMU type: */
5056 if (!pos && epc->pmu->type > pmu->type)
5057 pos = epc;
5058 }
5059
5060 epc = new;
5061 new = NULL;
5062
5063 if (!pos)
5064 list_add_tail(&epc->pmu_ctx_entry, &ctx->pmu_ctx_list);
5065 else
5066 list_add(&epc->pmu_ctx_entry, pos->pmu_ctx_entry.prev);
5067
5068 epc->ctx = ctx;
5069
5070 found_epc:
5071 if (task_ctx_data && !epc->task_ctx_data) {
5072 epc->task_ctx_data = task_ctx_data;
5073 task_ctx_data = NULL;
5074 ctx->nr_task_data++;
5075 }
5076 raw_spin_unlock_irq(&ctx->lock);
5077
5078 free_task_ctx_data(pmu, task_ctx_data);
5079 kfree(new);
5080
5081 return epc;
5082 }
5083
get_pmu_ctx(struct perf_event_pmu_context * epc)5084 static void get_pmu_ctx(struct perf_event_pmu_context *epc)
5085 {
5086 WARN_ON_ONCE(!atomic_inc_not_zero(&epc->refcount));
5087 }
5088
free_epc_rcu(struct rcu_head * head)5089 static void free_epc_rcu(struct rcu_head *head)
5090 {
5091 struct perf_event_pmu_context *epc = container_of(head, typeof(*epc), rcu_head);
5092
5093 kfree(epc->task_ctx_data);
5094 kfree(epc);
5095 }
5096
put_pmu_ctx(struct perf_event_pmu_context * epc)5097 static void put_pmu_ctx(struct perf_event_pmu_context *epc)
5098 {
5099 struct perf_event_context *ctx = epc->ctx;
5100 unsigned long flags;
5101
5102 /*
5103 * XXX
5104 *
5105 * lockdep_assert_held(&ctx->mutex);
5106 *
5107 * can't because of the call-site in _free_event()/put_event()
5108 * which isn't always called under ctx->mutex.
5109 */
5110 if (!atomic_dec_and_raw_lock_irqsave(&epc->refcount, &ctx->lock, flags))
5111 return;
5112
5113 WARN_ON_ONCE(list_empty(&epc->pmu_ctx_entry));
5114
5115 list_del_init(&epc->pmu_ctx_entry);
5116 epc->ctx = NULL;
5117
5118 WARN_ON_ONCE(!list_empty(&epc->pinned_active));
5119 WARN_ON_ONCE(!list_empty(&epc->flexible_active));
5120
5121 raw_spin_unlock_irqrestore(&ctx->lock, flags);
5122
5123 if (epc->embedded)
5124 return;
5125
5126 call_rcu(&epc->rcu_head, free_epc_rcu);
5127 }
5128
5129 static void perf_event_free_filter(struct perf_event *event);
5130
free_event_rcu(struct rcu_head * head)5131 static void free_event_rcu(struct rcu_head *head)
5132 {
5133 struct perf_event *event = container_of(head, typeof(*event), rcu_head);
5134
5135 if (event->ns)
5136 put_pid_ns(event->ns);
5137 perf_event_free_filter(event);
5138 kmem_cache_free(perf_event_cache, event);
5139 }
5140
5141 static void ring_buffer_attach(struct perf_event *event,
5142 struct perf_buffer *rb);
5143
detach_sb_event(struct perf_event * event)5144 static void detach_sb_event(struct perf_event *event)
5145 {
5146 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
5147
5148 raw_spin_lock(&pel->lock);
5149 list_del_rcu(&event->sb_list);
5150 raw_spin_unlock(&pel->lock);
5151 }
5152
is_sb_event(struct perf_event * event)5153 static bool is_sb_event(struct perf_event *event)
5154 {
5155 struct perf_event_attr *attr = &event->attr;
5156
5157 if (event->parent)
5158 return false;
5159
5160 if (event->attach_state & PERF_ATTACH_TASK)
5161 return false;
5162
5163 if (attr->mmap || attr->mmap_data || attr->mmap2 ||
5164 attr->comm || attr->comm_exec ||
5165 attr->task || attr->ksymbol ||
5166 attr->context_switch || attr->text_poke ||
5167 attr->bpf_event)
5168 return true;
5169 return false;
5170 }
5171
unaccount_pmu_sb_event(struct perf_event * event)5172 static void unaccount_pmu_sb_event(struct perf_event *event)
5173 {
5174 if (is_sb_event(event))
5175 detach_sb_event(event);
5176 }
5177
5178 #ifdef CONFIG_NO_HZ_FULL
5179 static DEFINE_SPINLOCK(nr_freq_lock);
5180 #endif
5181
unaccount_freq_event_nohz(void)5182 static void unaccount_freq_event_nohz(void)
5183 {
5184 #ifdef CONFIG_NO_HZ_FULL
5185 spin_lock(&nr_freq_lock);
5186 if (atomic_dec_and_test(&nr_freq_events))
5187 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS);
5188 spin_unlock(&nr_freq_lock);
5189 #endif
5190 }
5191
unaccount_freq_event(void)5192 static void unaccount_freq_event(void)
5193 {
5194 if (tick_nohz_full_enabled())
5195 unaccount_freq_event_nohz();
5196 else
5197 atomic_dec(&nr_freq_events);
5198 }
5199
unaccount_event(struct perf_event * event)5200 static void unaccount_event(struct perf_event *event)
5201 {
5202 bool dec = false;
5203
5204 if (event->parent)
5205 return;
5206
5207 if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB))
5208 dec = true;
5209 if (event->attr.mmap || event->attr.mmap_data)
5210 atomic_dec(&nr_mmap_events);
5211 if (event->attr.build_id)
5212 atomic_dec(&nr_build_id_events);
5213 if (event->attr.comm)
5214 atomic_dec(&nr_comm_events);
5215 if (event->attr.namespaces)
5216 atomic_dec(&nr_namespaces_events);
5217 if (event->attr.cgroup)
5218 atomic_dec(&nr_cgroup_events);
5219 if (event->attr.task)
5220 atomic_dec(&nr_task_events);
5221 if (event->attr.freq)
5222 unaccount_freq_event();
5223 if (event->attr.context_switch) {
5224 dec = true;
5225 atomic_dec(&nr_switch_events);
5226 }
5227 if (is_cgroup_event(event))
5228 dec = true;
5229 if (has_branch_stack(event))
5230 dec = true;
5231 if (event->attr.ksymbol)
5232 atomic_dec(&nr_ksymbol_events);
5233 if (event->attr.bpf_event)
5234 atomic_dec(&nr_bpf_events);
5235 if (event->attr.text_poke)
5236 atomic_dec(&nr_text_poke_events);
5237
5238 if (dec) {
5239 if (!atomic_add_unless(&perf_sched_count, -1, 1))
5240 schedule_delayed_work(&perf_sched_work, HZ);
5241 }
5242
5243 unaccount_pmu_sb_event(event);
5244 }
5245
perf_sched_delayed(struct work_struct * work)5246 static void perf_sched_delayed(struct work_struct *work)
5247 {
5248 mutex_lock(&perf_sched_mutex);
5249 if (atomic_dec_and_test(&perf_sched_count))
5250 static_branch_disable(&perf_sched_events);
5251 mutex_unlock(&perf_sched_mutex);
5252 }
5253
5254 /*
5255 * The following implement mutual exclusion of events on "exclusive" pmus
5256 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
5257 * at a time, so we disallow creating events that might conflict, namely:
5258 *
5259 * 1) cpu-wide events in the presence of per-task events,
5260 * 2) per-task events in the presence of cpu-wide events,
5261 * 3) two matching events on the same perf_event_context.
5262 *
5263 * The former two cases are handled in the allocation path (perf_event_alloc(),
5264 * _free_event()), the latter -- before the first perf_install_in_context().
5265 */
exclusive_event_init(struct perf_event * event)5266 static int exclusive_event_init(struct perf_event *event)
5267 {
5268 struct pmu *pmu = event->pmu;
5269
5270 if (!is_exclusive_pmu(pmu))
5271 return 0;
5272
5273 /*
5274 * Prevent co-existence of per-task and cpu-wide events on the
5275 * same exclusive pmu.
5276 *
5277 * Negative pmu::exclusive_cnt means there are cpu-wide
5278 * events on this "exclusive" pmu, positive means there are
5279 * per-task events.
5280 *
5281 * Since this is called in perf_event_alloc() path, event::ctx
5282 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
5283 * to mean "per-task event", because unlike other attach states it
5284 * never gets cleared.
5285 */
5286 if (event->attach_state & PERF_ATTACH_TASK) {
5287 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
5288 return -EBUSY;
5289 } else {
5290 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
5291 return -EBUSY;
5292 }
5293
5294 event->attach_state |= PERF_ATTACH_EXCLUSIVE;
5295
5296 return 0;
5297 }
5298
exclusive_event_destroy(struct perf_event * event)5299 static void exclusive_event_destroy(struct perf_event *event)
5300 {
5301 struct pmu *pmu = event->pmu;
5302
5303 /* see comment in exclusive_event_init() */
5304 if (event->attach_state & PERF_ATTACH_TASK)
5305 atomic_dec(&pmu->exclusive_cnt);
5306 else
5307 atomic_inc(&pmu->exclusive_cnt);
5308
5309 event->attach_state &= ~PERF_ATTACH_EXCLUSIVE;
5310 }
5311
exclusive_event_match(struct perf_event * e1,struct perf_event * e2)5312 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
5313 {
5314 if ((e1->pmu == e2->pmu) &&
5315 (e1->cpu == e2->cpu ||
5316 e1->cpu == -1 ||
5317 e2->cpu == -1))
5318 return true;
5319 return false;
5320 }
5321
exclusive_event_installable(struct perf_event * event,struct perf_event_context * ctx)5322 static bool exclusive_event_installable(struct perf_event *event,
5323 struct perf_event_context *ctx)
5324 {
5325 struct perf_event *iter_event;
5326 struct pmu *pmu = event->pmu;
5327
5328 lockdep_assert_held(&ctx->mutex);
5329
5330 if (!is_exclusive_pmu(pmu))
5331 return true;
5332
5333 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
5334 if (exclusive_event_match(iter_event, event))
5335 return false;
5336 }
5337
5338 return true;
5339 }
5340
5341 static void perf_addr_filters_splice(struct perf_event *event,
5342 struct list_head *head);
5343
5344 /* vs perf_event_alloc() error */
__free_event(struct perf_event * event)5345 static void __free_event(struct perf_event *event)
5346 {
5347 if (event->attach_state & PERF_ATTACH_CALLCHAIN)
5348 put_callchain_buffers();
5349
5350 kfree(event->addr_filter_ranges);
5351
5352 if (event->attach_state & PERF_ATTACH_EXCLUSIVE)
5353 exclusive_event_destroy(event);
5354
5355 if (is_cgroup_event(event))
5356 perf_detach_cgroup(event);
5357
5358 if (event->destroy)
5359 event->destroy(event);
5360
5361 /*
5362 * Must be after ->destroy(), due to uprobe_perf_close() using
5363 * hw.target.
5364 */
5365 if (event->hw.target)
5366 put_task_struct(event->hw.target);
5367
5368 if (event->pmu_ctx) {
5369 /*
5370 * put_pmu_ctx() needs an event->ctx reference, because of
5371 * epc->ctx.
5372 */
5373 WARN_ON_ONCE(!event->ctx);
5374 WARN_ON_ONCE(event->pmu_ctx->ctx != event->ctx);
5375 put_pmu_ctx(event->pmu_ctx);
5376 }
5377
5378 /*
5379 * perf_event_free_task() relies on put_ctx() being 'last', in
5380 * particular all task references must be cleaned up.
5381 */
5382 if (event->ctx)
5383 put_ctx(event->ctx);
5384
5385 if (event->pmu)
5386 module_put(event->pmu->module);
5387
5388 call_rcu(&event->rcu_head, free_event_rcu);
5389 }
5390
5391 /* vs perf_event_alloc() success */
_free_event(struct perf_event * event)5392 static void _free_event(struct perf_event *event)
5393 {
5394 irq_work_sync(&event->pending_irq);
5395 irq_work_sync(&event->pending_disable_irq);
5396
5397 unaccount_event(event);
5398
5399 security_perf_event_free(event);
5400
5401 if (event->rb) {
5402 /*
5403 * Can happen when we close an event with re-directed output.
5404 *
5405 * Since we have a 0 refcount, perf_mmap_close() will skip
5406 * over us; possibly making our ring_buffer_put() the last.
5407 */
5408 mutex_lock(&event->mmap_mutex);
5409 ring_buffer_attach(event, NULL);
5410 mutex_unlock(&event->mmap_mutex);
5411 }
5412
5413 perf_event_free_bpf_prog(event);
5414 perf_addr_filters_splice(event, NULL);
5415
5416 __free_event(event);
5417 }
5418
5419 /*
5420 * Used to free events which have a known refcount of 1, such as in error paths
5421 * where the event isn't exposed yet and inherited events.
5422 */
free_event(struct perf_event * event)5423 static void free_event(struct perf_event *event)
5424 {
5425 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
5426 "unexpected event refcount: %ld; ptr=%p\n",
5427 atomic_long_read(&event->refcount), event)) {
5428 /* leak to avoid use-after-free */
5429 return;
5430 }
5431
5432 _free_event(event);
5433 }
5434
5435 /*
5436 * Remove user event from the owner task.
5437 */
perf_remove_from_owner(struct perf_event * event)5438 static void perf_remove_from_owner(struct perf_event *event)
5439 {
5440 struct task_struct *owner;
5441
5442 rcu_read_lock();
5443 /*
5444 * Matches the smp_store_release() in perf_event_exit_task(). If we
5445 * observe !owner it means the list deletion is complete and we can
5446 * indeed free this event, otherwise we need to serialize on
5447 * owner->perf_event_mutex.
5448 */
5449 owner = READ_ONCE(event->owner);
5450 if (owner) {
5451 /*
5452 * Since delayed_put_task_struct() also drops the last
5453 * task reference we can safely take a new reference
5454 * while holding the rcu_read_lock().
5455 */
5456 get_task_struct(owner);
5457 }
5458 rcu_read_unlock();
5459
5460 if (owner) {
5461 /*
5462 * If we're here through perf_event_exit_task() we're already
5463 * holding ctx->mutex which would be an inversion wrt. the
5464 * normal lock order.
5465 *
5466 * However we can safely take this lock because its the child
5467 * ctx->mutex.
5468 */
5469 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
5470
5471 /*
5472 * We have to re-check the event->owner field, if it is cleared
5473 * we raced with perf_event_exit_task(), acquiring the mutex
5474 * ensured they're done, and we can proceed with freeing the
5475 * event.
5476 */
5477 if (event->owner) {
5478 list_del_init(&event->owner_entry);
5479 smp_store_release(&event->owner, NULL);
5480 }
5481 mutex_unlock(&owner->perf_event_mutex);
5482 put_task_struct(owner);
5483 }
5484 }
5485
put_event(struct perf_event * event)5486 static void put_event(struct perf_event *event)
5487 {
5488 struct perf_event *parent;
5489
5490 if (!atomic_long_dec_and_test(&event->refcount))
5491 return;
5492
5493 parent = event->parent;
5494 _free_event(event);
5495
5496 /* Matches the refcount bump in inherit_event() */
5497 if (parent)
5498 put_event(parent);
5499 }
5500
5501 /*
5502 * Kill an event dead; while event:refcount will preserve the event
5503 * object, it will not preserve its functionality. Once the last 'user'
5504 * gives up the object, we'll destroy the thing.
5505 */
perf_event_release_kernel(struct perf_event * event)5506 int perf_event_release_kernel(struct perf_event *event)
5507 {
5508 struct perf_event_context *ctx = event->ctx;
5509 struct perf_event *child, *tmp;
5510 LIST_HEAD(free_list);
5511
5512 /*
5513 * If we got here through err_alloc: free_event(event); we will not
5514 * have attached to a context yet.
5515 */
5516 if (!ctx) {
5517 WARN_ON_ONCE(event->attach_state &
5518 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
5519 goto no_ctx;
5520 }
5521
5522 if (!is_kernel_event(event))
5523 perf_remove_from_owner(event);
5524
5525 ctx = perf_event_ctx_lock(event);
5526 WARN_ON_ONCE(ctx->parent_ctx);
5527
5528 /*
5529 * Mark this event as STATE_DEAD, there is no external reference to it
5530 * anymore.
5531 *
5532 * Anybody acquiring event->child_mutex after the below loop _must_
5533 * also see this, most importantly inherit_event() which will avoid
5534 * placing more children on the list.
5535 *
5536 * Thus this guarantees that we will in fact observe and kill _ALL_
5537 * child events.
5538 */
5539 perf_remove_from_context(event, DETACH_GROUP|DETACH_DEAD);
5540
5541 perf_event_ctx_unlock(event, ctx);
5542
5543 again:
5544 mutex_lock(&event->child_mutex);
5545 list_for_each_entry(child, &event->child_list, child_list) {
5546 void *var = NULL;
5547
5548 /*
5549 * Cannot change, child events are not migrated, see the
5550 * comment with perf_event_ctx_lock_nested().
5551 */
5552 ctx = READ_ONCE(child->ctx);
5553 /*
5554 * Since child_mutex nests inside ctx::mutex, we must jump
5555 * through hoops. We start by grabbing a reference on the ctx.
5556 *
5557 * Since the event cannot get freed while we hold the
5558 * child_mutex, the context must also exist and have a !0
5559 * reference count.
5560 */
5561 get_ctx(ctx);
5562
5563 /*
5564 * Now that we have a ctx ref, we can drop child_mutex, and
5565 * acquire ctx::mutex without fear of it going away. Then we
5566 * can re-acquire child_mutex.
5567 */
5568 mutex_unlock(&event->child_mutex);
5569 mutex_lock(&ctx->mutex);
5570 mutex_lock(&event->child_mutex);
5571
5572 /*
5573 * Now that we hold ctx::mutex and child_mutex, revalidate our
5574 * state, if child is still the first entry, it didn't get freed
5575 * and we can continue doing so.
5576 */
5577 tmp = list_first_entry_or_null(&event->child_list,
5578 struct perf_event, child_list);
5579 if (tmp == child) {
5580 perf_remove_from_context(child, DETACH_GROUP);
5581 list_move(&child->child_list, &free_list);
5582 } else {
5583 var = &ctx->refcount;
5584 }
5585
5586 mutex_unlock(&event->child_mutex);
5587 mutex_unlock(&ctx->mutex);
5588 put_ctx(ctx);
5589
5590 if (var) {
5591 /*
5592 * If perf_event_free_task() has deleted all events from the
5593 * ctx while the child_mutex got released above, make sure to
5594 * notify about the preceding put_ctx().
5595 */
5596 smp_mb(); /* pairs with wait_var_event() */
5597 wake_up_var(var);
5598 }
5599 goto again;
5600 }
5601 mutex_unlock(&event->child_mutex);
5602
5603 list_for_each_entry_safe(child, tmp, &free_list, child_list) {
5604 void *var = &child->ctx->refcount;
5605
5606 list_del(&child->child_list);
5607 /* Last reference unless ->pending_task work is pending */
5608 put_event(child);
5609
5610 /*
5611 * Wake any perf_event_free_task() waiting for this event to be
5612 * freed.
5613 */
5614 smp_mb(); /* pairs with wait_var_event() */
5615 wake_up_var(var);
5616 }
5617
5618 no_ctx:
5619 /*
5620 * Last reference unless ->pending_task work is pending on this event
5621 * or any of its children.
5622 */
5623 put_event(event);
5624 return 0;
5625 }
5626 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
5627
5628 /*
5629 * Called when the last reference to the file is gone.
5630 */
perf_release(struct inode * inode,struct file * file)5631 static int perf_release(struct inode *inode, struct file *file)
5632 {
5633 perf_event_release_kernel(file->private_data);
5634 return 0;
5635 }
5636
__perf_event_read_value(struct perf_event * event,u64 * enabled,u64 * running)5637 static u64 __perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5638 {
5639 struct perf_event *child;
5640 u64 total = 0;
5641
5642 *enabled = 0;
5643 *running = 0;
5644
5645 mutex_lock(&event->child_mutex);
5646
5647 (void)perf_event_read(event, false);
5648 total += perf_event_count(event, false);
5649
5650 *enabled += event->total_time_enabled +
5651 atomic64_read(&event->child_total_time_enabled);
5652 *running += event->total_time_running +
5653 atomic64_read(&event->child_total_time_running);
5654
5655 list_for_each_entry(child, &event->child_list, child_list) {
5656 (void)perf_event_read(child, false);
5657 total += perf_event_count(child, false);
5658 *enabled += child->total_time_enabled;
5659 *running += child->total_time_running;
5660 }
5661 mutex_unlock(&event->child_mutex);
5662
5663 return total;
5664 }
5665
perf_event_read_value(struct perf_event * event,u64 * enabled,u64 * running)5666 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5667 {
5668 struct perf_event_context *ctx;
5669 u64 count;
5670
5671 ctx = perf_event_ctx_lock(event);
5672 count = __perf_event_read_value(event, enabled, running);
5673 perf_event_ctx_unlock(event, ctx);
5674
5675 return count;
5676 }
5677 EXPORT_SYMBOL_GPL(perf_event_read_value);
5678
__perf_read_group_add(struct perf_event * leader,u64 read_format,u64 * values)5679 static int __perf_read_group_add(struct perf_event *leader,
5680 u64 read_format, u64 *values)
5681 {
5682 struct perf_event_context *ctx = leader->ctx;
5683 struct perf_event *sub, *parent;
5684 unsigned long flags;
5685 int n = 1; /* skip @nr */
5686 int ret;
5687
5688 ret = perf_event_read(leader, true);
5689 if (ret)
5690 return ret;
5691
5692 raw_spin_lock_irqsave(&ctx->lock, flags);
5693 /*
5694 * Verify the grouping between the parent and child (inherited)
5695 * events is still in tact.
5696 *
5697 * Specifically:
5698 * - leader->ctx->lock pins leader->sibling_list
5699 * - parent->child_mutex pins parent->child_list
5700 * - parent->ctx->mutex pins parent->sibling_list
5701 *
5702 * Because parent->ctx != leader->ctx (and child_list nests inside
5703 * ctx->mutex), group destruction is not atomic between children, also
5704 * see perf_event_release_kernel(). Additionally, parent can grow the
5705 * group.
5706 *
5707 * Therefore it is possible to have parent and child groups in a
5708 * different configuration and summing over such a beast makes no sense
5709 * what so ever.
5710 *
5711 * Reject this.
5712 */
5713 parent = leader->parent;
5714 if (parent &&
5715 (parent->group_generation != leader->group_generation ||
5716 parent->nr_siblings != leader->nr_siblings)) {
5717 ret = -ECHILD;
5718 goto unlock;
5719 }
5720
5721 /*
5722 * Since we co-schedule groups, {enabled,running} times of siblings
5723 * will be identical to those of the leader, so we only publish one
5724 * set.
5725 */
5726 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5727 values[n++] += leader->total_time_enabled +
5728 atomic64_read(&leader->child_total_time_enabled);
5729 }
5730
5731 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5732 values[n++] += leader->total_time_running +
5733 atomic64_read(&leader->child_total_time_running);
5734 }
5735
5736 /*
5737 * Write {count,id} tuples for every sibling.
5738 */
5739 values[n++] += perf_event_count(leader, false);
5740 if (read_format & PERF_FORMAT_ID)
5741 values[n++] = primary_event_id(leader);
5742 if (read_format & PERF_FORMAT_LOST)
5743 values[n++] = atomic64_read(&leader->lost_samples);
5744
5745 for_each_sibling_event(sub, leader) {
5746 values[n++] += perf_event_count(sub, false);
5747 if (read_format & PERF_FORMAT_ID)
5748 values[n++] = primary_event_id(sub);
5749 if (read_format & PERF_FORMAT_LOST)
5750 values[n++] = atomic64_read(&sub->lost_samples);
5751 }
5752
5753 unlock:
5754 raw_spin_unlock_irqrestore(&ctx->lock, flags);
5755 return ret;
5756 }
5757
perf_read_group(struct perf_event * event,u64 read_format,char __user * buf)5758 static int perf_read_group(struct perf_event *event,
5759 u64 read_format, char __user *buf)
5760 {
5761 struct perf_event *leader = event->group_leader, *child;
5762 struct perf_event_context *ctx = leader->ctx;
5763 int ret;
5764 u64 *values;
5765
5766 lockdep_assert_held(&ctx->mutex);
5767
5768 values = kzalloc(event->read_size, GFP_KERNEL);
5769 if (!values)
5770 return -ENOMEM;
5771
5772 values[0] = 1 + leader->nr_siblings;
5773
5774 mutex_lock(&leader->child_mutex);
5775
5776 ret = __perf_read_group_add(leader, read_format, values);
5777 if (ret)
5778 goto unlock;
5779
5780 list_for_each_entry(child, &leader->child_list, child_list) {
5781 ret = __perf_read_group_add(child, read_format, values);
5782 if (ret)
5783 goto unlock;
5784 }
5785
5786 mutex_unlock(&leader->child_mutex);
5787
5788 ret = event->read_size;
5789 if (copy_to_user(buf, values, event->read_size))
5790 ret = -EFAULT;
5791 goto out;
5792
5793 unlock:
5794 mutex_unlock(&leader->child_mutex);
5795 out:
5796 kfree(values);
5797 return ret;
5798 }
5799
perf_read_one(struct perf_event * event,u64 read_format,char __user * buf)5800 static int perf_read_one(struct perf_event *event,
5801 u64 read_format, char __user *buf)
5802 {
5803 u64 enabled, running;
5804 u64 values[5];
5805 int n = 0;
5806
5807 values[n++] = __perf_event_read_value(event, &enabled, &running);
5808 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
5809 values[n++] = enabled;
5810 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
5811 values[n++] = running;
5812 if (read_format & PERF_FORMAT_ID)
5813 values[n++] = primary_event_id(event);
5814 if (read_format & PERF_FORMAT_LOST)
5815 values[n++] = atomic64_read(&event->lost_samples);
5816
5817 if (copy_to_user(buf, values, n * sizeof(u64)))
5818 return -EFAULT;
5819
5820 return n * sizeof(u64);
5821 }
5822
is_event_hup(struct perf_event * event)5823 static bool is_event_hup(struct perf_event *event)
5824 {
5825 bool no_children;
5826
5827 if (event->state > PERF_EVENT_STATE_EXIT)
5828 return false;
5829
5830 mutex_lock(&event->child_mutex);
5831 no_children = list_empty(&event->child_list);
5832 mutex_unlock(&event->child_mutex);
5833 return no_children;
5834 }
5835
5836 /*
5837 * Read the performance event - simple non blocking version for now
5838 */
5839 static ssize_t
__perf_read(struct perf_event * event,char __user * buf,size_t count)5840 __perf_read(struct perf_event *event, char __user *buf, size_t count)
5841 {
5842 u64 read_format = event->attr.read_format;
5843 int ret;
5844
5845 /*
5846 * Return end-of-file for a read on an event that is in
5847 * error state (i.e. because it was pinned but it couldn't be
5848 * scheduled on to the CPU at some point).
5849 */
5850 if (event->state == PERF_EVENT_STATE_ERROR)
5851 return 0;
5852
5853 if (count < event->read_size)
5854 return -ENOSPC;
5855
5856 WARN_ON_ONCE(event->ctx->parent_ctx);
5857 if (read_format & PERF_FORMAT_GROUP)
5858 ret = perf_read_group(event, read_format, buf);
5859 else
5860 ret = perf_read_one(event, read_format, buf);
5861
5862 return ret;
5863 }
5864
5865 static ssize_t
perf_read(struct file * file,char __user * buf,size_t count,loff_t * ppos)5866 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
5867 {
5868 struct perf_event *event = file->private_data;
5869 struct perf_event_context *ctx;
5870 int ret;
5871
5872 ret = security_perf_event_read(event);
5873 if (ret)
5874 return ret;
5875
5876 ctx = perf_event_ctx_lock(event);
5877 ret = __perf_read(event, buf, count);
5878 perf_event_ctx_unlock(event, ctx);
5879
5880 return ret;
5881 }
5882
perf_poll(struct file * file,poll_table * wait)5883 static __poll_t perf_poll(struct file *file, poll_table *wait)
5884 {
5885 struct perf_event *event = file->private_data;
5886 struct perf_buffer *rb;
5887 __poll_t events = EPOLLHUP;
5888
5889 poll_wait(file, &event->waitq, wait);
5890
5891 if (is_event_hup(event))
5892 return events;
5893
5894 /*
5895 * Pin the event->rb by taking event->mmap_mutex; otherwise
5896 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
5897 */
5898 mutex_lock(&event->mmap_mutex);
5899 rb = event->rb;
5900 if (rb)
5901 events = atomic_xchg(&rb->poll, 0);
5902 mutex_unlock(&event->mmap_mutex);
5903 return events;
5904 }
5905
_perf_event_reset(struct perf_event * event)5906 static void _perf_event_reset(struct perf_event *event)
5907 {
5908 (void)perf_event_read(event, false);
5909 local64_set(&event->count, 0);
5910 perf_event_update_userpage(event);
5911 }
5912
5913 /* Assume it's not an event with inherit set. */
perf_event_pause(struct perf_event * event,bool reset)5914 u64 perf_event_pause(struct perf_event *event, bool reset)
5915 {
5916 struct perf_event_context *ctx;
5917 u64 count;
5918
5919 ctx = perf_event_ctx_lock(event);
5920 WARN_ON_ONCE(event->attr.inherit);
5921 _perf_event_disable(event);
5922 count = local64_read(&event->count);
5923 if (reset)
5924 local64_set(&event->count, 0);
5925 perf_event_ctx_unlock(event, ctx);
5926
5927 return count;
5928 }
5929 EXPORT_SYMBOL_GPL(perf_event_pause);
5930
5931 /*
5932 * Holding the top-level event's child_mutex means that any
5933 * descendant process that has inherited this event will block
5934 * in perf_event_exit_event() if it goes to exit, thus satisfying the
5935 * task existence requirements of perf_event_enable/disable.
5936 */
perf_event_for_each_child(struct perf_event * event,void (* func)(struct perf_event *))5937 static void perf_event_for_each_child(struct perf_event *event,
5938 void (*func)(struct perf_event *))
5939 {
5940 struct perf_event *child;
5941
5942 WARN_ON_ONCE(event->ctx->parent_ctx);
5943
5944 mutex_lock(&event->child_mutex);
5945 func(event);
5946 list_for_each_entry(child, &event->child_list, child_list)
5947 func(child);
5948 mutex_unlock(&event->child_mutex);
5949 }
5950
perf_event_for_each(struct perf_event * event,void (* func)(struct perf_event *))5951 static void perf_event_for_each(struct perf_event *event,
5952 void (*func)(struct perf_event *))
5953 {
5954 struct perf_event_context *ctx = event->ctx;
5955 struct perf_event *sibling;
5956
5957 lockdep_assert_held(&ctx->mutex);
5958
5959 event = event->group_leader;
5960
5961 perf_event_for_each_child(event, func);
5962 for_each_sibling_event(sibling, event)
5963 perf_event_for_each_child(sibling, func);
5964 }
5965
__perf_event_period(struct perf_event * event,struct perf_cpu_context * cpuctx,struct perf_event_context * ctx,void * info)5966 static void __perf_event_period(struct perf_event *event,
5967 struct perf_cpu_context *cpuctx,
5968 struct perf_event_context *ctx,
5969 void *info)
5970 {
5971 u64 value = *((u64 *)info);
5972 bool active;
5973
5974 if (event->attr.freq) {
5975 event->attr.sample_freq = value;
5976 } else {
5977 event->attr.sample_period = value;
5978 event->hw.sample_period = value;
5979 }
5980
5981 active = (event->state == PERF_EVENT_STATE_ACTIVE);
5982 if (active) {
5983 perf_pmu_disable(event->pmu);
5984 /*
5985 * We could be throttled; unthrottle now to avoid the tick
5986 * trying to unthrottle while we already re-started the event.
5987 */
5988 if (event->hw.interrupts == MAX_INTERRUPTS) {
5989 event->hw.interrupts = 0;
5990 perf_log_throttle(event, 1);
5991 }
5992 event->pmu->stop(event, PERF_EF_UPDATE);
5993 }
5994
5995 local64_set(&event->hw.period_left, 0);
5996
5997 if (active) {
5998 event->pmu->start(event, PERF_EF_RELOAD);
5999 perf_pmu_enable(event->pmu);
6000 }
6001 }
6002
perf_event_check_period(struct perf_event * event,u64 value)6003 static int perf_event_check_period(struct perf_event *event, u64 value)
6004 {
6005 return event->pmu->check_period(event, value);
6006 }
6007
_perf_event_period(struct perf_event * event,u64 value)6008 static int _perf_event_period(struct perf_event *event, u64 value)
6009 {
6010 if (!is_sampling_event(event))
6011 return -EINVAL;
6012
6013 if (!value)
6014 return -EINVAL;
6015
6016 if (event->attr.freq) {
6017 if (value > sysctl_perf_event_sample_rate)
6018 return -EINVAL;
6019 } else {
6020 if (perf_event_check_period(event, value))
6021 return -EINVAL;
6022 if (value & (1ULL << 63))
6023 return -EINVAL;
6024 }
6025
6026 event_function_call(event, __perf_event_period, &value);
6027
6028 return 0;
6029 }
6030
perf_event_period(struct perf_event * event,u64 value)6031 int perf_event_period(struct perf_event *event, u64 value)
6032 {
6033 struct perf_event_context *ctx;
6034 int ret;
6035
6036 ctx = perf_event_ctx_lock(event);
6037 ret = _perf_event_period(event, value);
6038 perf_event_ctx_unlock(event, ctx);
6039
6040 return ret;
6041 }
6042 EXPORT_SYMBOL_GPL(perf_event_period);
6043
6044 static const struct file_operations perf_fops;
6045
perf_fget_light(int fd,struct fd * p)6046 static inline int perf_fget_light(int fd, struct fd *p)
6047 {
6048 struct fd f = fdget(fd);
6049 if (!fd_file(f))
6050 return -EBADF;
6051
6052 if (fd_file(f)->f_op != &perf_fops) {
6053 fdput(f);
6054 return -EBADF;
6055 }
6056 *p = f;
6057 return 0;
6058 }
6059
6060 static int perf_event_set_output(struct perf_event *event,
6061 struct perf_event *output_event);
6062 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
6063 static int perf_copy_attr(struct perf_event_attr __user *uattr,
6064 struct perf_event_attr *attr);
6065 static int __perf_event_set_bpf_prog(struct perf_event *event,
6066 struct bpf_prog *prog,
6067 u64 bpf_cookie);
6068
_perf_ioctl(struct perf_event * event,unsigned int cmd,unsigned long arg)6069 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
6070 {
6071 void (*func)(struct perf_event *);
6072 u32 flags = arg;
6073
6074 switch (cmd) {
6075 case PERF_EVENT_IOC_ENABLE:
6076 func = _perf_event_enable;
6077 break;
6078 case PERF_EVENT_IOC_DISABLE:
6079 func = _perf_event_disable;
6080 break;
6081 case PERF_EVENT_IOC_RESET:
6082 func = _perf_event_reset;
6083 break;
6084
6085 case PERF_EVENT_IOC_REFRESH:
6086 return _perf_event_refresh(event, arg);
6087
6088 case PERF_EVENT_IOC_PERIOD:
6089 {
6090 u64 value;
6091
6092 if (copy_from_user(&value, (u64 __user *)arg, sizeof(value)))
6093 return -EFAULT;
6094
6095 return _perf_event_period(event, value);
6096 }
6097 case PERF_EVENT_IOC_ID:
6098 {
6099 u64 id = primary_event_id(event);
6100
6101 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
6102 return -EFAULT;
6103 return 0;
6104 }
6105
6106 case PERF_EVENT_IOC_SET_OUTPUT:
6107 {
6108 int ret;
6109 if (arg != -1) {
6110 struct perf_event *output_event;
6111 struct fd output;
6112 ret = perf_fget_light(arg, &output);
6113 if (ret)
6114 return ret;
6115 output_event = fd_file(output)->private_data;
6116 ret = perf_event_set_output(event, output_event);
6117 fdput(output);
6118 } else {
6119 ret = perf_event_set_output(event, NULL);
6120 }
6121 return ret;
6122 }
6123
6124 case PERF_EVENT_IOC_SET_FILTER:
6125 return perf_event_set_filter(event, (void __user *)arg);
6126
6127 case PERF_EVENT_IOC_SET_BPF:
6128 {
6129 struct bpf_prog *prog;
6130 int err;
6131
6132 prog = bpf_prog_get(arg);
6133 if (IS_ERR(prog))
6134 return PTR_ERR(prog);
6135
6136 err = __perf_event_set_bpf_prog(event, prog, 0);
6137 if (err) {
6138 bpf_prog_put(prog);
6139 return err;
6140 }
6141
6142 return 0;
6143 }
6144
6145 case PERF_EVENT_IOC_PAUSE_OUTPUT: {
6146 struct perf_buffer *rb;
6147
6148 rcu_read_lock();
6149 rb = rcu_dereference(event->rb);
6150 if (!rb || !rb->nr_pages) {
6151 rcu_read_unlock();
6152 return -EINVAL;
6153 }
6154 rb_toggle_paused(rb, !!arg);
6155 rcu_read_unlock();
6156 return 0;
6157 }
6158
6159 case PERF_EVENT_IOC_QUERY_BPF:
6160 return perf_event_query_prog_array(event, (void __user *)arg);
6161
6162 case PERF_EVENT_IOC_MODIFY_ATTRIBUTES: {
6163 struct perf_event_attr new_attr;
6164 int err = perf_copy_attr((struct perf_event_attr __user *)arg,
6165 &new_attr);
6166
6167 if (err)
6168 return err;
6169
6170 return perf_event_modify_attr(event, &new_attr);
6171 }
6172 default:
6173 return -ENOTTY;
6174 }
6175
6176 if (flags & PERF_IOC_FLAG_GROUP)
6177 perf_event_for_each(event, func);
6178 else
6179 perf_event_for_each_child(event, func);
6180
6181 return 0;
6182 }
6183
perf_ioctl(struct file * file,unsigned int cmd,unsigned long arg)6184 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
6185 {
6186 struct perf_event *event = file->private_data;
6187 struct perf_event_context *ctx;
6188 long ret;
6189
6190 /* Treat ioctl like writes as it is likely a mutating operation. */
6191 ret = security_perf_event_write(event);
6192 if (ret)
6193 return ret;
6194
6195 ctx = perf_event_ctx_lock(event);
6196 ret = _perf_ioctl(event, cmd, arg);
6197 perf_event_ctx_unlock(event, ctx);
6198
6199 return ret;
6200 }
6201
6202 #ifdef CONFIG_COMPAT
perf_compat_ioctl(struct file * file,unsigned int cmd,unsigned long arg)6203 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
6204 unsigned long arg)
6205 {
6206 switch (_IOC_NR(cmd)) {
6207 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
6208 case _IOC_NR(PERF_EVENT_IOC_ID):
6209 case _IOC_NR(PERF_EVENT_IOC_QUERY_BPF):
6210 case _IOC_NR(PERF_EVENT_IOC_MODIFY_ATTRIBUTES):
6211 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
6212 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
6213 cmd &= ~IOCSIZE_MASK;
6214 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
6215 }
6216 break;
6217 }
6218 return perf_ioctl(file, cmd, arg);
6219 }
6220 #else
6221 # define perf_compat_ioctl NULL
6222 #endif
6223
perf_event_task_enable(void)6224 int perf_event_task_enable(void)
6225 {
6226 struct perf_event_context *ctx;
6227 struct perf_event *event;
6228
6229 mutex_lock(¤t->perf_event_mutex);
6230 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
6231 ctx = perf_event_ctx_lock(event);
6232 perf_event_for_each_child(event, _perf_event_enable);
6233 perf_event_ctx_unlock(event, ctx);
6234 }
6235 mutex_unlock(¤t->perf_event_mutex);
6236
6237 return 0;
6238 }
6239
perf_event_task_disable(void)6240 int perf_event_task_disable(void)
6241 {
6242 struct perf_event_context *ctx;
6243 struct perf_event *event;
6244
6245 mutex_lock(¤t->perf_event_mutex);
6246 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
6247 ctx = perf_event_ctx_lock(event);
6248 perf_event_for_each_child(event, _perf_event_disable);
6249 perf_event_ctx_unlock(event, ctx);
6250 }
6251 mutex_unlock(¤t->perf_event_mutex);
6252
6253 return 0;
6254 }
6255
perf_event_index(struct perf_event * event)6256 static int perf_event_index(struct perf_event *event)
6257 {
6258 if (event->hw.state & PERF_HES_STOPPED)
6259 return 0;
6260
6261 if (event->state != PERF_EVENT_STATE_ACTIVE)
6262 return 0;
6263
6264 return event->pmu->event_idx(event);
6265 }
6266
perf_event_init_userpage(struct perf_event * event)6267 static void perf_event_init_userpage(struct perf_event *event)
6268 {
6269 struct perf_event_mmap_page *userpg;
6270 struct perf_buffer *rb;
6271
6272 rcu_read_lock();
6273 rb = rcu_dereference(event->rb);
6274 if (!rb)
6275 goto unlock;
6276
6277 userpg = rb->user_page;
6278
6279 /* Allow new userspace to detect that bit 0 is deprecated */
6280 userpg->cap_bit0_is_deprecated = 1;
6281 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
6282 userpg->data_offset = PAGE_SIZE;
6283 userpg->data_size = perf_data_size(rb);
6284
6285 unlock:
6286 rcu_read_unlock();
6287 }
6288
arch_perf_update_userpage(struct perf_event * event,struct perf_event_mmap_page * userpg,u64 now)6289 void __weak arch_perf_update_userpage(
6290 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
6291 {
6292 }
6293
6294 /*
6295 * Callers need to ensure there can be no nesting of this function, otherwise
6296 * the seqlock logic goes bad. We can not serialize this because the arch
6297 * code calls this from NMI context.
6298 */
perf_event_update_userpage(struct perf_event * event)6299 void perf_event_update_userpage(struct perf_event *event)
6300 {
6301 struct perf_event_mmap_page *userpg;
6302 struct perf_buffer *rb;
6303 u64 enabled, running, now;
6304
6305 rcu_read_lock();
6306 rb = rcu_dereference(event->rb);
6307 if (!rb)
6308 goto unlock;
6309
6310 /*
6311 * compute total_time_enabled, total_time_running
6312 * based on snapshot values taken when the event
6313 * was last scheduled in.
6314 *
6315 * we cannot simply called update_context_time()
6316 * because of locking issue as we can be called in
6317 * NMI context
6318 */
6319 calc_timer_values(event, &now, &enabled, &running);
6320
6321 userpg = rb->user_page;
6322 /*
6323 * Disable preemption to guarantee consistent time stamps are stored to
6324 * the user page.
6325 */
6326 preempt_disable();
6327 ++userpg->lock;
6328 barrier();
6329 userpg->index = perf_event_index(event);
6330 userpg->offset = perf_event_count(event, false);
6331 if (userpg->index)
6332 userpg->offset -= local64_read(&event->hw.prev_count);
6333
6334 userpg->time_enabled = enabled +
6335 atomic64_read(&event->child_total_time_enabled);
6336
6337 userpg->time_running = running +
6338 atomic64_read(&event->child_total_time_running);
6339
6340 arch_perf_update_userpage(event, userpg, now);
6341
6342 barrier();
6343 ++userpg->lock;
6344 preempt_enable();
6345 unlock:
6346 rcu_read_unlock();
6347 }
6348 EXPORT_SYMBOL_GPL(perf_event_update_userpage);
6349
perf_mmap_fault(struct vm_fault * vmf)6350 static vm_fault_t perf_mmap_fault(struct vm_fault *vmf)
6351 {
6352 struct perf_event *event = vmf->vma->vm_file->private_data;
6353 struct perf_buffer *rb;
6354 vm_fault_t ret = VM_FAULT_SIGBUS;
6355
6356 if (vmf->flags & FAULT_FLAG_MKWRITE) {
6357 if (vmf->pgoff == 0)
6358 ret = 0;
6359 return ret;
6360 }
6361
6362 rcu_read_lock();
6363 rb = rcu_dereference(event->rb);
6364 if (!rb)
6365 goto unlock;
6366
6367 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
6368 goto unlock;
6369
6370 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
6371 if (!vmf->page)
6372 goto unlock;
6373
6374 get_page(vmf->page);
6375 vmf->page->mapping = vmf->vma->vm_file->f_mapping;
6376 vmf->page->index = vmf->pgoff;
6377
6378 ret = 0;
6379 unlock:
6380 rcu_read_unlock();
6381
6382 return ret;
6383 }
6384
ring_buffer_attach(struct perf_event * event,struct perf_buffer * rb)6385 static void ring_buffer_attach(struct perf_event *event,
6386 struct perf_buffer *rb)
6387 {
6388 struct perf_buffer *old_rb = NULL;
6389 unsigned long flags;
6390
6391 WARN_ON_ONCE(event->parent);
6392
6393 if (event->rb) {
6394 /*
6395 * Should be impossible, we set this when removing
6396 * event->rb_entry and wait/clear when adding event->rb_entry.
6397 */
6398 WARN_ON_ONCE(event->rcu_pending);
6399
6400 old_rb = event->rb;
6401 spin_lock_irqsave(&old_rb->event_lock, flags);
6402 list_del_rcu(&event->rb_entry);
6403 spin_unlock_irqrestore(&old_rb->event_lock, flags);
6404
6405 event->rcu_batches = get_state_synchronize_rcu();
6406 event->rcu_pending = 1;
6407 }
6408
6409 if (rb) {
6410 if (event->rcu_pending) {
6411 cond_synchronize_rcu(event->rcu_batches);
6412 event->rcu_pending = 0;
6413 }
6414
6415 spin_lock_irqsave(&rb->event_lock, flags);
6416 list_add_rcu(&event->rb_entry, &rb->event_list);
6417 spin_unlock_irqrestore(&rb->event_lock, flags);
6418 }
6419
6420 /*
6421 * Avoid racing with perf_mmap_close(AUX): stop the event
6422 * before swizzling the event::rb pointer; if it's getting
6423 * unmapped, its aux_mmap_count will be 0 and it won't
6424 * restart. See the comment in __perf_pmu_output_stop().
6425 *
6426 * Data will inevitably be lost when set_output is done in
6427 * mid-air, but then again, whoever does it like this is
6428 * not in for the data anyway.
6429 */
6430 if (has_aux(event))
6431 perf_event_stop(event, 0);
6432
6433 rcu_assign_pointer(event->rb, rb);
6434
6435 if (old_rb) {
6436 ring_buffer_put(old_rb);
6437 /*
6438 * Since we detached before setting the new rb, so that we
6439 * could attach the new rb, we could have missed a wakeup.
6440 * Provide it now.
6441 */
6442 wake_up_all(&event->waitq);
6443 }
6444 }
6445
ring_buffer_wakeup(struct perf_event * event)6446 static void ring_buffer_wakeup(struct perf_event *event)
6447 {
6448 struct perf_buffer *rb;
6449
6450 if (event->parent)
6451 event = event->parent;
6452
6453 rcu_read_lock();
6454 rb = rcu_dereference(event->rb);
6455 if (rb) {
6456 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
6457 wake_up_all(&event->waitq);
6458 }
6459 rcu_read_unlock();
6460 }
6461
ring_buffer_get(struct perf_event * event)6462 struct perf_buffer *ring_buffer_get(struct perf_event *event)
6463 {
6464 struct perf_buffer *rb;
6465
6466 if (event->parent)
6467 event = event->parent;
6468
6469 rcu_read_lock();
6470 rb = rcu_dereference(event->rb);
6471 if (rb) {
6472 if (!refcount_inc_not_zero(&rb->refcount))
6473 rb = NULL;
6474 }
6475 rcu_read_unlock();
6476
6477 return rb;
6478 }
6479
ring_buffer_put(struct perf_buffer * rb)6480 void ring_buffer_put(struct perf_buffer *rb)
6481 {
6482 if (!refcount_dec_and_test(&rb->refcount))
6483 return;
6484
6485 WARN_ON_ONCE(!list_empty(&rb->event_list));
6486
6487 call_rcu(&rb->rcu_head, rb_free_rcu);
6488 }
6489
perf_mmap_open(struct vm_area_struct * vma)6490 static void perf_mmap_open(struct vm_area_struct *vma)
6491 {
6492 struct perf_event *event = vma->vm_file->private_data;
6493
6494 atomic_inc(&event->mmap_count);
6495 atomic_inc(&event->rb->mmap_count);
6496
6497 if (vma->vm_pgoff)
6498 atomic_inc(&event->rb->aux_mmap_count);
6499
6500 if (event->pmu->event_mapped)
6501 event->pmu->event_mapped(event, vma->vm_mm);
6502 }
6503
6504 static void perf_pmu_output_stop(struct perf_event *event);
6505
6506 /*
6507 * A buffer can be mmap()ed multiple times; either directly through the same
6508 * event, or through other events by use of perf_event_set_output().
6509 *
6510 * In order to undo the VM accounting done by perf_mmap() we need to destroy
6511 * the buffer here, where we still have a VM context. This means we need
6512 * to detach all events redirecting to us.
6513 */
perf_mmap_close(struct vm_area_struct * vma)6514 static void perf_mmap_close(struct vm_area_struct *vma)
6515 {
6516 struct perf_event *event = vma->vm_file->private_data;
6517 struct perf_buffer *rb = ring_buffer_get(event);
6518 struct user_struct *mmap_user = rb->mmap_user;
6519 int mmap_locked = rb->mmap_locked;
6520 unsigned long size = perf_data_size(rb);
6521 bool detach_rest = false;
6522
6523 if (event->pmu->event_unmapped)
6524 event->pmu->event_unmapped(event, vma->vm_mm);
6525
6526 /*
6527 * The AUX buffer is strictly a sub-buffer, serialize using aux_mutex
6528 * to avoid complications.
6529 */
6530 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
6531 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &rb->aux_mutex)) {
6532 /*
6533 * Stop all AUX events that are writing to this buffer,
6534 * so that we can free its AUX pages and corresponding PMU
6535 * data. Note that after rb::aux_mmap_count dropped to zero,
6536 * they won't start any more (see perf_aux_output_begin()).
6537 */
6538 perf_pmu_output_stop(event);
6539
6540 /* now it's safe to free the pages */
6541 atomic_long_sub(rb->aux_nr_pages - rb->aux_mmap_locked, &mmap_user->locked_vm);
6542 atomic64_sub(rb->aux_mmap_locked, &vma->vm_mm->pinned_vm);
6543
6544 /* this has to be the last one */
6545 rb_free_aux(rb);
6546 WARN_ON_ONCE(refcount_read(&rb->aux_refcount));
6547
6548 mutex_unlock(&rb->aux_mutex);
6549 }
6550
6551 if (atomic_dec_and_test(&rb->mmap_count))
6552 detach_rest = true;
6553
6554 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
6555 goto out_put;
6556
6557 ring_buffer_attach(event, NULL);
6558 mutex_unlock(&event->mmap_mutex);
6559
6560 /* If there's still other mmap()s of this buffer, we're done. */
6561 if (!detach_rest)
6562 goto out_put;
6563
6564 /*
6565 * No other mmap()s, detach from all other events that might redirect
6566 * into the now unreachable buffer. Somewhat complicated by the
6567 * fact that rb::event_lock otherwise nests inside mmap_mutex.
6568 */
6569 again:
6570 rcu_read_lock();
6571 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
6572 if (!atomic_long_inc_not_zero(&event->refcount)) {
6573 /*
6574 * This event is en-route to free_event() which will
6575 * detach it and remove it from the list.
6576 */
6577 continue;
6578 }
6579 rcu_read_unlock();
6580
6581 mutex_lock(&event->mmap_mutex);
6582 /*
6583 * Check we didn't race with perf_event_set_output() which can
6584 * swizzle the rb from under us while we were waiting to
6585 * acquire mmap_mutex.
6586 *
6587 * If we find a different rb; ignore this event, a next
6588 * iteration will no longer find it on the list. We have to
6589 * still restart the iteration to make sure we're not now
6590 * iterating the wrong list.
6591 */
6592 if (event->rb == rb)
6593 ring_buffer_attach(event, NULL);
6594
6595 mutex_unlock(&event->mmap_mutex);
6596 put_event(event);
6597
6598 /*
6599 * Restart the iteration; either we're on the wrong list or
6600 * destroyed its integrity by doing a deletion.
6601 */
6602 goto again;
6603 }
6604 rcu_read_unlock();
6605
6606 /*
6607 * It could be there's still a few 0-ref events on the list; they'll
6608 * get cleaned up by free_event() -- they'll also still have their
6609 * ref on the rb and will free it whenever they are done with it.
6610 *
6611 * Aside from that, this buffer is 'fully' detached and unmapped,
6612 * undo the VM accounting.
6613 */
6614
6615 atomic_long_sub((size >> PAGE_SHIFT) + 1 - mmap_locked,
6616 &mmap_user->locked_vm);
6617 atomic64_sub(mmap_locked, &vma->vm_mm->pinned_vm);
6618 free_uid(mmap_user);
6619
6620 out_put:
6621 ring_buffer_put(rb); /* could be last */
6622 }
6623
perf_mmap_may_split(struct vm_area_struct * vma,unsigned long addr)6624 static int perf_mmap_may_split(struct vm_area_struct *vma, unsigned long addr)
6625 {
6626 /*
6627 * Forbid splitting perf mappings to prevent refcount leaks due to
6628 * the resulting non-matching offsets and sizes. See open()/close().
6629 */
6630 return -EINVAL;
6631 }
6632
6633 static const struct vm_operations_struct perf_mmap_vmops = {
6634 .open = perf_mmap_open,
6635 .close = perf_mmap_close, /* non mergeable */
6636 .fault = perf_mmap_fault,
6637 .page_mkwrite = perf_mmap_fault,
6638 .may_split = perf_mmap_may_split,
6639 };
6640
perf_mmap(struct file * file,struct vm_area_struct * vma)6641 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
6642 {
6643 struct perf_event *event = file->private_data;
6644 unsigned long user_locked, user_lock_limit;
6645 struct user_struct *user = current_user();
6646 struct mutex *aux_mutex = NULL;
6647 struct perf_buffer *rb = NULL;
6648 unsigned long locked, lock_limit;
6649 unsigned long vma_size;
6650 unsigned long nr_pages;
6651 long user_extra = 0, extra = 0;
6652 int ret = 0, flags = 0;
6653
6654 /*
6655 * Don't allow mmap() of inherited per-task counters. This would
6656 * create a performance issue due to all children writing to the
6657 * same rb.
6658 */
6659 if (event->cpu == -1 && event->attr.inherit)
6660 return -EINVAL;
6661
6662 if (!(vma->vm_flags & VM_SHARED))
6663 return -EINVAL;
6664
6665 ret = security_perf_event_read(event);
6666 if (ret)
6667 return ret;
6668
6669 vma_size = vma->vm_end - vma->vm_start;
6670
6671 if (vma->vm_pgoff == 0) {
6672 nr_pages = (vma_size / PAGE_SIZE) - (__PAGE_SIZE / PAGE_SIZE);
6673 } else {
6674 /*
6675 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
6676 * mapped, all subsequent mappings should have the same size
6677 * and offset. Must be above the normal perf buffer.
6678 */
6679 u64 aux_offset, aux_size;
6680
6681 if (!event->rb)
6682 return -EINVAL;
6683
6684 nr_pages = vma_size / PAGE_SIZE;
6685 if (nr_pages > INT_MAX)
6686 return -ENOMEM;
6687
6688 mutex_lock(&event->mmap_mutex);
6689 ret = -EINVAL;
6690
6691 rb = event->rb;
6692 if (!rb)
6693 goto aux_unlock;
6694
6695 aux_mutex = &rb->aux_mutex;
6696 mutex_lock(aux_mutex);
6697
6698 aux_offset = READ_ONCE(rb->user_page->aux_offset);
6699 aux_size = READ_ONCE(rb->user_page->aux_size);
6700
6701 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
6702 goto aux_unlock;
6703
6704 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
6705 goto aux_unlock;
6706
6707 /* already mapped with a different offset */
6708 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
6709 goto aux_unlock;
6710
6711 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
6712 goto aux_unlock;
6713
6714 /* already mapped with a different size */
6715 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
6716 goto aux_unlock;
6717
6718 if (!is_power_of_2(nr_pages))
6719 goto aux_unlock;
6720
6721 if (!atomic_inc_not_zero(&rb->mmap_count))
6722 goto aux_unlock;
6723
6724 if (rb_has_aux(rb)) {
6725 atomic_inc(&rb->aux_mmap_count);
6726 ret = 0;
6727 goto unlock;
6728 }
6729
6730 user_extra = nr_pages;
6731 goto accounting;
6732 }
6733
6734 /*
6735 * If we have rb pages ensure they're a power-of-two number, so we
6736 * can do bitmasks instead of modulo.
6737 */
6738 if (nr_pages != 0 && !is_power_of_2(nr_pages))
6739 return -EINVAL;
6740
6741 if (vma_size != PAGE_SIZE * ((__PAGE_SIZE / PAGE_SIZE) + nr_pages))
6742 return -EINVAL;
6743
6744 WARN_ON_ONCE(event->ctx->parent_ctx);
6745 again:
6746 mutex_lock(&event->mmap_mutex);
6747 if (event->rb) {
6748 if (data_page_nr(event->rb) != nr_pages) {
6749 ret = -EINVAL;
6750 goto unlock;
6751 }
6752
6753 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
6754 /*
6755 * Raced against perf_mmap_close(); remove the
6756 * event and try again.
6757 */
6758 ring_buffer_attach(event, NULL);
6759 mutex_unlock(&event->mmap_mutex);
6760 goto again;
6761 }
6762
6763 goto unlock;
6764 }
6765
6766 user_extra = nr_pages + 1;
6767
6768 accounting:
6769 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
6770
6771 /*
6772 * Increase the limit linearly with more CPUs:
6773 */
6774 user_lock_limit *= num_online_cpus();
6775
6776 user_locked = atomic_long_read(&user->locked_vm);
6777
6778 /*
6779 * sysctl_perf_event_mlock may have changed, so that
6780 * user->locked_vm > user_lock_limit
6781 */
6782 if (user_locked > user_lock_limit)
6783 user_locked = user_lock_limit;
6784 user_locked += user_extra;
6785
6786 if (user_locked > user_lock_limit) {
6787 /*
6788 * charge locked_vm until it hits user_lock_limit;
6789 * charge the rest from pinned_vm
6790 */
6791 extra = user_locked - user_lock_limit;
6792 user_extra -= extra;
6793 }
6794
6795 lock_limit = rlimit(RLIMIT_MEMLOCK);
6796 lock_limit >>= PAGE_SHIFT;
6797 locked = atomic64_read(&vma->vm_mm->pinned_vm) + extra;
6798
6799 if ((locked > lock_limit) && perf_is_paranoid() &&
6800 !capable(CAP_IPC_LOCK)) {
6801 ret = -EPERM;
6802 goto unlock;
6803 }
6804
6805 WARN_ON(!rb && event->rb);
6806
6807 if (vma->vm_flags & VM_WRITE)
6808 flags |= RING_BUFFER_WRITABLE;
6809
6810 if (!rb) {
6811 rb = rb_alloc(nr_pages,
6812 event->attr.watermark ? event->attr.wakeup_watermark : 0,
6813 event->cpu, flags);
6814
6815 if (!rb) {
6816 ret = -ENOMEM;
6817 goto unlock;
6818 }
6819
6820 atomic_set(&rb->mmap_count, 1);
6821 rb->mmap_user = get_current_user();
6822 rb->mmap_locked = extra;
6823
6824 ring_buffer_attach(event, rb);
6825
6826 perf_event_update_time(event);
6827 perf_event_init_userpage(event);
6828 perf_event_update_userpage(event);
6829 } else {
6830 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
6831 event->attr.aux_watermark, flags);
6832 if (!ret) {
6833 atomic_set(&rb->aux_mmap_count, 1);
6834 rb->aux_mmap_locked = extra;
6835 }
6836 }
6837
6838 unlock:
6839 if (!ret) {
6840 atomic_long_add(user_extra, &user->locked_vm);
6841 atomic64_add(extra, &vma->vm_mm->pinned_vm);
6842
6843 atomic_inc(&event->mmap_count);
6844 } else if (rb) {
6845 /* AUX allocation failed */
6846 atomic_dec(&rb->mmap_count);
6847 }
6848 aux_unlock:
6849 if (aux_mutex)
6850 mutex_unlock(aux_mutex);
6851 mutex_unlock(&event->mmap_mutex);
6852
6853 if (ret)
6854 return ret;
6855
6856 /*
6857 * Since pinned accounting is per vm we cannot allow fork() to copy our
6858 * vma.
6859 */
6860 vm_flags_set(vma, VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP);
6861 vma->vm_ops = &perf_mmap_vmops;
6862
6863 if (event->pmu->event_mapped)
6864 event->pmu->event_mapped(event, vma->vm_mm);
6865
6866 return ret;
6867 }
6868
perf_fasync(int fd,struct file * filp,int on)6869 static int perf_fasync(int fd, struct file *filp, int on)
6870 {
6871 struct inode *inode = file_inode(filp);
6872 struct perf_event *event = filp->private_data;
6873 int retval;
6874
6875 inode_lock(inode);
6876 retval = fasync_helper(fd, filp, on, &event->fasync);
6877 inode_unlock(inode);
6878
6879 if (retval < 0)
6880 return retval;
6881
6882 return 0;
6883 }
6884
6885 static const struct file_operations perf_fops = {
6886 .release = perf_release,
6887 .read = perf_read,
6888 .poll = perf_poll,
6889 .unlocked_ioctl = perf_ioctl,
6890 .compat_ioctl = perf_compat_ioctl,
6891 .mmap = perf_mmap,
6892 .fasync = perf_fasync,
6893 };
6894
6895 /*
6896 * Perf event wakeup
6897 *
6898 * If there's data, ensure we set the poll() state and publish everything
6899 * to user-space before waking everybody up.
6900 */
6901
perf_event_wakeup(struct perf_event * event)6902 void perf_event_wakeup(struct perf_event *event)
6903 {
6904 ring_buffer_wakeup(event);
6905
6906 if (event->pending_kill) {
6907 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
6908 event->pending_kill = 0;
6909 }
6910 }
6911
perf_sigtrap(struct perf_event * event)6912 static void perf_sigtrap(struct perf_event *event)
6913 {
6914 /*
6915 * We'd expect this to only occur if the irq_work is delayed and either
6916 * ctx->task or current has changed in the meantime. This can be the
6917 * case on architectures that do not implement arch_irq_work_raise().
6918 */
6919 if (WARN_ON_ONCE(event->ctx->task != current))
6920 return;
6921
6922 /*
6923 * Both perf_pending_task() and perf_pending_irq() can race with the
6924 * task exiting.
6925 */
6926 if (current->flags & PF_EXITING)
6927 return;
6928
6929 send_sig_perf((void __user *)event->pending_addr,
6930 event->orig_type, event->attr.sig_data);
6931 }
6932
6933 /*
6934 * Deliver the pending work in-event-context or follow the context.
6935 */
__perf_pending_disable(struct perf_event * event)6936 static void __perf_pending_disable(struct perf_event *event)
6937 {
6938 int cpu = READ_ONCE(event->oncpu);
6939
6940 /*
6941 * If the event isn't running; we done. event_sched_out() will have
6942 * taken care of things.
6943 */
6944 if (cpu < 0)
6945 return;
6946
6947 /*
6948 * Yay, we hit home and are in the context of the event.
6949 */
6950 if (cpu == smp_processor_id()) {
6951 if (event->pending_disable) {
6952 event->pending_disable = 0;
6953 perf_event_disable_local(event);
6954 }
6955 return;
6956 }
6957
6958 /*
6959 * CPU-A CPU-B
6960 *
6961 * perf_event_disable_inatomic()
6962 * @pending_disable = CPU-A;
6963 * irq_work_queue();
6964 *
6965 * sched-out
6966 * @pending_disable = -1;
6967 *
6968 * sched-in
6969 * perf_event_disable_inatomic()
6970 * @pending_disable = CPU-B;
6971 * irq_work_queue(); // FAILS
6972 *
6973 * irq_work_run()
6974 * perf_pending_disable()
6975 *
6976 * But the event runs on CPU-B and wants disabling there.
6977 */
6978 irq_work_queue_on(&event->pending_disable_irq, cpu);
6979 }
6980
perf_pending_disable(struct irq_work * entry)6981 static void perf_pending_disable(struct irq_work *entry)
6982 {
6983 struct perf_event *event = container_of(entry, struct perf_event, pending_disable_irq);
6984 int rctx;
6985
6986 /*
6987 * If we 'fail' here, that's OK, it means recursion is already disabled
6988 * and we won't recurse 'further'.
6989 */
6990 rctx = perf_swevent_get_recursion_context();
6991 __perf_pending_disable(event);
6992 if (rctx >= 0)
6993 perf_swevent_put_recursion_context(rctx);
6994 }
6995
perf_pending_irq(struct irq_work * entry)6996 static void perf_pending_irq(struct irq_work *entry)
6997 {
6998 struct perf_event *event = container_of(entry, struct perf_event, pending_irq);
6999 int rctx;
7000
7001 /*
7002 * If we 'fail' here, that's OK, it means recursion is already disabled
7003 * and we won't recurse 'further'.
7004 */
7005 rctx = perf_swevent_get_recursion_context();
7006
7007 /*
7008 * The wakeup isn't bound to the context of the event -- it can happen
7009 * irrespective of where the event is.
7010 */
7011 if (event->pending_wakeup) {
7012 event->pending_wakeup = 0;
7013 perf_event_wakeup(event);
7014 }
7015
7016 if (rctx >= 0)
7017 perf_swevent_put_recursion_context(rctx);
7018 }
7019
perf_pending_task(struct callback_head * head)7020 static void perf_pending_task(struct callback_head *head)
7021 {
7022 struct perf_event *event = container_of(head, struct perf_event, pending_task);
7023 int rctx;
7024
7025 /*
7026 * If we 'fail' here, that's OK, it means recursion is already disabled
7027 * and we won't recurse 'further'.
7028 */
7029 rctx = perf_swevent_get_recursion_context();
7030
7031 if (event->pending_work) {
7032 event->pending_work = 0;
7033 perf_sigtrap(event);
7034 local_dec(&event->ctx->nr_no_switch_fast);
7035 }
7036 put_event(event);
7037
7038 if (rctx >= 0)
7039 perf_swevent_put_recursion_context(rctx);
7040 }
7041
7042 #ifdef CONFIG_GUEST_PERF_EVENTS
7043 struct perf_guest_info_callbacks __rcu *perf_guest_cbs;
7044
perf_register_guest_info_callbacks(struct perf_guest_info_callbacks * cbs)7045 void perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
7046 {
7047 if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs)))
7048 return;
7049
7050 rcu_assign_pointer(perf_guest_cbs, cbs);
7051 }
7052 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
7053
perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks * cbs)7054 void perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
7055 {
7056 if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs) != cbs))
7057 return;
7058
7059 rcu_assign_pointer(perf_guest_cbs, NULL);
7060 synchronize_rcu();
7061 }
7062 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
7063 #endif
7064
7065 static void
perf_output_sample_regs(struct perf_output_handle * handle,struct pt_regs * regs,u64 mask)7066 perf_output_sample_regs(struct perf_output_handle *handle,
7067 struct pt_regs *regs, u64 mask)
7068 {
7069 int bit;
7070 DECLARE_BITMAP(_mask, 64);
7071
7072 bitmap_from_u64(_mask, mask);
7073 for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) {
7074 u64 val;
7075
7076 val = perf_reg_value(regs, bit);
7077 perf_output_put(handle, val);
7078 }
7079 }
7080
perf_sample_regs_user(struct perf_regs * regs_user,struct pt_regs * regs)7081 static void perf_sample_regs_user(struct perf_regs *regs_user,
7082 struct pt_regs *regs)
7083 {
7084 if (user_mode(regs)) {
7085 regs_user->abi = perf_reg_abi(current);
7086 regs_user->regs = regs;
7087 } else if (!(current->flags & PF_KTHREAD)) {
7088 perf_get_regs_user(regs_user, regs);
7089 } else {
7090 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
7091 regs_user->regs = NULL;
7092 }
7093 }
7094
perf_sample_regs_intr(struct perf_regs * regs_intr,struct pt_regs * regs)7095 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
7096 struct pt_regs *regs)
7097 {
7098 regs_intr->regs = regs;
7099 regs_intr->abi = perf_reg_abi(current);
7100 }
7101
7102
7103 /*
7104 * Get remaining task size from user stack pointer.
7105 *
7106 * It'd be better to take stack vma map and limit this more
7107 * precisely, but there's no way to get it safely under interrupt,
7108 * so using TASK_SIZE as limit.
7109 */
perf_ustack_task_size(struct pt_regs * regs)7110 static u64 perf_ustack_task_size(struct pt_regs *regs)
7111 {
7112 unsigned long addr = perf_user_stack_pointer(regs);
7113
7114 if (!addr || addr >= TASK_SIZE)
7115 return 0;
7116
7117 return TASK_SIZE - addr;
7118 }
7119
7120 static u16
perf_sample_ustack_size(u16 stack_size,u16 header_size,struct pt_regs * regs)7121 perf_sample_ustack_size(u16 stack_size, u16 header_size,
7122 struct pt_regs *regs)
7123 {
7124 u64 task_size;
7125
7126 /* No regs, no stack pointer, no dump. */
7127 if (!regs)
7128 return 0;
7129
7130 /* No mm, no stack, no dump. */
7131 if (!current->mm)
7132 return 0;
7133
7134 /*
7135 * Check if we fit in with the requested stack size into the:
7136 * - TASK_SIZE
7137 * If we don't, we limit the size to the TASK_SIZE.
7138 *
7139 * - remaining sample size
7140 * If we don't, we customize the stack size to
7141 * fit in to the remaining sample size.
7142 */
7143
7144 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
7145 stack_size = min(stack_size, (u16) task_size);
7146
7147 /* Current header size plus static size and dynamic size. */
7148 header_size += 2 * sizeof(u64);
7149
7150 /* Do we fit in with the current stack dump size? */
7151 if ((u16) (header_size + stack_size) < header_size) {
7152 /*
7153 * If we overflow the maximum size for the sample,
7154 * we customize the stack dump size to fit in.
7155 */
7156 stack_size = USHRT_MAX - header_size - sizeof(u64);
7157 stack_size = round_up(stack_size, sizeof(u64));
7158 }
7159
7160 return stack_size;
7161 }
7162
7163 static void
perf_output_sample_ustack(struct perf_output_handle * handle,u64 dump_size,struct pt_regs * regs)7164 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
7165 struct pt_regs *regs)
7166 {
7167 /* Case of a kernel thread, nothing to dump */
7168 if (!regs) {
7169 u64 size = 0;
7170 perf_output_put(handle, size);
7171 } else {
7172 unsigned long sp;
7173 unsigned int rem;
7174 u64 dyn_size;
7175
7176 /*
7177 * We dump:
7178 * static size
7179 * - the size requested by user or the best one we can fit
7180 * in to the sample max size
7181 * data
7182 * - user stack dump data
7183 * dynamic size
7184 * - the actual dumped size
7185 */
7186
7187 /* Static size. */
7188 perf_output_put(handle, dump_size);
7189
7190 /* Data. */
7191 sp = perf_user_stack_pointer(regs);
7192 rem = __output_copy_user(handle, (void *) sp, dump_size);
7193 dyn_size = dump_size - rem;
7194
7195 perf_output_skip(handle, rem);
7196
7197 /* Dynamic size. */
7198 perf_output_put(handle, dyn_size);
7199 }
7200 }
7201
perf_prepare_sample_aux(struct perf_event * event,struct perf_sample_data * data,size_t size)7202 static unsigned long perf_prepare_sample_aux(struct perf_event *event,
7203 struct perf_sample_data *data,
7204 size_t size)
7205 {
7206 struct perf_event *sampler = event->aux_event;
7207 struct perf_buffer *rb;
7208
7209 data->aux_size = 0;
7210
7211 if (!sampler)
7212 goto out;
7213
7214 if (WARN_ON_ONCE(READ_ONCE(sampler->state) != PERF_EVENT_STATE_ACTIVE))
7215 goto out;
7216
7217 if (WARN_ON_ONCE(READ_ONCE(sampler->oncpu) != smp_processor_id()))
7218 goto out;
7219
7220 rb = ring_buffer_get(sampler);
7221 if (!rb)
7222 goto out;
7223
7224 /*
7225 * If this is an NMI hit inside sampling code, don't take
7226 * the sample. See also perf_aux_sample_output().
7227 */
7228 if (READ_ONCE(rb->aux_in_sampling)) {
7229 data->aux_size = 0;
7230 } else {
7231 size = min_t(size_t, size, perf_aux_size(rb));
7232 data->aux_size = ALIGN(size, sizeof(u64));
7233 }
7234 ring_buffer_put(rb);
7235
7236 out:
7237 return data->aux_size;
7238 }
7239
perf_pmu_snapshot_aux(struct perf_buffer * rb,struct perf_event * event,struct perf_output_handle * handle,unsigned long size)7240 static long perf_pmu_snapshot_aux(struct perf_buffer *rb,
7241 struct perf_event *event,
7242 struct perf_output_handle *handle,
7243 unsigned long size)
7244 {
7245 unsigned long flags;
7246 long ret;
7247
7248 /*
7249 * Normal ->start()/->stop() callbacks run in IRQ mode in scheduler
7250 * paths. If we start calling them in NMI context, they may race with
7251 * the IRQ ones, that is, for example, re-starting an event that's just
7252 * been stopped, which is why we're using a separate callback that
7253 * doesn't change the event state.
7254 *
7255 * IRQs need to be disabled to prevent IPIs from racing with us.
7256 */
7257 local_irq_save(flags);
7258 /*
7259 * Guard against NMI hits inside the critical section;
7260 * see also perf_prepare_sample_aux().
7261 */
7262 WRITE_ONCE(rb->aux_in_sampling, 1);
7263 barrier();
7264
7265 ret = event->pmu->snapshot_aux(event, handle, size);
7266
7267 barrier();
7268 WRITE_ONCE(rb->aux_in_sampling, 0);
7269 local_irq_restore(flags);
7270
7271 return ret;
7272 }
7273
perf_aux_sample_output(struct perf_event * event,struct perf_output_handle * handle,struct perf_sample_data * data)7274 static void perf_aux_sample_output(struct perf_event *event,
7275 struct perf_output_handle *handle,
7276 struct perf_sample_data *data)
7277 {
7278 struct perf_event *sampler = event->aux_event;
7279 struct perf_buffer *rb;
7280 unsigned long pad;
7281 long size;
7282
7283 if (WARN_ON_ONCE(!sampler || !data->aux_size))
7284 return;
7285
7286 rb = ring_buffer_get(sampler);
7287 if (!rb)
7288 return;
7289
7290 size = perf_pmu_snapshot_aux(rb, sampler, handle, data->aux_size);
7291
7292 /*
7293 * An error here means that perf_output_copy() failed (returned a
7294 * non-zero surplus that it didn't copy), which in its current
7295 * enlightened implementation is not possible. If that changes, we'd
7296 * like to know.
7297 */
7298 if (WARN_ON_ONCE(size < 0))
7299 goto out_put;
7300
7301 /*
7302 * The pad comes from ALIGN()ing data->aux_size up to u64 in
7303 * perf_prepare_sample_aux(), so should not be more than that.
7304 */
7305 pad = data->aux_size - size;
7306 if (WARN_ON_ONCE(pad >= sizeof(u64)))
7307 pad = 8;
7308
7309 if (pad) {
7310 u64 zero = 0;
7311 perf_output_copy(handle, &zero, pad);
7312 }
7313
7314 out_put:
7315 ring_buffer_put(rb);
7316 }
7317
7318 /*
7319 * A set of common sample data types saved even for non-sample records
7320 * when event->attr.sample_id_all is set.
7321 */
7322 #define PERF_SAMPLE_ID_ALL (PERF_SAMPLE_TID | PERF_SAMPLE_TIME | \
7323 PERF_SAMPLE_ID | PERF_SAMPLE_STREAM_ID | \
7324 PERF_SAMPLE_CPU | PERF_SAMPLE_IDENTIFIER)
7325
__perf_event_header__init_id(struct perf_sample_data * data,struct perf_event * event,u64 sample_type)7326 static void __perf_event_header__init_id(struct perf_sample_data *data,
7327 struct perf_event *event,
7328 u64 sample_type)
7329 {
7330 data->type = event->attr.sample_type;
7331 data->sample_flags |= data->type & PERF_SAMPLE_ID_ALL;
7332
7333 if (sample_type & PERF_SAMPLE_TID) {
7334 /* namespace issues */
7335 data->tid_entry.pid = perf_event_pid(event, current);
7336 data->tid_entry.tid = perf_event_tid(event, current);
7337 }
7338
7339 if (sample_type & PERF_SAMPLE_TIME)
7340 data->time = perf_event_clock(event);
7341
7342 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
7343 data->id = primary_event_id(event);
7344
7345 if (sample_type & PERF_SAMPLE_STREAM_ID)
7346 data->stream_id = event->id;
7347
7348 if (sample_type & PERF_SAMPLE_CPU) {
7349 data->cpu_entry.cpu = raw_smp_processor_id();
7350 data->cpu_entry.reserved = 0;
7351 }
7352 }
7353
perf_event_header__init_id(struct perf_event_header * header,struct perf_sample_data * data,struct perf_event * event)7354 void perf_event_header__init_id(struct perf_event_header *header,
7355 struct perf_sample_data *data,
7356 struct perf_event *event)
7357 {
7358 if (event->attr.sample_id_all) {
7359 header->size += event->id_header_size;
7360 __perf_event_header__init_id(data, event, event->attr.sample_type);
7361 }
7362 }
7363
__perf_event__output_id_sample(struct perf_output_handle * handle,struct perf_sample_data * data)7364 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
7365 struct perf_sample_data *data)
7366 {
7367 u64 sample_type = data->type;
7368
7369 if (sample_type & PERF_SAMPLE_TID)
7370 perf_output_put(handle, data->tid_entry);
7371
7372 if (sample_type & PERF_SAMPLE_TIME)
7373 perf_output_put(handle, data->time);
7374
7375 if (sample_type & PERF_SAMPLE_ID)
7376 perf_output_put(handle, data->id);
7377
7378 if (sample_type & PERF_SAMPLE_STREAM_ID)
7379 perf_output_put(handle, data->stream_id);
7380
7381 if (sample_type & PERF_SAMPLE_CPU)
7382 perf_output_put(handle, data->cpu_entry);
7383
7384 if (sample_type & PERF_SAMPLE_IDENTIFIER)
7385 perf_output_put(handle, data->id);
7386 }
7387
perf_event__output_id_sample(struct perf_event * event,struct perf_output_handle * handle,struct perf_sample_data * sample)7388 void perf_event__output_id_sample(struct perf_event *event,
7389 struct perf_output_handle *handle,
7390 struct perf_sample_data *sample)
7391 {
7392 if (event->attr.sample_id_all)
7393 __perf_event__output_id_sample(handle, sample);
7394 }
7395
perf_output_read_one(struct perf_output_handle * handle,struct perf_event * event,u64 enabled,u64 running)7396 static void perf_output_read_one(struct perf_output_handle *handle,
7397 struct perf_event *event,
7398 u64 enabled, u64 running)
7399 {
7400 u64 read_format = event->attr.read_format;
7401 u64 values[5];
7402 int n = 0;
7403
7404 values[n++] = perf_event_count(event, has_inherit_and_sample_read(&event->attr));
7405 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
7406 values[n++] = enabled +
7407 atomic64_read(&event->child_total_time_enabled);
7408 }
7409 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
7410 values[n++] = running +
7411 atomic64_read(&event->child_total_time_running);
7412 }
7413 if (read_format & PERF_FORMAT_ID)
7414 values[n++] = primary_event_id(event);
7415 if (read_format & PERF_FORMAT_LOST)
7416 values[n++] = atomic64_read(&event->lost_samples);
7417
7418 __output_copy(handle, values, n * sizeof(u64));
7419 }
7420
perf_output_read_group(struct perf_output_handle * handle,struct perf_event * event,u64 enabled,u64 running)7421 static void perf_output_read_group(struct perf_output_handle *handle,
7422 struct perf_event *event,
7423 u64 enabled, u64 running)
7424 {
7425 struct perf_event *leader = event->group_leader, *sub;
7426 u64 read_format = event->attr.read_format;
7427 unsigned long flags;
7428 u64 values[6];
7429 int n = 0;
7430 bool self = has_inherit_and_sample_read(&event->attr);
7431
7432 /*
7433 * Disabling interrupts avoids all counter scheduling
7434 * (context switches, timer based rotation and IPIs).
7435 */
7436 local_irq_save(flags);
7437
7438 values[n++] = 1 + leader->nr_siblings;
7439
7440 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
7441 values[n++] = enabled;
7442
7443 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
7444 values[n++] = running;
7445
7446 if ((leader != event) &&
7447 (leader->state == PERF_EVENT_STATE_ACTIVE))
7448 leader->pmu->read(leader);
7449
7450 values[n++] = perf_event_count(leader, self);
7451 if (read_format & PERF_FORMAT_ID)
7452 values[n++] = primary_event_id(leader);
7453 if (read_format & PERF_FORMAT_LOST)
7454 values[n++] = atomic64_read(&leader->lost_samples);
7455
7456 __output_copy(handle, values, n * sizeof(u64));
7457
7458 for_each_sibling_event(sub, leader) {
7459 n = 0;
7460
7461 if ((sub != event) &&
7462 (sub->state == PERF_EVENT_STATE_ACTIVE))
7463 sub->pmu->read(sub);
7464
7465 values[n++] = perf_event_count(sub, self);
7466 if (read_format & PERF_FORMAT_ID)
7467 values[n++] = primary_event_id(sub);
7468 if (read_format & PERF_FORMAT_LOST)
7469 values[n++] = atomic64_read(&sub->lost_samples);
7470
7471 __output_copy(handle, values, n * sizeof(u64));
7472 }
7473
7474 local_irq_restore(flags);
7475 }
7476
7477 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
7478 PERF_FORMAT_TOTAL_TIME_RUNNING)
7479
7480 /*
7481 * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
7482 *
7483 * The problem is that its both hard and excessively expensive to iterate the
7484 * child list, not to mention that its impossible to IPI the children running
7485 * on another CPU, from interrupt/NMI context.
7486 *
7487 * Instead the combination of PERF_SAMPLE_READ and inherit will track per-thread
7488 * counts rather than attempting to accumulate some value across all children on
7489 * all cores.
7490 */
perf_output_read(struct perf_output_handle * handle,struct perf_event * event)7491 static void perf_output_read(struct perf_output_handle *handle,
7492 struct perf_event *event)
7493 {
7494 u64 enabled = 0, running = 0, now;
7495 u64 read_format = event->attr.read_format;
7496
7497 /*
7498 * compute total_time_enabled, total_time_running
7499 * based on snapshot values taken when the event
7500 * was last scheduled in.
7501 *
7502 * we cannot simply called update_context_time()
7503 * because of locking issue as we are called in
7504 * NMI context
7505 */
7506 if (read_format & PERF_FORMAT_TOTAL_TIMES)
7507 calc_timer_values(event, &now, &enabled, &running);
7508
7509 if (event->attr.read_format & PERF_FORMAT_GROUP)
7510 perf_output_read_group(handle, event, enabled, running);
7511 else
7512 perf_output_read_one(handle, event, enabled, running);
7513 }
7514
perf_output_sample(struct perf_output_handle * handle,struct perf_event_header * header,struct perf_sample_data * data,struct perf_event * event)7515 void perf_output_sample(struct perf_output_handle *handle,
7516 struct perf_event_header *header,
7517 struct perf_sample_data *data,
7518 struct perf_event *event)
7519 {
7520 u64 sample_type = data->type;
7521
7522 perf_output_put(handle, *header);
7523
7524 if (sample_type & PERF_SAMPLE_IDENTIFIER)
7525 perf_output_put(handle, data->id);
7526
7527 if (sample_type & PERF_SAMPLE_IP)
7528 perf_output_put(handle, data->ip);
7529
7530 if (sample_type & PERF_SAMPLE_TID)
7531 perf_output_put(handle, data->tid_entry);
7532
7533 if (sample_type & PERF_SAMPLE_TIME)
7534 perf_output_put(handle, data->time);
7535
7536 if (sample_type & PERF_SAMPLE_ADDR)
7537 perf_output_put(handle, data->addr);
7538
7539 if (sample_type & PERF_SAMPLE_ID)
7540 perf_output_put(handle, data->id);
7541
7542 if (sample_type & PERF_SAMPLE_STREAM_ID)
7543 perf_output_put(handle, data->stream_id);
7544
7545 if (sample_type & PERF_SAMPLE_CPU)
7546 perf_output_put(handle, data->cpu_entry);
7547
7548 if (sample_type & PERF_SAMPLE_PERIOD)
7549 perf_output_put(handle, data->period);
7550
7551 if (sample_type & PERF_SAMPLE_READ)
7552 perf_output_read(handle, event);
7553
7554 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
7555 int size = 1;
7556
7557 size += data->callchain->nr;
7558 size *= sizeof(u64);
7559 __output_copy(handle, data->callchain, size);
7560 }
7561
7562 if (sample_type & PERF_SAMPLE_RAW) {
7563 struct perf_raw_record *raw = data->raw;
7564
7565 if (raw) {
7566 struct perf_raw_frag *frag = &raw->frag;
7567
7568 perf_output_put(handle, raw->size);
7569 do {
7570 if (frag->copy) {
7571 __output_custom(handle, frag->copy,
7572 frag->data, frag->size);
7573 } else {
7574 __output_copy(handle, frag->data,
7575 frag->size);
7576 }
7577 if (perf_raw_frag_last(frag))
7578 break;
7579 frag = frag->next;
7580 } while (1);
7581 if (frag->pad)
7582 __output_skip(handle, NULL, frag->pad);
7583 } else {
7584 struct {
7585 u32 size;
7586 u32 data;
7587 } raw = {
7588 .size = sizeof(u32),
7589 .data = 0,
7590 };
7591 perf_output_put(handle, raw);
7592 }
7593 }
7594
7595 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
7596 if (data->br_stack) {
7597 size_t size;
7598
7599 size = data->br_stack->nr
7600 * sizeof(struct perf_branch_entry);
7601
7602 perf_output_put(handle, data->br_stack->nr);
7603 if (branch_sample_hw_index(event))
7604 perf_output_put(handle, data->br_stack->hw_idx);
7605 perf_output_copy(handle, data->br_stack->entries, size);
7606 /*
7607 * Add the extension space which is appended
7608 * right after the struct perf_branch_stack.
7609 */
7610 if (data->br_stack_cntr) {
7611 size = data->br_stack->nr * sizeof(u64);
7612 perf_output_copy(handle, data->br_stack_cntr, size);
7613 }
7614 } else {
7615 /*
7616 * we always store at least the value of nr
7617 */
7618 u64 nr = 0;
7619 perf_output_put(handle, nr);
7620 }
7621 }
7622
7623 if (sample_type & PERF_SAMPLE_REGS_USER) {
7624 u64 abi = data->regs_user.abi;
7625
7626 /*
7627 * If there are no regs to dump, notice it through
7628 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
7629 */
7630 perf_output_put(handle, abi);
7631
7632 if (abi) {
7633 u64 mask = event->attr.sample_regs_user;
7634 perf_output_sample_regs(handle,
7635 data->regs_user.regs,
7636 mask);
7637 }
7638 }
7639
7640 if (sample_type & PERF_SAMPLE_STACK_USER) {
7641 perf_output_sample_ustack(handle,
7642 data->stack_user_size,
7643 data->regs_user.regs);
7644 }
7645
7646 if (sample_type & PERF_SAMPLE_WEIGHT_TYPE)
7647 perf_output_put(handle, data->weight.full);
7648
7649 if (sample_type & PERF_SAMPLE_DATA_SRC)
7650 perf_output_put(handle, data->data_src.val);
7651
7652 if (sample_type & PERF_SAMPLE_TRANSACTION)
7653 perf_output_put(handle, data->txn);
7654
7655 if (sample_type & PERF_SAMPLE_REGS_INTR) {
7656 u64 abi = data->regs_intr.abi;
7657 /*
7658 * If there are no regs to dump, notice it through
7659 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
7660 */
7661 perf_output_put(handle, abi);
7662
7663 if (abi) {
7664 u64 mask = event->attr.sample_regs_intr;
7665
7666 perf_output_sample_regs(handle,
7667 data->regs_intr.regs,
7668 mask);
7669 }
7670 }
7671
7672 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
7673 perf_output_put(handle, data->phys_addr);
7674
7675 if (sample_type & PERF_SAMPLE_CGROUP)
7676 perf_output_put(handle, data->cgroup);
7677
7678 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
7679 perf_output_put(handle, data->data_page_size);
7680
7681 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
7682 perf_output_put(handle, data->code_page_size);
7683
7684 if (sample_type & PERF_SAMPLE_AUX) {
7685 perf_output_put(handle, data->aux_size);
7686
7687 if (data->aux_size)
7688 perf_aux_sample_output(event, handle, data);
7689 }
7690
7691 if (!event->attr.watermark) {
7692 int wakeup_events = event->attr.wakeup_events;
7693
7694 if (wakeup_events) {
7695 struct perf_buffer *rb = handle->rb;
7696 int events = local_inc_return(&rb->events);
7697
7698 if (events >= wakeup_events) {
7699 local_sub(wakeup_events, &rb->events);
7700 local_inc(&rb->wakeup);
7701 }
7702 }
7703 }
7704 }
7705
perf_virt_to_phys(u64 virt)7706 static u64 perf_virt_to_phys(u64 virt)
7707 {
7708 u64 phys_addr = 0;
7709
7710 if (!virt)
7711 return 0;
7712
7713 if (virt >= TASK_SIZE) {
7714 /* If it's vmalloc()d memory, leave phys_addr as 0 */
7715 if (virt_addr_valid((void *)(uintptr_t)virt) &&
7716 !(virt >= VMALLOC_START && virt < VMALLOC_END))
7717 phys_addr = (u64)virt_to_phys((void *)(uintptr_t)virt);
7718 } else {
7719 /*
7720 * Walking the pages tables for user address.
7721 * Interrupts are disabled, so it prevents any tear down
7722 * of the page tables.
7723 * Try IRQ-safe get_user_page_fast_only first.
7724 * If failed, leave phys_addr as 0.
7725 */
7726 if (current->mm != NULL) {
7727 struct page *p;
7728
7729 pagefault_disable();
7730 if (get_user_page_fast_only(virt, 0, &p)) {
7731 phys_addr = page_to_phys(p) + virt % PAGE_SIZE;
7732 put_page(p);
7733 }
7734 pagefault_enable();
7735 }
7736 }
7737
7738 return phys_addr;
7739 }
7740
7741 /*
7742 * Return the pagetable size of a given virtual address.
7743 */
perf_get_pgtable_size(struct mm_struct * mm,unsigned long addr)7744 static u64 perf_get_pgtable_size(struct mm_struct *mm, unsigned long addr)
7745 {
7746 u64 size = 0;
7747
7748 #ifdef CONFIG_HAVE_GUP_FAST
7749 pgd_t *pgdp, pgd;
7750 p4d_t *p4dp, p4d;
7751 pud_t *pudp, pud;
7752 pmd_t *pmdp, pmd;
7753 pte_t *ptep, pte;
7754
7755 pgdp = pgd_offset(mm, addr);
7756 pgd = READ_ONCE(*pgdp);
7757 if (pgd_none(pgd))
7758 return 0;
7759
7760 if (pgd_leaf(pgd))
7761 return pgd_leaf_size(pgd);
7762
7763 p4dp = p4d_offset_lockless(pgdp, pgd, addr);
7764 p4d = READ_ONCE(*p4dp);
7765 if (!p4d_present(p4d))
7766 return 0;
7767
7768 if (p4d_leaf(p4d))
7769 return p4d_leaf_size(p4d);
7770
7771 pudp = pud_offset_lockless(p4dp, p4d, addr);
7772 pud = READ_ONCE(*pudp);
7773 if (!pud_present(pud))
7774 return 0;
7775
7776 if (pud_leaf(pud))
7777 return pud_leaf_size(pud);
7778
7779 pmdp = pmd_offset_lockless(pudp, pud, addr);
7780 again:
7781 pmd = pmdp_get_lockless(pmdp);
7782 if (!pmd_present(pmd))
7783 return 0;
7784
7785 if (pmd_leaf(pmd))
7786 return pmd_leaf_size(pmd);
7787
7788 ptep = pte_offset_map(&pmd, addr);
7789 if (!ptep)
7790 goto again;
7791
7792 pte = ptep_get_lockless(ptep);
7793 if (pte_present(pte))
7794 size = __pte_leaf_size(pmd, pte);
7795 pte_unmap(ptep);
7796 #endif /* CONFIG_HAVE_GUP_FAST */
7797
7798 return size;
7799 }
7800
perf_get_page_size(unsigned long addr)7801 static u64 perf_get_page_size(unsigned long addr)
7802 {
7803 struct mm_struct *mm;
7804 unsigned long flags;
7805 u64 size;
7806
7807 if (!addr)
7808 return 0;
7809
7810 /*
7811 * Software page-table walkers must disable IRQs,
7812 * which prevents any tear down of the page tables.
7813 */
7814 local_irq_save(flags);
7815
7816 mm = current->mm;
7817 if (!mm) {
7818 /*
7819 * For kernel threads and the like, use init_mm so that
7820 * we can find kernel memory.
7821 */
7822 mm = &init_mm;
7823 }
7824
7825 size = perf_get_pgtable_size(mm, addr);
7826
7827 local_irq_restore(flags);
7828
7829 return size;
7830 }
7831
7832 static struct perf_callchain_entry __empty_callchain = { .nr = 0, };
7833
7834 struct perf_callchain_entry *
perf_callchain(struct perf_event * event,struct pt_regs * regs)7835 perf_callchain(struct perf_event *event, struct pt_regs *regs)
7836 {
7837 bool kernel = !event->attr.exclude_callchain_kernel;
7838 bool user = !event->attr.exclude_callchain_user;
7839 /* Disallow cross-task user callchains. */
7840 bool crosstask = event->ctx->task && event->ctx->task != current;
7841 const u32 max_stack = event->attr.sample_max_stack;
7842 struct perf_callchain_entry *callchain;
7843
7844 if (!current->mm)
7845 user = false;
7846
7847 if (!kernel && !user)
7848 return &__empty_callchain;
7849
7850 callchain = get_perf_callchain(regs, 0, kernel, user,
7851 max_stack, crosstask, true);
7852 return callchain ?: &__empty_callchain;
7853 }
7854
__cond_set(u64 flags,u64 s,u64 d)7855 static __always_inline u64 __cond_set(u64 flags, u64 s, u64 d)
7856 {
7857 return d * !!(flags & s);
7858 }
7859
perf_prepare_sample(struct perf_sample_data * data,struct perf_event * event,struct pt_regs * regs)7860 void perf_prepare_sample(struct perf_sample_data *data,
7861 struct perf_event *event,
7862 struct pt_regs *regs)
7863 {
7864 u64 sample_type = event->attr.sample_type;
7865 u64 filtered_sample_type;
7866
7867 /*
7868 * Add the sample flags that are dependent to others. And clear the
7869 * sample flags that have already been done by the PMU driver.
7870 */
7871 filtered_sample_type = sample_type;
7872 filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_CODE_PAGE_SIZE,
7873 PERF_SAMPLE_IP);
7874 filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_DATA_PAGE_SIZE |
7875 PERF_SAMPLE_PHYS_ADDR, PERF_SAMPLE_ADDR);
7876 filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_STACK_USER,
7877 PERF_SAMPLE_REGS_USER);
7878 filtered_sample_type &= ~data->sample_flags;
7879
7880 if (filtered_sample_type == 0) {
7881 /* Make sure it has the correct data->type for output */
7882 data->type = event->attr.sample_type;
7883 return;
7884 }
7885
7886 __perf_event_header__init_id(data, event, filtered_sample_type);
7887
7888 if (filtered_sample_type & PERF_SAMPLE_IP) {
7889 data->ip = perf_instruction_pointer(regs);
7890 data->sample_flags |= PERF_SAMPLE_IP;
7891 }
7892
7893 if (filtered_sample_type & PERF_SAMPLE_CALLCHAIN)
7894 perf_sample_save_callchain(data, event, regs);
7895
7896 if (filtered_sample_type & PERF_SAMPLE_RAW) {
7897 data->raw = NULL;
7898 data->dyn_size += sizeof(u64);
7899 data->sample_flags |= PERF_SAMPLE_RAW;
7900 }
7901
7902 if (filtered_sample_type & PERF_SAMPLE_BRANCH_STACK) {
7903 data->br_stack = NULL;
7904 data->dyn_size += sizeof(u64);
7905 data->sample_flags |= PERF_SAMPLE_BRANCH_STACK;
7906 }
7907
7908 if (filtered_sample_type & PERF_SAMPLE_REGS_USER)
7909 perf_sample_regs_user(&data->regs_user, regs);
7910
7911 /*
7912 * It cannot use the filtered_sample_type here as REGS_USER can be set
7913 * by STACK_USER (using __cond_set() above) and we don't want to update
7914 * the dyn_size if it's not requested by users.
7915 */
7916 if ((sample_type & ~data->sample_flags) & PERF_SAMPLE_REGS_USER) {
7917 /* regs dump ABI info */
7918 int size = sizeof(u64);
7919
7920 if (data->regs_user.regs) {
7921 u64 mask = event->attr.sample_regs_user;
7922 size += hweight64(mask) * sizeof(u64);
7923 }
7924
7925 data->dyn_size += size;
7926 data->sample_flags |= PERF_SAMPLE_REGS_USER;
7927 }
7928
7929 if (filtered_sample_type & PERF_SAMPLE_STACK_USER) {
7930 /*
7931 * Either we need PERF_SAMPLE_STACK_USER bit to be always
7932 * processed as the last one or have additional check added
7933 * in case new sample type is added, because we could eat
7934 * up the rest of the sample size.
7935 */
7936 u16 stack_size = event->attr.sample_stack_user;
7937 u16 header_size = perf_sample_data_size(data, event);
7938 u16 size = sizeof(u64);
7939
7940 stack_size = perf_sample_ustack_size(stack_size, header_size,
7941 data->regs_user.regs);
7942
7943 /*
7944 * If there is something to dump, add space for the dump
7945 * itself and for the field that tells the dynamic size,
7946 * which is how many have been actually dumped.
7947 */
7948 if (stack_size)
7949 size += sizeof(u64) + stack_size;
7950
7951 data->stack_user_size = stack_size;
7952 data->dyn_size += size;
7953 data->sample_flags |= PERF_SAMPLE_STACK_USER;
7954 }
7955
7956 if (filtered_sample_type & PERF_SAMPLE_WEIGHT_TYPE) {
7957 data->weight.full = 0;
7958 data->sample_flags |= PERF_SAMPLE_WEIGHT_TYPE;
7959 }
7960
7961 if (filtered_sample_type & PERF_SAMPLE_DATA_SRC) {
7962 data->data_src.val = PERF_MEM_NA;
7963 data->sample_flags |= PERF_SAMPLE_DATA_SRC;
7964 }
7965
7966 if (filtered_sample_type & PERF_SAMPLE_TRANSACTION) {
7967 data->txn = 0;
7968 data->sample_flags |= PERF_SAMPLE_TRANSACTION;
7969 }
7970
7971 if (filtered_sample_type & PERF_SAMPLE_ADDR) {
7972 data->addr = 0;
7973 data->sample_flags |= PERF_SAMPLE_ADDR;
7974 }
7975
7976 if (filtered_sample_type & PERF_SAMPLE_REGS_INTR) {
7977 /* regs dump ABI info */
7978 int size = sizeof(u64);
7979
7980 perf_sample_regs_intr(&data->regs_intr, regs);
7981
7982 if (data->regs_intr.regs) {
7983 u64 mask = event->attr.sample_regs_intr;
7984
7985 size += hweight64(mask) * sizeof(u64);
7986 }
7987
7988 data->dyn_size += size;
7989 data->sample_flags |= PERF_SAMPLE_REGS_INTR;
7990 }
7991
7992 if (filtered_sample_type & PERF_SAMPLE_PHYS_ADDR) {
7993 data->phys_addr = perf_virt_to_phys(data->addr);
7994 data->sample_flags |= PERF_SAMPLE_PHYS_ADDR;
7995 }
7996
7997 #ifdef CONFIG_CGROUP_PERF
7998 if (filtered_sample_type & PERF_SAMPLE_CGROUP) {
7999 struct cgroup *cgrp;
8000
8001 /* protected by RCU */
8002 cgrp = task_css_check(current, perf_event_cgrp_id, 1)->cgroup;
8003 data->cgroup = cgroup_id(cgrp);
8004 data->sample_flags |= PERF_SAMPLE_CGROUP;
8005 }
8006 #endif
8007
8008 /*
8009 * PERF_DATA_PAGE_SIZE requires PERF_SAMPLE_ADDR. If the user doesn't
8010 * require PERF_SAMPLE_ADDR, kernel implicitly retrieve the data->addr,
8011 * but the value will not dump to the userspace.
8012 */
8013 if (filtered_sample_type & PERF_SAMPLE_DATA_PAGE_SIZE) {
8014 data->data_page_size = perf_get_page_size(data->addr);
8015 data->sample_flags |= PERF_SAMPLE_DATA_PAGE_SIZE;
8016 }
8017
8018 if (filtered_sample_type & PERF_SAMPLE_CODE_PAGE_SIZE) {
8019 data->code_page_size = perf_get_page_size(data->ip);
8020 data->sample_flags |= PERF_SAMPLE_CODE_PAGE_SIZE;
8021 }
8022
8023 if (filtered_sample_type & PERF_SAMPLE_AUX) {
8024 u64 size;
8025 u16 header_size = perf_sample_data_size(data, event);
8026
8027 header_size += sizeof(u64); /* size */
8028
8029 /*
8030 * Given the 16bit nature of header::size, an AUX sample can
8031 * easily overflow it, what with all the preceding sample bits.
8032 * Make sure this doesn't happen by using up to U16_MAX bytes
8033 * per sample in total (rounded down to 8 byte boundary).
8034 */
8035 size = min_t(size_t, U16_MAX - header_size,
8036 event->attr.aux_sample_size);
8037 size = rounddown(size, 8);
8038 size = perf_prepare_sample_aux(event, data, size);
8039
8040 WARN_ON_ONCE(size + header_size > U16_MAX);
8041 data->dyn_size += size + sizeof(u64); /* size above */
8042 data->sample_flags |= PERF_SAMPLE_AUX;
8043 }
8044 }
8045
perf_prepare_header(struct perf_event_header * header,struct perf_sample_data * data,struct perf_event * event,struct pt_regs * regs)8046 void perf_prepare_header(struct perf_event_header *header,
8047 struct perf_sample_data *data,
8048 struct perf_event *event,
8049 struct pt_regs *regs)
8050 {
8051 header->type = PERF_RECORD_SAMPLE;
8052 header->size = perf_sample_data_size(data, event);
8053 header->misc = perf_misc_flags(regs);
8054
8055 /*
8056 * If you're adding more sample types here, you likely need to do
8057 * something about the overflowing header::size, like repurpose the
8058 * lowest 3 bits of size, which should be always zero at the moment.
8059 * This raises a more important question, do we really need 512k sized
8060 * samples and why, so good argumentation is in order for whatever you
8061 * do here next.
8062 */
8063 WARN_ON_ONCE(header->size & 7);
8064 }
8065
__perf_event_aux_pause(struct perf_event * event,bool pause)8066 static void __perf_event_aux_pause(struct perf_event *event, bool pause)
8067 {
8068 if (pause) {
8069 if (!event->hw.aux_paused) {
8070 event->hw.aux_paused = 1;
8071 event->pmu->stop(event, PERF_EF_PAUSE);
8072 }
8073 } else {
8074 if (event->hw.aux_paused) {
8075 event->hw.aux_paused = 0;
8076 event->pmu->start(event, PERF_EF_RESUME);
8077 }
8078 }
8079 }
8080
perf_event_aux_pause(struct perf_event * event,bool pause)8081 static void perf_event_aux_pause(struct perf_event *event, bool pause)
8082 {
8083 struct perf_buffer *rb;
8084
8085 if (WARN_ON_ONCE(!event))
8086 return;
8087
8088 rb = ring_buffer_get(event);
8089 if (!rb)
8090 return;
8091
8092 scoped_guard (irqsave) {
8093 /*
8094 * Guard against self-recursion here. Another event could trip
8095 * this same from NMI context.
8096 */
8097 if (READ_ONCE(rb->aux_in_pause_resume))
8098 break;
8099
8100 WRITE_ONCE(rb->aux_in_pause_resume, 1);
8101 barrier();
8102 __perf_event_aux_pause(event, pause);
8103 barrier();
8104 WRITE_ONCE(rb->aux_in_pause_resume, 0);
8105 }
8106 ring_buffer_put(rb);
8107 }
8108
8109 static __always_inline int
__perf_event_output(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs,int (* output_begin)(struct perf_output_handle *,struct perf_sample_data *,struct perf_event *,unsigned int))8110 __perf_event_output(struct perf_event *event,
8111 struct perf_sample_data *data,
8112 struct pt_regs *regs,
8113 int (*output_begin)(struct perf_output_handle *,
8114 struct perf_sample_data *,
8115 struct perf_event *,
8116 unsigned int))
8117 {
8118 struct perf_output_handle handle;
8119 struct perf_event_header header;
8120 int err;
8121
8122 /* protect the callchain buffers */
8123 rcu_read_lock();
8124
8125 perf_prepare_sample(data, event, regs);
8126 perf_prepare_header(&header, data, event, regs);
8127
8128 err = output_begin(&handle, data, event, header.size);
8129 if (err)
8130 goto exit;
8131
8132 perf_output_sample(&handle, &header, data, event);
8133
8134 perf_output_end(&handle);
8135
8136 exit:
8137 rcu_read_unlock();
8138 return err;
8139 }
8140
8141 void
perf_event_output_forward(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)8142 perf_event_output_forward(struct perf_event *event,
8143 struct perf_sample_data *data,
8144 struct pt_regs *regs)
8145 {
8146 __perf_event_output(event, data, regs, perf_output_begin_forward);
8147 }
8148
8149 void
perf_event_output_backward(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)8150 perf_event_output_backward(struct perf_event *event,
8151 struct perf_sample_data *data,
8152 struct pt_regs *regs)
8153 {
8154 __perf_event_output(event, data, regs, perf_output_begin_backward);
8155 }
8156
8157 int
perf_event_output(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)8158 perf_event_output(struct perf_event *event,
8159 struct perf_sample_data *data,
8160 struct pt_regs *regs)
8161 {
8162 return __perf_event_output(event, data, regs, perf_output_begin);
8163 }
8164
8165 /*
8166 * read event_id
8167 */
8168
8169 struct perf_read_event {
8170 struct perf_event_header header;
8171
8172 u32 pid;
8173 u32 tid;
8174 };
8175
8176 static void
perf_event_read_event(struct perf_event * event,struct task_struct * task)8177 perf_event_read_event(struct perf_event *event,
8178 struct task_struct *task)
8179 {
8180 struct perf_output_handle handle;
8181 struct perf_sample_data sample;
8182 struct perf_read_event read_event = {
8183 .header = {
8184 .type = PERF_RECORD_READ,
8185 .misc = 0,
8186 .size = sizeof(read_event) + event->read_size,
8187 },
8188 .pid = perf_event_pid(event, task),
8189 .tid = perf_event_tid(event, task),
8190 };
8191 int ret;
8192
8193 perf_event_header__init_id(&read_event.header, &sample, event);
8194 ret = perf_output_begin(&handle, &sample, event, read_event.header.size);
8195 if (ret)
8196 return;
8197
8198 perf_output_put(&handle, read_event);
8199 perf_output_read(&handle, event);
8200 perf_event__output_id_sample(event, &handle, &sample);
8201
8202 perf_output_end(&handle);
8203 }
8204
8205 typedef void (perf_iterate_f)(struct perf_event *event, void *data);
8206
8207 static void
perf_iterate_ctx(struct perf_event_context * ctx,perf_iterate_f output,void * data,bool all)8208 perf_iterate_ctx(struct perf_event_context *ctx,
8209 perf_iterate_f output,
8210 void *data, bool all)
8211 {
8212 struct perf_event *event;
8213
8214 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
8215 if (!all) {
8216 if (event->state < PERF_EVENT_STATE_INACTIVE)
8217 continue;
8218 if (!event_filter_match(event))
8219 continue;
8220 }
8221
8222 output(event, data);
8223 }
8224 }
8225
perf_iterate_sb_cpu(perf_iterate_f output,void * data)8226 static void perf_iterate_sb_cpu(perf_iterate_f output, void *data)
8227 {
8228 struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events);
8229 struct perf_event *event;
8230
8231 list_for_each_entry_rcu(event, &pel->list, sb_list) {
8232 /*
8233 * Skip events that are not fully formed yet; ensure that
8234 * if we observe event->ctx, both event and ctx will be
8235 * complete enough. See perf_install_in_context().
8236 */
8237 if (!smp_load_acquire(&event->ctx))
8238 continue;
8239
8240 if (event->state < PERF_EVENT_STATE_INACTIVE)
8241 continue;
8242 if (!event_filter_match(event))
8243 continue;
8244 output(event, data);
8245 }
8246 }
8247
8248 /*
8249 * Iterate all events that need to receive side-band events.
8250 *
8251 * For new callers; ensure that account_pmu_sb_event() includes
8252 * your event, otherwise it might not get delivered.
8253 */
8254 static void
perf_iterate_sb(perf_iterate_f output,void * data,struct perf_event_context * task_ctx)8255 perf_iterate_sb(perf_iterate_f output, void *data,
8256 struct perf_event_context *task_ctx)
8257 {
8258 struct perf_event_context *ctx;
8259
8260 rcu_read_lock();
8261 preempt_disable();
8262
8263 /*
8264 * If we have task_ctx != NULL we only notify the task context itself.
8265 * The task_ctx is set only for EXIT events before releasing task
8266 * context.
8267 */
8268 if (task_ctx) {
8269 perf_iterate_ctx(task_ctx, output, data, false);
8270 goto done;
8271 }
8272
8273 perf_iterate_sb_cpu(output, data);
8274
8275 ctx = rcu_dereference(current->perf_event_ctxp);
8276 if (ctx)
8277 perf_iterate_ctx(ctx, output, data, false);
8278 done:
8279 preempt_enable();
8280 rcu_read_unlock();
8281 }
8282
8283 /*
8284 * Clear all file-based filters at exec, they'll have to be
8285 * re-instated when/if these objects are mmapped again.
8286 */
perf_event_addr_filters_exec(struct perf_event * event,void * data)8287 static void perf_event_addr_filters_exec(struct perf_event *event, void *data)
8288 {
8289 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
8290 struct perf_addr_filter *filter;
8291 unsigned int restart = 0, count = 0;
8292 unsigned long flags;
8293
8294 if (!has_addr_filter(event))
8295 return;
8296
8297 raw_spin_lock_irqsave(&ifh->lock, flags);
8298 list_for_each_entry(filter, &ifh->list, entry) {
8299 if (filter->path.dentry) {
8300 event->addr_filter_ranges[count].start = 0;
8301 event->addr_filter_ranges[count].size = 0;
8302 restart++;
8303 }
8304
8305 count++;
8306 }
8307
8308 if (restart)
8309 event->addr_filters_gen++;
8310 raw_spin_unlock_irqrestore(&ifh->lock, flags);
8311
8312 if (restart)
8313 perf_event_stop(event, 1);
8314 }
8315
perf_event_exec(void)8316 void perf_event_exec(void)
8317 {
8318 struct perf_event_context *ctx;
8319
8320 ctx = perf_pin_task_context(current);
8321 if (!ctx)
8322 return;
8323
8324 perf_event_enable_on_exec(ctx);
8325 perf_event_remove_on_exec(ctx);
8326 scoped_guard(rcu)
8327 perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL, true);
8328
8329 perf_unpin_context(ctx);
8330 put_ctx(ctx);
8331 }
8332
8333 struct remote_output {
8334 struct perf_buffer *rb;
8335 int err;
8336 };
8337
__perf_event_output_stop(struct perf_event * event,void * data)8338 static void __perf_event_output_stop(struct perf_event *event, void *data)
8339 {
8340 struct perf_event *parent = event->parent;
8341 struct remote_output *ro = data;
8342 struct perf_buffer *rb = ro->rb;
8343 struct stop_event_data sd = {
8344 .event = event,
8345 };
8346
8347 if (!has_aux(event))
8348 return;
8349
8350 if (!parent)
8351 parent = event;
8352
8353 /*
8354 * In case of inheritance, it will be the parent that links to the
8355 * ring-buffer, but it will be the child that's actually using it.
8356 *
8357 * We are using event::rb to determine if the event should be stopped,
8358 * however this may race with ring_buffer_attach() (through set_output),
8359 * which will make us skip the event that actually needs to be stopped.
8360 * So ring_buffer_attach() has to stop an aux event before re-assigning
8361 * its rb pointer.
8362 */
8363 if (rcu_dereference(parent->rb) == rb)
8364 ro->err = __perf_event_stop(&sd);
8365 }
8366
__perf_pmu_output_stop(void * info)8367 static int __perf_pmu_output_stop(void *info)
8368 {
8369 struct perf_event *event = info;
8370 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
8371 struct remote_output ro = {
8372 .rb = event->rb,
8373 };
8374
8375 rcu_read_lock();
8376 perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false);
8377 if (cpuctx->task_ctx)
8378 perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop,
8379 &ro, false);
8380 rcu_read_unlock();
8381
8382 return ro.err;
8383 }
8384
perf_pmu_output_stop(struct perf_event * event)8385 static void perf_pmu_output_stop(struct perf_event *event)
8386 {
8387 struct perf_event *iter;
8388 int err, cpu;
8389
8390 restart:
8391 rcu_read_lock();
8392 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
8393 /*
8394 * For per-CPU events, we need to make sure that neither they
8395 * nor their children are running; for cpu==-1 events it's
8396 * sufficient to stop the event itself if it's active, since
8397 * it can't have children.
8398 */
8399 cpu = iter->cpu;
8400 if (cpu == -1)
8401 cpu = READ_ONCE(iter->oncpu);
8402
8403 if (cpu == -1)
8404 continue;
8405
8406 err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
8407 if (err == -EAGAIN) {
8408 rcu_read_unlock();
8409 goto restart;
8410 }
8411 }
8412 rcu_read_unlock();
8413 }
8414
8415 /*
8416 * task tracking -- fork/exit
8417 *
8418 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
8419 */
8420
8421 struct perf_task_event {
8422 struct task_struct *task;
8423 struct perf_event_context *task_ctx;
8424
8425 struct {
8426 struct perf_event_header header;
8427
8428 u32 pid;
8429 u32 ppid;
8430 u32 tid;
8431 u32 ptid;
8432 u64 time;
8433 } event_id;
8434 };
8435
perf_event_task_match(struct perf_event * event)8436 static int perf_event_task_match(struct perf_event *event)
8437 {
8438 return event->attr.comm || event->attr.mmap ||
8439 event->attr.mmap2 || event->attr.mmap_data ||
8440 event->attr.task;
8441 }
8442
perf_event_task_output(struct perf_event * event,void * data)8443 static void perf_event_task_output(struct perf_event *event,
8444 void *data)
8445 {
8446 struct perf_task_event *task_event = data;
8447 struct perf_output_handle handle;
8448 struct perf_sample_data sample;
8449 struct task_struct *task = task_event->task;
8450 int ret, size = task_event->event_id.header.size;
8451
8452 if (!perf_event_task_match(event))
8453 return;
8454
8455 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
8456
8457 ret = perf_output_begin(&handle, &sample, event,
8458 task_event->event_id.header.size);
8459 if (ret)
8460 goto out;
8461
8462 task_event->event_id.pid = perf_event_pid(event, task);
8463 task_event->event_id.tid = perf_event_tid(event, task);
8464
8465 if (task_event->event_id.header.type == PERF_RECORD_EXIT) {
8466 task_event->event_id.ppid = perf_event_pid(event,
8467 task->real_parent);
8468 task_event->event_id.ptid = perf_event_pid(event,
8469 task->real_parent);
8470 } else { /* PERF_RECORD_FORK */
8471 task_event->event_id.ppid = perf_event_pid(event, current);
8472 task_event->event_id.ptid = perf_event_tid(event, current);
8473 }
8474
8475 task_event->event_id.time = perf_event_clock(event);
8476
8477 perf_output_put(&handle, task_event->event_id);
8478
8479 perf_event__output_id_sample(event, &handle, &sample);
8480
8481 perf_output_end(&handle);
8482 out:
8483 task_event->event_id.header.size = size;
8484 }
8485
perf_event_task(struct task_struct * task,struct perf_event_context * task_ctx,int new)8486 static void perf_event_task(struct task_struct *task,
8487 struct perf_event_context *task_ctx,
8488 int new)
8489 {
8490 struct perf_task_event task_event;
8491
8492 if (!atomic_read(&nr_comm_events) &&
8493 !atomic_read(&nr_mmap_events) &&
8494 !atomic_read(&nr_task_events))
8495 return;
8496
8497 task_event = (struct perf_task_event){
8498 .task = task,
8499 .task_ctx = task_ctx,
8500 .event_id = {
8501 .header = {
8502 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
8503 .misc = 0,
8504 .size = sizeof(task_event.event_id),
8505 },
8506 /* .pid */
8507 /* .ppid */
8508 /* .tid */
8509 /* .ptid */
8510 /* .time */
8511 },
8512 };
8513
8514 perf_iterate_sb(perf_event_task_output,
8515 &task_event,
8516 task_ctx);
8517 }
8518
perf_event_fork(struct task_struct * task)8519 void perf_event_fork(struct task_struct *task)
8520 {
8521 perf_event_task(task, NULL, 1);
8522 perf_event_namespaces(task);
8523 }
8524
8525 /*
8526 * comm tracking
8527 */
8528
8529 struct perf_comm_event {
8530 struct task_struct *task;
8531 char *comm;
8532 int comm_size;
8533
8534 struct {
8535 struct perf_event_header header;
8536
8537 u32 pid;
8538 u32 tid;
8539 } event_id;
8540 };
8541
perf_event_comm_match(struct perf_event * event)8542 static int perf_event_comm_match(struct perf_event *event)
8543 {
8544 return event->attr.comm;
8545 }
8546
perf_event_comm_output(struct perf_event * event,void * data)8547 static void perf_event_comm_output(struct perf_event *event,
8548 void *data)
8549 {
8550 struct perf_comm_event *comm_event = data;
8551 struct perf_output_handle handle;
8552 struct perf_sample_data sample;
8553 int size = comm_event->event_id.header.size;
8554 int ret;
8555
8556 if (!perf_event_comm_match(event))
8557 return;
8558
8559 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
8560 ret = perf_output_begin(&handle, &sample, event,
8561 comm_event->event_id.header.size);
8562
8563 if (ret)
8564 goto out;
8565
8566 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
8567 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
8568
8569 perf_output_put(&handle, comm_event->event_id);
8570 __output_copy(&handle, comm_event->comm,
8571 comm_event->comm_size);
8572
8573 perf_event__output_id_sample(event, &handle, &sample);
8574
8575 perf_output_end(&handle);
8576 out:
8577 comm_event->event_id.header.size = size;
8578 }
8579
perf_event_comm_event(struct perf_comm_event * comm_event)8580 static void perf_event_comm_event(struct perf_comm_event *comm_event)
8581 {
8582 char comm[TASK_COMM_LEN];
8583 unsigned int size;
8584
8585 memset(comm, 0, sizeof(comm));
8586 strscpy(comm, comm_event->task->comm, sizeof(comm));
8587 size = ALIGN(strlen(comm)+1, sizeof(u64));
8588
8589 comm_event->comm = comm;
8590 comm_event->comm_size = size;
8591
8592 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
8593
8594 perf_iterate_sb(perf_event_comm_output,
8595 comm_event,
8596 NULL);
8597 }
8598
perf_event_comm(struct task_struct * task,bool exec)8599 void perf_event_comm(struct task_struct *task, bool exec)
8600 {
8601 struct perf_comm_event comm_event;
8602
8603 if (!atomic_read(&nr_comm_events))
8604 return;
8605
8606 comm_event = (struct perf_comm_event){
8607 .task = task,
8608 /* .comm */
8609 /* .comm_size */
8610 .event_id = {
8611 .header = {
8612 .type = PERF_RECORD_COMM,
8613 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
8614 /* .size */
8615 },
8616 /* .pid */
8617 /* .tid */
8618 },
8619 };
8620
8621 perf_event_comm_event(&comm_event);
8622 }
8623
8624 /*
8625 * namespaces tracking
8626 */
8627
8628 struct perf_namespaces_event {
8629 struct task_struct *task;
8630
8631 struct {
8632 struct perf_event_header header;
8633
8634 u32 pid;
8635 u32 tid;
8636 u64 nr_namespaces;
8637 struct perf_ns_link_info link_info[NR_NAMESPACES];
8638 } event_id;
8639 };
8640
perf_event_namespaces_match(struct perf_event * event)8641 static int perf_event_namespaces_match(struct perf_event *event)
8642 {
8643 return event->attr.namespaces;
8644 }
8645
perf_event_namespaces_output(struct perf_event * event,void * data)8646 static void perf_event_namespaces_output(struct perf_event *event,
8647 void *data)
8648 {
8649 struct perf_namespaces_event *namespaces_event = data;
8650 struct perf_output_handle handle;
8651 struct perf_sample_data sample;
8652 u16 header_size = namespaces_event->event_id.header.size;
8653 int ret;
8654
8655 if (!perf_event_namespaces_match(event))
8656 return;
8657
8658 perf_event_header__init_id(&namespaces_event->event_id.header,
8659 &sample, event);
8660 ret = perf_output_begin(&handle, &sample, event,
8661 namespaces_event->event_id.header.size);
8662 if (ret)
8663 goto out;
8664
8665 namespaces_event->event_id.pid = perf_event_pid(event,
8666 namespaces_event->task);
8667 namespaces_event->event_id.tid = perf_event_tid(event,
8668 namespaces_event->task);
8669
8670 perf_output_put(&handle, namespaces_event->event_id);
8671
8672 perf_event__output_id_sample(event, &handle, &sample);
8673
8674 perf_output_end(&handle);
8675 out:
8676 namespaces_event->event_id.header.size = header_size;
8677 }
8678
perf_fill_ns_link_info(struct perf_ns_link_info * ns_link_info,struct task_struct * task,const struct proc_ns_operations * ns_ops)8679 static void perf_fill_ns_link_info(struct perf_ns_link_info *ns_link_info,
8680 struct task_struct *task,
8681 const struct proc_ns_operations *ns_ops)
8682 {
8683 struct path ns_path;
8684 struct inode *ns_inode;
8685 int error;
8686
8687 error = ns_get_path(&ns_path, task, ns_ops);
8688 if (!error) {
8689 ns_inode = ns_path.dentry->d_inode;
8690 ns_link_info->dev = new_encode_dev(ns_inode->i_sb->s_dev);
8691 ns_link_info->ino = ns_inode->i_ino;
8692 path_put(&ns_path);
8693 }
8694 }
8695
perf_event_namespaces(struct task_struct * task)8696 void perf_event_namespaces(struct task_struct *task)
8697 {
8698 struct perf_namespaces_event namespaces_event;
8699 struct perf_ns_link_info *ns_link_info;
8700
8701 if (!atomic_read(&nr_namespaces_events))
8702 return;
8703
8704 namespaces_event = (struct perf_namespaces_event){
8705 .task = task,
8706 .event_id = {
8707 .header = {
8708 .type = PERF_RECORD_NAMESPACES,
8709 .misc = 0,
8710 .size = sizeof(namespaces_event.event_id),
8711 },
8712 /* .pid */
8713 /* .tid */
8714 .nr_namespaces = NR_NAMESPACES,
8715 /* .link_info[NR_NAMESPACES] */
8716 },
8717 };
8718
8719 ns_link_info = namespaces_event.event_id.link_info;
8720
8721 perf_fill_ns_link_info(&ns_link_info[MNT_NS_INDEX],
8722 task, &mntns_operations);
8723
8724 #ifdef CONFIG_USER_NS
8725 perf_fill_ns_link_info(&ns_link_info[USER_NS_INDEX],
8726 task, &userns_operations);
8727 #endif
8728 #ifdef CONFIG_NET_NS
8729 perf_fill_ns_link_info(&ns_link_info[NET_NS_INDEX],
8730 task, &netns_operations);
8731 #endif
8732 #ifdef CONFIG_UTS_NS
8733 perf_fill_ns_link_info(&ns_link_info[UTS_NS_INDEX],
8734 task, &utsns_operations);
8735 #endif
8736 #ifdef CONFIG_IPC_NS
8737 perf_fill_ns_link_info(&ns_link_info[IPC_NS_INDEX],
8738 task, &ipcns_operations);
8739 #endif
8740 #ifdef CONFIG_PID_NS
8741 perf_fill_ns_link_info(&ns_link_info[PID_NS_INDEX],
8742 task, &pidns_operations);
8743 #endif
8744 #ifdef CONFIG_CGROUPS
8745 perf_fill_ns_link_info(&ns_link_info[CGROUP_NS_INDEX],
8746 task, &cgroupns_operations);
8747 #endif
8748
8749 perf_iterate_sb(perf_event_namespaces_output,
8750 &namespaces_event,
8751 NULL);
8752 }
8753
8754 /*
8755 * cgroup tracking
8756 */
8757 #ifdef CONFIG_CGROUP_PERF
8758
8759 struct perf_cgroup_event {
8760 char *path;
8761 int path_size;
8762 struct {
8763 struct perf_event_header header;
8764 u64 id;
8765 char path[];
8766 } event_id;
8767 };
8768
perf_event_cgroup_match(struct perf_event * event)8769 static int perf_event_cgroup_match(struct perf_event *event)
8770 {
8771 return event->attr.cgroup;
8772 }
8773
perf_event_cgroup_output(struct perf_event * event,void * data)8774 static void perf_event_cgroup_output(struct perf_event *event, void *data)
8775 {
8776 struct perf_cgroup_event *cgroup_event = data;
8777 struct perf_output_handle handle;
8778 struct perf_sample_data sample;
8779 u16 header_size = cgroup_event->event_id.header.size;
8780 int ret;
8781
8782 if (!perf_event_cgroup_match(event))
8783 return;
8784
8785 perf_event_header__init_id(&cgroup_event->event_id.header,
8786 &sample, event);
8787 ret = perf_output_begin(&handle, &sample, event,
8788 cgroup_event->event_id.header.size);
8789 if (ret)
8790 goto out;
8791
8792 perf_output_put(&handle, cgroup_event->event_id);
8793 __output_copy(&handle, cgroup_event->path, cgroup_event->path_size);
8794
8795 perf_event__output_id_sample(event, &handle, &sample);
8796
8797 perf_output_end(&handle);
8798 out:
8799 cgroup_event->event_id.header.size = header_size;
8800 }
8801
perf_event_cgroup(struct cgroup * cgrp)8802 static void perf_event_cgroup(struct cgroup *cgrp)
8803 {
8804 struct perf_cgroup_event cgroup_event;
8805 char path_enomem[16] = "//enomem";
8806 char *pathname;
8807 size_t size;
8808
8809 if (!atomic_read(&nr_cgroup_events))
8810 return;
8811
8812 cgroup_event = (struct perf_cgroup_event){
8813 .event_id = {
8814 .header = {
8815 .type = PERF_RECORD_CGROUP,
8816 .misc = 0,
8817 .size = sizeof(cgroup_event.event_id),
8818 },
8819 .id = cgroup_id(cgrp),
8820 },
8821 };
8822
8823 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
8824 if (pathname == NULL) {
8825 cgroup_event.path = path_enomem;
8826 } else {
8827 /* just to be sure to have enough space for alignment */
8828 cgroup_path(cgrp, pathname, PATH_MAX - sizeof(u64));
8829 cgroup_event.path = pathname;
8830 }
8831
8832 /*
8833 * Since our buffer works in 8 byte units we need to align our string
8834 * size to a multiple of 8. However, we must guarantee the tail end is
8835 * zero'd out to avoid leaking random bits to userspace.
8836 */
8837 size = strlen(cgroup_event.path) + 1;
8838 while (!IS_ALIGNED(size, sizeof(u64)))
8839 cgroup_event.path[size++] = '\0';
8840
8841 cgroup_event.event_id.header.size += size;
8842 cgroup_event.path_size = size;
8843
8844 perf_iterate_sb(perf_event_cgroup_output,
8845 &cgroup_event,
8846 NULL);
8847
8848 kfree(pathname);
8849 }
8850
8851 #endif
8852
8853 /*
8854 * mmap tracking
8855 */
8856
8857 struct perf_mmap_event {
8858 struct vm_area_struct *vma;
8859
8860 const char *file_name;
8861 int file_size;
8862 int maj, min;
8863 u64 ino;
8864 u64 ino_generation;
8865 u32 prot, flags;
8866 u8 build_id[BUILD_ID_SIZE_MAX];
8867 u32 build_id_size;
8868
8869 struct {
8870 struct perf_event_header header;
8871
8872 u32 pid;
8873 u32 tid;
8874 u64 start;
8875 u64 len;
8876 u64 pgoff;
8877 } event_id;
8878 };
8879
perf_event_mmap_match(struct perf_event * event,void * data)8880 static int perf_event_mmap_match(struct perf_event *event,
8881 void *data)
8882 {
8883 struct perf_mmap_event *mmap_event = data;
8884 struct vm_area_struct *vma = mmap_event->vma;
8885 int executable = vma->vm_flags & VM_EXEC;
8886
8887 return (!executable && event->attr.mmap_data) ||
8888 (executable && (event->attr.mmap || event->attr.mmap2));
8889 }
8890
perf_event_mmap_output(struct perf_event * event,void * data)8891 static void perf_event_mmap_output(struct perf_event *event,
8892 void *data)
8893 {
8894 struct perf_mmap_event *mmap_event = data;
8895 struct perf_output_handle handle;
8896 struct perf_sample_data sample;
8897 int size = mmap_event->event_id.header.size;
8898 u32 type = mmap_event->event_id.header.type;
8899 bool use_build_id;
8900 int ret;
8901
8902 if (!perf_event_mmap_match(event, data))
8903 return;
8904
8905 if (event->attr.mmap2) {
8906 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
8907 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
8908 mmap_event->event_id.header.size += sizeof(mmap_event->min);
8909 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
8910 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
8911 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
8912 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
8913 }
8914
8915 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
8916 ret = perf_output_begin(&handle, &sample, event,
8917 mmap_event->event_id.header.size);
8918 if (ret)
8919 goto out;
8920
8921 mmap_event->event_id.pid = perf_event_pid(event, current);
8922 mmap_event->event_id.tid = perf_event_tid(event, current);
8923
8924 use_build_id = event->attr.build_id && mmap_event->build_id_size;
8925
8926 if (event->attr.mmap2 && use_build_id)
8927 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_BUILD_ID;
8928
8929 perf_output_put(&handle, mmap_event->event_id);
8930
8931 if (event->attr.mmap2) {
8932 if (use_build_id) {
8933 u8 size[4] = { (u8) mmap_event->build_id_size, 0, 0, 0 };
8934
8935 __output_copy(&handle, size, 4);
8936 __output_copy(&handle, mmap_event->build_id, BUILD_ID_SIZE_MAX);
8937 } else {
8938 perf_output_put(&handle, mmap_event->maj);
8939 perf_output_put(&handle, mmap_event->min);
8940 perf_output_put(&handle, mmap_event->ino);
8941 perf_output_put(&handle, mmap_event->ino_generation);
8942 }
8943 perf_output_put(&handle, mmap_event->prot);
8944 perf_output_put(&handle, mmap_event->flags);
8945 }
8946
8947 __output_copy(&handle, mmap_event->file_name,
8948 mmap_event->file_size);
8949
8950 perf_event__output_id_sample(event, &handle, &sample);
8951
8952 perf_output_end(&handle);
8953 out:
8954 mmap_event->event_id.header.size = size;
8955 mmap_event->event_id.header.type = type;
8956 }
8957
perf_event_mmap_event(struct perf_mmap_event * mmap_event)8958 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
8959 {
8960 struct vm_area_struct *vma = mmap_event->vma;
8961 struct file *file = vma->vm_file;
8962 int maj = 0, min = 0;
8963 u64 ino = 0, gen = 0;
8964 u32 prot = 0, flags = 0;
8965 unsigned int size;
8966 char tmp[16];
8967 char *buf = NULL;
8968 char *name = NULL;
8969
8970 if (vma->vm_flags & VM_READ)
8971 prot |= PROT_READ;
8972 if (vma->vm_flags & VM_WRITE)
8973 prot |= PROT_WRITE;
8974 if (vma->vm_flags & VM_EXEC)
8975 prot |= PROT_EXEC;
8976
8977 if (vma->vm_flags & VM_MAYSHARE)
8978 flags = MAP_SHARED;
8979 else
8980 flags = MAP_PRIVATE;
8981
8982 if (vma->vm_flags & VM_LOCKED)
8983 flags |= MAP_LOCKED;
8984 if (is_vm_hugetlb_page(vma))
8985 flags |= MAP_HUGETLB;
8986
8987 if (file) {
8988 struct inode *inode;
8989 dev_t dev;
8990
8991 buf = kmalloc(PATH_MAX, GFP_KERNEL);
8992 if (!buf) {
8993 name = "//enomem";
8994 goto cpy_name;
8995 }
8996 /*
8997 * d_path() works from the end of the rb backwards, so we
8998 * need to add enough zero bytes after the string to handle
8999 * the 64bit alignment we do later.
9000 */
9001 name = file_path(file, buf, PATH_MAX - sizeof(u64));
9002 if (IS_ERR(name)) {
9003 name = "//toolong";
9004 goto cpy_name;
9005 }
9006 inode = file_inode(vma->vm_file);
9007 dev = inode->i_sb->s_dev;
9008 ino = inode->i_ino;
9009 gen = inode->i_generation;
9010 maj = MAJOR(dev);
9011 min = MINOR(dev);
9012
9013 goto got_name;
9014 } else {
9015 if (vma->vm_ops && vma->vm_ops->name)
9016 name = (char *) vma->vm_ops->name(vma);
9017 if (!name)
9018 name = (char *)arch_vma_name(vma);
9019 if (!name) {
9020 if (vma_is_initial_heap(vma))
9021 name = "[heap]";
9022 else if (vma_is_initial_stack(vma))
9023 name = "[stack]";
9024 else
9025 name = "//anon";
9026 }
9027 }
9028
9029 cpy_name:
9030 strscpy(tmp, name, sizeof(tmp));
9031 name = tmp;
9032 got_name:
9033 /*
9034 * Since our buffer works in 8 byte units we need to align our string
9035 * size to a multiple of 8. However, we must guarantee the tail end is
9036 * zero'd out to avoid leaking random bits to userspace.
9037 */
9038 size = strlen(name)+1;
9039 while (!IS_ALIGNED(size, sizeof(u64)))
9040 name[size++] = '\0';
9041
9042 mmap_event->file_name = name;
9043 mmap_event->file_size = size;
9044 mmap_event->maj = maj;
9045 mmap_event->min = min;
9046 mmap_event->ino = ino;
9047 mmap_event->ino_generation = gen;
9048 mmap_event->prot = prot;
9049 mmap_event->flags = flags;
9050
9051 if (!(vma->vm_flags & VM_EXEC))
9052 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
9053
9054 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
9055
9056 if (atomic_read(&nr_build_id_events))
9057 build_id_parse_nofault(vma, mmap_event->build_id, &mmap_event->build_id_size);
9058
9059 perf_iterate_sb(perf_event_mmap_output,
9060 mmap_event,
9061 NULL);
9062
9063 kfree(buf);
9064 }
9065
9066 /*
9067 * Check whether inode and address range match filter criteria.
9068 */
perf_addr_filter_match(struct perf_addr_filter * filter,struct file * file,unsigned long offset,unsigned long size)9069 static bool perf_addr_filter_match(struct perf_addr_filter *filter,
9070 struct file *file, unsigned long offset,
9071 unsigned long size)
9072 {
9073 /* d_inode(NULL) won't be equal to any mapped user-space file */
9074 if (!filter->path.dentry)
9075 return false;
9076
9077 if (d_inode(filter->path.dentry) != file_inode(file))
9078 return false;
9079
9080 if (filter->offset > offset + size)
9081 return false;
9082
9083 if (filter->offset + filter->size < offset)
9084 return false;
9085
9086 return true;
9087 }
9088
perf_addr_filter_vma_adjust(struct perf_addr_filter * filter,struct vm_area_struct * vma,struct perf_addr_filter_range * fr)9089 static bool perf_addr_filter_vma_adjust(struct perf_addr_filter *filter,
9090 struct vm_area_struct *vma,
9091 struct perf_addr_filter_range *fr)
9092 {
9093 unsigned long vma_size = vma->vm_end - vma->vm_start;
9094 unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
9095 struct file *file = vma->vm_file;
9096
9097 if (!perf_addr_filter_match(filter, file, off, vma_size))
9098 return false;
9099
9100 if (filter->offset < off) {
9101 fr->start = vma->vm_start;
9102 fr->size = min(vma_size, filter->size - (off - filter->offset));
9103 } else {
9104 fr->start = vma->vm_start + filter->offset - off;
9105 fr->size = min(vma->vm_end - fr->start, filter->size);
9106 }
9107
9108 return true;
9109 }
9110
__perf_addr_filters_adjust(struct perf_event * event,void * data)9111 static void __perf_addr_filters_adjust(struct perf_event *event, void *data)
9112 {
9113 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
9114 struct vm_area_struct *vma = data;
9115 struct perf_addr_filter *filter;
9116 unsigned int restart = 0, count = 0;
9117 unsigned long flags;
9118
9119 if (!has_addr_filter(event))
9120 return;
9121
9122 if (!vma->vm_file)
9123 return;
9124
9125 raw_spin_lock_irqsave(&ifh->lock, flags);
9126 list_for_each_entry(filter, &ifh->list, entry) {
9127 if (perf_addr_filter_vma_adjust(filter, vma,
9128 &event->addr_filter_ranges[count]))
9129 restart++;
9130
9131 count++;
9132 }
9133
9134 if (restart)
9135 event->addr_filters_gen++;
9136 raw_spin_unlock_irqrestore(&ifh->lock, flags);
9137
9138 if (restart)
9139 perf_event_stop(event, 1);
9140 }
9141
9142 /*
9143 * Adjust all task's events' filters to the new vma
9144 */
perf_addr_filters_adjust(struct vm_area_struct * vma)9145 static void perf_addr_filters_adjust(struct vm_area_struct *vma)
9146 {
9147 struct perf_event_context *ctx;
9148
9149 /*
9150 * Data tracing isn't supported yet and as such there is no need
9151 * to keep track of anything that isn't related to executable code:
9152 */
9153 if (!(vma->vm_flags & VM_EXEC))
9154 return;
9155
9156 rcu_read_lock();
9157 ctx = rcu_dereference(current->perf_event_ctxp);
9158 if (ctx)
9159 perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true);
9160 rcu_read_unlock();
9161 }
9162
perf_event_mmap(struct vm_area_struct * vma)9163 void perf_event_mmap(struct vm_area_struct *vma)
9164 {
9165 struct perf_mmap_event mmap_event;
9166
9167 if (!atomic_read(&nr_mmap_events))
9168 return;
9169
9170 mmap_event = (struct perf_mmap_event){
9171 .vma = vma,
9172 /* .file_name */
9173 /* .file_size */
9174 .event_id = {
9175 .header = {
9176 .type = PERF_RECORD_MMAP,
9177 .misc = PERF_RECORD_MISC_USER,
9178 /* .size */
9179 },
9180 /* .pid */
9181 /* .tid */
9182 .start = vma->vm_start,
9183 .len = vma->vm_end - vma->vm_start,
9184 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
9185 },
9186 /* .maj (attr_mmap2 only) */
9187 /* .min (attr_mmap2 only) */
9188 /* .ino (attr_mmap2 only) */
9189 /* .ino_generation (attr_mmap2 only) */
9190 /* .prot (attr_mmap2 only) */
9191 /* .flags (attr_mmap2 only) */
9192 };
9193
9194 perf_addr_filters_adjust(vma);
9195 perf_event_mmap_event(&mmap_event);
9196 }
9197
perf_event_aux_event(struct perf_event * event,unsigned long head,unsigned long size,u64 flags)9198 void perf_event_aux_event(struct perf_event *event, unsigned long head,
9199 unsigned long size, u64 flags)
9200 {
9201 struct perf_output_handle handle;
9202 struct perf_sample_data sample;
9203 struct perf_aux_event {
9204 struct perf_event_header header;
9205 u64 offset;
9206 u64 size;
9207 u64 flags;
9208 } rec = {
9209 .header = {
9210 .type = PERF_RECORD_AUX,
9211 .misc = 0,
9212 .size = sizeof(rec),
9213 },
9214 .offset = head,
9215 .size = size,
9216 .flags = flags,
9217 };
9218 int ret;
9219
9220 perf_event_header__init_id(&rec.header, &sample, event);
9221 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
9222
9223 if (ret)
9224 return;
9225
9226 perf_output_put(&handle, rec);
9227 perf_event__output_id_sample(event, &handle, &sample);
9228
9229 perf_output_end(&handle);
9230 }
9231
9232 /*
9233 * Lost/dropped samples logging
9234 */
perf_log_lost_samples(struct perf_event * event,u64 lost)9235 void perf_log_lost_samples(struct perf_event *event, u64 lost)
9236 {
9237 struct perf_output_handle handle;
9238 struct perf_sample_data sample;
9239 int ret;
9240
9241 struct {
9242 struct perf_event_header header;
9243 u64 lost;
9244 } lost_samples_event = {
9245 .header = {
9246 .type = PERF_RECORD_LOST_SAMPLES,
9247 .misc = 0,
9248 .size = sizeof(lost_samples_event),
9249 },
9250 .lost = lost,
9251 };
9252
9253 perf_event_header__init_id(&lost_samples_event.header, &sample, event);
9254
9255 ret = perf_output_begin(&handle, &sample, event,
9256 lost_samples_event.header.size);
9257 if (ret)
9258 return;
9259
9260 perf_output_put(&handle, lost_samples_event);
9261 perf_event__output_id_sample(event, &handle, &sample);
9262 perf_output_end(&handle);
9263 }
9264
9265 /*
9266 * context_switch tracking
9267 */
9268
9269 struct perf_switch_event {
9270 struct task_struct *task;
9271 struct task_struct *next_prev;
9272
9273 struct {
9274 struct perf_event_header header;
9275 u32 next_prev_pid;
9276 u32 next_prev_tid;
9277 } event_id;
9278 };
9279
perf_event_switch_match(struct perf_event * event)9280 static int perf_event_switch_match(struct perf_event *event)
9281 {
9282 return event->attr.context_switch;
9283 }
9284
perf_event_switch_output(struct perf_event * event,void * data)9285 static void perf_event_switch_output(struct perf_event *event, void *data)
9286 {
9287 struct perf_switch_event *se = data;
9288 struct perf_output_handle handle;
9289 struct perf_sample_data sample;
9290 int ret;
9291
9292 if (!perf_event_switch_match(event))
9293 return;
9294
9295 /* Only CPU-wide events are allowed to see next/prev pid/tid */
9296 if (event->ctx->task) {
9297 se->event_id.header.type = PERF_RECORD_SWITCH;
9298 se->event_id.header.size = sizeof(se->event_id.header);
9299 } else {
9300 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
9301 se->event_id.header.size = sizeof(se->event_id);
9302 se->event_id.next_prev_pid =
9303 perf_event_pid(event, se->next_prev);
9304 se->event_id.next_prev_tid =
9305 perf_event_tid(event, se->next_prev);
9306 }
9307
9308 perf_event_header__init_id(&se->event_id.header, &sample, event);
9309
9310 ret = perf_output_begin(&handle, &sample, event, se->event_id.header.size);
9311 if (ret)
9312 return;
9313
9314 if (event->ctx->task)
9315 perf_output_put(&handle, se->event_id.header);
9316 else
9317 perf_output_put(&handle, se->event_id);
9318
9319 perf_event__output_id_sample(event, &handle, &sample);
9320
9321 perf_output_end(&handle);
9322 }
9323
perf_event_switch(struct task_struct * task,struct task_struct * next_prev,bool sched_in)9324 static void perf_event_switch(struct task_struct *task,
9325 struct task_struct *next_prev, bool sched_in)
9326 {
9327 struct perf_switch_event switch_event;
9328
9329 /* N.B. caller checks nr_switch_events != 0 */
9330
9331 switch_event = (struct perf_switch_event){
9332 .task = task,
9333 .next_prev = next_prev,
9334 .event_id = {
9335 .header = {
9336 /* .type */
9337 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
9338 /* .size */
9339 },
9340 /* .next_prev_pid */
9341 /* .next_prev_tid */
9342 },
9343 };
9344
9345 if (!sched_in && task_is_runnable(task)) {
9346 switch_event.event_id.header.misc |=
9347 PERF_RECORD_MISC_SWITCH_OUT_PREEMPT;
9348 }
9349
9350 perf_iterate_sb(perf_event_switch_output, &switch_event, NULL);
9351 }
9352
9353 /*
9354 * IRQ throttle logging
9355 */
9356
perf_log_throttle(struct perf_event * event,int enable)9357 static void perf_log_throttle(struct perf_event *event, int enable)
9358 {
9359 struct perf_output_handle handle;
9360 struct perf_sample_data sample;
9361 int ret;
9362
9363 struct {
9364 struct perf_event_header header;
9365 u64 time;
9366 u64 id;
9367 u64 stream_id;
9368 } throttle_event = {
9369 .header = {
9370 .type = PERF_RECORD_THROTTLE,
9371 .misc = 0,
9372 .size = sizeof(throttle_event),
9373 },
9374 .time = perf_event_clock(event),
9375 .id = primary_event_id(event),
9376 .stream_id = event->id,
9377 };
9378
9379 if (enable)
9380 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
9381
9382 perf_event_header__init_id(&throttle_event.header, &sample, event);
9383
9384 ret = perf_output_begin(&handle, &sample, event,
9385 throttle_event.header.size);
9386 if (ret)
9387 return;
9388
9389 perf_output_put(&handle, throttle_event);
9390 perf_event__output_id_sample(event, &handle, &sample);
9391 perf_output_end(&handle);
9392 }
9393
9394 /*
9395 * ksymbol register/unregister tracking
9396 */
9397
9398 struct perf_ksymbol_event {
9399 const char *name;
9400 int name_len;
9401 struct {
9402 struct perf_event_header header;
9403 u64 addr;
9404 u32 len;
9405 u16 ksym_type;
9406 u16 flags;
9407 } event_id;
9408 };
9409
perf_event_ksymbol_match(struct perf_event * event)9410 static int perf_event_ksymbol_match(struct perf_event *event)
9411 {
9412 return event->attr.ksymbol;
9413 }
9414
perf_event_ksymbol_output(struct perf_event * event,void * data)9415 static void perf_event_ksymbol_output(struct perf_event *event, void *data)
9416 {
9417 struct perf_ksymbol_event *ksymbol_event = data;
9418 struct perf_output_handle handle;
9419 struct perf_sample_data sample;
9420 int ret;
9421
9422 if (!perf_event_ksymbol_match(event))
9423 return;
9424
9425 perf_event_header__init_id(&ksymbol_event->event_id.header,
9426 &sample, event);
9427 ret = perf_output_begin(&handle, &sample, event,
9428 ksymbol_event->event_id.header.size);
9429 if (ret)
9430 return;
9431
9432 perf_output_put(&handle, ksymbol_event->event_id);
9433 __output_copy(&handle, ksymbol_event->name, ksymbol_event->name_len);
9434 perf_event__output_id_sample(event, &handle, &sample);
9435
9436 perf_output_end(&handle);
9437 }
9438
perf_event_ksymbol(u16 ksym_type,u64 addr,u32 len,bool unregister,const char * sym)9439 void perf_event_ksymbol(u16 ksym_type, u64 addr, u32 len, bool unregister,
9440 const char *sym)
9441 {
9442 struct perf_ksymbol_event ksymbol_event;
9443 char name[KSYM_NAME_LEN];
9444 u16 flags = 0;
9445 int name_len;
9446
9447 if (!atomic_read(&nr_ksymbol_events))
9448 return;
9449
9450 if (ksym_type >= PERF_RECORD_KSYMBOL_TYPE_MAX ||
9451 ksym_type == PERF_RECORD_KSYMBOL_TYPE_UNKNOWN)
9452 goto err;
9453
9454 strscpy(name, sym, KSYM_NAME_LEN);
9455 name_len = strlen(name) + 1;
9456 while (!IS_ALIGNED(name_len, sizeof(u64)))
9457 name[name_len++] = '\0';
9458 BUILD_BUG_ON(KSYM_NAME_LEN % sizeof(u64));
9459
9460 if (unregister)
9461 flags |= PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER;
9462
9463 ksymbol_event = (struct perf_ksymbol_event){
9464 .name = name,
9465 .name_len = name_len,
9466 .event_id = {
9467 .header = {
9468 .type = PERF_RECORD_KSYMBOL,
9469 .size = sizeof(ksymbol_event.event_id) +
9470 name_len,
9471 },
9472 .addr = addr,
9473 .len = len,
9474 .ksym_type = ksym_type,
9475 .flags = flags,
9476 },
9477 };
9478
9479 perf_iterate_sb(perf_event_ksymbol_output, &ksymbol_event, NULL);
9480 return;
9481 err:
9482 WARN_ONCE(1, "%s: Invalid KSYMBOL type 0x%x\n", __func__, ksym_type);
9483 }
9484
9485 /*
9486 * bpf program load/unload tracking
9487 */
9488
9489 struct perf_bpf_event {
9490 struct bpf_prog *prog;
9491 struct {
9492 struct perf_event_header header;
9493 u16 type;
9494 u16 flags;
9495 u32 id;
9496 u8 tag[BPF_TAG_SIZE];
9497 } event_id;
9498 };
9499
perf_event_bpf_match(struct perf_event * event)9500 static int perf_event_bpf_match(struct perf_event *event)
9501 {
9502 return event->attr.bpf_event;
9503 }
9504
perf_event_bpf_output(struct perf_event * event,void * data)9505 static void perf_event_bpf_output(struct perf_event *event, void *data)
9506 {
9507 struct perf_bpf_event *bpf_event = data;
9508 struct perf_output_handle handle;
9509 struct perf_sample_data sample;
9510 int ret;
9511
9512 if (!perf_event_bpf_match(event))
9513 return;
9514
9515 perf_event_header__init_id(&bpf_event->event_id.header,
9516 &sample, event);
9517 ret = perf_output_begin(&handle, &sample, event,
9518 bpf_event->event_id.header.size);
9519 if (ret)
9520 return;
9521
9522 perf_output_put(&handle, bpf_event->event_id);
9523 perf_event__output_id_sample(event, &handle, &sample);
9524
9525 perf_output_end(&handle);
9526 }
9527
perf_event_bpf_emit_ksymbols(struct bpf_prog * prog,enum perf_bpf_event_type type)9528 static void perf_event_bpf_emit_ksymbols(struct bpf_prog *prog,
9529 enum perf_bpf_event_type type)
9530 {
9531 bool unregister = type == PERF_BPF_EVENT_PROG_UNLOAD;
9532 int i;
9533
9534 perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF,
9535 (u64)(unsigned long)prog->bpf_func,
9536 prog->jited_len, unregister,
9537 prog->aux->ksym.name);
9538
9539 for (i = 1; i < prog->aux->func_cnt; i++) {
9540 struct bpf_prog *subprog = prog->aux->func[i];
9541
9542 perf_event_ksymbol(
9543 PERF_RECORD_KSYMBOL_TYPE_BPF,
9544 (u64)(unsigned long)subprog->bpf_func,
9545 subprog->jited_len, unregister,
9546 subprog->aux->ksym.name);
9547 }
9548 }
9549
perf_event_bpf_event(struct bpf_prog * prog,enum perf_bpf_event_type type,u16 flags)9550 void perf_event_bpf_event(struct bpf_prog *prog,
9551 enum perf_bpf_event_type type,
9552 u16 flags)
9553 {
9554 struct perf_bpf_event bpf_event;
9555
9556 switch (type) {
9557 case PERF_BPF_EVENT_PROG_LOAD:
9558 case PERF_BPF_EVENT_PROG_UNLOAD:
9559 if (atomic_read(&nr_ksymbol_events))
9560 perf_event_bpf_emit_ksymbols(prog, type);
9561 break;
9562 default:
9563 return;
9564 }
9565
9566 if (!atomic_read(&nr_bpf_events))
9567 return;
9568
9569 bpf_event = (struct perf_bpf_event){
9570 .prog = prog,
9571 .event_id = {
9572 .header = {
9573 .type = PERF_RECORD_BPF_EVENT,
9574 .size = sizeof(bpf_event.event_id),
9575 },
9576 .type = type,
9577 .flags = flags,
9578 .id = prog->aux->id,
9579 },
9580 };
9581
9582 BUILD_BUG_ON(BPF_TAG_SIZE % sizeof(u64));
9583
9584 memcpy(bpf_event.event_id.tag, prog->tag, BPF_TAG_SIZE);
9585 perf_iterate_sb(perf_event_bpf_output, &bpf_event, NULL);
9586 }
9587
9588 struct perf_text_poke_event {
9589 const void *old_bytes;
9590 const void *new_bytes;
9591 size_t pad;
9592 u16 old_len;
9593 u16 new_len;
9594
9595 struct {
9596 struct perf_event_header header;
9597
9598 u64 addr;
9599 } event_id;
9600 };
9601
perf_event_text_poke_match(struct perf_event * event)9602 static int perf_event_text_poke_match(struct perf_event *event)
9603 {
9604 return event->attr.text_poke;
9605 }
9606
perf_event_text_poke_output(struct perf_event * event,void * data)9607 static void perf_event_text_poke_output(struct perf_event *event, void *data)
9608 {
9609 struct perf_text_poke_event *text_poke_event = data;
9610 struct perf_output_handle handle;
9611 struct perf_sample_data sample;
9612 u64 padding = 0;
9613 int ret;
9614
9615 if (!perf_event_text_poke_match(event))
9616 return;
9617
9618 perf_event_header__init_id(&text_poke_event->event_id.header, &sample, event);
9619
9620 ret = perf_output_begin(&handle, &sample, event,
9621 text_poke_event->event_id.header.size);
9622 if (ret)
9623 return;
9624
9625 perf_output_put(&handle, text_poke_event->event_id);
9626 perf_output_put(&handle, text_poke_event->old_len);
9627 perf_output_put(&handle, text_poke_event->new_len);
9628
9629 __output_copy(&handle, text_poke_event->old_bytes, text_poke_event->old_len);
9630 __output_copy(&handle, text_poke_event->new_bytes, text_poke_event->new_len);
9631
9632 if (text_poke_event->pad)
9633 __output_copy(&handle, &padding, text_poke_event->pad);
9634
9635 perf_event__output_id_sample(event, &handle, &sample);
9636
9637 perf_output_end(&handle);
9638 }
9639
perf_event_text_poke(const void * addr,const void * old_bytes,size_t old_len,const void * new_bytes,size_t new_len)9640 void perf_event_text_poke(const void *addr, const void *old_bytes,
9641 size_t old_len, const void *new_bytes, size_t new_len)
9642 {
9643 struct perf_text_poke_event text_poke_event;
9644 size_t tot, pad;
9645
9646 if (!atomic_read(&nr_text_poke_events))
9647 return;
9648
9649 tot = sizeof(text_poke_event.old_len) + old_len;
9650 tot += sizeof(text_poke_event.new_len) + new_len;
9651 pad = ALIGN(tot, sizeof(u64)) - tot;
9652
9653 text_poke_event = (struct perf_text_poke_event){
9654 .old_bytes = old_bytes,
9655 .new_bytes = new_bytes,
9656 .pad = pad,
9657 .old_len = old_len,
9658 .new_len = new_len,
9659 .event_id = {
9660 .header = {
9661 .type = PERF_RECORD_TEXT_POKE,
9662 .misc = PERF_RECORD_MISC_KERNEL,
9663 .size = sizeof(text_poke_event.event_id) + tot + pad,
9664 },
9665 .addr = (unsigned long)addr,
9666 },
9667 };
9668
9669 perf_iterate_sb(perf_event_text_poke_output, &text_poke_event, NULL);
9670 }
9671
perf_event_itrace_started(struct perf_event * event)9672 void perf_event_itrace_started(struct perf_event *event)
9673 {
9674 event->attach_state |= PERF_ATTACH_ITRACE;
9675 }
9676
perf_log_itrace_start(struct perf_event * event)9677 static void perf_log_itrace_start(struct perf_event *event)
9678 {
9679 struct perf_output_handle handle;
9680 struct perf_sample_data sample;
9681 struct perf_aux_event {
9682 struct perf_event_header header;
9683 u32 pid;
9684 u32 tid;
9685 } rec;
9686 int ret;
9687
9688 if (event->parent)
9689 event = event->parent;
9690
9691 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
9692 event->attach_state & PERF_ATTACH_ITRACE)
9693 return;
9694
9695 rec.header.type = PERF_RECORD_ITRACE_START;
9696 rec.header.misc = 0;
9697 rec.header.size = sizeof(rec);
9698 rec.pid = perf_event_pid(event, current);
9699 rec.tid = perf_event_tid(event, current);
9700
9701 perf_event_header__init_id(&rec.header, &sample, event);
9702 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
9703
9704 if (ret)
9705 return;
9706
9707 perf_output_put(&handle, rec);
9708 perf_event__output_id_sample(event, &handle, &sample);
9709
9710 perf_output_end(&handle);
9711 }
9712
perf_report_aux_output_id(struct perf_event * event,u64 hw_id)9713 void perf_report_aux_output_id(struct perf_event *event, u64 hw_id)
9714 {
9715 struct perf_output_handle handle;
9716 struct perf_sample_data sample;
9717 struct perf_aux_event {
9718 struct perf_event_header header;
9719 u64 hw_id;
9720 } rec;
9721 int ret;
9722
9723 if (event->parent)
9724 event = event->parent;
9725
9726 rec.header.type = PERF_RECORD_AUX_OUTPUT_HW_ID;
9727 rec.header.misc = 0;
9728 rec.header.size = sizeof(rec);
9729 rec.hw_id = hw_id;
9730
9731 perf_event_header__init_id(&rec.header, &sample, event);
9732 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
9733
9734 if (ret)
9735 return;
9736
9737 perf_output_put(&handle, rec);
9738 perf_event__output_id_sample(event, &handle, &sample);
9739
9740 perf_output_end(&handle);
9741 }
9742 EXPORT_SYMBOL_GPL(perf_report_aux_output_id);
9743
9744 static int
__perf_event_account_interrupt(struct perf_event * event,int throttle)9745 __perf_event_account_interrupt(struct perf_event *event, int throttle)
9746 {
9747 struct hw_perf_event *hwc = &event->hw;
9748 int ret = 0;
9749 u64 seq;
9750
9751 seq = __this_cpu_read(perf_throttled_seq);
9752 if (seq != hwc->interrupts_seq) {
9753 hwc->interrupts_seq = seq;
9754 hwc->interrupts = 1;
9755 } else {
9756 hwc->interrupts++;
9757 }
9758
9759 if (unlikely(throttle && hwc->interrupts >= max_samples_per_tick)) {
9760 __this_cpu_inc(perf_throttled_count);
9761 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
9762 hwc->interrupts = MAX_INTERRUPTS;
9763 perf_log_throttle(event, 0);
9764 ret = 1;
9765 }
9766
9767 if (event->attr.freq) {
9768 u64 now = perf_clock();
9769 s64 delta = now - hwc->freq_time_stamp;
9770
9771 hwc->freq_time_stamp = now;
9772
9773 if (delta > 0 && delta < 2*TICK_NSEC)
9774 perf_adjust_period(event, delta, hwc->last_period, true);
9775 }
9776
9777 return ret;
9778 }
9779
perf_event_account_interrupt(struct perf_event * event)9780 int perf_event_account_interrupt(struct perf_event *event)
9781 {
9782 return __perf_event_account_interrupt(event, 1);
9783 }
9784
sample_is_allowed(struct perf_event * event,struct pt_regs * regs)9785 static inline bool sample_is_allowed(struct perf_event *event, struct pt_regs *regs)
9786 {
9787 /*
9788 * Due to interrupt latency (AKA "skid"), we may enter the
9789 * kernel before taking an overflow, even if the PMU is only
9790 * counting user events.
9791 */
9792 if (event->attr.exclude_kernel && !user_mode(regs))
9793 return false;
9794
9795 return true;
9796 }
9797
9798 #ifdef CONFIG_BPF_SYSCALL
bpf_overflow_handler(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)9799 static int bpf_overflow_handler(struct perf_event *event,
9800 struct perf_sample_data *data,
9801 struct pt_regs *regs)
9802 {
9803 struct bpf_perf_event_data_kern ctx = {
9804 .data = data,
9805 .event = event,
9806 };
9807 struct bpf_prog *prog;
9808 int ret = 0;
9809
9810 ctx.regs = perf_arch_bpf_user_pt_regs(regs);
9811 if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1))
9812 goto out;
9813 rcu_read_lock();
9814 prog = READ_ONCE(event->prog);
9815 if (prog) {
9816 perf_prepare_sample(data, event, regs);
9817 ret = bpf_prog_run(prog, &ctx);
9818 }
9819 rcu_read_unlock();
9820 out:
9821 __this_cpu_dec(bpf_prog_active);
9822
9823 return ret;
9824 }
9825
perf_event_set_bpf_handler(struct perf_event * event,struct bpf_prog * prog,u64 bpf_cookie)9826 static inline int perf_event_set_bpf_handler(struct perf_event *event,
9827 struct bpf_prog *prog,
9828 u64 bpf_cookie)
9829 {
9830 if (event->overflow_handler_context)
9831 /* hw breakpoint or kernel counter */
9832 return -EINVAL;
9833
9834 if (event->prog)
9835 return -EEXIST;
9836
9837 if (prog->type != BPF_PROG_TYPE_PERF_EVENT)
9838 return -EINVAL;
9839
9840 if (event->attr.precise_ip &&
9841 prog->call_get_stack &&
9842 (!(event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) ||
9843 event->attr.exclude_callchain_kernel ||
9844 event->attr.exclude_callchain_user)) {
9845 /*
9846 * On perf_event with precise_ip, calling bpf_get_stack()
9847 * may trigger unwinder warnings and occasional crashes.
9848 * bpf_get_[stack|stackid] works around this issue by using
9849 * callchain attached to perf_sample_data. If the
9850 * perf_event does not full (kernel and user) callchain
9851 * attached to perf_sample_data, do not allow attaching BPF
9852 * program that calls bpf_get_[stack|stackid].
9853 */
9854 return -EPROTO;
9855 }
9856
9857 event->prog = prog;
9858 event->bpf_cookie = bpf_cookie;
9859 return 0;
9860 }
9861
perf_event_free_bpf_handler(struct perf_event * event)9862 static inline void perf_event_free_bpf_handler(struct perf_event *event)
9863 {
9864 struct bpf_prog *prog = event->prog;
9865
9866 if (!prog)
9867 return;
9868
9869 event->prog = NULL;
9870 bpf_prog_put(prog);
9871 }
9872 #else
bpf_overflow_handler(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)9873 static inline int bpf_overflow_handler(struct perf_event *event,
9874 struct perf_sample_data *data,
9875 struct pt_regs *regs)
9876 {
9877 return 1;
9878 }
9879
perf_event_set_bpf_handler(struct perf_event * event,struct bpf_prog * prog,u64 bpf_cookie)9880 static inline int perf_event_set_bpf_handler(struct perf_event *event,
9881 struct bpf_prog *prog,
9882 u64 bpf_cookie)
9883 {
9884 return -EOPNOTSUPP;
9885 }
9886
perf_event_free_bpf_handler(struct perf_event * event)9887 static inline void perf_event_free_bpf_handler(struct perf_event *event)
9888 {
9889 }
9890 #endif
9891
9892 /*
9893 * Generic event overflow handling, sampling.
9894 */
9895
__perf_event_overflow(struct perf_event * event,int throttle,struct perf_sample_data * data,struct pt_regs * regs)9896 static int __perf_event_overflow(struct perf_event *event,
9897 int throttle, struct perf_sample_data *data,
9898 struct pt_regs *regs)
9899 {
9900 int events = atomic_read(&event->event_limit);
9901 int ret = 0;
9902
9903 /*
9904 * Non-sampling counters might still use the PMI to fold short
9905 * hardware counters, ignore those.
9906 */
9907 if (unlikely(!is_sampling_event(event)))
9908 return 0;
9909
9910 ret = __perf_event_account_interrupt(event, throttle);
9911
9912 if (event->attr.aux_pause)
9913 perf_event_aux_pause(event->aux_event, true);
9914
9915 if (event->prog && event->prog->type == BPF_PROG_TYPE_PERF_EVENT &&
9916 !bpf_overflow_handler(event, data, regs))
9917 goto out;
9918
9919 /*
9920 * XXX event_limit might not quite work as expected on inherited
9921 * events
9922 */
9923
9924 event->pending_kill = POLL_IN;
9925 if (events && atomic_dec_and_test(&event->event_limit)) {
9926 ret = 1;
9927 event->pending_kill = POLL_HUP;
9928 perf_event_disable_inatomic(event);
9929 }
9930
9931 if (event->attr.sigtrap) {
9932 /*
9933 * The desired behaviour of sigtrap vs invalid samples is a bit
9934 * tricky; on the one hand, one should not loose the SIGTRAP if
9935 * it is the first event, on the other hand, we should also not
9936 * trigger the WARN or override the data address.
9937 */
9938 bool valid_sample = sample_is_allowed(event, regs);
9939 unsigned int pending_id = 1;
9940 enum task_work_notify_mode notify_mode;
9941
9942 if (regs)
9943 pending_id = hash32_ptr((void *)instruction_pointer(regs)) ?: 1;
9944
9945 notify_mode = in_nmi() ? TWA_NMI_CURRENT : TWA_RESUME;
9946
9947 if (!event->pending_work &&
9948 !task_work_add(current, &event->pending_task, notify_mode)) {
9949 event->pending_work = pending_id;
9950 local_inc(&event->ctx->nr_no_switch_fast);
9951 WARN_ON_ONCE(!atomic_long_inc_not_zero(&event->refcount));
9952
9953 event->pending_addr = 0;
9954 if (valid_sample && (data->sample_flags & PERF_SAMPLE_ADDR))
9955 event->pending_addr = data->addr;
9956
9957 } else if (event->attr.exclude_kernel && valid_sample) {
9958 /*
9959 * Should not be able to return to user space without
9960 * consuming pending_work; with exceptions:
9961 *
9962 * 1. Where !exclude_kernel, events can overflow again
9963 * in the kernel without returning to user space.
9964 *
9965 * 2. Events that can overflow again before the IRQ-
9966 * work without user space progress (e.g. hrtimer).
9967 * To approximate progress (with false negatives),
9968 * check 32-bit hash of the current IP.
9969 */
9970 WARN_ON_ONCE(event->pending_work != pending_id);
9971 }
9972 }
9973
9974 READ_ONCE(event->overflow_handler)(event, data, regs);
9975
9976 if (*perf_event_fasync(event) && event->pending_kill) {
9977 event->pending_wakeup = 1;
9978 irq_work_queue(&event->pending_irq);
9979 }
9980 out:
9981 if (event->attr.aux_resume)
9982 perf_event_aux_pause(event->aux_event, false);
9983
9984 return ret;
9985 }
9986
perf_event_overflow(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)9987 int perf_event_overflow(struct perf_event *event,
9988 struct perf_sample_data *data,
9989 struct pt_regs *regs)
9990 {
9991 return __perf_event_overflow(event, 1, data, regs);
9992 }
9993
9994 /*
9995 * Generic software event infrastructure
9996 */
9997
9998 struct swevent_htable {
9999 struct swevent_hlist *swevent_hlist;
10000 struct mutex hlist_mutex;
10001 int hlist_refcount;
10002 };
10003 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
10004
10005 /*
10006 * We directly increment event->count and keep a second value in
10007 * event->hw.period_left to count intervals. This period event
10008 * is kept in the range [-sample_period, 0] so that we can use the
10009 * sign as trigger.
10010 */
10011
perf_swevent_set_period(struct perf_event * event)10012 u64 perf_swevent_set_period(struct perf_event *event)
10013 {
10014 struct hw_perf_event *hwc = &event->hw;
10015 u64 period = hwc->last_period;
10016 u64 nr, offset;
10017 s64 old, val;
10018
10019 hwc->last_period = hwc->sample_period;
10020
10021 old = local64_read(&hwc->period_left);
10022 do {
10023 val = old;
10024 if (val < 0)
10025 return 0;
10026
10027 nr = div64_u64(period + val, period);
10028 offset = nr * period;
10029 val -= offset;
10030 } while (!local64_try_cmpxchg(&hwc->period_left, &old, val));
10031
10032 return nr;
10033 }
10034
perf_swevent_overflow(struct perf_event * event,u64 overflow,struct perf_sample_data * data,struct pt_regs * regs)10035 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
10036 struct perf_sample_data *data,
10037 struct pt_regs *regs)
10038 {
10039 struct hw_perf_event *hwc = &event->hw;
10040 int throttle = 0;
10041
10042 if (!overflow)
10043 overflow = perf_swevent_set_period(event);
10044
10045 if (hwc->interrupts == MAX_INTERRUPTS)
10046 return;
10047
10048 for (; overflow; overflow--) {
10049 if (__perf_event_overflow(event, throttle,
10050 data, regs)) {
10051 /*
10052 * We inhibit the overflow from happening when
10053 * hwc->interrupts == MAX_INTERRUPTS.
10054 */
10055 break;
10056 }
10057 throttle = 1;
10058 }
10059 }
10060
perf_swevent_event(struct perf_event * event,u64 nr,struct perf_sample_data * data,struct pt_regs * regs)10061 static void perf_swevent_event(struct perf_event *event, u64 nr,
10062 struct perf_sample_data *data,
10063 struct pt_regs *regs)
10064 {
10065 struct hw_perf_event *hwc = &event->hw;
10066
10067 local64_add(nr, &event->count);
10068
10069 if (!regs)
10070 return;
10071
10072 if (!is_sampling_event(event))
10073 return;
10074
10075 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
10076 data->period = nr;
10077 return perf_swevent_overflow(event, 1, data, regs);
10078 } else
10079 data->period = event->hw.last_period;
10080
10081 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
10082 return perf_swevent_overflow(event, 1, data, regs);
10083
10084 if (local64_add_negative(nr, &hwc->period_left))
10085 return;
10086
10087 perf_swevent_overflow(event, 0, data, regs);
10088 }
10089
perf_exclude_event(struct perf_event * event,struct pt_regs * regs)10090 static int perf_exclude_event(struct perf_event *event,
10091 struct pt_regs *regs)
10092 {
10093 if (event->hw.state & PERF_HES_STOPPED)
10094 return 1;
10095
10096 if (regs) {
10097 if (event->attr.exclude_user && user_mode(regs))
10098 return 1;
10099
10100 if (event->attr.exclude_kernel && !user_mode(regs))
10101 return 1;
10102 }
10103
10104 return 0;
10105 }
10106
perf_swevent_match(struct perf_event * event,enum perf_type_id type,u32 event_id,struct perf_sample_data * data,struct pt_regs * regs)10107 static int perf_swevent_match(struct perf_event *event,
10108 enum perf_type_id type,
10109 u32 event_id,
10110 struct perf_sample_data *data,
10111 struct pt_regs *regs)
10112 {
10113 if (event->attr.type != type)
10114 return 0;
10115
10116 if (event->attr.config != event_id)
10117 return 0;
10118
10119 if (perf_exclude_event(event, regs))
10120 return 0;
10121
10122 return 1;
10123 }
10124
swevent_hash(u64 type,u32 event_id)10125 static inline u64 swevent_hash(u64 type, u32 event_id)
10126 {
10127 u64 val = event_id | (type << 32);
10128
10129 return hash_64(val, SWEVENT_HLIST_BITS);
10130 }
10131
10132 static inline struct hlist_head *
__find_swevent_head(struct swevent_hlist * hlist,u64 type,u32 event_id)10133 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
10134 {
10135 u64 hash = swevent_hash(type, event_id);
10136
10137 return &hlist->heads[hash];
10138 }
10139
10140 /* For the read side: events when they trigger */
10141 static inline struct hlist_head *
find_swevent_head_rcu(struct swevent_htable * swhash,u64 type,u32 event_id)10142 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
10143 {
10144 struct swevent_hlist *hlist;
10145
10146 hlist = rcu_dereference(swhash->swevent_hlist);
10147 if (!hlist)
10148 return NULL;
10149
10150 return __find_swevent_head(hlist, type, event_id);
10151 }
10152
10153 /* For the event head insertion and removal in the hlist */
10154 static inline struct hlist_head *
find_swevent_head(struct swevent_htable * swhash,struct perf_event * event)10155 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
10156 {
10157 struct swevent_hlist *hlist;
10158 u32 event_id = event->attr.config;
10159 u64 type = event->attr.type;
10160
10161 /*
10162 * Event scheduling is always serialized against hlist allocation
10163 * and release. Which makes the protected version suitable here.
10164 * The context lock guarantees that.
10165 */
10166 hlist = rcu_dereference_protected(swhash->swevent_hlist,
10167 lockdep_is_held(&event->ctx->lock));
10168 if (!hlist)
10169 return NULL;
10170
10171 return __find_swevent_head(hlist, type, event_id);
10172 }
10173
do_perf_sw_event(enum perf_type_id type,u32 event_id,u64 nr,struct perf_sample_data * data,struct pt_regs * regs)10174 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
10175 u64 nr,
10176 struct perf_sample_data *data,
10177 struct pt_regs *regs)
10178 {
10179 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
10180 struct perf_event *event;
10181 struct hlist_head *head;
10182
10183 rcu_read_lock();
10184 head = find_swevent_head_rcu(swhash, type, event_id);
10185 if (!head)
10186 goto end;
10187
10188 hlist_for_each_entry_rcu(event, head, hlist_entry) {
10189 if (perf_swevent_match(event, type, event_id, data, regs))
10190 perf_swevent_event(event, nr, data, regs);
10191 }
10192 end:
10193 rcu_read_unlock();
10194 }
10195
10196 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
10197
perf_swevent_get_recursion_context(void)10198 int perf_swevent_get_recursion_context(void)
10199 {
10200 return get_recursion_context(current->perf_recursion);
10201 }
10202 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
10203
perf_swevent_put_recursion_context(int rctx)10204 void perf_swevent_put_recursion_context(int rctx)
10205 {
10206 put_recursion_context(current->perf_recursion, rctx);
10207 }
10208
___perf_sw_event(u32 event_id,u64 nr,struct pt_regs * regs,u64 addr)10209 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
10210 {
10211 struct perf_sample_data data;
10212
10213 if (WARN_ON_ONCE(!regs))
10214 return;
10215
10216 perf_sample_data_init(&data, addr, 0);
10217 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
10218 }
10219
__perf_sw_event(u32 event_id,u64 nr,struct pt_regs * regs,u64 addr)10220 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
10221 {
10222 int rctx;
10223
10224 preempt_disable_notrace();
10225 rctx = perf_swevent_get_recursion_context();
10226 if (unlikely(rctx < 0))
10227 goto fail;
10228
10229 ___perf_sw_event(event_id, nr, regs, addr);
10230
10231 perf_swevent_put_recursion_context(rctx);
10232 fail:
10233 preempt_enable_notrace();
10234 }
10235
perf_swevent_read(struct perf_event * event)10236 static void perf_swevent_read(struct perf_event *event)
10237 {
10238 }
10239
perf_swevent_add(struct perf_event * event,int flags)10240 static int perf_swevent_add(struct perf_event *event, int flags)
10241 {
10242 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
10243 struct hw_perf_event *hwc = &event->hw;
10244 struct hlist_head *head;
10245
10246 if (is_sampling_event(event)) {
10247 hwc->last_period = hwc->sample_period;
10248 perf_swevent_set_period(event);
10249 }
10250
10251 hwc->state = !(flags & PERF_EF_START);
10252
10253 head = find_swevent_head(swhash, event);
10254 if (WARN_ON_ONCE(!head))
10255 return -EINVAL;
10256
10257 hlist_add_head_rcu(&event->hlist_entry, head);
10258 perf_event_update_userpage(event);
10259
10260 return 0;
10261 }
10262
perf_swevent_del(struct perf_event * event,int flags)10263 static void perf_swevent_del(struct perf_event *event, int flags)
10264 {
10265 hlist_del_rcu(&event->hlist_entry);
10266 }
10267
perf_swevent_start(struct perf_event * event,int flags)10268 static void perf_swevent_start(struct perf_event *event, int flags)
10269 {
10270 event->hw.state = 0;
10271 }
10272
perf_swevent_stop(struct perf_event * event,int flags)10273 static void perf_swevent_stop(struct perf_event *event, int flags)
10274 {
10275 event->hw.state = PERF_HES_STOPPED;
10276 }
10277
10278 /* Deref the hlist from the update side */
10279 static inline struct swevent_hlist *
swevent_hlist_deref(struct swevent_htable * swhash)10280 swevent_hlist_deref(struct swevent_htable *swhash)
10281 {
10282 return rcu_dereference_protected(swhash->swevent_hlist,
10283 lockdep_is_held(&swhash->hlist_mutex));
10284 }
10285
swevent_hlist_release(struct swevent_htable * swhash)10286 static void swevent_hlist_release(struct swevent_htable *swhash)
10287 {
10288 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
10289
10290 if (!hlist)
10291 return;
10292
10293 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
10294 kfree_rcu(hlist, rcu_head);
10295 }
10296
swevent_hlist_put_cpu(int cpu)10297 static void swevent_hlist_put_cpu(int cpu)
10298 {
10299 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
10300
10301 mutex_lock(&swhash->hlist_mutex);
10302
10303 if (!--swhash->hlist_refcount)
10304 swevent_hlist_release(swhash);
10305
10306 mutex_unlock(&swhash->hlist_mutex);
10307 }
10308
swevent_hlist_put(void)10309 static void swevent_hlist_put(void)
10310 {
10311 int cpu;
10312
10313 for_each_possible_cpu(cpu)
10314 swevent_hlist_put_cpu(cpu);
10315 }
10316
swevent_hlist_get_cpu(int cpu)10317 static int swevent_hlist_get_cpu(int cpu)
10318 {
10319 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
10320 int err = 0;
10321
10322 mutex_lock(&swhash->hlist_mutex);
10323 if (!swevent_hlist_deref(swhash) &&
10324 cpumask_test_cpu(cpu, perf_online_mask)) {
10325 struct swevent_hlist *hlist;
10326
10327 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
10328 if (!hlist) {
10329 err = -ENOMEM;
10330 goto exit;
10331 }
10332 rcu_assign_pointer(swhash->swevent_hlist, hlist);
10333 }
10334 swhash->hlist_refcount++;
10335 exit:
10336 mutex_unlock(&swhash->hlist_mutex);
10337
10338 return err;
10339 }
10340
swevent_hlist_get(void)10341 static int swevent_hlist_get(void)
10342 {
10343 int err, cpu, failed_cpu;
10344
10345 mutex_lock(&pmus_lock);
10346 for_each_possible_cpu(cpu) {
10347 err = swevent_hlist_get_cpu(cpu);
10348 if (err) {
10349 failed_cpu = cpu;
10350 goto fail;
10351 }
10352 }
10353 mutex_unlock(&pmus_lock);
10354 return 0;
10355 fail:
10356 for_each_possible_cpu(cpu) {
10357 if (cpu == failed_cpu)
10358 break;
10359 swevent_hlist_put_cpu(cpu);
10360 }
10361 mutex_unlock(&pmus_lock);
10362 return err;
10363 }
10364
10365 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
10366
sw_perf_event_destroy(struct perf_event * event)10367 static void sw_perf_event_destroy(struct perf_event *event)
10368 {
10369 u64 event_id = event->attr.config;
10370
10371 WARN_ON(event->parent);
10372
10373 static_key_slow_dec(&perf_swevent_enabled[event_id]);
10374 swevent_hlist_put();
10375 }
10376
10377 static struct pmu perf_cpu_clock; /* fwd declaration */
10378 static struct pmu perf_task_clock;
10379
perf_swevent_init(struct perf_event * event)10380 static int perf_swevent_init(struct perf_event *event)
10381 {
10382 u64 event_id = event->attr.config;
10383
10384 if (event->attr.type != PERF_TYPE_SOFTWARE)
10385 return -ENOENT;
10386
10387 /*
10388 * no branch sampling for software events
10389 */
10390 if (has_branch_stack(event))
10391 return -EOPNOTSUPP;
10392
10393 switch (event_id) {
10394 case PERF_COUNT_SW_CPU_CLOCK:
10395 event->attr.type = perf_cpu_clock.type;
10396 return -ENOENT;
10397 case PERF_COUNT_SW_TASK_CLOCK:
10398 event->attr.type = perf_task_clock.type;
10399 return -ENOENT;
10400
10401 default:
10402 break;
10403 }
10404
10405 if (event_id >= PERF_COUNT_SW_MAX)
10406 return -ENOENT;
10407
10408 if (!event->parent) {
10409 int err;
10410
10411 err = swevent_hlist_get();
10412 if (err)
10413 return err;
10414
10415 static_key_slow_inc(&perf_swevent_enabled[event_id]);
10416 event->destroy = sw_perf_event_destroy;
10417 }
10418
10419 return 0;
10420 }
10421
10422 static struct pmu perf_swevent = {
10423 .task_ctx_nr = perf_sw_context,
10424
10425 .capabilities = PERF_PMU_CAP_NO_NMI,
10426
10427 .event_init = perf_swevent_init,
10428 .add = perf_swevent_add,
10429 .del = perf_swevent_del,
10430 .start = perf_swevent_start,
10431 .stop = perf_swevent_stop,
10432 .read = perf_swevent_read,
10433 };
10434
10435 #ifdef CONFIG_EVENT_TRACING
10436
tp_perf_event_destroy(struct perf_event * event)10437 static void tp_perf_event_destroy(struct perf_event *event)
10438 {
10439 perf_trace_destroy(event);
10440 }
10441
perf_tp_event_init(struct perf_event * event)10442 static int perf_tp_event_init(struct perf_event *event)
10443 {
10444 int err;
10445
10446 if (event->attr.type != PERF_TYPE_TRACEPOINT)
10447 return -ENOENT;
10448
10449 /*
10450 * no branch sampling for tracepoint events
10451 */
10452 if (has_branch_stack(event))
10453 return -EOPNOTSUPP;
10454
10455 err = perf_trace_init(event);
10456 if (err)
10457 return err;
10458
10459 event->destroy = tp_perf_event_destroy;
10460
10461 return 0;
10462 }
10463
10464 static struct pmu perf_tracepoint = {
10465 .task_ctx_nr = perf_sw_context,
10466
10467 .event_init = perf_tp_event_init,
10468 .add = perf_trace_add,
10469 .del = perf_trace_del,
10470 .start = perf_swevent_start,
10471 .stop = perf_swevent_stop,
10472 .read = perf_swevent_read,
10473 };
10474
perf_tp_filter_match(struct perf_event * event,struct perf_raw_record * raw)10475 static int perf_tp_filter_match(struct perf_event *event,
10476 struct perf_raw_record *raw)
10477 {
10478 void *record = raw->frag.data;
10479
10480 /* only top level events have filters set */
10481 if (event->parent)
10482 event = event->parent;
10483
10484 if (likely(!event->filter) || filter_match_preds(event->filter, record))
10485 return 1;
10486 return 0;
10487 }
10488
perf_tp_event_match(struct perf_event * event,struct perf_raw_record * raw,struct pt_regs * regs)10489 static int perf_tp_event_match(struct perf_event *event,
10490 struct perf_raw_record *raw,
10491 struct pt_regs *regs)
10492 {
10493 if (event->hw.state & PERF_HES_STOPPED)
10494 return 0;
10495 /*
10496 * If exclude_kernel, only trace user-space tracepoints (uprobes)
10497 */
10498 if (event->attr.exclude_kernel && !user_mode(regs))
10499 return 0;
10500
10501 if (!perf_tp_filter_match(event, raw))
10502 return 0;
10503
10504 return 1;
10505 }
10506
perf_trace_run_bpf_submit(void * raw_data,int size,int rctx,struct trace_event_call * call,u64 count,struct pt_regs * regs,struct hlist_head * head,struct task_struct * task)10507 void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx,
10508 struct trace_event_call *call, u64 count,
10509 struct pt_regs *regs, struct hlist_head *head,
10510 struct task_struct *task)
10511 {
10512 if (bpf_prog_array_valid(call)) {
10513 *(struct pt_regs **)raw_data = regs;
10514 if (!trace_call_bpf(call, raw_data) || hlist_empty(head)) {
10515 perf_swevent_put_recursion_context(rctx);
10516 return;
10517 }
10518 }
10519 perf_tp_event(call->event.type, count, raw_data, size, regs, head,
10520 rctx, task);
10521 }
10522 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit);
10523
__perf_tp_event_target_task(u64 count,void * record,struct pt_regs * regs,struct perf_sample_data * data,struct perf_raw_record * raw,struct perf_event * event)10524 static void __perf_tp_event_target_task(u64 count, void *record,
10525 struct pt_regs *regs,
10526 struct perf_sample_data *data,
10527 struct perf_raw_record *raw,
10528 struct perf_event *event)
10529 {
10530 struct trace_entry *entry = record;
10531
10532 if (event->attr.config != entry->type)
10533 return;
10534 /* Cannot deliver synchronous signal to other task. */
10535 if (event->attr.sigtrap)
10536 return;
10537 if (perf_tp_event_match(event, raw, regs)) {
10538 perf_sample_data_init(data, 0, 0);
10539 perf_sample_save_raw_data(data, event, raw);
10540 perf_swevent_event(event, count, data, regs);
10541 }
10542 }
10543
perf_tp_event_target_task(u64 count,void * record,struct pt_regs * regs,struct perf_sample_data * data,struct perf_raw_record * raw,struct perf_event_context * ctx)10544 static void perf_tp_event_target_task(u64 count, void *record,
10545 struct pt_regs *regs,
10546 struct perf_sample_data *data,
10547 struct perf_raw_record *raw,
10548 struct perf_event_context *ctx)
10549 {
10550 unsigned int cpu = smp_processor_id();
10551 struct pmu *pmu = &perf_tracepoint;
10552 struct perf_event *event, *sibling;
10553
10554 perf_event_groups_for_cpu_pmu(event, &ctx->pinned_groups, cpu, pmu) {
10555 __perf_tp_event_target_task(count, record, regs, data, raw, event);
10556 for_each_sibling_event(sibling, event)
10557 __perf_tp_event_target_task(count, record, regs, data, raw, sibling);
10558 }
10559
10560 perf_event_groups_for_cpu_pmu(event, &ctx->flexible_groups, cpu, pmu) {
10561 __perf_tp_event_target_task(count, record, regs, data, raw, event);
10562 for_each_sibling_event(sibling, event)
10563 __perf_tp_event_target_task(count, record, regs, data, raw, sibling);
10564 }
10565 }
10566
perf_tp_event(u16 event_type,u64 count,void * record,int entry_size,struct pt_regs * regs,struct hlist_head * head,int rctx,struct task_struct * task)10567 void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size,
10568 struct pt_regs *regs, struct hlist_head *head, int rctx,
10569 struct task_struct *task)
10570 {
10571 struct perf_sample_data data;
10572 struct perf_event *event;
10573
10574 struct perf_raw_record raw = {
10575 .frag = {
10576 .size = entry_size,
10577 .data = record,
10578 },
10579 };
10580
10581 perf_trace_buf_update(record, event_type);
10582
10583 hlist_for_each_entry_rcu(event, head, hlist_entry) {
10584 if (perf_tp_event_match(event, &raw, regs)) {
10585 /*
10586 * Here use the same on-stack perf_sample_data,
10587 * some members in data are event-specific and
10588 * need to be re-computed for different sweveents.
10589 * Re-initialize data->sample_flags safely to avoid
10590 * the problem that next event skips preparing data
10591 * because data->sample_flags is set.
10592 */
10593 perf_sample_data_init(&data, 0, 0);
10594 perf_sample_save_raw_data(&data, event, &raw);
10595 perf_swevent_event(event, count, &data, regs);
10596 }
10597 }
10598
10599 /*
10600 * If we got specified a target task, also iterate its context and
10601 * deliver this event there too.
10602 */
10603 if (task && task != current) {
10604 struct perf_event_context *ctx;
10605
10606 rcu_read_lock();
10607 ctx = rcu_dereference(task->perf_event_ctxp);
10608 if (!ctx)
10609 goto unlock;
10610
10611 raw_spin_lock(&ctx->lock);
10612 perf_tp_event_target_task(count, record, regs, &data, &raw, ctx);
10613 raw_spin_unlock(&ctx->lock);
10614 unlock:
10615 rcu_read_unlock();
10616 }
10617
10618 perf_swevent_put_recursion_context(rctx);
10619 }
10620 EXPORT_SYMBOL_GPL(perf_tp_event);
10621
10622 #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS)
10623 /*
10624 * Flags in config, used by dynamic PMU kprobe and uprobe
10625 * The flags should match following PMU_FORMAT_ATTR().
10626 *
10627 * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe
10628 * if not set, create kprobe/uprobe
10629 *
10630 * The following values specify a reference counter (or semaphore in the
10631 * terminology of tools like dtrace, systemtap, etc.) Userspace Statically
10632 * Defined Tracepoints (USDT). Currently, we use 40 bit for the offset.
10633 *
10634 * PERF_UPROBE_REF_CTR_OFFSET_BITS # of bits in config as th offset
10635 * PERF_UPROBE_REF_CTR_OFFSET_SHIFT # of bits to shift left
10636 */
10637 enum perf_probe_config {
10638 PERF_PROBE_CONFIG_IS_RETPROBE = 1U << 0, /* [k,u]retprobe */
10639 PERF_UPROBE_REF_CTR_OFFSET_BITS = 32,
10640 PERF_UPROBE_REF_CTR_OFFSET_SHIFT = 64 - PERF_UPROBE_REF_CTR_OFFSET_BITS,
10641 };
10642
10643 PMU_FORMAT_ATTR(retprobe, "config:0");
10644 #endif
10645
10646 #ifdef CONFIG_KPROBE_EVENTS
10647 static struct attribute *kprobe_attrs[] = {
10648 &format_attr_retprobe.attr,
10649 NULL,
10650 };
10651
10652 static struct attribute_group kprobe_format_group = {
10653 .name = "format",
10654 .attrs = kprobe_attrs,
10655 };
10656
10657 static const struct attribute_group *kprobe_attr_groups[] = {
10658 &kprobe_format_group,
10659 NULL,
10660 };
10661
10662 static int perf_kprobe_event_init(struct perf_event *event);
10663 static struct pmu perf_kprobe = {
10664 .task_ctx_nr = perf_sw_context,
10665 .event_init = perf_kprobe_event_init,
10666 .add = perf_trace_add,
10667 .del = perf_trace_del,
10668 .start = perf_swevent_start,
10669 .stop = perf_swevent_stop,
10670 .read = perf_swevent_read,
10671 .attr_groups = kprobe_attr_groups,
10672 };
10673
perf_kprobe_event_init(struct perf_event * event)10674 static int perf_kprobe_event_init(struct perf_event *event)
10675 {
10676 int err;
10677 bool is_retprobe;
10678
10679 if (event->attr.type != perf_kprobe.type)
10680 return -ENOENT;
10681
10682 if (!perfmon_capable())
10683 return -EACCES;
10684
10685 /*
10686 * no branch sampling for probe events
10687 */
10688 if (has_branch_stack(event))
10689 return -EOPNOTSUPP;
10690
10691 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
10692 err = perf_kprobe_init(event, is_retprobe);
10693 if (err)
10694 return err;
10695
10696 event->destroy = perf_kprobe_destroy;
10697
10698 return 0;
10699 }
10700 #endif /* CONFIG_KPROBE_EVENTS */
10701
10702 #ifdef CONFIG_UPROBE_EVENTS
10703 PMU_FORMAT_ATTR(ref_ctr_offset, "config:32-63");
10704
10705 static struct attribute *uprobe_attrs[] = {
10706 &format_attr_retprobe.attr,
10707 &format_attr_ref_ctr_offset.attr,
10708 NULL,
10709 };
10710
10711 static struct attribute_group uprobe_format_group = {
10712 .name = "format",
10713 .attrs = uprobe_attrs,
10714 };
10715
10716 static const struct attribute_group *uprobe_attr_groups[] = {
10717 &uprobe_format_group,
10718 NULL,
10719 };
10720
10721 static int perf_uprobe_event_init(struct perf_event *event);
10722 static struct pmu perf_uprobe = {
10723 .task_ctx_nr = perf_sw_context,
10724 .event_init = perf_uprobe_event_init,
10725 .add = perf_trace_add,
10726 .del = perf_trace_del,
10727 .start = perf_swevent_start,
10728 .stop = perf_swevent_stop,
10729 .read = perf_swevent_read,
10730 .attr_groups = uprobe_attr_groups,
10731 };
10732
perf_uprobe_event_init(struct perf_event * event)10733 static int perf_uprobe_event_init(struct perf_event *event)
10734 {
10735 int err;
10736 unsigned long ref_ctr_offset;
10737 bool is_retprobe;
10738
10739 if (event->attr.type != perf_uprobe.type)
10740 return -ENOENT;
10741
10742 if (!capable(CAP_SYS_ADMIN))
10743 return -EACCES;
10744
10745 /*
10746 * no branch sampling for probe events
10747 */
10748 if (has_branch_stack(event))
10749 return -EOPNOTSUPP;
10750
10751 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
10752 ref_ctr_offset = event->attr.config >> PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
10753 err = perf_uprobe_init(event, ref_ctr_offset, is_retprobe);
10754 if (err)
10755 return err;
10756
10757 event->destroy = perf_uprobe_destroy;
10758
10759 return 0;
10760 }
10761 #endif /* CONFIG_UPROBE_EVENTS */
10762
perf_tp_register(void)10763 static inline void perf_tp_register(void)
10764 {
10765 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
10766 #ifdef CONFIG_KPROBE_EVENTS
10767 perf_pmu_register(&perf_kprobe, "kprobe", -1);
10768 #endif
10769 #ifdef CONFIG_UPROBE_EVENTS
10770 perf_pmu_register(&perf_uprobe, "uprobe", -1);
10771 #endif
10772 }
10773
perf_event_free_filter(struct perf_event * event)10774 static void perf_event_free_filter(struct perf_event *event)
10775 {
10776 ftrace_profile_free_filter(event);
10777 }
10778
10779 /*
10780 * returns true if the event is a tracepoint, or a kprobe/upprobe created
10781 * with perf_event_open()
10782 */
perf_event_is_tracing(struct perf_event * event)10783 static inline bool perf_event_is_tracing(struct perf_event *event)
10784 {
10785 if (event->pmu == &perf_tracepoint)
10786 return true;
10787 #ifdef CONFIG_KPROBE_EVENTS
10788 if (event->pmu == &perf_kprobe)
10789 return true;
10790 #endif
10791 #ifdef CONFIG_UPROBE_EVENTS
10792 if (event->pmu == &perf_uprobe)
10793 return true;
10794 #endif
10795 return false;
10796 }
10797
__perf_event_set_bpf_prog(struct perf_event * event,struct bpf_prog * prog,u64 bpf_cookie)10798 static int __perf_event_set_bpf_prog(struct perf_event *event,
10799 struct bpf_prog *prog,
10800 u64 bpf_cookie)
10801 {
10802 bool is_kprobe, is_uprobe, is_tracepoint, is_syscall_tp;
10803
10804 if (!perf_event_is_tracing(event))
10805 return perf_event_set_bpf_handler(event, prog, bpf_cookie);
10806
10807 is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_KPROBE;
10808 is_uprobe = event->tp_event->flags & TRACE_EVENT_FL_UPROBE;
10809 is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT;
10810 is_syscall_tp = is_syscall_trace_event(event->tp_event);
10811 if (!is_kprobe && !is_uprobe && !is_tracepoint && !is_syscall_tp)
10812 /* bpf programs can only be attached to u/kprobe or tracepoint */
10813 return -EINVAL;
10814
10815 if (((is_kprobe || is_uprobe) && prog->type != BPF_PROG_TYPE_KPROBE) ||
10816 (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT) ||
10817 (is_syscall_tp && prog->type != BPF_PROG_TYPE_TRACEPOINT))
10818 return -EINVAL;
10819
10820 if (prog->type == BPF_PROG_TYPE_KPROBE && prog->sleepable && !is_uprobe)
10821 /* only uprobe programs are allowed to be sleepable */
10822 return -EINVAL;
10823
10824 /* Kprobe override only works for kprobes, not uprobes. */
10825 if (prog->kprobe_override && !is_kprobe)
10826 return -EINVAL;
10827
10828 if (is_tracepoint || is_syscall_tp) {
10829 int off = trace_event_get_offsets(event->tp_event);
10830
10831 if (prog->aux->max_ctx_offset > off)
10832 return -EACCES;
10833 }
10834
10835 return perf_event_attach_bpf_prog(event, prog, bpf_cookie);
10836 }
10837
perf_event_set_bpf_prog(struct perf_event * event,struct bpf_prog * prog,u64 bpf_cookie)10838 int perf_event_set_bpf_prog(struct perf_event *event,
10839 struct bpf_prog *prog,
10840 u64 bpf_cookie)
10841 {
10842 struct perf_event_context *ctx;
10843 int ret;
10844
10845 ctx = perf_event_ctx_lock(event);
10846 ret = __perf_event_set_bpf_prog(event, prog, bpf_cookie);
10847 perf_event_ctx_unlock(event, ctx);
10848
10849 return ret;
10850 }
10851
perf_event_free_bpf_prog(struct perf_event * event)10852 void perf_event_free_bpf_prog(struct perf_event *event)
10853 {
10854 if (!perf_event_is_tracing(event)) {
10855 perf_event_free_bpf_handler(event);
10856 return;
10857 }
10858 perf_event_detach_bpf_prog(event);
10859 }
10860
10861 #else
10862
perf_tp_register(void)10863 static inline void perf_tp_register(void)
10864 {
10865 }
10866
perf_event_free_filter(struct perf_event * event)10867 static void perf_event_free_filter(struct perf_event *event)
10868 {
10869 }
10870
__perf_event_set_bpf_prog(struct perf_event * event,struct bpf_prog * prog,u64 bpf_cookie)10871 static int __perf_event_set_bpf_prog(struct perf_event *event,
10872 struct bpf_prog *prog,
10873 u64 bpf_cookie)
10874 {
10875 return -ENOENT;
10876 }
10877
perf_event_set_bpf_prog(struct perf_event * event,struct bpf_prog * prog,u64 bpf_cookie)10878 int perf_event_set_bpf_prog(struct perf_event *event,
10879 struct bpf_prog *prog,
10880 u64 bpf_cookie)
10881 {
10882 return -ENOENT;
10883 }
10884
perf_event_free_bpf_prog(struct perf_event * event)10885 void perf_event_free_bpf_prog(struct perf_event *event)
10886 {
10887 }
10888 #endif /* CONFIG_EVENT_TRACING */
10889
10890 #ifdef CONFIG_HAVE_HW_BREAKPOINT
perf_bp_event(struct perf_event * bp,void * data)10891 void perf_bp_event(struct perf_event *bp, void *data)
10892 {
10893 struct perf_sample_data sample;
10894 struct pt_regs *regs = data;
10895
10896 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
10897
10898 if (!bp->hw.state && !perf_exclude_event(bp, regs))
10899 perf_swevent_event(bp, 1, &sample, regs);
10900 }
10901 #endif
10902
10903 /*
10904 * Allocate a new address filter
10905 */
10906 static struct perf_addr_filter *
perf_addr_filter_new(struct perf_event * event,struct list_head * filters)10907 perf_addr_filter_new(struct perf_event *event, struct list_head *filters)
10908 {
10909 int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu);
10910 struct perf_addr_filter *filter;
10911
10912 filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node);
10913 if (!filter)
10914 return NULL;
10915
10916 INIT_LIST_HEAD(&filter->entry);
10917 list_add_tail(&filter->entry, filters);
10918
10919 return filter;
10920 }
10921
free_filters_list(struct list_head * filters)10922 static void free_filters_list(struct list_head *filters)
10923 {
10924 struct perf_addr_filter *filter, *iter;
10925
10926 list_for_each_entry_safe(filter, iter, filters, entry) {
10927 path_put(&filter->path);
10928 list_del(&filter->entry);
10929 kfree(filter);
10930 }
10931 }
10932
10933 /*
10934 * Free existing address filters and optionally install new ones
10935 */
perf_addr_filters_splice(struct perf_event * event,struct list_head * head)10936 static void perf_addr_filters_splice(struct perf_event *event,
10937 struct list_head *head)
10938 {
10939 unsigned long flags;
10940 LIST_HEAD(list);
10941
10942 if (!has_addr_filter(event))
10943 return;
10944
10945 /* don't bother with children, they don't have their own filters */
10946 if (event->parent)
10947 return;
10948
10949 raw_spin_lock_irqsave(&event->addr_filters.lock, flags);
10950
10951 list_splice_init(&event->addr_filters.list, &list);
10952 if (head)
10953 list_splice(head, &event->addr_filters.list);
10954
10955 raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags);
10956
10957 free_filters_list(&list);
10958 }
10959
10960 /*
10961 * Scan through mm's vmas and see if one of them matches the
10962 * @filter; if so, adjust filter's address range.
10963 * Called with mm::mmap_lock down for reading.
10964 */
perf_addr_filter_apply(struct perf_addr_filter * filter,struct mm_struct * mm,struct perf_addr_filter_range * fr)10965 static void perf_addr_filter_apply(struct perf_addr_filter *filter,
10966 struct mm_struct *mm,
10967 struct perf_addr_filter_range *fr)
10968 {
10969 struct vm_area_struct *vma;
10970 VMA_ITERATOR(vmi, mm, 0);
10971
10972 for_each_vma(vmi, vma) {
10973 if (!vma->vm_file)
10974 continue;
10975
10976 if (perf_addr_filter_vma_adjust(filter, vma, fr))
10977 return;
10978 }
10979 }
10980
10981 /*
10982 * Update event's address range filters based on the
10983 * task's existing mappings, if any.
10984 */
perf_event_addr_filters_apply(struct perf_event * event)10985 static void perf_event_addr_filters_apply(struct perf_event *event)
10986 {
10987 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
10988 struct task_struct *task = READ_ONCE(event->ctx->task);
10989 struct perf_addr_filter *filter;
10990 struct mm_struct *mm = NULL;
10991 unsigned int count = 0;
10992 unsigned long flags;
10993
10994 /*
10995 * We may observe TASK_TOMBSTONE, which means that the event tear-down
10996 * will stop on the parent's child_mutex that our caller is also holding
10997 */
10998 if (task == TASK_TOMBSTONE)
10999 return;
11000
11001 if (ifh->nr_file_filters) {
11002 mm = get_task_mm(task);
11003 if (!mm)
11004 goto restart;
11005
11006 mmap_read_lock(mm);
11007 }
11008
11009 raw_spin_lock_irqsave(&ifh->lock, flags);
11010 list_for_each_entry(filter, &ifh->list, entry) {
11011 if (filter->path.dentry) {
11012 /*
11013 * Adjust base offset if the filter is associated to a
11014 * binary that needs to be mapped:
11015 */
11016 event->addr_filter_ranges[count].start = 0;
11017 event->addr_filter_ranges[count].size = 0;
11018
11019 perf_addr_filter_apply(filter, mm, &event->addr_filter_ranges[count]);
11020 } else {
11021 event->addr_filter_ranges[count].start = filter->offset;
11022 event->addr_filter_ranges[count].size = filter->size;
11023 }
11024
11025 count++;
11026 }
11027
11028 event->addr_filters_gen++;
11029 raw_spin_unlock_irqrestore(&ifh->lock, flags);
11030
11031 if (ifh->nr_file_filters) {
11032 mmap_read_unlock(mm);
11033
11034 mmput(mm);
11035 }
11036
11037 restart:
11038 perf_event_stop(event, 1);
11039 }
11040
11041 /*
11042 * Address range filtering: limiting the data to certain
11043 * instruction address ranges. Filters are ioctl()ed to us from
11044 * userspace as ascii strings.
11045 *
11046 * Filter string format:
11047 *
11048 * ACTION RANGE_SPEC
11049 * where ACTION is one of the
11050 * * "filter": limit the trace to this region
11051 * * "start": start tracing from this address
11052 * * "stop": stop tracing at this address/region;
11053 * RANGE_SPEC is
11054 * * for kernel addresses: <start address>[/<size>]
11055 * * for object files: <start address>[/<size>]@</path/to/object/file>
11056 *
11057 * if <size> is not specified or is zero, the range is treated as a single
11058 * address; not valid for ACTION=="filter".
11059 */
11060 enum {
11061 IF_ACT_NONE = -1,
11062 IF_ACT_FILTER,
11063 IF_ACT_START,
11064 IF_ACT_STOP,
11065 IF_SRC_FILE,
11066 IF_SRC_KERNEL,
11067 IF_SRC_FILEADDR,
11068 IF_SRC_KERNELADDR,
11069 };
11070
11071 enum {
11072 IF_STATE_ACTION = 0,
11073 IF_STATE_SOURCE,
11074 IF_STATE_END,
11075 };
11076
11077 static const match_table_t if_tokens = {
11078 { IF_ACT_FILTER, "filter" },
11079 { IF_ACT_START, "start" },
11080 { IF_ACT_STOP, "stop" },
11081 { IF_SRC_FILE, "%u/%u@%s" },
11082 { IF_SRC_KERNEL, "%u/%u" },
11083 { IF_SRC_FILEADDR, "%u@%s" },
11084 { IF_SRC_KERNELADDR, "%u" },
11085 { IF_ACT_NONE, NULL },
11086 };
11087
11088 /*
11089 * Address filter string parser
11090 */
11091 static int
perf_event_parse_addr_filter(struct perf_event * event,char * fstr,struct list_head * filters)11092 perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
11093 struct list_head *filters)
11094 {
11095 struct perf_addr_filter *filter = NULL;
11096 char *start, *orig, *filename = NULL;
11097 substring_t args[MAX_OPT_ARGS];
11098 int state = IF_STATE_ACTION, token;
11099 unsigned int kernel = 0;
11100 int ret = -EINVAL;
11101
11102 orig = fstr = kstrdup(fstr, GFP_KERNEL);
11103 if (!fstr)
11104 return -ENOMEM;
11105
11106 while ((start = strsep(&fstr, " ,\n")) != NULL) {
11107 static const enum perf_addr_filter_action_t actions[] = {
11108 [IF_ACT_FILTER] = PERF_ADDR_FILTER_ACTION_FILTER,
11109 [IF_ACT_START] = PERF_ADDR_FILTER_ACTION_START,
11110 [IF_ACT_STOP] = PERF_ADDR_FILTER_ACTION_STOP,
11111 };
11112 ret = -EINVAL;
11113
11114 if (!*start)
11115 continue;
11116
11117 /* filter definition begins */
11118 if (state == IF_STATE_ACTION) {
11119 filter = perf_addr_filter_new(event, filters);
11120 if (!filter)
11121 goto fail;
11122 }
11123
11124 token = match_token(start, if_tokens, args);
11125 switch (token) {
11126 case IF_ACT_FILTER:
11127 case IF_ACT_START:
11128 case IF_ACT_STOP:
11129 if (state != IF_STATE_ACTION)
11130 goto fail;
11131
11132 filter->action = actions[token];
11133 state = IF_STATE_SOURCE;
11134 break;
11135
11136 case IF_SRC_KERNELADDR:
11137 case IF_SRC_KERNEL:
11138 kernel = 1;
11139 fallthrough;
11140
11141 case IF_SRC_FILEADDR:
11142 case IF_SRC_FILE:
11143 if (state != IF_STATE_SOURCE)
11144 goto fail;
11145
11146 *args[0].to = 0;
11147 ret = kstrtoul(args[0].from, 0, &filter->offset);
11148 if (ret)
11149 goto fail;
11150
11151 if (token == IF_SRC_KERNEL || token == IF_SRC_FILE) {
11152 *args[1].to = 0;
11153 ret = kstrtoul(args[1].from, 0, &filter->size);
11154 if (ret)
11155 goto fail;
11156 }
11157
11158 if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) {
11159 int fpos = token == IF_SRC_FILE ? 2 : 1;
11160
11161 kfree(filename);
11162 filename = match_strdup(&args[fpos]);
11163 if (!filename) {
11164 ret = -ENOMEM;
11165 goto fail;
11166 }
11167 }
11168
11169 state = IF_STATE_END;
11170 break;
11171
11172 default:
11173 goto fail;
11174 }
11175
11176 /*
11177 * Filter definition is fully parsed, validate and install it.
11178 * Make sure that it doesn't contradict itself or the event's
11179 * attribute.
11180 */
11181 if (state == IF_STATE_END) {
11182 ret = -EINVAL;
11183
11184 /*
11185 * ACTION "filter" must have a non-zero length region
11186 * specified.
11187 */
11188 if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER &&
11189 !filter->size)
11190 goto fail;
11191
11192 if (!kernel) {
11193 if (!filename)
11194 goto fail;
11195
11196 /*
11197 * For now, we only support file-based filters
11198 * in per-task events; doing so for CPU-wide
11199 * events requires additional context switching
11200 * trickery, since same object code will be
11201 * mapped at different virtual addresses in
11202 * different processes.
11203 */
11204 ret = -EOPNOTSUPP;
11205 if (!event->ctx->task)
11206 goto fail;
11207
11208 /* look up the path and grab its inode */
11209 ret = kern_path(filename, LOOKUP_FOLLOW,
11210 &filter->path);
11211 if (ret)
11212 goto fail;
11213
11214 ret = -EINVAL;
11215 if (!filter->path.dentry ||
11216 !S_ISREG(d_inode(filter->path.dentry)
11217 ->i_mode))
11218 goto fail;
11219
11220 event->addr_filters.nr_file_filters++;
11221 }
11222
11223 /* ready to consume more filters */
11224 kfree(filename);
11225 filename = NULL;
11226 state = IF_STATE_ACTION;
11227 filter = NULL;
11228 kernel = 0;
11229 }
11230 }
11231
11232 if (state != IF_STATE_ACTION)
11233 goto fail;
11234
11235 kfree(filename);
11236 kfree(orig);
11237
11238 return 0;
11239
11240 fail:
11241 kfree(filename);
11242 free_filters_list(filters);
11243 kfree(orig);
11244
11245 return ret;
11246 }
11247
11248 static int
perf_event_set_addr_filter(struct perf_event * event,char * filter_str)11249 perf_event_set_addr_filter(struct perf_event *event, char *filter_str)
11250 {
11251 LIST_HEAD(filters);
11252 int ret;
11253
11254 /*
11255 * Since this is called in perf_ioctl() path, we're already holding
11256 * ctx::mutex.
11257 */
11258 lockdep_assert_held(&event->ctx->mutex);
11259
11260 if (WARN_ON_ONCE(event->parent))
11261 return -EINVAL;
11262
11263 ret = perf_event_parse_addr_filter(event, filter_str, &filters);
11264 if (ret)
11265 goto fail_clear_files;
11266
11267 ret = event->pmu->addr_filters_validate(&filters);
11268 if (ret)
11269 goto fail_free_filters;
11270
11271 /* remove existing filters, if any */
11272 perf_addr_filters_splice(event, &filters);
11273
11274 /* install new filters */
11275 perf_event_for_each_child(event, perf_event_addr_filters_apply);
11276
11277 return ret;
11278
11279 fail_free_filters:
11280 free_filters_list(&filters);
11281
11282 fail_clear_files:
11283 event->addr_filters.nr_file_filters = 0;
11284
11285 return ret;
11286 }
11287
perf_event_set_filter(struct perf_event * event,void __user * arg)11288 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
11289 {
11290 int ret = -EINVAL;
11291 char *filter_str;
11292
11293 filter_str = strndup_user(arg, PAGE_SIZE);
11294 if (IS_ERR(filter_str))
11295 return PTR_ERR(filter_str);
11296
11297 #ifdef CONFIG_EVENT_TRACING
11298 if (perf_event_is_tracing(event)) {
11299 struct perf_event_context *ctx = event->ctx;
11300
11301 /*
11302 * Beware, here be dragons!!
11303 *
11304 * the tracepoint muck will deadlock against ctx->mutex, but
11305 * the tracepoint stuff does not actually need it. So
11306 * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we
11307 * already have a reference on ctx.
11308 *
11309 * This can result in event getting moved to a different ctx,
11310 * but that does not affect the tracepoint state.
11311 */
11312 mutex_unlock(&ctx->mutex);
11313 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
11314 mutex_lock(&ctx->mutex);
11315 } else
11316 #endif
11317 if (has_addr_filter(event))
11318 ret = perf_event_set_addr_filter(event, filter_str);
11319
11320 kfree(filter_str);
11321 return ret;
11322 }
11323
11324 /*
11325 * hrtimer based swevent callback
11326 */
11327
perf_swevent_hrtimer(struct hrtimer * hrtimer)11328 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
11329 {
11330 enum hrtimer_restart ret = HRTIMER_RESTART;
11331 struct perf_sample_data data;
11332 struct pt_regs *regs;
11333 struct perf_event *event;
11334 u64 period;
11335
11336 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
11337
11338 if (event->state != PERF_EVENT_STATE_ACTIVE)
11339 return HRTIMER_NORESTART;
11340
11341 event->pmu->read(event);
11342
11343 perf_sample_data_init(&data, 0, event->hw.last_period);
11344 regs = get_irq_regs();
11345
11346 if (regs && !perf_exclude_event(event, regs)) {
11347 if (!(event->attr.exclude_idle && is_idle_task(current)))
11348 if (__perf_event_overflow(event, 1, &data, regs))
11349 ret = HRTIMER_NORESTART;
11350 }
11351
11352 period = max_t(u64, 10000, event->hw.sample_period);
11353 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
11354
11355 return ret;
11356 }
11357
perf_swevent_start_hrtimer(struct perf_event * event)11358 static void perf_swevent_start_hrtimer(struct perf_event *event)
11359 {
11360 struct hw_perf_event *hwc = &event->hw;
11361 s64 period;
11362
11363 if (!is_sampling_event(event))
11364 return;
11365
11366 period = local64_read(&hwc->period_left);
11367 if (period) {
11368 if (period < 0)
11369 period = 10000;
11370
11371 local64_set(&hwc->period_left, 0);
11372 } else {
11373 period = max_t(u64, 10000, hwc->sample_period);
11374 }
11375 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
11376 HRTIMER_MODE_REL_PINNED_HARD);
11377 }
11378
perf_swevent_cancel_hrtimer(struct perf_event * event)11379 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
11380 {
11381 struct hw_perf_event *hwc = &event->hw;
11382
11383 if (is_sampling_event(event)) {
11384 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
11385 local64_set(&hwc->period_left, ktime_to_ns(remaining));
11386
11387 hrtimer_cancel(&hwc->hrtimer);
11388 }
11389 }
11390
perf_swevent_init_hrtimer(struct perf_event * event)11391 static void perf_swevent_init_hrtimer(struct perf_event *event)
11392 {
11393 struct hw_perf_event *hwc = &event->hw;
11394
11395 if (!is_sampling_event(event))
11396 return;
11397
11398 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
11399 hwc->hrtimer.function = perf_swevent_hrtimer;
11400
11401 /*
11402 * Since hrtimers have a fixed rate, we can do a static freq->period
11403 * mapping and avoid the whole period adjust feedback stuff.
11404 */
11405 if (event->attr.freq) {
11406 long freq = event->attr.sample_freq;
11407
11408 event->attr.sample_period = NSEC_PER_SEC / freq;
11409 hwc->sample_period = event->attr.sample_period;
11410 local64_set(&hwc->period_left, hwc->sample_period);
11411 hwc->last_period = hwc->sample_period;
11412 event->attr.freq = 0;
11413 }
11414 }
11415
11416 /*
11417 * Software event: cpu wall time clock
11418 */
11419
cpu_clock_event_update(struct perf_event * event)11420 static void cpu_clock_event_update(struct perf_event *event)
11421 {
11422 s64 prev;
11423 u64 now;
11424
11425 now = local_clock();
11426 prev = local64_xchg(&event->hw.prev_count, now);
11427 local64_add(now - prev, &event->count);
11428 }
11429
cpu_clock_event_start(struct perf_event * event,int flags)11430 static void cpu_clock_event_start(struct perf_event *event, int flags)
11431 {
11432 local64_set(&event->hw.prev_count, local_clock());
11433 perf_swevent_start_hrtimer(event);
11434 }
11435
cpu_clock_event_stop(struct perf_event * event,int flags)11436 static void cpu_clock_event_stop(struct perf_event *event, int flags)
11437 {
11438 perf_swevent_cancel_hrtimer(event);
11439 cpu_clock_event_update(event);
11440 }
11441
cpu_clock_event_add(struct perf_event * event,int flags)11442 static int cpu_clock_event_add(struct perf_event *event, int flags)
11443 {
11444 if (flags & PERF_EF_START)
11445 cpu_clock_event_start(event, flags);
11446 perf_event_update_userpage(event);
11447
11448 return 0;
11449 }
11450
cpu_clock_event_del(struct perf_event * event,int flags)11451 static void cpu_clock_event_del(struct perf_event *event, int flags)
11452 {
11453 cpu_clock_event_stop(event, flags);
11454 }
11455
cpu_clock_event_read(struct perf_event * event)11456 static void cpu_clock_event_read(struct perf_event *event)
11457 {
11458 cpu_clock_event_update(event);
11459 }
11460
cpu_clock_event_init(struct perf_event * event)11461 static int cpu_clock_event_init(struct perf_event *event)
11462 {
11463 if (event->attr.type != perf_cpu_clock.type)
11464 return -ENOENT;
11465
11466 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
11467 return -ENOENT;
11468
11469 /*
11470 * no branch sampling for software events
11471 */
11472 if (has_branch_stack(event))
11473 return -EOPNOTSUPP;
11474
11475 perf_swevent_init_hrtimer(event);
11476
11477 return 0;
11478 }
11479
11480 static struct pmu perf_cpu_clock = {
11481 .task_ctx_nr = perf_sw_context,
11482
11483 .capabilities = PERF_PMU_CAP_NO_NMI,
11484 .dev = PMU_NULL_DEV,
11485
11486 .event_init = cpu_clock_event_init,
11487 .add = cpu_clock_event_add,
11488 .del = cpu_clock_event_del,
11489 .start = cpu_clock_event_start,
11490 .stop = cpu_clock_event_stop,
11491 .read = cpu_clock_event_read,
11492 };
11493
11494 /*
11495 * Software event: task time clock
11496 */
11497
task_clock_event_update(struct perf_event * event,u64 now)11498 static void task_clock_event_update(struct perf_event *event, u64 now)
11499 {
11500 u64 prev;
11501 s64 delta;
11502
11503 prev = local64_xchg(&event->hw.prev_count, now);
11504 delta = now - prev;
11505 local64_add(delta, &event->count);
11506 }
11507
task_clock_event_start(struct perf_event * event,int flags)11508 static void task_clock_event_start(struct perf_event *event, int flags)
11509 {
11510 local64_set(&event->hw.prev_count, event->ctx->time);
11511 perf_swevent_start_hrtimer(event);
11512 }
11513
task_clock_event_stop(struct perf_event * event,int flags)11514 static void task_clock_event_stop(struct perf_event *event, int flags)
11515 {
11516 perf_swevent_cancel_hrtimer(event);
11517 task_clock_event_update(event, event->ctx->time);
11518 }
11519
task_clock_event_add(struct perf_event * event,int flags)11520 static int task_clock_event_add(struct perf_event *event, int flags)
11521 {
11522 if (flags & PERF_EF_START)
11523 task_clock_event_start(event, flags);
11524 perf_event_update_userpage(event);
11525
11526 return 0;
11527 }
11528
task_clock_event_del(struct perf_event * event,int flags)11529 static void task_clock_event_del(struct perf_event *event, int flags)
11530 {
11531 task_clock_event_stop(event, PERF_EF_UPDATE);
11532 }
11533
task_clock_event_read(struct perf_event * event)11534 static void task_clock_event_read(struct perf_event *event)
11535 {
11536 u64 now = perf_clock();
11537 u64 delta = now - event->ctx->timestamp;
11538 u64 time = event->ctx->time + delta;
11539
11540 task_clock_event_update(event, time);
11541 }
11542
task_clock_event_init(struct perf_event * event)11543 static int task_clock_event_init(struct perf_event *event)
11544 {
11545 if (event->attr.type != perf_task_clock.type)
11546 return -ENOENT;
11547
11548 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
11549 return -ENOENT;
11550
11551 /*
11552 * no branch sampling for software events
11553 */
11554 if (has_branch_stack(event))
11555 return -EOPNOTSUPP;
11556
11557 perf_swevent_init_hrtimer(event);
11558
11559 return 0;
11560 }
11561
11562 static struct pmu perf_task_clock = {
11563 .task_ctx_nr = perf_sw_context,
11564
11565 .capabilities = PERF_PMU_CAP_NO_NMI,
11566 .dev = PMU_NULL_DEV,
11567
11568 .event_init = task_clock_event_init,
11569 .add = task_clock_event_add,
11570 .del = task_clock_event_del,
11571 .start = task_clock_event_start,
11572 .stop = task_clock_event_stop,
11573 .read = task_clock_event_read,
11574 };
11575
perf_pmu_nop_void(struct pmu * pmu)11576 static void perf_pmu_nop_void(struct pmu *pmu)
11577 {
11578 }
11579
perf_pmu_nop_txn(struct pmu * pmu,unsigned int flags)11580 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
11581 {
11582 }
11583
perf_pmu_nop_int(struct pmu * pmu)11584 static int perf_pmu_nop_int(struct pmu *pmu)
11585 {
11586 return 0;
11587 }
11588
perf_event_nop_int(struct perf_event * event,u64 value)11589 static int perf_event_nop_int(struct perf_event *event, u64 value)
11590 {
11591 return 0;
11592 }
11593
11594 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
11595
perf_pmu_start_txn(struct pmu * pmu,unsigned int flags)11596 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
11597 {
11598 __this_cpu_write(nop_txn_flags, flags);
11599
11600 if (flags & ~PERF_PMU_TXN_ADD)
11601 return;
11602
11603 perf_pmu_disable(pmu);
11604 }
11605
perf_pmu_commit_txn(struct pmu * pmu)11606 static int perf_pmu_commit_txn(struct pmu *pmu)
11607 {
11608 unsigned int flags = __this_cpu_read(nop_txn_flags);
11609
11610 __this_cpu_write(nop_txn_flags, 0);
11611
11612 if (flags & ~PERF_PMU_TXN_ADD)
11613 return 0;
11614
11615 perf_pmu_enable(pmu);
11616 return 0;
11617 }
11618
perf_pmu_cancel_txn(struct pmu * pmu)11619 static void perf_pmu_cancel_txn(struct pmu *pmu)
11620 {
11621 unsigned int flags = __this_cpu_read(nop_txn_flags);
11622
11623 __this_cpu_write(nop_txn_flags, 0);
11624
11625 if (flags & ~PERF_PMU_TXN_ADD)
11626 return;
11627
11628 perf_pmu_enable(pmu);
11629 }
11630
perf_event_idx_default(struct perf_event * event)11631 static int perf_event_idx_default(struct perf_event *event)
11632 {
11633 return 0;
11634 }
11635
free_pmu_context(struct pmu * pmu)11636 static void free_pmu_context(struct pmu *pmu)
11637 {
11638 free_percpu(pmu->cpu_pmu_context);
11639 }
11640
11641 /*
11642 * Let userspace know that this PMU supports address range filtering:
11643 */
nr_addr_filters_show(struct device * dev,struct device_attribute * attr,char * page)11644 static ssize_t nr_addr_filters_show(struct device *dev,
11645 struct device_attribute *attr,
11646 char *page)
11647 {
11648 struct pmu *pmu = dev_get_drvdata(dev);
11649
11650 return scnprintf(page, PAGE_SIZE - 1, "%d\n", pmu->nr_addr_filters);
11651 }
11652 DEVICE_ATTR_RO(nr_addr_filters);
11653
11654 static struct idr pmu_idr;
11655
11656 static ssize_t
type_show(struct device * dev,struct device_attribute * attr,char * page)11657 type_show(struct device *dev, struct device_attribute *attr, char *page)
11658 {
11659 struct pmu *pmu = dev_get_drvdata(dev);
11660
11661 return scnprintf(page, PAGE_SIZE - 1, "%d\n", pmu->type);
11662 }
11663 static DEVICE_ATTR_RO(type);
11664
11665 static ssize_t
perf_event_mux_interval_ms_show(struct device * dev,struct device_attribute * attr,char * page)11666 perf_event_mux_interval_ms_show(struct device *dev,
11667 struct device_attribute *attr,
11668 char *page)
11669 {
11670 struct pmu *pmu = dev_get_drvdata(dev);
11671
11672 return scnprintf(page, PAGE_SIZE - 1, "%d\n", pmu->hrtimer_interval_ms);
11673 }
11674
11675 static DEFINE_MUTEX(mux_interval_mutex);
11676
11677 static ssize_t
perf_event_mux_interval_ms_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)11678 perf_event_mux_interval_ms_store(struct device *dev,
11679 struct device_attribute *attr,
11680 const char *buf, size_t count)
11681 {
11682 struct pmu *pmu = dev_get_drvdata(dev);
11683 int timer, cpu, ret;
11684
11685 ret = kstrtoint(buf, 0, &timer);
11686 if (ret)
11687 return ret;
11688
11689 if (timer < 1)
11690 return -EINVAL;
11691
11692 /* same value, noting to do */
11693 if (timer == pmu->hrtimer_interval_ms)
11694 return count;
11695
11696 mutex_lock(&mux_interval_mutex);
11697 pmu->hrtimer_interval_ms = timer;
11698
11699 /* update all cpuctx for this PMU */
11700 cpus_read_lock();
11701 for_each_online_cpu(cpu) {
11702 struct perf_cpu_pmu_context *cpc;
11703 cpc = per_cpu_ptr(pmu->cpu_pmu_context, cpu);
11704 cpc->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
11705
11706 cpu_function_call(cpu, perf_mux_hrtimer_restart_ipi, cpc);
11707 }
11708 cpus_read_unlock();
11709 mutex_unlock(&mux_interval_mutex);
11710
11711 return count;
11712 }
11713 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
11714
perf_scope_cpu_topology_cpumask(unsigned int scope,int cpu)11715 static inline const struct cpumask *perf_scope_cpu_topology_cpumask(unsigned int scope, int cpu)
11716 {
11717 switch (scope) {
11718 case PERF_PMU_SCOPE_CORE:
11719 return topology_sibling_cpumask(cpu);
11720 case PERF_PMU_SCOPE_DIE:
11721 return topology_die_cpumask(cpu);
11722 case PERF_PMU_SCOPE_CLUSTER:
11723 return topology_cluster_cpumask(cpu);
11724 case PERF_PMU_SCOPE_PKG:
11725 return topology_core_cpumask(cpu);
11726 case PERF_PMU_SCOPE_SYS_WIDE:
11727 return cpu_online_mask;
11728 }
11729
11730 return NULL;
11731 }
11732
perf_scope_cpumask(unsigned int scope)11733 static inline struct cpumask *perf_scope_cpumask(unsigned int scope)
11734 {
11735 switch (scope) {
11736 case PERF_PMU_SCOPE_CORE:
11737 return perf_online_core_mask;
11738 case PERF_PMU_SCOPE_DIE:
11739 return perf_online_die_mask;
11740 case PERF_PMU_SCOPE_CLUSTER:
11741 return perf_online_cluster_mask;
11742 case PERF_PMU_SCOPE_PKG:
11743 return perf_online_pkg_mask;
11744 case PERF_PMU_SCOPE_SYS_WIDE:
11745 return perf_online_sys_mask;
11746 }
11747
11748 return NULL;
11749 }
11750
cpumask_show(struct device * dev,struct device_attribute * attr,char * buf)11751 static ssize_t cpumask_show(struct device *dev, struct device_attribute *attr,
11752 char *buf)
11753 {
11754 struct pmu *pmu = dev_get_drvdata(dev);
11755 struct cpumask *mask = perf_scope_cpumask(pmu->scope);
11756
11757 if (mask)
11758 return cpumap_print_to_pagebuf(true, buf, mask);
11759 return 0;
11760 }
11761
11762 static DEVICE_ATTR_RO(cpumask);
11763
11764 static struct attribute *pmu_dev_attrs[] = {
11765 &dev_attr_type.attr,
11766 &dev_attr_perf_event_mux_interval_ms.attr,
11767 &dev_attr_nr_addr_filters.attr,
11768 &dev_attr_cpumask.attr,
11769 NULL,
11770 };
11771
pmu_dev_is_visible(struct kobject * kobj,struct attribute * a,int n)11772 static umode_t pmu_dev_is_visible(struct kobject *kobj, struct attribute *a, int n)
11773 {
11774 struct device *dev = kobj_to_dev(kobj);
11775 struct pmu *pmu = dev_get_drvdata(dev);
11776
11777 if (n == 2 && !pmu->nr_addr_filters)
11778 return 0;
11779
11780 /* cpumask */
11781 if (n == 3 && pmu->scope == PERF_PMU_SCOPE_NONE)
11782 return 0;
11783
11784 return a->mode;
11785 }
11786
11787 static struct attribute_group pmu_dev_attr_group = {
11788 .is_visible = pmu_dev_is_visible,
11789 .attrs = pmu_dev_attrs,
11790 };
11791
11792 static const struct attribute_group *pmu_dev_groups[] = {
11793 &pmu_dev_attr_group,
11794 NULL,
11795 };
11796
11797 static int pmu_bus_running;
11798 static struct bus_type pmu_bus = {
11799 .name = "event_source",
11800 .dev_groups = pmu_dev_groups,
11801 };
11802
pmu_dev_release(struct device * dev)11803 static void pmu_dev_release(struct device *dev)
11804 {
11805 kfree(dev);
11806 }
11807
pmu_dev_alloc(struct pmu * pmu)11808 static int pmu_dev_alloc(struct pmu *pmu)
11809 {
11810 int ret = -ENOMEM;
11811
11812 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
11813 if (!pmu->dev)
11814 goto out;
11815
11816 pmu->dev->groups = pmu->attr_groups;
11817 device_initialize(pmu->dev);
11818
11819 dev_set_drvdata(pmu->dev, pmu);
11820 pmu->dev->bus = &pmu_bus;
11821 pmu->dev->parent = pmu->parent;
11822 pmu->dev->release = pmu_dev_release;
11823
11824 ret = dev_set_name(pmu->dev, "%s", pmu->name);
11825 if (ret)
11826 goto free_dev;
11827
11828 ret = device_add(pmu->dev);
11829 if (ret)
11830 goto free_dev;
11831
11832 if (pmu->attr_update) {
11833 ret = sysfs_update_groups(&pmu->dev->kobj, pmu->attr_update);
11834 if (ret)
11835 goto del_dev;
11836 }
11837
11838 out:
11839 return ret;
11840
11841 del_dev:
11842 device_del(pmu->dev);
11843
11844 free_dev:
11845 put_device(pmu->dev);
11846 goto out;
11847 }
11848
11849 static struct lock_class_key cpuctx_mutex;
11850 static struct lock_class_key cpuctx_lock;
11851
idr_cmpxchg(struct idr * idr,unsigned long id,void * old,void * new)11852 static bool idr_cmpxchg(struct idr *idr, unsigned long id, void *old, void *new)
11853 {
11854 void *tmp, *val = idr_find(idr, id);
11855
11856 if (val != old)
11857 return false;
11858
11859 tmp = idr_replace(idr, new, id);
11860 if (IS_ERR(tmp))
11861 return false;
11862
11863 WARN_ON_ONCE(tmp != val);
11864 return true;
11865 }
11866
perf_pmu_register(struct pmu * pmu,const char * name,int type)11867 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
11868 {
11869 int cpu, ret, max = PERF_TYPE_MAX;
11870
11871 mutex_lock(&pmus_lock);
11872 ret = -ENOMEM;
11873 pmu->pmu_disable_count = alloc_percpu(int);
11874 if (!pmu->pmu_disable_count)
11875 goto unlock;
11876
11877 pmu->type = -1;
11878 if (WARN_ONCE(!name, "Can not register anonymous pmu.\n")) {
11879 ret = -EINVAL;
11880 goto free_pdc;
11881 }
11882
11883 if (WARN_ONCE(pmu->scope >= PERF_PMU_MAX_SCOPE, "Can not register a pmu with an invalid scope.\n")) {
11884 ret = -EINVAL;
11885 goto free_pdc;
11886 }
11887
11888 pmu->name = name;
11889
11890 if (type >= 0)
11891 max = type;
11892
11893 ret = idr_alloc(&pmu_idr, NULL, max, 0, GFP_KERNEL);
11894 if (ret < 0)
11895 goto free_pdc;
11896
11897 WARN_ON(type >= 0 && ret != type);
11898
11899 type = ret;
11900 pmu->type = type;
11901 atomic_set(&pmu->exclusive_cnt, 0);
11902
11903 if (pmu_bus_running && !pmu->dev) {
11904 ret = pmu_dev_alloc(pmu);
11905 if (ret)
11906 goto free_idr;
11907 }
11908
11909 ret = -ENOMEM;
11910 pmu->cpu_pmu_context = alloc_percpu(struct perf_cpu_pmu_context);
11911 if (!pmu->cpu_pmu_context)
11912 goto free_dev;
11913
11914 for_each_possible_cpu(cpu) {
11915 struct perf_cpu_pmu_context *cpc;
11916
11917 cpc = per_cpu_ptr(pmu->cpu_pmu_context, cpu);
11918 __perf_init_event_pmu_context(&cpc->epc, pmu);
11919 __perf_mux_hrtimer_init(cpc, cpu);
11920 }
11921
11922 if (!pmu->start_txn) {
11923 if (pmu->pmu_enable) {
11924 /*
11925 * If we have pmu_enable/pmu_disable calls, install
11926 * transaction stubs that use that to try and batch
11927 * hardware accesses.
11928 */
11929 pmu->start_txn = perf_pmu_start_txn;
11930 pmu->commit_txn = perf_pmu_commit_txn;
11931 pmu->cancel_txn = perf_pmu_cancel_txn;
11932 } else {
11933 pmu->start_txn = perf_pmu_nop_txn;
11934 pmu->commit_txn = perf_pmu_nop_int;
11935 pmu->cancel_txn = perf_pmu_nop_void;
11936 }
11937 }
11938
11939 if (!pmu->pmu_enable) {
11940 pmu->pmu_enable = perf_pmu_nop_void;
11941 pmu->pmu_disable = perf_pmu_nop_void;
11942 }
11943
11944 if (!pmu->check_period)
11945 pmu->check_period = perf_event_nop_int;
11946
11947 if (!pmu->event_idx)
11948 pmu->event_idx = perf_event_idx_default;
11949
11950 /*
11951 * Now that the PMU is complete, make it visible to perf_try_init_event().
11952 */
11953 if (!idr_cmpxchg(&pmu_idr, pmu->type, NULL, pmu))
11954 goto free_context;
11955 list_add_rcu(&pmu->entry, &pmus);
11956
11957 ret = 0;
11958 unlock:
11959 mutex_unlock(&pmus_lock);
11960
11961 return ret;
11962
11963 free_context:
11964 free_percpu(pmu->cpu_pmu_context);
11965
11966 free_dev:
11967 if (pmu->dev && pmu->dev != PMU_NULL_DEV) {
11968 device_del(pmu->dev);
11969 put_device(pmu->dev);
11970 }
11971
11972 free_idr:
11973 idr_remove(&pmu_idr, pmu->type);
11974
11975 free_pdc:
11976 free_percpu(pmu->pmu_disable_count);
11977 goto unlock;
11978 }
11979 EXPORT_SYMBOL_GPL(perf_pmu_register);
11980
perf_pmu_unregister(struct pmu * pmu)11981 void perf_pmu_unregister(struct pmu *pmu)
11982 {
11983 mutex_lock(&pmus_lock);
11984 list_del_rcu(&pmu->entry);
11985 idr_remove(&pmu_idr, pmu->type);
11986 mutex_unlock(&pmus_lock);
11987
11988 /*
11989 * We dereference the pmu list under both SRCU and regular RCU, so
11990 * synchronize against both of those.
11991 */
11992 synchronize_srcu(&pmus_srcu);
11993 synchronize_rcu();
11994
11995 free_percpu(pmu->pmu_disable_count);
11996 if (pmu_bus_running && pmu->dev && pmu->dev != PMU_NULL_DEV) {
11997 if (pmu->nr_addr_filters)
11998 device_remove_file(pmu->dev, &dev_attr_nr_addr_filters);
11999 device_del(pmu->dev);
12000 put_device(pmu->dev);
12001 }
12002 free_pmu_context(pmu);
12003 }
12004 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
12005
has_extended_regs(struct perf_event * event)12006 static inline bool has_extended_regs(struct perf_event *event)
12007 {
12008 return (event->attr.sample_regs_user & PERF_REG_EXTENDED_MASK) ||
12009 (event->attr.sample_regs_intr & PERF_REG_EXTENDED_MASK);
12010 }
12011
perf_try_init_event(struct pmu * pmu,struct perf_event * event)12012 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
12013 {
12014 struct perf_event_context *ctx = NULL;
12015 int ret;
12016
12017 if (!try_module_get(pmu->module))
12018 return -ENODEV;
12019
12020 /*
12021 * A number of pmu->event_init() methods iterate the sibling_list to,
12022 * for example, validate if the group fits on the PMU. Therefore,
12023 * if this is a sibling event, acquire the ctx->mutex to protect
12024 * the sibling_list.
12025 */
12026 if (event->group_leader != event && pmu->task_ctx_nr != perf_sw_context) {
12027 /*
12028 * This ctx->mutex can nest when we're called through
12029 * inheritance. See the perf_event_ctx_lock_nested() comment.
12030 */
12031 ctx = perf_event_ctx_lock_nested(event->group_leader,
12032 SINGLE_DEPTH_NESTING);
12033 BUG_ON(!ctx);
12034 }
12035
12036 event->pmu = pmu;
12037 ret = pmu->event_init(event);
12038
12039 if (ctx)
12040 perf_event_ctx_unlock(event->group_leader, ctx);
12041
12042 if (ret)
12043 goto err_pmu;
12044
12045 if (!(pmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS) &&
12046 has_extended_regs(event)) {
12047 ret = -EOPNOTSUPP;
12048 goto err_destroy;
12049 }
12050
12051 if (pmu->capabilities & PERF_PMU_CAP_NO_EXCLUDE &&
12052 event_has_any_exclude_flag(event)) {
12053 ret = -EINVAL;
12054 goto err_destroy;
12055 }
12056
12057 if (pmu->scope != PERF_PMU_SCOPE_NONE && event->cpu >= 0) {
12058 const struct cpumask *cpumask;
12059 struct cpumask *pmu_cpumask;
12060 int cpu;
12061
12062 cpumask = perf_scope_cpu_topology_cpumask(pmu->scope, event->cpu);
12063 pmu_cpumask = perf_scope_cpumask(pmu->scope);
12064
12065 ret = -ENODEV;
12066 if (!pmu_cpumask || !cpumask)
12067 goto err_destroy;
12068
12069 cpu = cpumask_any_and(pmu_cpumask, cpumask);
12070 if (cpu >= nr_cpu_ids)
12071 goto err_destroy;
12072
12073 event->event_caps |= PERF_EV_CAP_READ_SCOPE;
12074 }
12075
12076 return 0;
12077
12078 err_destroy:
12079 if (event->destroy) {
12080 event->destroy(event);
12081 event->destroy = NULL;
12082 }
12083
12084 err_pmu:
12085 event->pmu = NULL;
12086 module_put(pmu->module);
12087 return ret;
12088 }
12089
perf_init_event(struct perf_event * event)12090 static struct pmu *perf_init_event(struct perf_event *event)
12091 {
12092 bool extended_type = false;
12093 int idx, type, ret;
12094 struct pmu *pmu;
12095
12096 idx = srcu_read_lock(&pmus_srcu);
12097
12098 /*
12099 * Save original type before calling pmu->event_init() since certain
12100 * pmus overwrites event->attr.type to forward event to another pmu.
12101 */
12102 event->orig_type = event->attr.type;
12103
12104 /* Try parent's PMU first: */
12105 if (event->parent && event->parent->pmu) {
12106 pmu = event->parent->pmu;
12107 ret = perf_try_init_event(pmu, event);
12108 if (!ret)
12109 goto unlock;
12110 }
12111
12112 /*
12113 * PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE
12114 * are often aliases for PERF_TYPE_RAW.
12115 */
12116 type = event->attr.type;
12117 if (type == PERF_TYPE_HARDWARE || type == PERF_TYPE_HW_CACHE) {
12118 type = event->attr.config >> PERF_PMU_TYPE_SHIFT;
12119 if (!type) {
12120 type = PERF_TYPE_RAW;
12121 } else {
12122 extended_type = true;
12123 event->attr.config &= PERF_HW_EVENT_MASK;
12124 }
12125 }
12126
12127 again:
12128 rcu_read_lock();
12129 pmu = idr_find(&pmu_idr, type);
12130 rcu_read_unlock();
12131 if (pmu) {
12132 if (event->attr.type != type && type != PERF_TYPE_RAW &&
12133 !(pmu->capabilities & PERF_PMU_CAP_EXTENDED_HW_TYPE))
12134 goto fail;
12135
12136 ret = perf_try_init_event(pmu, event);
12137 if (ret == -ENOENT && event->attr.type != type && !extended_type) {
12138 type = event->attr.type;
12139 goto again;
12140 }
12141
12142 if (ret)
12143 pmu = ERR_PTR(ret);
12144
12145 goto unlock;
12146 }
12147
12148 list_for_each_entry_rcu(pmu, &pmus, entry, lockdep_is_held(&pmus_srcu)) {
12149 ret = perf_try_init_event(pmu, event);
12150 if (!ret)
12151 goto unlock;
12152
12153 if (ret != -ENOENT) {
12154 pmu = ERR_PTR(ret);
12155 goto unlock;
12156 }
12157 }
12158 fail:
12159 pmu = ERR_PTR(-ENOENT);
12160 unlock:
12161 srcu_read_unlock(&pmus_srcu, idx);
12162
12163 return pmu;
12164 }
12165
attach_sb_event(struct perf_event * event)12166 static void attach_sb_event(struct perf_event *event)
12167 {
12168 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
12169
12170 raw_spin_lock(&pel->lock);
12171 list_add_rcu(&event->sb_list, &pel->list);
12172 raw_spin_unlock(&pel->lock);
12173 }
12174
12175 /*
12176 * We keep a list of all !task (and therefore per-cpu) events
12177 * that need to receive side-band records.
12178 *
12179 * This avoids having to scan all the various PMU per-cpu contexts
12180 * looking for them.
12181 */
account_pmu_sb_event(struct perf_event * event)12182 static void account_pmu_sb_event(struct perf_event *event)
12183 {
12184 if (is_sb_event(event))
12185 attach_sb_event(event);
12186 }
12187
12188 /* Freq events need the tick to stay alive (see perf_event_task_tick). */
account_freq_event_nohz(void)12189 static void account_freq_event_nohz(void)
12190 {
12191 #ifdef CONFIG_NO_HZ_FULL
12192 /* Lock so we don't race with concurrent unaccount */
12193 spin_lock(&nr_freq_lock);
12194 if (atomic_inc_return(&nr_freq_events) == 1)
12195 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS);
12196 spin_unlock(&nr_freq_lock);
12197 #endif
12198 }
12199
account_freq_event(void)12200 static void account_freq_event(void)
12201 {
12202 if (tick_nohz_full_enabled())
12203 account_freq_event_nohz();
12204 else
12205 atomic_inc(&nr_freq_events);
12206 }
12207
12208
account_event(struct perf_event * event)12209 static void account_event(struct perf_event *event)
12210 {
12211 bool inc = false;
12212
12213 if (event->parent)
12214 return;
12215
12216 if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB))
12217 inc = true;
12218 if (event->attr.mmap || event->attr.mmap_data)
12219 atomic_inc(&nr_mmap_events);
12220 if (event->attr.build_id)
12221 atomic_inc(&nr_build_id_events);
12222 if (event->attr.comm)
12223 atomic_inc(&nr_comm_events);
12224 if (event->attr.namespaces)
12225 atomic_inc(&nr_namespaces_events);
12226 if (event->attr.cgroup)
12227 atomic_inc(&nr_cgroup_events);
12228 if (event->attr.task)
12229 atomic_inc(&nr_task_events);
12230 if (event->attr.freq)
12231 account_freq_event();
12232 if (event->attr.context_switch) {
12233 atomic_inc(&nr_switch_events);
12234 inc = true;
12235 }
12236 if (has_branch_stack(event))
12237 inc = true;
12238 if (is_cgroup_event(event))
12239 inc = true;
12240 if (event->attr.ksymbol)
12241 atomic_inc(&nr_ksymbol_events);
12242 if (event->attr.bpf_event)
12243 atomic_inc(&nr_bpf_events);
12244 if (event->attr.text_poke)
12245 atomic_inc(&nr_text_poke_events);
12246
12247 if (inc) {
12248 /*
12249 * We need the mutex here because static_branch_enable()
12250 * must complete *before* the perf_sched_count increment
12251 * becomes visible.
12252 */
12253 if (atomic_inc_not_zero(&perf_sched_count))
12254 goto enabled;
12255
12256 mutex_lock(&perf_sched_mutex);
12257 if (!atomic_read(&perf_sched_count)) {
12258 static_branch_enable(&perf_sched_events);
12259 /*
12260 * Guarantee that all CPUs observe they key change and
12261 * call the perf scheduling hooks before proceeding to
12262 * install events that need them.
12263 */
12264 synchronize_rcu();
12265 }
12266 /*
12267 * Now that we have waited for the sync_sched(), allow further
12268 * increments to by-pass the mutex.
12269 */
12270 atomic_inc(&perf_sched_count);
12271 mutex_unlock(&perf_sched_mutex);
12272 }
12273 enabled:
12274
12275 account_pmu_sb_event(event);
12276 }
12277
12278 /*
12279 * Allocate and initialize an event structure
12280 */
12281 static struct perf_event *
perf_event_alloc(struct perf_event_attr * attr,int cpu,struct task_struct * task,struct perf_event * group_leader,struct perf_event * parent_event,perf_overflow_handler_t overflow_handler,void * context,int cgroup_fd)12282 perf_event_alloc(struct perf_event_attr *attr, int cpu,
12283 struct task_struct *task,
12284 struct perf_event *group_leader,
12285 struct perf_event *parent_event,
12286 perf_overflow_handler_t overflow_handler,
12287 void *context, int cgroup_fd)
12288 {
12289 struct pmu *pmu;
12290 struct perf_event *event;
12291 struct hw_perf_event *hwc;
12292 long err = -EINVAL;
12293 int node;
12294
12295 if ((unsigned)cpu >= nr_cpu_ids) {
12296 if (!task || cpu != -1)
12297 return ERR_PTR(-EINVAL);
12298 }
12299 if (attr->sigtrap && !task) {
12300 /* Requires a task: avoid signalling random tasks. */
12301 return ERR_PTR(-EINVAL);
12302 }
12303
12304 node = (cpu >= 0) ? cpu_to_node(cpu) : -1;
12305 event = kmem_cache_alloc_node(perf_event_cache, GFP_KERNEL | __GFP_ZERO,
12306 node);
12307 if (!event)
12308 return ERR_PTR(-ENOMEM);
12309
12310 /*
12311 * Single events are their own group leaders, with an
12312 * empty sibling list:
12313 */
12314 if (!group_leader)
12315 group_leader = event;
12316
12317 mutex_init(&event->child_mutex);
12318 INIT_LIST_HEAD(&event->child_list);
12319
12320 INIT_LIST_HEAD(&event->event_entry);
12321 INIT_LIST_HEAD(&event->sibling_list);
12322 INIT_LIST_HEAD(&event->active_list);
12323 init_event_group(event);
12324 INIT_LIST_HEAD(&event->rb_entry);
12325 INIT_LIST_HEAD(&event->active_entry);
12326 INIT_LIST_HEAD(&event->addr_filters.list);
12327 INIT_HLIST_NODE(&event->hlist_entry);
12328
12329
12330 init_waitqueue_head(&event->waitq);
12331 init_irq_work(&event->pending_irq, perf_pending_irq);
12332 event->pending_disable_irq = IRQ_WORK_INIT_HARD(perf_pending_disable);
12333 init_task_work(&event->pending_task, perf_pending_task);
12334
12335 mutex_init(&event->mmap_mutex);
12336 raw_spin_lock_init(&event->addr_filters.lock);
12337
12338 atomic_long_set(&event->refcount, 1);
12339 event->cpu = cpu;
12340 event->attr = *attr;
12341 event->group_leader = group_leader;
12342 event->pmu = NULL;
12343 event->oncpu = -1;
12344
12345 event->parent = parent_event;
12346
12347 event->ns = get_pid_ns(task_active_pid_ns(current));
12348 event->id = atomic64_inc_return(&perf_event_id);
12349
12350 event->state = PERF_EVENT_STATE_INACTIVE;
12351
12352 if (parent_event)
12353 event->event_caps = parent_event->event_caps;
12354
12355 if (task) {
12356 event->attach_state = PERF_ATTACH_TASK;
12357 /*
12358 * XXX pmu::event_init needs to know what task to account to
12359 * and we cannot use the ctx information because we need the
12360 * pmu before we get a ctx.
12361 */
12362 event->hw.target = get_task_struct(task);
12363 }
12364
12365 event->clock = &local_clock;
12366 if (parent_event)
12367 event->clock = parent_event->clock;
12368
12369 if (!overflow_handler && parent_event) {
12370 overflow_handler = parent_event->overflow_handler;
12371 context = parent_event->overflow_handler_context;
12372 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING)
12373 if (parent_event->prog) {
12374 struct bpf_prog *prog = parent_event->prog;
12375
12376 bpf_prog_inc(prog);
12377 event->prog = prog;
12378 }
12379 #endif
12380 }
12381
12382 if (overflow_handler) {
12383 event->overflow_handler = overflow_handler;
12384 event->overflow_handler_context = context;
12385 } else if (is_write_backward(event)){
12386 event->overflow_handler = perf_event_output_backward;
12387 event->overflow_handler_context = NULL;
12388 } else {
12389 event->overflow_handler = perf_event_output_forward;
12390 event->overflow_handler_context = NULL;
12391 }
12392
12393 perf_event__state_init(event);
12394
12395 pmu = NULL;
12396
12397 hwc = &event->hw;
12398 hwc->sample_period = attr->sample_period;
12399 if (attr->freq && attr->sample_freq)
12400 hwc->sample_period = 1;
12401 hwc->last_period = hwc->sample_period;
12402
12403 local64_set(&hwc->period_left, hwc->sample_period);
12404
12405 /*
12406 * We do not support PERF_SAMPLE_READ on inherited events unless
12407 * PERF_SAMPLE_TID is also selected, which allows inherited events to
12408 * collect per-thread samples.
12409 * See perf_output_read().
12410 */
12411 if (has_inherit_and_sample_read(attr) && !(attr->sample_type & PERF_SAMPLE_TID))
12412 goto err;
12413
12414 if (!has_branch_stack(event))
12415 event->attr.branch_sample_type = 0;
12416
12417 pmu = perf_init_event(event);
12418 if (IS_ERR(pmu)) {
12419 err = PTR_ERR(pmu);
12420 goto err;
12421 }
12422
12423 /*
12424 * Disallow uncore-task events. Similarly, disallow uncore-cgroup
12425 * events (they don't make sense as the cgroup will be different
12426 * on other CPUs in the uncore mask).
12427 */
12428 if (pmu->task_ctx_nr == perf_invalid_context && (task || cgroup_fd != -1)) {
12429 err = -EINVAL;
12430 goto err;
12431 }
12432
12433 if (event->attr.aux_output &&
12434 (!(pmu->capabilities & PERF_PMU_CAP_AUX_OUTPUT) ||
12435 event->attr.aux_pause || event->attr.aux_resume)) {
12436 err = -EOPNOTSUPP;
12437 goto err;
12438 }
12439
12440 if (event->attr.aux_pause && event->attr.aux_resume) {
12441 err = -EINVAL;
12442 goto err;
12443 }
12444
12445 if (event->attr.aux_start_paused) {
12446 if (!(pmu->capabilities & PERF_PMU_CAP_AUX_PAUSE)) {
12447 err = -EOPNOTSUPP;
12448 goto err;
12449 }
12450 event->hw.aux_paused = 1;
12451 }
12452
12453 if (cgroup_fd != -1) {
12454 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
12455 if (err)
12456 goto err;
12457 }
12458
12459 err = exclusive_event_init(event);
12460 if (err)
12461 goto err;
12462
12463 if (has_addr_filter(event)) {
12464 event->addr_filter_ranges = kcalloc(pmu->nr_addr_filters,
12465 sizeof(struct perf_addr_filter_range),
12466 GFP_KERNEL);
12467 if (!event->addr_filter_ranges) {
12468 err = -ENOMEM;
12469 goto err;
12470 }
12471
12472 /*
12473 * Clone the parent's vma offsets: they are valid until exec()
12474 * even if the mm is not shared with the parent.
12475 */
12476 if (event->parent) {
12477 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
12478
12479 raw_spin_lock_irq(&ifh->lock);
12480 memcpy(event->addr_filter_ranges,
12481 event->parent->addr_filter_ranges,
12482 pmu->nr_addr_filters * sizeof(struct perf_addr_filter_range));
12483 raw_spin_unlock_irq(&ifh->lock);
12484 }
12485
12486 /* force hw sync on the address filters */
12487 event->addr_filters_gen = 1;
12488 }
12489
12490 if (!event->parent) {
12491 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
12492 err = get_callchain_buffers(attr->sample_max_stack);
12493 if (err)
12494 goto err;
12495 event->attach_state |= PERF_ATTACH_CALLCHAIN;
12496 }
12497 }
12498
12499 err = security_perf_event_alloc(event);
12500 if (err)
12501 goto err;
12502
12503 /* symmetric to unaccount_event() in _free_event() */
12504 account_event(event);
12505
12506 return event;
12507
12508 err:
12509 __free_event(event);
12510 return ERR_PTR(err);
12511 }
12512
perf_copy_attr(struct perf_event_attr __user * uattr,struct perf_event_attr * attr)12513 static int perf_copy_attr(struct perf_event_attr __user *uattr,
12514 struct perf_event_attr *attr)
12515 {
12516 u32 size;
12517 int ret;
12518
12519 /* Zero the full structure, so that a short copy will be nice. */
12520 memset(attr, 0, sizeof(*attr));
12521
12522 ret = get_user(size, &uattr->size);
12523 if (ret)
12524 return ret;
12525
12526 /* ABI compatibility quirk: */
12527 if (!size)
12528 size = PERF_ATTR_SIZE_VER0;
12529 if (size < PERF_ATTR_SIZE_VER0 || size > PAGE_SIZE)
12530 goto err_size;
12531
12532 ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size);
12533 if (ret) {
12534 if (ret == -E2BIG)
12535 goto err_size;
12536 return ret;
12537 }
12538
12539 attr->size = size;
12540
12541 if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3)
12542 return -EINVAL;
12543
12544 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
12545 return -EINVAL;
12546
12547 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
12548 return -EINVAL;
12549
12550 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
12551 u64 mask = attr->branch_sample_type;
12552
12553 /* only using defined bits */
12554 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
12555 return -EINVAL;
12556
12557 /* at least one branch bit must be set */
12558 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
12559 return -EINVAL;
12560
12561 /* propagate priv level, when not set for branch */
12562 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
12563
12564 /* exclude_kernel checked on syscall entry */
12565 if (!attr->exclude_kernel)
12566 mask |= PERF_SAMPLE_BRANCH_KERNEL;
12567
12568 if (!attr->exclude_user)
12569 mask |= PERF_SAMPLE_BRANCH_USER;
12570
12571 if (!attr->exclude_hv)
12572 mask |= PERF_SAMPLE_BRANCH_HV;
12573 /*
12574 * adjust user setting (for HW filter setup)
12575 */
12576 attr->branch_sample_type = mask;
12577 }
12578 /* privileged levels capture (kernel, hv): check permissions */
12579 if (mask & PERF_SAMPLE_BRANCH_PERM_PLM) {
12580 ret = perf_allow_kernel(attr);
12581 if (ret)
12582 return ret;
12583 }
12584 }
12585
12586 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
12587 ret = perf_reg_validate(attr->sample_regs_user);
12588 if (ret)
12589 return ret;
12590 }
12591
12592 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
12593 if (!arch_perf_have_user_stack_dump())
12594 return -ENOSYS;
12595
12596 /*
12597 * We have __u32 type for the size, but so far
12598 * we can only use __u16 as maximum due to the
12599 * __u16 sample size limit.
12600 */
12601 if (attr->sample_stack_user >= USHRT_MAX)
12602 return -EINVAL;
12603 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
12604 return -EINVAL;
12605 }
12606
12607 if (!attr->sample_max_stack)
12608 attr->sample_max_stack = sysctl_perf_event_max_stack;
12609
12610 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
12611 ret = perf_reg_validate(attr->sample_regs_intr);
12612
12613 #ifndef CONFIG_CGROUP_PERF
12614 if (attr->sample_type & PERF_SAMPLE_CGROUP)
12615 return -EINVAL;
12616 #endif
12617 if ((attr->sample_type & PERF_SAMPLE_WEIGHT) &&
12618 (attr->sample_type & PERF_SAMPLE_WEIGHT_STRUCT))
12619 return -EINVAL;
12620
12621 if (!attr->inherit && attr->inherit_thread)
12622 return -EINVAL;
12623
12624 if (attr->remove_on_exec && attr->enable_on_exec)
12625 return -EINVAL;
12626
12627 if (attr->sigtrap && !attr->remove_on_exec)
12628 return -EINVAL;
12629
12630 out:
12631 return ret;
12632
12633 err_size:
12634 put_user(sizeof(*attr), &uattr->size);
12635 ret = -E2BIG;
12636 goto out;
12637 }
12638
mutex_lock_double(struct mutex * a,struct mutex * b)12639 static void mutex_lock_double(struct mutex *a, struct mutex *b)
12640 {
12641 if (b < a)
12642 swap(a, b);
12643
12644 mutex_lock(a);
12645 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
12646 }
12647
12648 static int
perf_event_set_output(struct perf_event * event,struct perf_event * output_event)12649 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
12650 {
12651 struct perf_buffer *rb = NULL;
12652 int ret = -EINVAL;
12653
12654 if (!output_event) {
12655 mutex_lock(&event->mmap_mutex);
12656 goto set;
12657 }
12658
12659 /* don't allow circular references */
12660 if (event == output_event)
12661 goto out;
12662
12663 /*
12664 * Don't allow cross-cpu buffers
12665 */
12666 if (output_event->cpu != event->cpu)
12667 goto out;
12668
12669 /*
12670 * If its not a per-cpu rb, it must be the same task.
12671 */
12672 if (output_event->cpu == -1 && output_event->hw.target != event->hw.target)
12673 goto out;
12674
12675 /*
12676 * Mixing clocks in the same buffer is trouble you don't need.
12677 */
12678 if (output_event->clock != event->clock)
12679 goto out;
12680
12681 /*
12682 * Either writing ring buffer from beginning or from end.
12683 * Mixing is not allowed.
12684 */
12685 if (is_write_backward(output_event) != is_write_backward(event))
12686 goto out;
12687
12688 /*
12689 * If both events generate aux data, they must be on the same PMU
12690 */
12691 if (has_aux(event) && has_aux(output_event) &&
12692 event->pmu != output_event->pmu)
12693 goto out;
12694
12695 /*
12696 * Hold both mmap_mutex to serialize against perf_mmap_close(). Since
12697 * output_event is already on rb->event_list, and the list iteration
12698 * restarts after every removal, it is guaranteed this new event is
12699 * observed *OR* if output_event is already removed, it's guaranteed we
12700 * observe !rb->mmap_count.
12701 */
12702 mutex_lock_double(&event->mmap_mutex, &output_event->mmap_mutex);
12703 set:
12704 /* Can't redirect output if we've got an active mmap() */
12705 if (atomic_read(&event->mmap_count))
12706 goto unlock;
12707
12708 if (output_event) {
12709 /* get the rb we want to redirect to */
12710 rb = ring_buffer_get(output_event);
12711 if (!rb)
12712 goto unlock;
12713
12714 /* did we race against perf_mmap_close() */
12715 if (!atomic_read(&rb->mmap_count)) {
12716 ring_buffer_put(rb);
12717 goto unlock;
12718 }
12719 }
12720
12721 ring_buffer_attach(event, rb);
12722
12723 ret = 0;
12724 unlock:
12725 mutex_unlock(&event->mmap_mutex);
12726 if (output_event)
12727 mutex_unlock(&output_event->mmap_mutex);
12728
12729 out:
12730 return ret;
12731 }
12732
perf_event_set_clock(struct perf_event * event,clockid_t clk_id)12733 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
12734 {
12735 bool nmi_safe = false;
12736
12737 switch (clk_id) {
12738 case CLOCK_MONOTONIC:
12739 event->clock = &ktime_get_mono_fast_ns;
12740 nmi_safe = true;
12741 break;
12742
12743 case CLOCK_MONOTONIC_RAW:
12744 event->clock = &ktime_get_raw_fast_ns;
12745 nmi_safe = true;
12746 break;
12747
12748 case CLOCK_REALTIME:
12749 event->clock = &ktime_get_real_ns;
12750 break;
12751
12752 case CLOCK_BOOTTIME:
12753 event->clock = &ktime_get_boottime_ns;
12754 break;
12755
12756 case CLOCK_TAI:
12757 event->clock = &ktime_get_clocktai_ns;
12758 break;
12759
12760 default:
12761 return -EINVAL;
12762 }
12763
12764 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
12765 return -EINVAL;
12766
12767 return 0;
12768 }
12769
12770 static bool
perf_check_permission(struct perf_event_attr * attr,struct task_struct * task)12771 perf_check_permission(struct perf_event_attr *attr, struct task_struct *task)
12772 {
12773 unsigned int ptrace_mode = PTRACE_MODE_READ_REALCREDS;
12774 bool is_capable = perfmon_capable();
12775
12776 if (attr->sigtrap) {
12777 /*
12778 * perf_event_attr::sigtrap sends signals to the other task.
12779 * Require the current task to also have CAP_KILL.
12780 */
12781 rcu_read_lock();
12782 is_capable &= ns_capable(__task_cred(task)->user_ns, CAP_KILL);
12783 rcu_read_unlock();
12784
12785 /*
12786 * If the required capabilities aren't available, checks for
12787 * ptrace permissions: upgrade to ATTACH, since sending signals
12788 * can effectively change the target task.
12789 */
12790 ptrace_mode = PTRACE_MODE_ATTACH_REALCREDS;
12791 }
12792
12793 /*
12794 * Preserve ptrace permission check for backwards compatibility. The
12795 * ptrace check also includes checks that the current task and other
12796 * task have matching uids, and is therefore not done here explicitly.
12797 */
12798 return is_capable || ptrace_may_access(task, ptrace_mode);
12799 }
12800
12801 /**
12802 * sys_perf_event_open - open a performance event, associate it to a task/cpu
12803 *
12804 * @attr_uptr: event_id type attributes for monitoring/sampling
12805 * @pid: target pid
12806 * @cpu: target cpu
12807 * @group_fd: group leader event fd
12808 * @flags: perf event open flags
12809 */
SYSCALL_DEFINE5(perf_event_open,struct perf_event_attr __user *,attr_uptr,pid_t,pid,int,cpu,int,group_fd,unsigned long,flags)12810 SYSCALL_DEFINE5(perf_event_open,
12811 struct perf_event_attr __user *, attr_uptr,
12812 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
12813 {
12814 struct perf_event *group_leader = NULL, *output_event = NULL;
12815 struct perf_event_pmu_context *pmu_ctx;
12816 struct perf_event *event, *sibling;
12817 struct perf_event_attr attr;
12818 struct perf_event_context *ctx;
12819 struct file *event_file = NULL;
12820 struct fd group = EMPTY_FD;
12821 struct task_struct *task = NULL;
12822 struct pmu *pmu;
12823 int event_fd;
12824 int move_group = 0;
12825 int err;
12826 int f_flags = O_RDWR;
12827 int cgroup_fd = -1;
12828
12829 /* for future expandability... */
12830 if (flags & ~PERF_FLAG_ALL)
12831 return -EINVAL;
12832
12833 err = perf_copy_attr(attr_uptr, &attr);
12834 if (err)
12835 return err;
12836
12837 /* Do we allow access to perf_event_open(2) ? */
12838 err = security_perf_event_open(&attr, PERF_SECURITY_OPEN);
12839 if (err)
12840 return err;
12841
12842 if (!attr.exclude_kernel) {
12843 err = perf_allow_kernel(&attr);
12844 if (err)
12845 return err;
12846 }
12847
12848 if (attr.namespaces) {
12849 if (!perfmon_capable())
12850 return -EACCES;
12851 }
12852
12853 if (attr.freq) {
12854 if (attr.sample_freq > sysctl_perf_event_sample_rate)
12855 return -EINVAL;
12856 } else {
12857 if (attr.sample_period & (1ULL << 63))
12858 return -EINVAL;
12859 }
12860
12861 /* Only privileged users can get physical addresses */
12862 if ((attr.sample_type & PERF_SAMPLE_PHYS_ADDR)) {
12863 err = perf_allow_kernel(&attr);
12864 if (err)
12865 return err;
12866 }
12867
12868 /* REGS_INTR can leak data, lockdown must prevent this */
12869 if (attr.sample_type & PERF_SAMPLE_REGS_INTR) {
12870 err = security_locked_down(LOCKDOWN_PERF);
12871 if (err)
12872 return err;
12873 }
12874
12875 /*
12876 * In cgroup mode, the pid argument is used to pass the fd
12877 * opened to the cgroup directory in cgroupfs. The cpu argument
12878 * designates the cpu on which to monitor threads from that
12879 * cgroup.
12880 */
12881 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
12882 return -EINVAL;
12883
12884 if (flags & PERF_FLAG_FD_CLOEXEC)
12885 f_flags |= O_CLOEXEC;
12886
12887 event_fd = get_unused_fd_flags(f_flags);
12888 if (event_fd < 0)
12889 return event_fd;
12890
12891 if (group_fd != -1) {
12892 err = perf_fget_light(group_fd, &group);
12893 if (err)
12894 goto err_fd;
12895 group_leader = fd_file(group)->private_data;
12896 if (flags & PERF_FLAG_FD_OUTPUT)
12897 output_event = group_leader;
12898 if (flags & PERF_FLAG_FD_NO_GROUP)
12899 group_leader = NULL;
12900 }
12901
12902 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
12903 task = find_lively_task_by_vpid(pid);
12904 if (IS_ERR(task)) {
12905 err = PTR_ERR(task);
12906 goto err_group_fd;
12907 }
12908 }
12909
12910 if (task && group_leader &&
12911 group_leader->attr.inherit != attr.inherit) {
12912 err = -EINVAL;
12913 goto err_task;
12914 }
12915
12916 if (flags & PERF_FLAG_PID_CGROUP)
12917 cgroup_fd = pid;
12918
12919 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
12920 NULL, NULL, cgroup_fd);
12921 if (IS_ERR(event)) {
12922 err = PTR_ERR(event);
12923 goto err_task;
12924 }
12925
12926 if (is_sampling_event(event)) {
12927 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
12928 err = -EOPNOTSUPP;
12929 goto err_alloc;
12930 }
12931 }
12932
12933 /*
12934 * Special case software events and allow them to be part of
12935 * any hardware group.
12936 */
12937 pmu = event->pmu;
12938
12939 if (attr.use_clockid) {
12940 err = perf_event_set_clock(event, attr.clockid);
12941 if (err)
12942 goto err_alloc;
12943 }
12944
12945 if (pmu->task_ctx_nr == perf_sw_context)
12946 event->event_caps |= PERF_EV_CAP_SOFTWARE;
12947
12948 if (task) {
12949 err = down_read_interruptible(&task->signal->exec_update_lock);
12950 if (err)
12951 goto err_alloc;
12952
12953 /*
12954 * We must hold exec_update_lock across this and any potential
12955 * perf_install_in_context() call for this new event to
12956 * serialize against exec() altering our credentials (and the
12957 * perf_event_exit_task() that could imply).
12958 */
12959 err = -EACCES;
12960 if (!perf_check_permission(&attr, task))
12961 goto err_cred;
12962 }
12963
12964 /*
12965 * Get the target context (task or percpu):
12966 */
12967 ctx = find_get_context(task, event);
12968 if (IS_ERR(ctx)) {
12969 err = PTR_ERR(ctx);
12970 goto err_cred;
12971 }
12972
12973 mutex_lock(&ctx->mutex);
12974
12975 if (ctx->task == TASK_TOMBSTONE) {
12976 err = -ESRCH;
12977 goto err_locked;
12978 }
12979
12980 if (!task) {
12981 /*
12982 * Check if the @cpu we're creating an event for is online.
12983 *
12984 * We use the perf_cpu_context::ctx::mutex to serialize against
12985 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
12986 */
12987 struct perf_cpu_context *cpuctx = per_cpu_ptr(&perf_cpu_context, event->cpu);
12988
12989 if (!cpuctx->online) {
12990 err = -ENODEV;
12991 goto err_locked;
12992 }
12993 }
12994
12995 if (group_leader) {
12996 err = -EINVAL;
12997
12998 /*
12999 * Do not allow a recursive hierarchy (this new sibling
13000 * becoming part of another group-sibling):
13001 */
13002 if (group_leader->group_leader != group_leader)
13003 goto err_locked;
13004
13005 /* All events in a group should have the same clock */
13006 if (group_leader->clock != event->clock)
13007 goto err_locked;
13008
13009 /*
13010 * Make sure we're both events for the same CPU;
13011 * grouping events for different CPUs is broken; since
13012 * you can never concurrently schedule them anyhow.
13013 */
13014 if (group_leader->cpu != event->cpu)
13015 goto err_locked;
13016
13017 /*
13018 * Make sure we're both on the same context; either task or cpu.
13019 */
13020 if (group_leader->ctx != ctx)
13021 goto err_locked;
13022
13023 /*
13024 * Only a group leader can be exclusive or pinned
13025 */
13026 if (attr.exclusive || attr.pinned)
13027 goto err_locked;
13028
13029 if (is_software_event(event) &&
13030 !in_software_context(group_leader)) {
13031 /*
13032 * If the event is a sw event, but the group_leader
13033 * is on hw context.
13034 *
13035 * Allow the addition of software events to hw
13036 * groups, this is safe because software events
13037 * never fail to schedule.
13038 *
13039 * Note the comment that goes with struct
13040 * perf_event_pmu_context.
13041 */
13042 pmu = group_leader->pmu_ctx->pmu;
13043 } else if (!is_software_event(event)) {
13044 if (is_software_event(group_leader) &&
13045 (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
13046 /*
13047 * In case the group is a pure software group, and we
13048 * try to add a hardware event, move the whole group to
13049 * the hardware context.
13050 */
13051 move_group = 1;
13052 }
13053
13054 /* Don't allow group of multiple hw events from different pmus */
13055 if (!in_software_context(group_leader) &&
13056 group_leader->pmu_ctx->pmu != pmu)
13057 goto err_locked;
13058 }
13059 }
13060
13061 /*
13062 * Now that we're certain of the pmu; find the pmu_ctx.
13063 */
13064 pmu_ctx = find_get_pmu_context(pmu, ctx, event);
13065 if (IS_ERR(pmu_ctx)) {
13066 err = PTR_ERR(pmu_ctx);
13067 goto err_locked;
13068 }
13069 event->pmu_ctx = pmu_ctx;
13070
13071 if (output_event) {
13072 err = perf_event_set_output(event, output_event);
13073 if (err)
13074 goto err_context;
13075 }
13076
13077 if (!perf_event_validate_size(event)) {
13078 err = -E2BIG;
13079 goto err_context;
13080 }
13081
13082 if (perf_need_aux_event(event) && !perf_get_aux_event(event, group_leader)) {
13083 err = -EINVAL;
13084 goto err_context;
13085 }
13086
13087 /*
13088 * Must be under the same ctx::mutex as perf_install_in_context(),
13089 * because we need to serialize with concurrent event creation.
13090 */
13091 if (!exclusive_event_installable(event, ctx)) {
13092 err = -EBUSY;
13093 goto err_context;
13094 }
13095
13096 WARN_ON_ONCE(ctx->parent_ctx);
13097
13098 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event, f_flags);
13099 if (IS_ERR(event_file)) {
13100 err = PTR_ERR(event_file);
13101 event_file = NULL;
13102 goto err_context;
13103 }
13104
13105 /*
13106 * This is the point on no return; we cannot fail hereafter. This is
13107 * where we start modifying current state.
13108 */
13109
13110 if (move_group) {
13111 perf_remove_from_context(group_leader, 0);
13112 put_pmu_ctx(group_leader->pmu_ctx);
13113
13114 for_each_sibling_event(sibling, group_leader) {
13115 perf_remove_from_context(sibling, 0);
13116 put_pmu_ctx(sibling->pmu_ctx);
13117 }
13118
13119 /*
13120 * Install the group siblings before the group leader.
13121 *
13122 * Because a group leader will try and install the entire group
13123 * (through the sibling list, which is still in-tact), we can
13124 * end up with siblings installed in the wrong context.
13125 *
13126 * By installing siblings first we NO-OP because they're not
13127 * reachable through the group lists.
13128 */
13129 for_each_sibling_event(sibling, group_leader) {
13130 sibling->pmu_ctx = pmu_ctx;
13131 get_pmu_ctx(pmu_ctx);
13132 perf_event__state_init(sibling);
13133 perf_install_in_context(ctx, sibling, sibling->cpu);
13134 }
13135
13136 /*
13137 * Removing from the context ends up with disabled
13138 * event. What we want here is event in the initial
13139 * startup state, ready to be add into new context.
13140 */
13141 group_leader->pmu_ctx = pmu_ctx;
13142 get_pmu_ctx(pmu_ctx);
13143 perf_event__state_init(group_leader);
13144 perf_install_in_context(ctx, group_leader, group_leader->cpu);
13145 }
13146
13147 /*
13148 * Precalculate sample_data sizes; do while holding ctx::mutex such
13149 * that we're serialized against further additions and before
13150 * perf_install_in_context() which is the point the event is active and
13151 * can use these values.
13152 */
13153 perf_event__header_size(event);
13154 perf_event__id_header_size(event);
13155
13156 event->owner = current;
13157
13158 perf_install_in_context(ctx, event, event->cpu);
13159 perf_unpin_context(ctx);
13160
13161 mutex_unlock(&ctx->mutex);
13162
13163 if (task) {
13164 up_read(&task->signal->exec_update_lock);
13165 put_task_struct(task);
13166 }
13167
13168 mutex_lock(¤t->perf_event_mutex);
13169 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
13170 mutex_unlock(¤t->perf_event_mutex);
13171
13172 /*
13173 * Drop the reference on the group_event after placing the
13174 * new event on the sibling_list. This ensures destruction
13175 * of the group leader will find the pointer to itself in
13176 * perf_group_detach().
13177 */
13178 fdput(group);
13179 fd_install(event_fd, event_file);
13180 return event_fd;
13181
13182 err_context:
13183 put_pmu_ctx(event->pmu_ctx);
13184 event->pmu_ctx = NULL; /* _free_event() */
13185 err_locked:
13186 mutex_unlock(&ctx->mutex);
13187 perf_unpin_context(ctx);
13188 put_ctx(ctx);
13189 err_cred:
13190 if (task)
13191 up_read(&task->signal->exec_update_lock);
13192 err_alloc:
13193 free_event(event);
13194 err_task:
13195 if (task)
13196 put_task_struct(task);
13197 err_group_fd:
13198 fdput(group);
13199 err_fd:
13200 put_unused_fd(event_fd);
13201 return err;
13202 }
13203
13204 /**
13205 * perf_event_create_kernel_counter
13206 *
13207 * @attr: attributes of the counter to create
13208 * @cpu: cpu in which the counter is bound
13209 * @task: task to profile (NULL for percpu)
13210 * @overflow_handler: callback to trigger when we hit the event
13211 * @context: context data could be used in overflow_handler callback
13212 */
13213 struct perf_event *
perf_event_create_kernel_counter(struct perf_event_attr * attr,int cpu,struct task_struct * task,perf_overflow_handler_t overflow_handler,void * context)13214 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
13215 struct task_struct *task,
13216 perf_overflow_handler_t overflow_handler,
13217 void *context)
13218 {
13219 struct perf_event_pmu_context *pmu_ctx;
13220 struct perf_event_context *ctx;
13221 struct perf_event *event;
13222 struct pmu *pmu;
13223 int err;
13224
13225 /*
13226 * Grouping is not supported for kernel events, neither is 'AUX',
13227 * make sure the caller's intentions are adjusted.
13228 */
13229 if (attr->aux_output || attr->aux_action)
13230 return ERR_PTR(-EINVAL);
13231
13232 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
13233 overflow_handler, context, -1);
13234 if (IS_ERR(event)) {
13235 err = PTR_ERR(event);
13236 goto err;
13237 }
13238
13239 /* Mark owner so we could distinguish it from user events. */
13240 event->owner = TASK_TOMBSTONE;
13241 pmu = event->pmu;
13242
13243 if (pmu->task_ctx_nr == perf_sw_context)
13244 event->event_caps |= PERF_EV_CAP_SOFTWARE;
13245
13246 /*
13247 * Get the target context (task or percpu):
13248 */
13249 ctx = find_get_context(task, event);
13250 if (IS_ERR(ctx)) {
13251 err = PTR_ERR(ctx);
13252 goto err_alloc;
13253 }
13254
13255 WARN_ON_ONCE(ctx->parent_ctx);
13256 mutex_lock(&ctx->mutex);
13257 if (ctx->task == TASK_TOMBSTONE) {
13258 err = -ESRCH;
13259 goto err_unlock;
13260 }
13261
13262 pmu_ctx = find_get_pmu_context(pmu, ctx, event);
13263 if (IS_ERR(pmu_ctx)) {
13264 err = PTR_ERR(pmu_ctx);
13265 goto err_unlock;
13266 }
13267 event->pmu_ctx = pmu_ctx;
13268
13269 if (!task) {
13270 /*
13271 * Check if the @cpu we're creating an event for is online.
13272 *
13273 * We use the perf_cpu_context::ctx::mutex to serialize against
13274 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
13275 */
13276 struct perf_cpu_context *cpuctx =
13277 container_of(ctx, struct perf_cpu_context, ctx);
13278 if (!cpuctx->online) {
13279 err = -ENODEV;
13280 goto err_pmu_ctx;
13281 }
13282 }
13283
13284 if (!exclusive_event_installable(event, ctx)) {
13285 err = -EBUSY;
13286 goto err_pmu_ctx;
13287 }
13288
13289 perf_install_in_context(ctx, event, event->cpu);
13290 perf_unpin_context(ctx);
13291 mutex_unlock(&ctx->mutex);
13292
13293 return event;
13294
13295 err_pmu_ctx:
13296 put_pmu_ctx(pmu_ctx);
13297 event->pmu_ctx = NULL; /* _free_event() */
13298 err_unlock:
13299 mutex_unlock(&ctx->mutex);
13300 perf_unpin_context(ctx);
13301 put_ctx(ctx);
13302 err_alloc:
13303 free_event(event);
13304 err:
13305 return ERR_PTR(err);
13306 }
13307 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
13308
__perf_pmu_remove(struct perf_event_context * ctx,int cpu,struct pmu * pmu,struct perf_event_groups * groups,struct list_head * events)13309 static void __perf_pmu_remove(struct perf_event_context *ctx,
13310 int cpu, struct pmu *pmu,
13311 struct perf_event_groups *groups,
13312 struct list_head *events)
13313 {
13314 struct perf_event *event, *sibling;
13315
13316 perf_event_groups_for_cpu_pmu(event, groups, cpu, pmu) {
13317 perf_remove_from_context(event, 0);
13318 put_pmu_ctx(event->pmu_ctx);
13319 list_add(&event->migrate_entry, events);
13320
13321 for_each_sibling_event(sibling, event) {
13322 perf_remove_from_context(sibling, 0);
13323 put_pmu_ctx(sibling->pmu_ctx);
13324 list_add(&sibling->migrate_entry, events);
13325 }
13326 }
13327 }
13328
__perf_pmu_install_event(struct pmu * pmu,struct perf_event_context * ctx,int cpu,struct perf_event * event)13329 static void __perf_pmu_install_event(struct pmu *pmu,
13330 struct perf_event_context *ctx,
13331 int cpu, struct perf_event *event)
13332 {
13333 struct perf_event_pmu_context *epc;
13334 struct perf_event_context *old_ctx = event->ctx;
13335
13336 get_ctx(ctx); /* normally find_get_context() */
13337
13338 event->cpu = cpu;
13339 epc = find_get_pmu_context(pmu, ctx, event);
13340 event->pmu_ctx = epc;
13341
13342 if (event->state >= PERF_EVENT_STATE_OFF)
13343 event->state = PERF_EVENT_STATE_INACTIVE;
13344 perf_install_in_context(ctx, event, cpu);
13345
13346 /*
13347 * Now that event->ctx is updated and visible, put the old ctx.
13348 */
13349 put_ctx(old_ctx);
13350 }
13351
__perf_pmu_install(struct perf_event_context * ctx,int cpu,struct pmu * pmu,struct list_head * events)13352 static void __perf_pmu_install(struct perf_event_context *ctx,
13353 int cpu, struct pmu *pmu, struct list_head *events)
13354 {
13355 struct perf_event *event, *tmp;
13356
13357 /*
13358 * Re-instate events in 2 passes.
13359 *
13360 * Skip over group leaders and only install siblings on this first
13361 * pass, siblings will not get enabled without a leader, however a
13362 * leader will enable its siblings, even if those are still on the old
13363 * context.
13364 */
13365 list_for_each_entry_safe(event, tmp, events, migrate_entry) {
13366 if (event->group_leader == event)
13367 continue;
13368
13369 list_del(&event->migrate_entry);
13370 __perf_pmu_install_event(pmu, ctx, cpu, event);
13371 }
13372
13373 /*
13374 * Once all the siblings are setup properly, install the group leaders
13375 * to make it go.
13376 */
13377 list_for_each_entry_safe(event, tmp, events, migrate_entry) {
13378 list_del(&event->migrate_entry);
13379 __perf_pmu_install_event(pmu, ctx, cpu, event);
13380 }
13381 }
13382
perf_pmu_migrate_context(struct pmu * pmu,int src_cpu,int dst_cpu)13383 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
13384 {
13385 struct perf_event_context *src_ctx, *dst_ctx;
13386 LIST_HEAD(events);
13387
13388 /*
13389 * Since per-cpu context is persistent, no need to grab an extra
13390 * reference.
13391 */
13392 src_ctx = &per_cpu_ptr(&perf_cpu_context, src_cpu)->ctx;
13393 dst_ctx = &per_cpu_ptr(&perf_cpu_context, dst_cpu)->ctx;
13394
13395 /*
13396 * See perf_event_ctx_lock() for comments on the details
13397 * of swizzling perf_event::ctx.
13398 */
13399 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
13400
13401 __perf_pmu_remove(src_ctx, src_cpu, pmu, &src_ctx->pinned_groups, &events);
13402 __perf_pmu_remove(src_ctx, src_cpu, pmu, &src_ctx->flexible_groups, &events);
13403
13404 if (!list_empty(&events)) {
13405 /*
13406 * Wait for the events to quiesce before re-instating them.
13407 */
13408 synchronize_rcu();
13409
13410 __perf_pmu_install(dst_ctx, dst_cpu, pmu, &events);
13411 }
13412
13413 mutex_unlock(&dst_ctx->mutex);
13414 mutex_unlock(&src_ctx->mutex);
13415 }
13416 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
13417
sync_child_event(struct perf_event * child_event)13418 static void sync_child_event(struct perf_event *child_event)
13419 {
13420 struct perf_event *parent_event = child_event->parent;
13421 u64 child_val;
13422
13423 if (child_event->attr.inherit_stat) {
13424 struct task_struct *task = child_event->ctx->task;
13425
13426 if (task && task != TASK_TOMBSTONE)
13427 perf_event_read_event(child_event, task);
13428 }
13429
13430 child_val = perf_event_count(child_event, false);
13431
13432 /*
13433 * Add back the child's count to the parent's count:
13434 */
13435 atomic64_add(child_val, &parent_event->child_count);
13436 atomic64_add(child_event->total_time_enabled,
13437 &parent_event->child_total_time_enabled);
13438 atomic64_add(child_event->total_time_running,
13439 &parent_event->child_total_time_running);
13440 }
13441
13442 static void
perf_event_exit_event(struct perf_event * event,struct perf_event_context * ctx)13443 perf_event_exit_event(struct perf_event *event, struct perf_event_context *ctx)
13444 {
13445 struct perf_event *parent_event = event->parent;
13446 unsigned long detach_flags = 0;
13447
13448 if (parent_event) {
13449 /*
13450 * Do not destroy the 'original' grouping; because of the
13451 * context switch optimization the original events could've
13452 * ended up in a random child task.
13453 *
13454 * If we were to destroy the original group, all group related
13455 * operations would cease to function properly after this
13456 * random child dies.
13457 *
13458 * Do destroy all inherited groups, we don't care about those
13459 * and being thorough is better.
13460 */
13461 detach_flags = DETACH_GROUP | DETACH_CHILD;
13462 mutex_lock(&parent_event->child_mutex);
13463 }
13464
13465 perf_remove_from_context(event, detach_flags | DETACH_EXIT);
13466
13467 /*
13468 * Child events can be freed.
13469 */
13470 if (parent_event) {
13471 mutex_unlock(&parent_event->child_mutex);
13472 /*
13473 * Kick perf_poll() for is_event_hup();
13474 */
13475 perf_event_wakeup(parent_event);
13476 put_event(event);
13477 return;
13478 }
13479
13480 /*
13481 * Parent events are governed by their filedesc, retain them.
13482 */
13483 perf_event_wakeup(event);
13484 }
13485
perf_event_exit_task_context(struct task_struct * child)13486 static void perf_event_exit_task_context(struct task_struct *child)
13487 {
13488 struct perf_event_context *child_ctx, *clone_ctx = NULL;
13489 struct perf_event *child_event, *next;
13490
13491 WARN_ON_ONCE(child != current);
13492
13493 child_ctx = perf_pin_task_context(child);
13494 if (!child_ctx)
13495 return;
13496
13497 /*
13498 * In order to reduce the amount of tricky in ctx tear-down, we hold
13499 * ctx::mutex over the entire thing. This serializes against almost
13500 * everything that wants to access the ctx.
13501 *
13502 * The exception is sys_perf_event_open() /
13503 * perf_event_create_kernel_count() which does find_get_context()
13504 * without ctx::mutex (it cannot because of the move_group double mutex
13505 * lock thing). See the comments in perf_install_in_context().
13506 */
13507 mutex_lock(&child_ctx->mutex);
13508
13509 /*
13510 * In a single ctx::lock section, de-schedule the events and detach the
13511 * context from the task such that we cannot ever get it scheduled back
13512 * in.
13513 */
13514 raw_spin_lock_irq(&child_ctx->lock);
13515 task_ctx_sched_out(child_ctx, NULL, EVENT_ALL);
13516
13517 /*
13518 * Now that the context is inactive, destroy the task <-> ctx relation
13519 * and mark the context dead.
13520 */
13521 RCU_INIT_POINTER(child->perf_event_ctxp, NULL);
13522 put_ctx(child_ctx); /* cannot be last */
13523 WRITE_ONCE(child_ctx->task, TASK_TOMBSTONE);
13524 put_task_struct(current); /* cannot be last */
13525
13526 clone_ctx = unclone_ctx(child_ctx);
13527 raw_spin_unlock_irq(&child_ctx->lock);
13528
13529 if (clone_ctx)
13530 put_ctx(clone_ctx);
13531
13532 /*
13533 * Report the task dead after unscheduling the events so that we
13534 * won't get any samples after PERF_RECORD_EXIT. We can however still
13535 * get a few PERF_RECORD_READ events.
13536 */
13537 perf_event_task(child, child_ctx, 0);
13538
13539 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
13540 perf_event_exit_event(child_event, child_ctx);
13541
13542 mutex_unlock(&child_ctx->mutex);
13543
13544 put_ctx(child_ctx);
13545 }
13546
13547 /*
13548 * When a child task exits, feed back event values to parent events.
13549 *
13550 * Can be called with exec_update_lock held when called from
13551 * setup_new_exec().
13552 */
perf_event_exit_task(struct task_struct * child)13553 void perf_event_exit_task(struct task_struct *child)
13554 {
13555 struct perf_event *event, *tmp;
13556
13557 mutex_lock(&child->perf_event_mutex);
13558 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
13559 owner_entry) {
13560 list_del_init(&event->owner_entry);
13561
13562 /*
13563 * Ensure the list deletion is visible before we clear
13564 * the owner, closes a race against perf_release() where
13565 * we need to serialize on the owner->perf_event_mutex.
13566 */
13567 smp_store_release(&event->owner, NULL);
13568 }
13569 mutex_unlock(&child->perf_event_mutex);
13570
13571 perf_event_exit_task_context(child);
13572
13573 /*
13574 * The perf_event_exit_task_context calls perf_event_task
13575 * with child's task_ctx, which generates EXIT events for
13576 * child contexts and sets child->perf_event_ctxp[] to NULL.
13577 * At this point we need to send EXIT events to cpu contexts.
13578 */
13579 perf_event_task(child, NULL, 0);
13580 }
13581
perf_free_event(struct perf_event * event,struct perf_event_context * ctx)13582 static void perf_free_event(struct perf_event *event,
13583 struct perf_event_context *ctx)
13584 {
13585 struct perf_event *parent = event->parent;
13586
13587 if (WARN_ON_ONCE(!parent))
13588 return;
13589
13590 mutex_lock(&parent->child_mutex);
13591 list_del_init(&event->child_list);
13592 mutex_unlock(&parent->child_mutex);
13593
13594 raw_spin_lock_irq(&ctx->lock);
13595 perf_group_detach(event);
13596 list_del_event(event, ctx);
13597 raw_spin_unlock_irq(&ctx->lock);
13598 put_event(event);
13599 }
13600
13601 /*
13602 * Free a context as created by inheritance by perf_event_init_task() below,
13603 * used by fork() in case of fail.
13604 *
13605 * Even though the task has never lived, the context and events have been
13606 * exposed through the child_list, so we must take care tearing it all down.
13607 */
perf_event_free_task(struct task_struct * task)13608 void perf_event_free_task(struct task_struct *task)
13609 {
13610 struct perf_event_context *ctx;
13611 struct perf_event *event, *tmp;
13612
13613 ctx = rcu_access_pointer(task->perf_event_ctxp);
13614 if (!ctx)
13615 return;
13616
13617 mutex_lock(&ctx->mutex);
13618 raw_spin_lock_irq(&ctx->lock);
13619 /*
13620 * Destroy the task <-> ctx relation and mark the context dead.
13621 *
13622 * This is important because even though the task hasn't been
13623 * exposed yet the context has been (through child_list).
13624 */
13625 RCU_INIT_POINTER(task->perf_event_ctxp, NULL);
13626 WRITE_ONCE(ctx->task, TASK_TOMBSTONE);
13627 put_task_struct(task); /* cannot be last */
13628 raw_spin_unlock_irq(&ctx->lock);
13629
13630
13631 list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry)
13632 perf_free_event(event, ctx);
13633
13634 mutex_unlock(&ctx->mutex);
13635
13636 /*
13637 * perf_event_release_kernel() could've stolen some of our
13638 * child events and still have them on its free_list. In that
13639 * case we must wait for these events to have been freed (in
13640 * particular all their references to this task must've been
13641 * dropped).
13642 *
13643 * Without this copy_process() will unconditionally free this
13644 * task (irrespective of its reference count) and
13645 * _free_event()'s put_task_struct(event->hw.target) will be a
13646 * use-after-free.
13647 *
13648 * Wait for all events to drop their context reference.
13649 */
13650 wait_var_event(&ctx->refcount, refcount_read(&ctx->refcount) == 1);
13651 put_ctx(ctx); /* must be last */
13652 }
13653
perf_event_delayed_put(struct task_struct * task)13654 void perf_event_delayed_put(struct task_struct *task)
13655 {
13656 WARN_ON_ONCE(task->perf_event_ctxp);
13657 }
13658
perf_event_get(unsigned int fd)13659 struct file *perf_event_get(unsigned int fd)
13660 {
13661 struct file *file = fget(fd);
13662 if (!file)
13663 return ERR_PTR(-EBADF);
13664
13665 if (file->f_op != &perf_fops) {
13666 fput(file);
13667 return ERR_PTR(-EBADF);
13668 }
13669
13670 return file;
13671 }
13672
perf_get_event(struct file * file)13673 const struct perf_event *perf_get_event(struct file *file)
13674 {
13675 if (file->f_op != &perf_fops)
13676 return ERR_PTR(-EINVAL);
13677
13678 return file->private_data;
13679 }
13680
perf_event_attrs(struct perf_event * event)13681 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
13682 {
13683 if (!event)
13684 return ERR_PTR(-EINVAL);
13685
13686 return &event->attr;
13687 }
13688
perf_allow_kernel(struct perf_event_attr * attr)13689 int perf_allow_kernel(struct perf_event_attr *attr)
13690 {
13691 if (sysctl_perf_event_paranoid > 1 && !perfmon_capable())
13692 return -EACCES;
13693
13694 return security_perf_event_open(attr, PERF_SECURITY_KERNEL);
13695 }
13696 EXPORT_SYMBOL_GPL(perf_allow_kernel);
13697
13698 /*
13699 * Inherit an event from parent task to child task.
13700 *
13701 * Returns:
13702 * - valid pointer on success
13703 * - NULL for orphaned events
13704 * - IS_ERR() on error
13705 */
13706 static struct perf_event *
inherit_event(struct perf_event * parent_event,struct task_struct * parent,struct perf_event_context * parent_ctx,struct task_struct * child,struct perf_event * group_leader,struct perf_event_context * child_ctx)13707 inherit_event(struct perf_event *parent_event,
13708 struct task_struct *parent,
13709 struct perf_event_context *parent_ctx,
13710 struct task_struct *child,
13711 struct perf_event *group_leader,
13712 struct perf_event_context *child_ctx)
13713 {
13714 enum perf_event_state parent_state = parent_event->state;
13715 struct perf_event_pmu_context *pmu_ctx;
13716 struct perf_event *child_event;
13717 unsigned long flags;
13718
13719 /*
13720 * Instead of creating recursive hierarchies of events,
13721 * we link inherited events back to the original parent,
13722 * which has a filp for sure, which we use as the reference
13723 * count:
13724 */
13725 if (parent_event->parent)
13726 parent_event = parent_event->parent;
13727
13728 child_event = perf_event_alloc(&parent_event->attr,
13729 parent_event->cpu,
13730 child,
13731 group_leader, parent_event,
13732 NULL, NULL, -1);
13733 if (IS_ERR(child_event))
13734 return child_event;
13735
13736 get_ctx(child_ctx);
13737 child_event->ctx = child_ctx;
13738
13739 pmu_ctx = find_get_pmu_context(child_event->pmu, child_ctx, child_event);
13740 if (IS_ERR(pmu_ctx)) {
13741 free_event(child_event);
13742 return ERR_CAST(pmu_ctx);
13743 }
13744 child_event->pmu_ctx = pmu_ctx;
13745
13746 /*
13747 * is_orphaned_event() and list_add_tail(&parent_event->child_list)
13748 * must be under the same lock in order to serialize against
13749 * perf_event_release_kernel(), such that either we must observe
13750 * is_orphaned_event() or they will observe us on the child_list.
13751 */
13752 mutex_lock(&parent_event->child_mutex);
13753 if (is_orphaned_event(parent_event) ||
13754 !atomic_long_inc_not_zero(&parent_event->refcount)) {
13755 mutex_unlock(&parent_event->child_mutex);
13756 /* task_ctx_data is freed with child_ctx */
13757 free_event(child_event);
13758 return NULL;
13759 }
13760
13761 /*
13762 * Make the child state follow the state of the parent event,
13763 * not its attr.disabled bit. We hold the parent's mutex,
13764 * so we won't race with perf_event_{en, dis}able_family.
13765 */
13766 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
13767 child_event->state = PERF_EVENT_STATE_INACTIVE;
13768 else
13769 child_event->state = PERF_EVENT_STATE_OFF;
13770
13771 if (parent_event->attr.freq) {
13772 u64 sample_period = parent_event->hw.sample_period;
13773 struct hw_perf_event *hwc = &child_event->hw;
13774
13775 hwc->sample_period = sample_period;
13776 hwc->last_period = sample_period;
13777
13778 local64_set(&hwc->period_left, sample_period);
13779 }
13780
13781 child_event->overflow_handler = parent_event->overflow_handler;
13782 child_event->overflow_handler_context
13783 = parent_event->overflow_handler_context;
13784
13785 /*
13786 * Precalculate sample_data sizes
13787 */
13788 perf_event__header_size(child_event);
13789 perf_event__id_header_size(child_event);
13790
13791 /*
13792 * Link it up in the child's context:
13793 */
13794 raw_spin_lock_irqsave(&child_ctx->lock, flags);
13795 add_event_to_ctx(child_event, child_ctx);
13796 child_event->attach_state |= PERF_ATTACH_CHILD;
13797 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
13798
13799 /*
13800 * Link this into the parent event's child list
13801 */
13802 list_add_tail(&child_event->child_list, &parent_event->child_list);
13803 mutex_unlock(&parent_event->child_mutex);
13804
13805 return child_event;
13806 }
13807
13808 /*
13809 * Inherits an event group.
13810 *
13811 * This will quietly suppress orphaned events; !inherit_event() is not an error.
13812 * This matches with perf_event_release_kernel() removing all child events.
13813 *
13814 * Returns:
13815 * - 0 on success
13816 * - <0 on error
13817 */
inherit_group(struct perf_event * parent_event,struct task_struct * parent,struct perf_event_context * parent_ctx,struct task_struct * child,struct perf_event_context * child_ctx)13818 static int inherit_group(struct perf_event *parent_event,
13819 struct task_struct *parent,
13820 struct perf_event_context *parent_ctx,
13821 struct task_struct *child,
13822 struct perf_event_context *child_ctx)
13823 {
13824 struct perf_event *leader;
13825 struct perf_event *sub;
13826 struct perf_event *child_ctr;
13827
13828 leader = inherit_event(parent_event, parent, parent_ctx,
13829 child, NULL, child_ctx);
13830 if (IS_ERR(leader))
13831 return PTR_ERR(leader);
13832 /*
13833 * @leader can be NULL here because of is_orphaned_event(). In this
13834 * case inherit_event() will create individual events, similar to what
13835 * perf_group_detach() would do anyway.
13836 */
13837 for_each_sibling_event(sub, parent_event) {
13838 child_ctr = inherit_event(sub, parent, parent_ctx,
13839 child, leader, child_ctx);
13840 if (IS_ERR(child_ctr))
13841 return PTR_ERR(child_ctr);
13842
13843 if (sub->aux_event == parent_event && child_ctr &&
13844 !perf_get_aux_event(child_ctr, leader))
13845 return -EINVAL;
13846 }
13847 if (leader)
13848 leader->group_generation = parent_event->group_generation;
13849 return 0;
13850 }
13851
13852 /*
13853 * Creates the child task context and tries to inherit the event-group.
13854 *
13855 * Clears @inherited_all on !attr.inherited or error. Note that we'll leave
13856 * inherited_all set when we 'fail' to inherit an orphaned event; this is
13857 * consistent with perf_event_release_kernel() removing all child events.
13858 *
13859 * Returns:
13860 * - 0 on success
13861 * - <0 on error
13862 */
13863 static int
inherit_task_group(struct perf_event * event,struct task_struct * parent,struct perf_event_context * parent_ctx,struct task_struct * child,u64 clone_flags,int * inherited_all)13864 inherit_task_group(struct perf_event *event, struct task_struct *parent,
13865 struct perf_event_context *parent_ctx,
13866 struct task_struct *child,
13867 u64 clone_flags, int *inherited_all)
13868 {
13869 struct perf_event_context *child_ctx;
13870 int ret;
13871
13872 if (!event->attr.inherit ||
13873 (event->attr.inherit_thread && !(clone_flags & CLONE_THREAD)) ||
13874 /* Do not inherit if sigtrap and signal handlers were cleared. */
13875 (event->attr.sigtrap && (clone_flags & CLONE_CLEAR_SIGHAND))) {
13876 *inherited_all = 0;
13877 return 0;
13878 }
13879
13880 child_ctx = child->perf_event_ctxp;
13881 if (!child_ctx) {
13882 /*
13883 * This is executed from the parent task context, so
13884 * inherit events that have been marked for cloning.
13885 * First allocate and initialize a context for the
13886 * child.
13887 */
13888 child_ctx = alloc_perf_context(child);
13889 if (!child_ctx)
13890 return -ENOMEM;
13891
13892 child->perf_event_ctxp = child_ctx;
13893 }
13894
13895 ret = inherit_group(event, parent, parent_ctx, child, child_ctx);
13896 if (ret)
13897 *inherited_all = 0;
13898
13899 return ret;
13900 }
13901
13902 /*
13903 * Initialize the perf_event context in task_struct
13904 */
perf_event_init_context(struct task_struct * child,u64 clone_flags)13905 static int perf_event_init_context(struct task_struct *child, u64 clone_flags)
13906 {
13907 struct perf_event_context *child_ctx, *parent_ctx;
13908 struct perf_event_context *cloned_ctx;
13909 struct perf_event *event;
13910 struct task_struct *parent = current;
13911 int inherited_all = 1;
13912 unsigned long flags;
13913 int ret = 0;
13914
13915 if (likely(!parent->perf_event_ctxp))
13916 return 0;
13917
13918 /*
13919 * If the parent's context is a clone, pin it so it won't get
13920 * swapped under us.
13921 */
13922 parent_ctx = perf_pin_task_context(parent);
13923 if (!parent_ctx)
13924 return 0;
13925
13926 /*
13927 * No need to check if parent_ctx != NULL here; since we saw
13928 * it non-NULL earlier, the only reason for it to become NULL
13929 * is if we exit, and since we're currently in the middle of
13930 * a fork we can't be exiting at the same time.
13931 */
13932
13933 /*
13934 * Lock the parent list. No need to lock the child - not PID
13935 * hashed yet and not running, so nobody can access it.
13936 */
13937 mutex_lock(&parent_ctx->mutex);
13938
13939 /*
13940 * We dont have to disable NMIs - we are only looking at
13941 * the list, not manipulating it:
13942 */
13943 perf_event_groups_for_each(event, &parent_ctx->pinned_groups) {
13944 ret = inherit_task_group(event, parent, parent_ctx,
13945 child, clone_flags, &inherited_all);
13946 if (ret)
13947 goto out_unlock;
13948 }
13949
13950 /*
13951 * We can't hold ctx->lock when iterating the ->flexible_group list due
13952 * to allocations, but we need to prevent rotation because
13953 * rotate_ctx() will change the list from interrupt context.
13954 */
13955 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
13956 parent_ctx->rotate_disable = 1;
13957 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
13958
13959 perf_event_groups_for_each(event, &parent_ctx->flexible_groups) {
13960 ret = inherit_task_group(event, parent, parent_ctx,
13961 child, clone_flags, &inherited_all);
13962 if (ret)
13963 goto out_unlock;
13964 }
13965
13966 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
13967 parent_ctx->rotate_disable = 0;
13968
13969 child_ctx = child->perf_event_ctxp;
13970
13971 if (child_ctx && inherited_all) {
13972 /*
13973 * Mark the child context as a clone of the parent
13974 * context, or of whatever the parent is a clone of.
13975 *
13976 * Note that if the parent is a clone, the holding of
13977 * parent_ctx->lock avoids it from being uncloned.
13978 */
13979 cloned_ctx = parent_ctx->parent_ctx;
13980 if (cloned_ctx) {
13981 child_ctx->parent_ctx = cloned_ctx;
13982 child_ctx->parent_gen = parent_ctx->parent_gen;
13983 } else {
13984 child_ctx->parent_ctx = parent_ctx;
13985 child_ctx->parent_gen = parent_ctx->generation;
13986 }
13987 get_ctx(child_ctx->parent_ctx);
13988 }
13989
13990 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
13991 out_unlock:
13992 mutex_unlock(&parent_ctx->mutex);
13993
13994 perf_unpin_context(parent_ctx);
13995 put_ctx(parent_ctx);
13996
13997 return ret;
13998 }
13999
14000 /*
14001 * Initialize the perf_event context in task_struct
14002 */
perf_event_init_task(struct task_struct * child,u64 clone_flags)14003 int perf_event_init_task(struct task_struct *child, u64 clone_flags)
14004 {
14005 int ret;
14006
14007 memset(child->perf_recursion, 0, sizeof(child->perf_recursion));
14008 child->perf_event_ctxp = NULL;
14009 mutex_init(&child->perf_event_mutex);
14010 INIT_LIST_HEAD(&child->perf_event_list);
14011
14012 ret = perf_event_init_context(child, clone_flags);
14013 if (ret) {
14014 perf_event_free_task(child);
14015 return ret;
14016 }
14017
14018 return 0;
14019 }
14020
perf_event_init_all_cpus(void)14021 static void __init perf_event_init_all_cpus(void)
14022 {
14023 struct swevent_htable *swhash;
14024 struct perf_cpu_context *cpuctx;
14025 int cpu;
14026
14027 zalloc_cpumask_var(&perf_online_mask, GFP_KERNEL);
14028 zalloc_cpumask_var(&perf_online_core_mask, GFP_KERNEL);
14029 zalloc_cpumask_var(&perf_online_die_mask, GFP_KERNEL);
14030 zalloc_cpumask_var(&perf_online_cluster_mask, GFP_KERNEL);
14031 zalloc_cpumask_var(&perf_online_pkg_mask, GFP_KERNEL);
14032 zalloc_cpumask_var(&perf_online_sys_mask, GFP_KERNEL);
14033
14034
14035 for_each_possible_cpu(cpu) {
14036 swhash = &per_cpu(swevent_htable, cpu);
14037 mutex_init(&swhash->hlist_mutex);
14038
14039 INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu));
14040 raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu));
14041
14042 INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu));
14043
14044 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
14045 __perf_event_init_context(&cpuctx->ctx);
14046 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
14047 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
14048 cpuctx->online = cpumask_test_cpu(cpu, perf_online_mask);
14049 cpuctx->heap_size = ARRAY_SIZE(cpuctx->heap_default);
14050 cpuctx->heap = cpuctx->heap_default;
14051 }
14052 }
14053
perf_swevent_init_cpu(unsigned int cpu)14054 static void perf_swevent_init_cpu(unsigned int cpu)
14055 {
14056 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
14057
14058 mutex_lock(&swhash->hlist_mutex);
14059 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
14060 struct swevent_hlist *hlist;
14061
14062 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
14063 WARN_ON(!hlist);
14064 rcu_assign_pointer(swhash->swevent_hlist, hlist);
14065 }
14066 mutex_unlock(&swhash->hlist_mutex);
14067 }
14068
14069 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
__perf_event_exit_context(void * __info)14070 static void __perf_event_exit_context(void *__info)
14071 {
14072 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
14073 struct perf_event_context *ctx = __info;
14074 struct perf_event *event;
14075
14076 raw_spin_lock(&ctx->lock);
14077 ctx_sched_out(ctx, NULL, EVENT_TIME);
14078 list_for_each_entry(event, &ctx->event_list, event_entry)
14079 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
14080 raw_spin_unlock(&ctx->lock);
14081 }
14082
perf_event_clear_cpumask(unsigned int cpu)14083 static void perf_event_clear_cpumask(unsigned int cpu)
14084 {
14085 int target[PERF_PMU_MAX_SCOPE];
14086 unsigned int scope;
14087 struct pmu *pmu;
14088
14089 cpumask_clear_cpu(cpu, perf_online_mask);
14090
14091 for (scope = PERF_PMU_SCOPE_NONE + 1; scope < PERF_PMU_MAX_SCOPE; scope++) {
14092 const struct cpumask *cpumask = perf_scope_cpu_topology_cpumask(scope, cpu);
14093 struct cpumask *pmu_cpumask = perf_scope_cpumask(scope);
14094
14095 target[scope] = -1;
14096 if (WARN_ON_ONCE(!pmu_cpumask || !cpumask))
14097 continue;
14098
14099 if (!cpumask_test_and_clear_cpu(cpu, pmu_cpumask))
14100 continue;
14101 target[scope] = cpumask_any_but(cpumask, cpu);
14102 if (target[scope] < nr_cpu_ids)
14103 cpumask_set_cpu(target[scope], pmu_cpumask);
14104 }
14105
14106 /* migrate */
14107 list_for_each_entry(pmu, &pmus, entry) {
14108 if (pmu->scope == PERF_PMU_SCOPE_NONE ||
14109 WARN_ON_ONCE(pmu->scope >= PERF_PMU_MAX_SCOPE))
14110 continue;
14111
14112 if (target[pmu->scope] >= 0 && target[pmu->scope] < nr_cpu_ids)
14113 perf_pmu_migrate_context(pmu, cpu, target[pmu->scope]);
14114 }
14115 }
14116
perf_event_exit_cpu_context(int cpu)14117 static void perf_event_exit_cpu_context(int cpu)
14118 {
14119 struct perf_cpu_context *cpuctx;
14120 struct perf_event_context *ctx;
14121
14122 // XXX simplify cpuctx->online
14123 mutex_lock(&pmus_lock);
14124 /*
14125 * Clear the cpumasks, and migrate to other CPUs if possible.
14126 * Must be invoked before the __perf_event_exit_context.
14127 */
14128 perf_event_clear_cpumask(cpu);
14129 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
14130 ctx = &cpuctx->ctx;
14131
14132 mutex_lock(&ctx->mutex);
14133 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
14134 cpuctx->online = 0;
14135 mutex_unlock(&ctx->mutex);
14136 mutex_unlock(&pmus_lock);
14137 }
14138 #else
14139
perf_event_exit_cpu_context(int cpu)14140 static void perf_event_exit_cpu_context(int cpu) { }
14141
14142 #endif
14143
perf_event_setup_cpumask(unsigned int cpu)14144 static void perf_event_setup_cpumask(unsigned int cpu)
14145 {
14146 struct cpumask *pmu_cpumask;
14147 unsigned int scope;
14148
14149 /*
14150 * Early boot stage, the cpumask hasn't been set yet.
14151 * The perf_online_<domain>_masks includes the first CPU of each domain.
14152 * Always unconditionally set the boot CPU for the perf_online_<domain>_masks.
14153 */
14154 if (cpumask_empty(perf_online_mask)) {
14155 for (scope = PERF_PMU_SCOPE_NONE + 1; scope < PERF_PMU_MAX_SCOPE; scope++) {
14156 pmu_cpumask = perf_scope_cpumask(scope);
14157 if (WARN_ON_ONCE(!pmu_cpumask))
14158 continue;
14159 cpumask_set_cpu(cpu, pmu_cpumask);
14160 }
14161 goto end;
14162 }
14163
14164 for (scope = PERF_PMU_SCOPE_NONE + 1; scope < PERF_PMU_MAX_SCOPE; scope++) {
14165 const struct cpumask *cpumask = perf_scope_cpu_topology_cpumask(scope, cpu);
14166
14167 pmu_cpumask = perf_scope_cpumask(scope);
14168
14169 if (WARN_ON_ONCE(!pmu_cpumask || !cpumask))
14170 continue;
14171
14172 if (!cpumask_empty(cpumask) &&
14173 cpumask_any_and(pmu_cpumask, cpumask) >= nr_cpu_ids)
14174 cpumask_set_cpu(cpu, pmu_cpumask);
14175 }
14176 end:
14177 cpumask_set_cpu(cpu, perf_online_mask);
14178 }
14179
perf_event_init_cpu(unsigned int cpu)14180 int perf_event_init_cpu(unsigned int cpu)
14181 {
14182 struct perf_cpu_context *cpuctx;
14183 struct perf_event_context *ctx;
14184
14185 perf_swevent_init_cpu(cpu);
14186
14187 mutex_lock(&pmus_lock);
14188 perf_event_setup_cpumask(cpu);
14189 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
14190 ctx = &cpuctx->ctx;
14191
14192 mutex_lock(&ctx->mutex);
14193 cpuctx->online = 1;
14194 mutex_unlock(&ctx->mutex);
14195 mutex_unlock(&pmus_lock);
14196
14197 return 0;
14198 }
14199
perf_event_exit_cpu(unsigned int cpu)14200 int perf_event_exit_cpu(unsigned int cpu)
14201 {
14202 perf_event_exit_cpu_context(cpu);
14203 return 0;
14204 }
14205
14206 static int
perf_reboot(struct notifier_block * notifier,unsigned long val,void * v)14207 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
14208 {
14209 int cpu;
14210
14211 for_each_online_cpu(cpu)
14212 perf_event_exit_cpu(cpu);
14213
14214 return NOTIFY_OK;
14215 }
14216
14217 /*
14218 * Run the perf reboot notifier at the very last possible moment so that
14219 * the generic watchdog code runs as long as possible.
14220 */
14221 static struct notifier_block perf_reboot_notifier = {
14222 .notifier_call = perf_reboot,
14223 .priority = INT_MIN,
14224 };
14225
perf_event_init(void)14226 void __init perf_event_init(void)
14227 {
14228 int ret;
14229
14230 idr_init(&pmu_idr);
14231
14232 perf_event_init_all_cpus();
14233 init_srcu_struct(&pmus_srcu);
14234 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
14235 perf_pmu_register(&perf_cpu_clock, "cpu_clock", -1);
14236 perf_pmu_register(&perf_task_clock, "task_clock", -1);
14237 perf_tp_register();
14238 perf_event_init_cpu(smp_processor_id());
14239 register_reboot_notifier(&perf_reboot_notifier);
14240
14241 ret = init_hw_breakpoint();
14242 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
14243
14244 perf_event_cache = KMEM_CACHE(perf_event, SLAB_PANIC);
14245
14246 /*
14247 * Build time assertion that we keep the data_head at the intended
14248 * location. IOW, validation we got the __reserved[] size right.
14249 */
14250 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
14251 != 1024);
14252 }
14253
perf_event_sysfs_show(struct device * dev,struct device_attribute * attr,char * page)14254 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
14255 char *page)
14256 {
14257 struct perf_pmu_events_attr *pmu_attr =
14258 container_of(attr, struct perf_pmu_events_attr, attr);
14259
14260 if (pmu_attr->event_str)
14261 return sprintf(page, "%s\n", pmu_attr->event_str);
14262
14263 return 0;
14264 }
14265 EXPORT_SYMBOL_GPL(perf_event_sysfs_show);
14266
perf_event_sysfs_init(void)14267 static int __init perf_event_sysfs_init(void)
14268 {
14269 struct pmu *pmu;
14270 int ret;
14271
14272 mutex_lock(&pmus_lock);
14273
14274 ret = bus_register(&pmu_bus);
14275 if (ret)
14276 goto unlock;
14277
14278 list_for_each_entry(pmu, &pmus, entry) {
14279 if (pmu->dev)
14280 continue;
14281
14282 ret = pmu_dev_alloc(pmu);
14283 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
14284 }
14285 pmu_bus_running = 1;
14286 ret = 0;
14287
14288 unlock:
14289 mutex_unlock(&pmus_lock);
14290
14291 return ret;
14292 }
14293 device_initcall(perf_event_sysfs_init);
14294
14295 #ifdef CONFIG_CGROUP_PERF
14296 static struct cgroup_subsys_state *
perf_cgroup_css_alloc(struct cgroup_subsys_state * parent_css)14297 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
14298 {
14299 struct perf_cgroup *jc;
14300
14301 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
14302 if (!jc)
14303 return ERR_PTR(-ENOMEM);
14304
14305 jc->info = alloc_percpu(struct perf_cgroup_info);
14306 if (!jc->info) {
14307 kfree(jc);
14308 return ERR_PTR(-ENOMEM);
14309 }
14310
14311 return &jc->css;
14312 }
14313
perf_cgroup_css_free(struct cgroup_subsys_state * css)14314 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
14315 {
14316 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
14317
14318 free_percpu(jc->info);
14319 kfree(jc);
14320 }
14321
perf_cgroup_css_online(struct cgroup_subsys_state * css)14322 static int perf_cgroup_css_online(struct cgroup_subsys_state *css)
14323 {
14324 perf_event_cgroup(css->cgroup);
14325 return 0;
14326 }
14327
__perf_cgroup_move(void * info)14328 static int __perf_cgroup_move(void *info)
14329 {
14330 struct task_struct *task = info;
14331
14332 preempt_disable();
14333 perf_cgroup_switch(task);
14334 preempt_enable();
14335
14336 return 0;
14337 }
14338
perf_cgroup_attach(struct cgroup_taskset * tset)14339 static void perf_cgroup_attach(struct cgroup_taskset *tset)
14340 {
14341 struct task_struct *task;
14342 struct cgroup_subsys_state *css;
14343
14344 cgroup_taskset_for_each(task, css, tset)
14345 task_function_call(task, __perf_cgroup_move, task);
14346 }
14347
14348 struct cgroup_subsys perf_event_cgrp_subsys = {
14349 .css_alloc = perf_cgroup_css_alloc,
14350 .css_free = perf_cgroup_css_free,
14351 .css_online = perf_cgroup_css_online,
14352 .attach = perf_cgroup_attach,
14353 /*
14354 * Implicitly enable on dfl hierarchy so that perf events can
14355 * always be filtered by cgroup2 path as long as perf_event
14356 * controller is not mounted on a legacy hierarchy.
14357 */
14358 .implicit_on_dfl = true,
14359 .threaded = true,
14360 };
14361 #endif /* CONFIG_CGROUP_PERF */
14362
14363 DEFINE_STATIC_CALL_RET0(perf_snapshot_branch_stack, perf_snapshot_branch_stack_t);
14364