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