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