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