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