~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/kernel/events/core.c

Version: ~ [ linux-5.1-rc1 ] ~ [ linux-5.0.3 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.30 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.107 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.164 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.176 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.19.8 ] ~ [ linux-3.18.136 ] ~ [ linux-3.17.8 ] ~ [ linux-3.16.63 ] ~ [ linux-3.15.10 ] ~ [ linux-3.14.79 ] ~ [ linux-3.13.11 ] ~ [ linux-3.12.74 ] ~ [ linux-3.11.10 ] ~ [ linux-3.10.108 ] ~ [ linux-3.9.11 ] ~ [ linux-3.8.13 ] ~ [ linux-3.7.10 ] ~ [ linux-3.6.11 ] ~ [ linux-3.5.7 ] ~ [ linux-3.4.113 ] ~ [ linux-3.3.8 ] ~ [ linux-3.2.102 ] ~ [ linux-3.1.10 ] ~ [ linux-3.0.101 ] ~ [ linux-2.6.39.4 ] ~ [ linux-2.6.38.8 ] ~ [ linux-2.6.37.6 ] ~ [ linux-2.6.36.4 ] ~ [ linux-2.6.35.14 ] ~ [ linux-2.6.34.15 ] ~ [ linux-2.6.33.20 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

  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/sysfs.h>
 22 #include <linux/dcache.h>
 23 #include <linux/percpu.h>
 24 #include <linux/ptrace.h>
 25 #include <linux/reboot.h>
 26 #include <linux/vmstat.h>
 27 #include <linux/device.h>
 28 #include <linux/vmalloc.h>
 29 #include <linux/hardirq.h>
 30 #include <linux/rculist.h>
 31 #include <linux/uaccess.h>
 32 #include <linux/syscalls.h>
 33 #include <linux/anon_inodes.h>
 34 #include <linux/kernel_stat.h>
 35 #include <linux/perf_event.h>
 36 #include <linux/ftrace_event.h>
 37 #include <linux/hw_breakpoint.h>
 38 
 39 #include <asm/irq_regs.h>
 40 
 41 struct remote_function_call {
 42         struct task_struct      *p;
 43         int                     (*func)(void *info);
 44         void                    *info;
 45         int                     ret;
 46 };
 47 
 48 static void remote_function(void *data)
 49 {
 50         struct remote_function_call *tfc = data;
 51         struct task_struct *p = tfc->p;
 52 
 53         if (p) {
 54                 tfc->ret = -EAGAIN;
 55                 if (task_cpu(p) != smp_processor_id() || !task_curr(p))
 56                         return;
 57         }
 58 
 59         tfc->ret = tfc->func(tfc->info);
 60 }
 61 
 62 /**
 63  * task_function_call - call a function on the cpu on which a task runs
 64  * @p:          the task to evaluate
 65  * @func:       the function to be called
 66  * @info:       the function call argument
 67  *
 68  * Calls the function @func when the task is currently running. This might
 69  * be on the current CPU, which just calls the function directly
 70  *
 71  * returns: @func return value, or
 72  *          -ESRCH  - when the process isn't running
 73  *          -EAGAIN - when the process moved away
 74  */
 75 static int
 76 task_function_call(struct task_struct *p, int (*func) (void *info), void *info)
 77 {
 78         struct remote_function_call data = {
 79                 .p      = p,
 80                 .func   = func,
 81                 .info   = info,
 82                 .ret    = -ESRCH, /* No such (running) process */
 83         };
 84 
 85         if (task_curr(p))
 86                 smp_call_function_single(task_cpu(p), remote_function, &data, 1);
 87 
 88         return data.ret;
 89 }
 90 
 91 /**
 92  * cpu_function_call - call a function on the cpu
 93  * @func:       the function to be called
 94  * @info:       the function call argument
 95  *
 96  * Calls the function @func on the remote cpu.
 97  *
 98  * returns: @func return value or -ENXIO when the cpu is offline
 99  */
100 static int cpu_function_call(int cpu, int (*func) (void *info), void *info)
101 {
102         struct remote_function_call data = {
103                 .p      = NULL,
104                 .func   = func,
105                 .info   = info,
106                 .ret    = -ENXIO, /* No such CPU */
107         };
108 
109         smp_call_function_single(cpu, remote_function, &data, 1);
110 
111         return data.ret;
112 }
113 
114 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
115                        PERF_FLAG_FD_OUTPUT  |\
116                        PERF_FLAG_PID_CGROUP)
117 
118 enum event_type_t {
119         EVENT_FLEXIBLE = 0x1,
120         EVENT_PINNED = 0x2,
121         EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
122 };
123 
124 /*
125  * perf_sched_events : >0 events exist
126  * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
127  */
128 struct jump_label_key perf_sched_events __read_mostly;
129 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
130 
131 static atomic_t nr_mmap_events __read_mostly;
132 static atomic_t nr_comm_events __read_mostly;
133 static atomic_t nr_task_events __read_mostly;
134 
135 static LIST_HEAD(pmus);
136 static DEFINE_MUTEX(pmus_lock);
137 static struct srcu_struct pmus_srcu;
138 
139 /*
140  * perf event paranoia level:
141  *  -1 - not paranoid at all
142  *   0 - disallow raw tracepoint access for unpriv
143  *   1 - disallow cpu events for unpriv
144  *   2 - disallow kernel profiling for unpriv
145  */
146 int sysctl_perf_event_paranoid __read_mostly = 1;
147 
148 /* Minimum for 512 kiB + 1 user control page */
149 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
150 
151 /*
152  * max perf event sample rate
153  */
154 #define DEFAULT_MAX_SAMPLE_RATE 100000
155 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
156 static int max_samples_per_tick __read_mostly =
157         DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
158 
159 int perf_proc_update_handler(struct ctl_table *table, int write,
160                 void __user *buffer, size_t *lenp,
161                 loff_t *ppos)
162 {
163         int ret = proc_dointvec(table, write, buffer, lenp, ppos);
164 
165         if (ret || !write)
166                 return ret;
167 
168         max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
169 
170         return 0;
171 }
172 
173 static atomic64_t perf_event_id;
174 
175 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
176                               enum event_type_t event_type);
177 
178 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
179                              enum event_type_t event_type,
180                              struct task_struct *task);
181 
182 static void update_context_time(struct perf_event_context *ctx);
183 static u64 perf_event_time(struct perf_event *event);
184 
185 void __weak perf_event_print_debug(void)        { }
186 
187 extern __weak const char *perf_pmu_name(void)
188 {
189         return "pmu";
190 }
191 
192 static inline u64 perf_clock(void)
193 {
194         return local_clock();
195 }
196 
197 static inline struct perf_cpu_context *
198 __get_cpu_context(struct perf_event_context *ctx)
199 {
200         return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
201 }
202 
203 #ifdef CONFIG_CGROUP_PERF
204 
205 /*
206  * Must ensure cgroup is pinned (css_get) before calling
207  * this function. In other words, we cannot call this function
208  * if there is no cgroup event for the current CPU context.
209  */
210 static inline struct perf_cgroup *
211 perf_cgroup_from_task(struct task_struct *task)
212 {
213         return container_of(task_subsys_state(task, perf_subsys_id),
214                         struct perf_cgroup, css);
215 }
216 
217 static inline bool
218 perf_cgroup_match(struct perf_event *event)
219 {
220         struct perf_event_context *ctx = event->ctx;
221         struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
222 
223         return !event->cgrp || event->cgrp == cpuctx->cgrp;
224 }
225 
226 static inline bool perf_tryget_cgroup(struct perf_event *event)
227 {
228         return css_tryget(&event->cgrp->css);
229 }
230 
231 static inline void perf_put_cgroup(struct perf_event *event)
232 {
233         css_put(&event->cgrp->css);
234 }
235 
236 static inline void perf_detach_cgroup(struct perf_event *event)
237 {
238         perf_put_cgroup(event);
239         event->cgrp = NULL;
240 }
241 
242 static inline int is_cgroup_event(struct perf_event *event)
243 {
244         return event->cgrp != NULL;
245 }
246 
247 static inline u64 perf_cgroup_event_time(struct perf_event *event)
248 {
249         struct perf_cgroup_info *t;
250 
251         t = per_cpu_ptr(event->cgrp->info, event->cpu);
252         return t->time;
253 }
254 
255 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
256 {
257         struct perf_cgroup_info *info;
258         u64 now;
259 
260         now = perf_clock();
261 
262         info = this_cpu_ptr(cgrp->info);
263 
264         info->time += now - info->timestamp;
265         info->timestamp = now;
266 }
267 
268 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
269 {
270         struct perf_cgroup *cgrp_out = cpuctx->cgrp;
271         if (cgrp_out)
272                 __update_cgrp_time(cgrp_out);
273 }
274 
275 static inline void update_cgrp_time_from_event(struct perf_event *event)
276 {
277         struct perf_cgroup *cgrp;
278 
279         /*
280          * ensure we access cgroup data only when needed and
281          * when we know the cgroup is pinned (css_get)
282          */
283         if (!is_cgroup_event(event))
284                 return;
285 
286         cgrp = perf_cgroup_from_task(current);
287         /*
288          * Do not update time when cgroup is not active
289          */
290         if (cgrp == event->cgrp)
291                 __update_cgrp_time(event->cgrp);
292 }
293 
294 static inline void
295 perf_cgroup_set_timestamp(struct task_struct *task,
296                           struct perf_event_context *ctx)
297 {
298         struct perf_cgroup *cgrp;
299         struct perf_cgroup_info *info;
300 
301         /*
302          * ctx->lock held by caller
303          * ensure we do not access cgroup data
304          * unless we have the cgroup pinned (css_get)
305          */
306         if (!task || !ctx->nr_cgroups)
307                 return;
308 
309         cgrp = perf_cgroup_from_task(task);
310         info = this_cpu_ptr(cgrp->info);
311         info->timestamp = ctx->timestamp;
312 }
313 
314 #define PERF_CGROUP_SWOUT       0x1 /* cgroup switch out every event */
315 #define PERF_CGROUP_SWIN        0x2 /* cgroup switch in events based on task */
316 
317 /*
318  * reschedule events based on the cgroup constraint of task.
319  *
320  * mode SWOUT : schedule out everything
321  * mode SWIN : schedule in based on cgroup for next
322  */
323 void perf_cgroup_switch(struct task_struct *task, int mode)
324 {
325         struct perf_cpu_context *cpuctx;
326         struct pmu *pmu;
327         unsigned long flags;
328 
329         /*
330          * disable interrupts to avoid geting nr_cgroup
331          * changes via __perf_event_disable(). Also
332          * avoids preemption.
333          */
334         local_irq_save(flags);
335 
336         /*
337          * we reschedule only in the presence of cgroup
338          * constrained events.
339          */
340         rcu_read_lock();
341 
342         list_for_each_entry_rcu(pmu, &pmus, entry) {
343 
344                 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
345                 if (cpuctx->unique_pmu != pmu)
346                         continue; /* ensure we process each cpuctx once */
347 
348                 perf_pmu_disable(cpuctx->ctx.pmu);
349 
350                 /*
351                  * perf_cgroup_events says at least one
352                  * context on this CPU has cgroup events.
353                  *
354                  * ctx->nr_cgroups reports the number of cgroup
355                  * events for a context.
356                  */
357                 if (cpuctx->ctx.nr_cgroups > 0) {
358 
359                         if (mode & PERF_CGROUP_SWOUT) {
360                                 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
361                                 /*
362                                  * must not be done before ctxswout due
363                                  * to event_filter_match() in event_sched_out()
364                                  */
365                                 cpuctx->cgrp = NULL;
366                         }
367 
368                         if (mode & PERF_CGROUP_SWIN) {
369                                 WARN_ON_ONCE(cpuctx->cgrp);
370                                 /*
371                                  * set cgrp before ctxsw in to allow
372                                  * event_filter_match() to not have to pass
373                                  * task around
374                                  */
375                                 cpuctx->cgrp = perf_cgroup_from_task(task);
376                                 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
377                         }
378                 }
379 
380                 perf_pmu_enable(cpuctx->ctx.pmu);
381         }
382 
383         rcu_read_unlock();
384 
385         local_irq_restore(flags);
386 }
387 
388 static inline void perf_cgroup_sched_out(struct task_struct *task)
389 {
390         perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
391 }
392 
393 static inline void perf_cgroup_sched_in(struct task_struct *task)
394 {
395         perf_cgroup_switch(task, PERF_CGROUP_SWIN);
396 }
397 
398 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
399                                       struct perf_event_attr *attr,
400                                       struct perf_event *group_leader)
401 {
402         struct perf_cgroup *cgrp;
403         struct cgroup_subsys_state *css;
404         struct file *file;
405         int ret = 0, fput_needed;
406 
407         file = fget_light(fd, &fput_needed);
408         if (!file)
409                 return -EBADF;
410 
411         css = cgroup_css_from_dir(file, perf_subsys_id);
412         if (IS_ERR(css)) {
413                 ret = PTR_ERR(css);
414                 goto out;
415         }
416 
417         cgrp = container_of(css, struct perf_cgroup, css);
418         event->cgrp = cgrp;
419 
420         /* must be done before we fput() the file */
421         if (!perf_tryget_cgroup(event)) {
422                 event->cgrp = NULL;
423                 ret = -ENOENT;
424                 goto out;
425         }
426 
427         /*
428          * all events in a group must monitor
429          * the same cgroup because a task belongs
430          * to only one perf cgroup at a time
431          */
432         if (group_leader && group_leader->cgrp != cgrp) {
433                 perf_detach_cgroup(event);
434                 ret = -EINVAL;
435         }
436 out:
437         fput_light(file, fput_needed);
438         return ret;
439 }
440 
441 static inline void
442 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
443 {
444         struct perf_cgroup_info *t;
445         t = per_cpu_ptr(event->cgrp->info, event->cpu);
446         event->shadow_ctx_time = now - t->timestamp;
447 }
448 
449 static inline void
450 perf_cgroup_defer_enabled(struct perf_event *event)
451 {
452         /*
453          * when the current task's perf cgroup does not match
454          * the event's, we need to remember to call the
455          * perf_mark_enable() function the first time a task with
456          * a matching perf cgroup is scheduled in.
457          */
458         if (is_cgroup_event(event) && !perf_cgroup_match(event))
459                 event->cgrp_defer_enabled = 1;
460 }
461 
462 static inline void
463 perf_cgroup_mark_enabled(struct perf_event *event,
464                          struct perf_event_context *ctx)
465 {
466         struct perf_event *sub;
467         u64 tstamp = perf_event_time(event);
468 
469         if (!event->cgrp_defer_enabled)
470                 return;
471 
472         event->cgrp_defer_enabled = 0;
473 
474         event->tstamp_enabled = tstamp - event->total_time_enabled;
475         list_for_each_entry(sub, &event->sibling_list, group_entry) {
476                 if (sub->state >= PERF_EVENT_STATE_INACTIVE) {
477                         sub->tstamp_enabled = tstamp - sub->total_time_enabled;
478                         sub->cgrp_defer_enabled = 0;
479                 }
480         }
481 }
482 #else /* !CONFIG_CGROUP_PERF */
483 
484 static inline bool
485 perf_cgroup_match(struct perf_event *event)
486 {
487         return true;
488 }
489 
490 static inline void perf_detach_cgroup(struct perf_event *event)
491 {}
492 
493 static inline int is_cgroup_event(struct perf_event *event)
494 {
495         return 0;
496 }
497 
498 static inline u64 perf_cgroup_event_cgrp_time(struct perf_event *event)
499 {
500         return 0;
501 }
502 
503 static inline void update_cgrp_time_from_event(struct perf_event *event)
504 {
505 }
506 
507 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
508 {
509 }
510 
511 static inline void perf_cgroup_sched_out(struct task_struct *task)
512 {
513 }
514 
515 static inline void perf_cgroup_sched_in(struct task_struct *task)
516 {
517 }
518 
519 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
520                                       struct perf_event_attr *attr,
521                                       struct perf_event *group_leader)
522 {
523         return -EINVAL;
524 }
525 
526 static inline void
527 perf_cgroup_set_timestamp(struct task_struct *task,
528                           struct perf_event_context *ctx)
529 {
530 }
531 
532 void
533 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
534 {
535 }
536 
537 static inline void
538 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
539 {
540 }
541 
542 static inline u64 perf_cgroup_event_time(struct perf_event *event)
543 {
544         return 0;
545 }
546 
547 static inline void
548 perf_cgroup_defer_enabled(struct perf_event *event)
549 {
550 }
551 
552 static inline void
553 perf_cgroup_mark_enabled(struct perf_event *event,
554                          struct perf_event_context *ctx)
555 {
556 }
557 #endif
558 
559 void perf_pmu_disable(struct pmu *pmu)
560 {
561         int *count = this_cpu_ptr(pmu->pmu_disable_count);
562         if (!(*count)++)
563                 pmu->pmu_disable(pmu);
564 }
565 
566 void perf_pmu_enable(struct pmu *pmu)
567 {
568         int *count = this_cpu_ptr(pmu->pmu_disable_count);
569         if (!--(*count))
570                 pmu->pmu_enable(pmu);
571 }
572 
573 static DEFINE_PER_CPU(struct list_head, rotation_list);
574 
575 /*
576  * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized
577  * because they're strictly cpu affine and rotate_start is called with IRQs
578  * disabled, while rotate_context is called from IRQ context.
579  */
580 static void perf_pmu_rotate_start(struct pmu *pmu)
581 {
582         struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
583         struct list_head *head = &__get_cpu_var(rotation_list);
584 
585         WARN_ON(!irqs_disabled());
586 
587         if (list_empty(&cpuctx->rotation_list))
588                 list_add(&cpuctx->rotation_list, head);
589 }
590 
591 static void get_ctx(struct perf_event_context *ctx)
592 {
593         WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
594 }
595 
596 static void put_ctx(struct perf_event_context *ctx)
597 {
598         if (atomic_dec_and_test(&ctx->refcount)) {
599                 if (ctx->parent_ctx)
600                         put_ctx(ctx->parent_ctx);
601                 if (ctx->task)
602                         put_task_struct(ctx->task);
603                 kfree_rcu(ctx, rcu_head);
604         }
605 }
606 
607 static void unclone_ctx(struct perf_event_context *ctx)
608 {
609         if (ctx->parent_ctx) {
610                 put_ctx(ctx->parent_ctx);
611                 ctx->parent_ctx = NULL;
612         }
613 }
614 
615 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
616 {
617         /*
618          * only top level events have the pid namespace they were created in
619          */
620         if (event->parent)
621                 event = event->parent;
622 
623         return task_tgid_nr_ns(p, event->ns);
624 }
625 
626 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
627 {
628         /*
629          * only top level events have the pid namespace they were created in
630          */
631         if (event->parent)
632                 event = event->parent;
633 
634         return task_pid_nr_ns(p, event->ns);
635 }
636 
637 /*
638  * If we inherit events we want to return the parent event id
639  * to userspace.
640  */
641 static u64 primary_event_id(struct perf_event *event)
642 {
643         u64 id = event->id;
644 
645         if (event->parent)
646                 id = event->parent->id;
647 
648         return id;
649 }
650 
651 /*
652  * Get the perf_event_context for a task and lock it.
653  * This has to cope with with the fact that until it is locked,
654  * the context could get moved to another task.
655  */
656 static struct perf_event_context *
657 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
658 {
659         struct perf_event_context *ctx;
660 
661 retry:
662         /*
663          * One of the few rules of preemptible RCU is that one cannot do
664          * rcu_read_unlock() while holding a scheduler (or nested) lock when
665          * part of the read side critical section was preemptible -- see
666          * rcu_read_unlock_special().
667          *
668          * Since ctx->lock nests under rq->lock we must ensure the entire read
669          * side critical section is non-preemptible.
670          */
671         preempt_disable();
672         rcu_read_lock();
673         ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
674         if (ctx) {
675                 /*
676                  * If this context is a clone of another, it might
677                  * get swapped for another underneath us by
678                  * perf_event_task_sched_out, though the
679                  * rcu_read_lock() protects us from any context
680                  * getting freed.  Lock the context and check if it
681                  * got swapped before we could get the lock, and retry
682                  * if so.  If we locked the right context, then it
683                  * can't get swapped on us any more.
684                  */
685                 raw_spin_lock_irqsave(&ctx->lock, *flags);
686                 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
687                         raw_spin_unlock_irqrestore(&ctx->lock, *flags);
688                         rcu_read_unlock();
689                         preempt_enable();
690                         goto retry;
691                 }
692 
693                 if (!atomic_inc_not_zero(&ctx->refcount)) {
694                         raw_spin_unlock_irqrestore(&ctx->lock, *flags);
695                         ctx = NULL;
696                 }
697         }
698         rcu_read_unlock();
699         preempt_enable();
700         return ctx;
701 }
702 
703 /*
704  * Get the context for a task and increment its pin_count so it
705  * can't get swapped to another task.  This also increments its
706  * reference count so that the context can't get freed.
707  */
708 static struct perf_event_context *
709 perf_pin_task_context(struct task_struct *task, int ctxn)
710 {
711         struct perf_event_context *ctx;
712         unsigned long flags;
713 
714         ctx = perf_lock_task_context(task, ctxn, &flags);
715         if (ctx) {
716                 ++ctx->pin_count;
717                 raw_spin_unlock_irqrestore(&ctx->lock, flags);
718         }
719         return ctx;
720 }
721 
722 static void perf_unpin_context(struct perf_event_context *ctx)
723 {
724         unsigned long flags;
725 
726         raw_spin_lock_irqsave(&ctx->lock, flags);
727         --ctx->pin_count;
728         raw_spin_unlock_irqrestore(&ctx->lock, flags);
729 }
730 
731 /*
732  * Update the record of the current time in a context.
733  */
734 static void update_context_time(struct perf_event_context *ctx)
735 {
736         u64 now = perf_clock();
737 
738         ctx->time += now - ctx->timestamp;
739         ctx->timestamp = now;
740 }
741 
742 static u64 perf_event_time(struct perf_event *event)
743 {
744         struct perf_event_context *ctx = event->ctx;
745 
746         if (is_cgroup_event(event))
747                 return perf_cgroup_event_time(event);
748 
749         return ctx ? ctx->time : 0;
750 }
751 
752 /*
753  * Update the total_time_enabled and total_time_running fields for a event.
754  */
755 static void update_event_times(struct perf_event *event)
756 {
757         struct perf_event_context *ctx = event->ctx;
758         u64 run_end;
759 
760         if (event->state < PERF_EVENT_STATE_INACTIVE ||
761             event->group_leader->state < PERF_EVENT_STATE_INACTIVE)
762                 return;
763         /*
764          * in cgroup mode, time_enabled represents
765          * the time the event was enabled AND active
766          * tasks were in the monitored cgroup. This is
767          * independent of the activity of the context as
768          * there may be a mix of cgroup and non-cgroup events.
769          *
770          * That is why we treat cgroup events differently
771          * here.
772          */
773         if (is_cgroup_event(event))
774                 run_end = perf_event_time(event);
775         else if (ctx->is_active)
776                 run_end = ctx->time;
777         else
778                 run_end = event->tstamp_stopped;
779 
780         event->total_time_enabled = run_end - event->tstamp_enabled;
781 
782         if (event->state == PERF_EVENT_STATE_INACTIVE)
783                 run_end = event->tstamp_stopped;
784         else
785                 run_end = perf_event_time(event);
786 
787         event->total_time_running = run_end - event->tstamp_running;
788 
789 }
790 
791 /*
792  * Update total_time_enabled and total_time_running for all events in a group.
793  */
794 static void update_group_times(struct perf_event *leader)
795 {
796         struct perf_event *event;
797 
798         update_event_times(leader);
799         list_for_each_entry(event, &leader->sibling_list, group_entry)
800                 update_event_times(event);
801 }
802 
803 static struct list_head *
804 ctx_group_list(struct perf_event *event, struct perf_event_context *ctx)
805 {
806         if (event->attr.pinned)
807                 return &ctx->pinned_groups;
808         else
809                 return &ctx->flexible_groups;
810 }
811 
812 /*
813  * Add a event from the lists for its context.
814  * Must be called with ctx->mutex and ctx->lock held.
815  */
816 static void
817 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
818 {
819         WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
820         event->attach_state |= PERF_ATTACH_CONTEXT;
821 
822         /*
823          * If we're a stand alone event or group leader, we go to the context
824          * list, group events are kept attached to the group so that
825          * perf_group_detach can, at all times, locate all siblings.
826          */
827         if (event->group_leader == event) {
828                 struct list_head *list;
829 
830                 if (is_software_event(event))
831                         event->group_flags |= PERF_GROUP_SOFTWARE;
832 
833                 list = ctx_group_list(event, ctx);
834                 list_add_tail(&event->group_entry, list);
835         }
836 
837         if (is_cgroup_event(event))
838                 ctx->nr_cgroups++;
839 
840         list_add_rcu(&event->event_entry, &ctx->event_list);
841         if (!ctx->nr_events)
842                 perf_pmu_rotate_start(ctx->pmu);
843         ctx->nr_events++;
844         if (event->attr.inherit_stat)
845                 ctx->nr_stat++;
846 }
847 
848 /*
849  * Initialize event state based on the perf_event_attr::disabled.
850  */
851 static inline void perf_event__state_init(struct perf_event *event)
852 {
853         event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
854                                               PERF_EVENT_STATE_INACTIVE;
855 }
856 
857 /*
858  * Called at perf_event creation and when events are attached/detached from a
859  * group.
860  */
861 static void perf_event__read_size(struct perf_event *event)
862 {
863         int entry = sizeof(u64); /* value */
864         int size = 0;
865         int nr = 1;
866 
867         if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
868                 size += sizeof(u64);
869 
870         if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
871                 size += sizeof(u64);
872 
873         if (event->attr.read_format & PERF_FORMAT_ID)
874                 entry += sizeof(u64);
875 
876         if (event->attr.read_format & PERF_FORMAT_GROUP) {
877                 nr += event->group_leader->nr_siblings;
878                 size += sizeof(u64);
879         }
880 
881         size += entry * nr;
882         event->read_size = size;
883 }
884 
885 static void perf_event__header_size(struct perf_event *event)
886 {
887         struct perf_sample_data *data;
888         u64 sample_type = event->attr.sample_type;
889         u16 size = 0;
890 
891         perf_event__read_size(event);
892 
893         if (sample_type & PERF_SAMPLE_IP)
894                 size += sizeof(data->ip);
895 
896         if (sample_type & PERF_SAMPLE_ADDR)
897                 size += sizeof(data->addr);
898 
899         if (sample_type & PERF_SAMPLE_PERIOD)
900                 size += sizeof(data->period);
901 
902         if (sample_type & PERF_SAMPLE_READ)
903                 size += event->read_size;
904 
905         event->header_size = size;
906 }
907 
908 static void perf_event__id_header_size(struct perf_event *event)
909 {
910         struct perf_sample_data *data;
911         u64 sample_type = event->attr.sample_type;
912         u16 size = 0;
913 
914         if (sample_type & PERF_SAMPLE_TID)
915                 size += sizeof(data->tid_entry);
916 
917         if (sample_type & PERF_SAMPLE_TIME)
918                 size += sizeof(data->time);
919 
920         if (sample_type & PERF_SAMPLE_ID)
921                 size += sizeof(data->id);
922 
923         if (sample_type & PERF_SAMPLE_STREAM_ID)
924                 size += sizeof(data->stream_id);
925 
926         if (sample_type & PERF_SAMPLE_CPU)
927                 size += sizeof(data->cpu_entry);
928 
929         event->id_header_size = size;
930 }
931 
932 static void perf_group_attach(struct perf_event *event)
933 {
934         struct perf_event *group_leader = event->group_leader, *pos;
935 
936         /*
937          * We can have double attach due to group movement in perf_event_open.
938          */
939         if (event->attach_state & PERF_ATTACH_GROUP)
940                 return;
941 
942         event->attach_state |= PERF_ATTACH_GROUP;
943 
944         if (group_leader == event)
945                 return;
946 
947         if (group_leader->group_flags & PERF_GROUP_SOFTWARE &&
948                         !is_software_event(event))
949                 group_leader->group_flags &= ~PERF_GROUP_SOFTWARE;
950 
951         list_add_tail(&event->group_entry, &group_leader->sibling_list);
952         group_leader->nr_siblings++;
953 
954         perf_event__header_size(group_leader);
955 
956         list_for_each_entry(pos, &group_leader->sibling_list, group_entry)
957                 perf_event__header_size(pos);
958 }
959 
960 /*
961  * Remove a event from the lists for its context.
962  * Must be called with ctx->mutex and ctx->lock held.
963  */
964 static void
965 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
966 {
967         struct perf_cpu_context *cpuctx;
968         /*
969          * We can have double detach due to exit/hot-unplug + close.
970          */
971         if (!(event->attach_state & PERF_ATTACH_CONTEXT))
972                 return;
973 
974         event->attach_state &= ~PERF_ATTACH_CONTEXT;
975 
976         if (is_cgroup_event(event)) {
977                 ctx->nr_cgroups--;
978                 cpuctx = __get_cpu_context(ctx);
979                 /*
980                  * if there are no more cgroup events
981                  * then cler cgrp to avoid stale pointer
982                  * in update_cgrp_time_from_cpuctx()
983                  */
984                 if (!ctx->nr_cgroups)
985                         cpuctx->cgrp = NULL;
986         }
987 
988         ctx->nr_events--;
989         if (event->attr.inherit_stat)
990                 ctx->nr_stat--;
991 
992         list_del_rcu(&event->event_entry);
993 
994         if (event->group_leader == event)
995                 list_del_init(&event->group_entry);
996 
997         update_group_times(event);
998 
999         /*
1000          * If event was in error state, then keep it
1001          * that way, otherwise bogus counts will be
1002          * returned on read(). The only way to get out
1003          * of error state is by explicit re-enabling
1004          * of the event
1005          */
1006         if (event->state > PERF_EVENT_STATE_OFF)
1007                 event->state = PERF_EVENT_STATE_OFF;
1008 }
1009 
1010 static void perf_group_detach(struct perf_event *event)
1011 {
1012         struct perf_event *sibling, *tmp;
1013         struct list_head *list = NULL;
1014 
1015         /*
1016          * We can have double detach due to exit/hot-unplug + close.
1017          */
1018         if (!(event->attach_state & PERF_ATTACH_GROUP))
1019                 return;
1020 
1021         event->attach_state &= ~PERF_ATTACH_GROUP;
1022 
1023         /*
1024          * If this is a sibling, remove it from its group.
1025          */
1026         if (event->group_leader != event) {
1027                 list_del_init(&event->group_entry);
1028                 event->group_leader->nr_siblings--;
1029                 goto out;
1030         }
1031 
1032         if (!list_empty(&event->group_entry))
1033                 list = &event->group_entry;
1034 
1035         /*
1036          * If this was a group event with sibling events then
1037          * upgrade the siblings to singleton events by adding them
1038          * to whatever list we are on.
1039          */
1040         list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) {
1041                 if (list)
1042                         list_move_tail(&sibling->group_entry, list);
1043                 sibling->group_leader = sibling;
1044 
1045                 /* Inherit group flags from the previous leader */
1046                 sibling->group_flags = event->group_flags;
1047         }
1048 
1049 out:
1050         perf_event__header_size(event->group_leader);
1051 
1052         list_for_each_entry(tmp, &event->group_leader->sibling_list, group_entry)
1053                 perf_event__header_size(tmp);
1054 }
1055 
1056 static inline int
1057 event_filter_match(struct perf_event *event)
1058 {
1059         return (event->cpu == -1 || event->cpu == smp_processor_id())
1060             && perf_cgroup_match(event);
1061 }
1062 
1063 static void
1064 event_sched_out(struct perf_event *event,
1065                   struct perf_cpu_context *cpuctx,
1066                   struct perf_event_context *ctx)
1067 {
1068         u64 tstamp = perf_event_time(event);
1069         u64 delta;
1070         /*
1071          * An event which could not be activated because of
1072          * filter mismatch still needs to have its timings
1073          * maintained, otherwise bogus information is return
1074          * via read() for time_enabled, time_running:
1075          */
1076         if (event->state == PERF_EVENT_STATE_INACTIVE
1077             && !event_filter_match(event)) {
1078                 delta = tstamp - event->tstamp_stopped;
1079                 event->tstamp_running += delta;
1080                 event->tstamp_stopped = tstamp;
1081         }
1082 
1083         if (event->state != PERF_EVENT_STATE_ACTIVE)
1084                 return;
1085 
1086         event->state = PERF_EVENT_STATE_INACTIVE;
1087         if (event->pending_disable) {
1088                 event->pending_disable = 0;
1089                 event->state = PERF_EVENT_STATE_OFF;
1090         }
1091         event->tstamp_stopped = tstamp;
1092         event->pmu->del(event, 0);
1093         event->oncpu = -1;
1094 
1095         if (!is_software_event(event))
1096                 cpuctx->active_oncpu--;
1097         ctx->nr_active--;
1098         if (event->attr.exclusive || !cpuctx->active_oncpu)
1099                 cpuctx->exclusive = 0;
1100 }
1101 
1102 static void
1103 group_sched_out(struct perf_event *group_event,
1104                 struct perf_cpu_context *cpuctx,
1105                 struct perf_event_context *ctx)
1106 {
1107         struct perf_event *event;
1108         int state = group_event->state;
1109 
1110         event_sched_out(group_event, cpuctx, ctx);
1111 
1112         /*
1113          * Schedule out siblings (if any):
1114          */
1115         list_for_each_entry(event, &group_event->sibling_list, group_entry)
1116                 event_sched_out(event, cpuctx, ctx);
1117 
1118         if (state == PERF_EVENT_STATE_ACTIVE && group_event->attr.exclusive)
1119                 cpuctx->exclusive = 0;
1120 }
1121 
1122 /*
1123  * Cross CPU call to remove a performance event
1124  *
1125  * We disable the event on the hardware level first. After that we
1126  * remove it from the context list.
1127  */
1128 static int __perf_remove_from_context(void *info)
1129 {
1130         struct perf_event *event = info;
1131         struct perf_event_context *ctx = event->ctx;
1132         struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1133 
1134         raw_spin_lock(&ctx->lock);
1135         event_sched_out(event, cpuctx, ctx);
1136         list_del_event(event, ctx);
1137         raw_spin_unlock(&ctx->lock);
1138 
1139         return 0;
1140 }
1141 
1142 
1143 /*
1144  * Remove the event from a task's (or a CPU's) list of events.
1145  *
1146  * CPU events are removed with a smp call. For task events we only
1147  * call when the task is on a CPU.
1148  *
1149  * If event->ctx is a cloned context, callers must make sure that
1150  * every task struct that event->ctx->task could possibly point to
1151  * remains valid.  This is OK when called from perf_release since
1152  * that only calls us on the top-level context, which can't be a clone.
1153  * When called from perf_event_exit_task, it's OK because the
1154  * context has been detached from its task.
1155  */
1156 static void perf_remove_from_context(struct perf_event *event)
1157 {
1158         struct perf_event_context *ctx = event->ctx;
1159         struct task_struct *task = ctx->task;
1160 
1161         lockdep_assert_held(&ctx->mutex);
1162 
1163         if (!task) {
1164                 /*
1165                  * Per cpu events are removed via an smp call and
1166                  * the removal is always successful.
1167                  */
1168                 cpu_function_call(event->cpu, __perf_remove_from_context, event);
1169                 return;
1170         }
1171 
1172 retry:
1173         if (!task_function_call(task, __perf_remove_from_context, event))
1174                 return;
1175 
1176         raw_spin_lock_irq(&ctx->lock);
1177         /*
1178          * If we failed to find a running task, but find the context active now
1179          * that we've acquired the ctx->lock, retry.
1180          */
1181         if (ctx->is_active) {
1182                 raw_spin_unlock_irq(&ctx->lock);
1183                 goto retry;
1184         }
1185 
1186         /*
1187          * Since the task isn't running, its safe to remove the event, us
1188          * holding the ctx->lock ensures the task won't get scheduled in.
1189          */
1190         list_del_event(event, ctx);
1191         raw_spin_unlock_irq(&ctx->lock);
1192 }
1193 
1194 /*
1195  * Cross CPU call to disable a performance event
1196  */
1197 static int __perf_event_disable(void *info)
1198 {
1199         struct perf_event *event = info;
1200         struct perf_event_context *ctx = event->ctx;
1201         struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1202 
1203         /*
1204          * If this is a per-task event, need to check whether this
1205          * event's task is the current task on this cpu.
1206          *
1207          * Can trigger due to concurrent perf_event_context_sched_out()
1208          * flipping contexts around.
1209          */
1210         if (ctx->task && cpuctx->task_ctx != ctx)
1211                 return -EINVAL;
1212 
1213         raw_spin_lock(&ctx->lock);
1214 
1215         /*
1216          * If the event is on, turn it off.
1217          * If it is in error state, leave it in error state.
1218          */
1219         if (event->state >= PERF_EVENT_STATE_INACTIVE) {
1220                 update_context_time(ctx);
1221                 update_cgrp_time_from_event(event);
1222                 update_group_times(event);
1223                 if (event == event->group_leader)
1224                         group_sched_out(event, cpuctx, ctx);
1225                 else
1226                         event_sched_out(event, cpuctx, ctx);
1227                 event->state = PERF_EVENT_STATE_OFF;
1228         }
1229 
1230         raw_spin_unlock(&ctx->lock);
1231 
1232         return 0;
1233 }
1234 
1235 /*
1236  * Disable a event.
1237  *
1238  * If event->ctx is a cloned context, callers must make sure that
1239  * every task struct that event->ctx->task could possibly point to
1240  * remains valid.  This condition is satisifed when called through
1241  * perf_event_for_each_child or perf_event_for_each because they
1242  * hold the top-level event's child_mutex, so any descendant that
1243  * goes to exit will block in sync_child_event.
1244  * When called from perf_pending_event it's OK because event->ctx
1245  * is the current context on this CPU and preemption is disabled,
1246  * hence we can't get into perf_event_task_sched_out for this context.
1247  */
1248 void perf_event_disable(struct perf_event *event)
1249 {
1250         struct perf_event_context *ctx = event->ctx;
1251         struct task_struct *task = ctx->task;
1252 
1253         if (!task) {
1254                 /*
1255                  * Disable the event on the cpu that it's on
1256                  */
1257                 cpu_function_call(event->cpu, __perf_event_disable, event);
1258                 return;
1259         }
1260 
1261 retry:
1262         if (!task_function_call(task, __perf_event_disable, event))
1263                 return;
1264 
1265         raw_spin_lock_irq(&ctx->lock);
1266         /*
1267          * If the event is still active, we need to retry the cross-call.
1268          */
1269         if (event->state == PERF_EVENT_STATE_ACTIVE) {
1270                 raw_spin_unlock_irq(&ctx->lock);
1271                 /*
1272                  * Reload the task pointer, it might have been changed by
1273                  * a concurrent perf_event_context_sched_out().
1274                  */
1275                 task = ctx->task;
1276                 goto retry;
1277         }
1278 
1279         /*
1280          * Since we have the lock this context can't be scheduled
1281          * in, so we can change the state safely.
1282          */
1283         if (event->state == PERF_EVENT_STATE_INACTIVE) {
1284                 update_group_times(event);
1285                 event->state = PERF_EVENT_STATE_OFF;
1286         }
1287         raw_spin_unlock_irq(&ctx->lock);
1288 }
1289 
1290 static void perf_set_shadow_time(struct perf_event *event,
1291                                  struct perf_event_context *ctx,
1292                                  u64 tstamp)
1293 {
1294         /*
1295          * use the correct time source for the time snapshot
1296          *
1297          * We could get by without this by leveraging the
1298          * fact that to get to this function, the caller
1299          * has most likely already called update_context_time()
1300          * and update_cgrp_time_xx() and thus both timestamp
1301          * are identical (or very close). Given that tstamp is,
1302          * already adjusted for cgroup, we could say that:
1303          *    tstamp - ctx->timestamp
1304          * is equivalent to
1305          *    tstamp - cgrp->timestamp.
1306          *
1307          * Then, in perf_output_read(), the calculation would
1308          * work with no changes because:
1309          * - event is guaranteed scheduled in
1310          * - no scheduled out in between
1311          * - thus the timestamp would be the same
1312          *
1313          * But this is a bit hairy.
1314          *
1315          * So instead, we have an explicit cgroup call to remain
1316          * within the time time source all along. We believe it
1317          * is cleaner and simpler to understand.
1318          */
1319         if (is_cgroup_event(event))
1320                 perf_cgroup_set_shadow_time(event, tstamp);
1321         else
1322                 event->shadow_ctx_time = tstamp - ctx->timestamp;
1323 }
1324 
1325 #define MAX_INTERRUPTS (~0ULL)
1326 
1327 static void perf_log_throttle(struct perf_event *event, int enable);
1328 
1329 static int
1330 event_sched_in(struct perf_event *event,
1331                  struct perf_cpu_context *cpuctx,
1332                  struct perf_event_context *ctx)
1333 {
1334         u64 tstamp = perf_event_time(event);
1335 
1336         if (event->state <= PERF_EVENT_STATE_OFF)
1337                 return 0;
1338 
1339         event->state = PERF_EVENT_STATE_ACTIVE;
1340         event->oncpu = smp_processor_id();
1341 
1342         /*
1343          * Unthrottle events, since we scheduled we might have missed several
1344          * ticks already, also for a heavily scheduling task there is little
1345          * guarantee it'll get a tick in a timely manner.
1346          */
1347         if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
1348                 perf_log_throttle(event, 1);
1349                 event->hw.interrupts = 0;
1350         }
1351 
1352         /*
1353          * The new state must be visible before we turn it on in the hardware:
1354          */
1355         smp_wmb();
1356 
1357         if (event->pmu->add(event, PERF_EF_START)) {
1358                 event->state = PERF_EVENT_STATE_INACTIVE;
1359                 event->oncpu = -1;
1360                 return -EAGAIN;
1361         }
1362 
1363         event->tstamp_running += tstamp - event->tstamp_stopped;
1364 
1365         perf_set_shadow_time(event, ctx, tstamp);
1366 
1367         if (!is_software_event(event))
1368                 cpuctx->active_oncpu++;
1369         ctx->nr_active++;
1370 
1371         if (event->attr.exclusive)
1372                 cpuctx->exclusive = 1;
1373 
1374         return 0;
1375 }
1376 
1377 static int
1378 group_sched_in(struct perf_event *group_event,
1379                struct perf_cpu_context *cpuctx,
1380                struct perf_event_context *ctx)
1381 {
1382         struct perf_event *event, *partial_group = NULL;
1383         struct pmu *pmu = group_event->pmu;
1384         u64 now = ctx->time;
1385         bool simulate = false;
1386 
1387         if (group_event->state == PERF_EVENT_STATE_OFF)
1388                 return 0;
1389 
1390         pmu->start_txn(pmu);
1391 
1392         if (event_sched_in(group_event, cpuctx, ctx)) {
1393                 pmu->cancel_txn(pmu);
1394                 return -EAGAIN;
1395         }
1396 
1397         /*
1398          * Schedule in siblings as one group (if any):
1399          */
1400         list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1401                 if (event_sched_in(event, cpuctx, ctx)) {
1402                         partial_group = event;
1403                         goto group_error;
1404                 }
1405         }
1406 
1407         if (!pmu->commit_txn(pmu))
1408                 return 0;
1409 
1410 group_error:
1411         /*
1412          * Groups can be scheduled in as one unit only, so undo any
1413          * partial group before returning:
1414          * The events up to the failed event are scheduled out normally,
1415          * tstamp_stopped will be updated.
1416          *
1417          * The failed events and the remaining siblings need to have
1418          * their timings updated as if they had gone thru event_sched_in()
1419          * and event_sched_out(). This is required to get consistent timings
1420          * across the group. This also takes care of the case where the group
1421          * could never be scheduled by ensuring tstamp_stopped is set to mark
1422          * the time the event was actually stopped, such that time delta
1423          * calculation in update_event_times() is correct.
1424          */
1425         list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1426                 if (event == partial_group)
1427                         simulate = true;
1428 
1429                 if (simulate) {
1430                         event->tstamp_running += now - event->tstamp_stopped;
1431                         event->tstamp_stopped = now;
1432                 } else {
1433                         event_sched_out(event, cpuctx, ctx);
1434                 }
1435         }
1436         event_sched_out(group_event, cpuctx, ctx);
1437 
1438         pmu->cancel_txn(pmu);
1439 
1440         return -EAGAIN;
1441 }
1442 
1443 /*
1444  * Work out whether we can put this event group on the CPU now.
1445  */
1446 static int group_can_go_on(struct perf_event *event,
1447                            struct perf_cpu_context *cpuctx,
1448                            int can_add_hw)
1449 {
1450         /*
1451          * Groups consisting entirely of software events can always go on.
1452          */
1453         if (event->group_flags & PERF_GROUP_SOFTWARE)
1454                 return 1;
1455         /*
1456          * If an exclusive group is already on, no other hardware
1457          * events can go on.
1458          */
1459         if (cpuctx->exclusive)
1460                 return 0;
1461         /*
1462          * If this group is exclusive and there are already
1463          * events on the CPU, it can't go on.
1464          */
1465         if (event->attr.exclusive && cpuctx->active_oncpu)
1466                 return 0;
1467         /*
1468          * Otherwise, try to add it if all previous groups were able
1469          * to go on.
1470          */
1471         return can_add_hw;
1472 }
1473 
1474 static void add_event_to_ctx(struct perf_event *event,
1475                                struct perf_event_context *ctx)
1476 {
1477         u64 tstamp = perf_event_time(event);
1478 
1479         list_add_event(event, ctx);
1480         perf_group_attach(event);
1481         event->tstamp_enabled = tstamp;
1482         event->tstamp_running = tstamp;
1483         event->tstamp_stopped = tstamp;
1484 }
1485 
1486 static void perf_event_context_sched_in(struct perf_event_context *ctx,
1487                                         struct task_struct *tsk);
1488 
1489 /*
1490  * Cross CPU call to install and enable a performance event
1491  *
1492  * Must be called with ctx->mutex held
1493  */
1494 static int  __perf_install_in_context(void *info)
1495 {
1496         struct perf_event *event = info;
1497         struct perf_event_context *ctx = event->ctx;
1498         struct perf_event *leader = event->group_leader;
1499         struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1500         int err;
1501 
1502         /*
1503          * In case we're installing a new context to an already running task,
1504          * could also happen before perf_event_task_sched_in() on architectures
1505          * which do context switches with IRQs enabled.
1506          */
1507         if (ctx->task && !cpuctx->task_ctx)
1508                 perf_event_context_sched_in(ctx, ctx->task);
1509 
1510         raw_spin_lock(&ctx->lock);
1511         ctx->is_active = 1;
1512         update_context_time(ctx);
1513         /*
1514          * update cgrp time only if current cgrp
1515          * matches event->cgrp. Must be done before
1516          * calling add_event_to_ctx()
1517          */
1518         update_cgrp_time_from_event(event);
1519 
1520         add_event_to_ctx(event, ctx);
1521 
1522         if (!event_filter_match(event))
1523                 goto unlock;
1524 
1525         /*
1526          * Don't put the event on if it is disabled or if
1527          * it is in a group and the group isn't on.
1528          */
1529         if (event->state != PERF_EVENT_STATE_INACTIVE ||
1530             (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE))
1531                 goto unlock;
1532 
1533         /*
1534          * An exclusive event can't go on if there are already active
1535          * hardware events, and no hardware event can go on if there
1536          * is already an exclusive event on.
1537          */
1538         if (!group_can_go_on(event, cpuctx, 1))
1539                 err = -EEXIST;
1540         else
1541                 err = event_sched_in(event, cpuctx, ctx);
1542 
1543         if (err) {
1544                 /*
1545                  * This event couldn't go on.  If it is in a group
1546                  * then we have to pull the whole group off.
1547                  * If the event group is pinned then put it in error state.
1548                  */
1549                 if (leader != event)
1550                         group_sched_out(leader, cpuctx, ctx);
1551                 if (leader->attr.pinned) {
1552                         update_group_times(leader);
1553                         leader->state = PERF_EVENT_STATE_ERROR;
1554                 }
1555         }
1556 
1557 unlock:
1558         raw_spin_unlock(&ctx->lock);
1559 
1560         return 0;
1561 }
1562 
1563 /*
1564  * Attach a performance event to a context
1565  *
1566  * First we add the event to the list with the hardware enable bit
1567  * in event->hw_config cleared.
1568  *
1569  * If the event is attached to a task which is on a CPU we use a smp
1570  * call to enable it in the task context. The task might have been
1571  * scheduled away, but we check this in the smp call again.
1572  */
1573 static void
1574 perf_install_in_context(struct perf_event_context *ctx,
1575                         struct perf_event *event,
1576                         int cpu)
1577 {
1578         struct task_struct *task = ctx->task;
1579 
1580         lockdep_assert_held(&ctx->mutex);
1581 
1582         event->ctx = ctx;
1583 
1584         if (!task) {
1585                 /*
1586                  * Per cpu events are installed via an smp call and
1587                  * the install is always successful.
1588                  */
1589                 cpu_function_call(cpu, __perf_install_in_context, event);
1590                 return;
1591         }
1592 
1593 retry:
1594         if (!task_function_call(task, __perf_install_in_context, event))
1595                 return;
1596 
1597         raw_spin_lock_irq(&ctx->lock);
1598         /*
1599          * If we failed to find a running task, but find the context active now
1600          * that we've acquired the ctx->lock, retry.
1601          */
1602         if (ctx->is_active) {
1603                 raw_spin_unlock_irq(&ctx->lock);
1604                 goto retry;
1605         }
1606 
1607         /*
1608          * Since the task isn't running, its safe to add the event, us holding
1609          * the ctx->lock ensures the task won't get scheduled in.
1610          */
1611         add_event_to_ctx(event, ctx);
1612         raw_spin_unlock_irq(&ctx->lock);
1613 }
1614 
1615 /*
1616  * Put a event into inactive state and update time fields.
1617  * Enabling the leader of a group effectively enables all
1618  * the group members that aren't explicitly disabled, so we
1619  * have to update their ->tstamp_enabled also.
1620  * Note: this works for group members as well as group leaders
1621  * since the non-leader members' sibling_lists will be empty.
1622  */
1623 static void __perf_event_mark_enabled(struct perf_event *event,
1624                                         struct perf_event_context *ctx)
1625 {
1626         struct perf_event *sub;
1627         u64 tstamp = perf_event_time(event);
1628 
1629         event->state = PERF_EVENT_STATE_INACTIVE;
1630         event->tstamp_enabled = tstamp - event->total_time_enabled;
1631         list_for_each_entry(sub, &event->sibling_list, group_entry) {
1632                 if (sub->state >= PERF_EVENT_STATE_INACTIVE)
1633                         sub->tstamp_enabled = tstamp - sub->total_time_enabled;
1634         }
1635 }
1636 
1637 /*
1638  * Cross CPU call to enable a performance event
1639  */
1640 static int __perf_event_enable(void *info)
1641 {
1642         struct perf_event *event = info;
1643         struct perf_event_context *ctx = event->ctx;
1644         struct perf_event *leader = event->group_leader;
1645         struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1646         int err;
1647 
1648         /*
1649          * There's a time window between 'ctx->is_active' check
1650          * in perf_event_enable function and this place having:
1651          *   - IRQs on
1652          *   - ctx->lock unlocked
1653          *
1654          * where the task could be killed and 'ctx' deactivated
1655          * by perf_event_exit_task.
1656          */
1657         if (!ctx->is_active)
1658                 return -EINVAL;
1659 
1660         raw_spin_lock(&ctx->lock);
1661         update_context_time(ctx);
1662 
1663         if (event->state >= PERF_EVENT_STATE_INACTIVE)
1664                 goto unlock;
1665 
1666         /*
1667          * set current task's cgroup time reference point
1668          */
1669         perf_cgroup_set_timestamp(current, ctx);
1670 
1671         __perf_event_mark_enabled(event, ctx);
1672 
1673         if (!event_filter_match(event)) {
1674                 if (is_cgroup_event(event))
1675                         perf_cgroup_defer_enabled(event);
1676                 goto unlock;
1677         }
1678 
1679         /*
1680          * If the event is in a group and isn't the group leader,
1681          * then don't put it on unless the group is on.
1682          */
1683         if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
1684                 goto unlock;
1685 
1686         if (!group_can_go_on(event, cpuctx, 1)) {
1687                 err = -EEXIST;
1688         } else {
1689                 if (event == leader)
1690                         err = group_sched_in(event, cpuctx, ctx);
1691                 else
1692                         err = event_sched_in(event, cpuctx, ctx);
1693         }
1694 
1695         if (err) {
1696                 /*
1697                  * If this event can't go on and it's part of a
1698                  * group, then the whole group has to come off.
1699                  */
1700                 if (leader != event)
1701                         group_sched_out(leader, cpuctx, ctx);
1702                 if (leader->attr.pinned) {
1703                         update_group_times(leader);
1704                         leader->state = PERF_EVENT_STATE_ERROR;
1705                 }
1706         }
1707 
1708 unlock:
1709         raw_spin_unlock(&ctx->lock);
1710 
1711         return 0;
1712 }
1713 
1714 /*
1715  * Enable a event.
1716  *
1717  * If event->ctx is a cloned context, callers must make sure that
1718  * every task struct that event->ctx->task could possibly point to
1719  * remains valid.  This condition is satisfied when called through
1720  * perf_event_for_each_child or perf_event_for_each as described
1721  * for perf_event_disable.
1722  */
1723 void perf_event_enable(struct perf_event *event)
1724 {
1725         struct perf_event_context *ctx = event->ctx;
1726         struct task_struct *task = ctx->task;
1727 
1728         if (!task) {
1729                 /*
1730                  * Enable the event on the cpu that it's on
1731                  */
1732                 cpu_function_call(event->cpu, __perf_event_enable, event);
1733                 return;
1734         }
1735 
1736         raw_spin_lock_irq(&ctx->lock);
1737         if (event->state >= PERF_EVENT_STATE_INACTIVE)
1738                 goto out;
1739 
1740         /*
1741          * If the event is in error state, clear that first.
1742          * That way, if we see the event in error state below, we
1743          * know that it has gone back into error state, as distinct
1744          * from the task having been scheduled away before the
1745          * cross-call arrived.
1746          */
1747         if (event->state == PERF_EVENT_STATE_ERROR)
1748                 event->state = PERF_EVENT_STATE_OFF;
1749 
1750 retry:
1751         if (!ctx->is_active) {
1752                 __perf_event_mark_enabled(event, ctx);
1753                 goto out;
1754         }
1755 
1756         raw_spin_unlock_irq(&ctx->lock);
1757 
1758         if (!task_function_call(task, __perf_event_enable, event))
1759                 return;
1760 
1761         raw_spin_lock_irq(&ctx->lock);
1762 
1763         /*
1764          * If the context is active and the event is still off,
1765          * we need to retry the cross-call.
1766          */
1767         if (ctx->is_active && event->state == PERF_EVENT_STATE_OFF) {
1768                 /*
1769                  * task could have been flipped by a concurrent
1770                  * perf_event_context_sched_out()
1771                  */
1772                 task = ctx->task;
1773                 goto retry;
1774         }
1775 
1776 out:
1777         raw_spin_unlock_irq(&ctx->lock);
1778 }
1779 
1780 static int perf_event_refresh(struct perf_event *event, int refresh)
1781 {
1782         /*
1783          * not supported on inherited events
1784          */
1785         if (event->attr.inherit || !is_sampling_event(event))
1786                 return -EINVAL;
1787 
1788         atomic_add(refresh, &event->event_limit);
1789         perf_event_enable(event);
1790 
1791         return 0;
1792 }
1793 
1794 static void ctx_sched_out(struct perf_event_context *ctx,
1795                           struct perf_cpu_context *cpuctx,
1796                           enum event_type_t event_type)
1797 {
1798         struct perf_event *event;
1799 
1800         raw_spin_lock(&ctx->lock);
1801         perf_pmu_disable(ctx->pmu);
1802         ctx->is_active = 0;
1803         if (likely(!ctx->nr_events))
1804                 goto out;
1805         update_context_time(ctx);
1806         update_cgrp_time_from_cpuctx(cpuctx);
1807 
1808         if (!ctx->nr_active)
1809                 goto out;
1810 
1811         if (event_type & EVENT_PINNED) {
1812                 list_for_each_entry(event, &ctx->pinned_groups, group_entry)
1813                         group_sched_out(event, cpuctx, ctx);
1814         }
1815 
1816         if (event_type & EVENT_FLEXIBLE) {
1817                 list_for_each_entry(event, &ctx->flexible_groups, group_entry)
1818                         group_sched_out(event, cpuctx, ctx);
1819         }
1820 out:
1821         perf_pmu_enable(ctx->pmu);
1822         raw_spin_unlock(&ctx->lock);
1823 }
1824 
1825 /*
1826  * Test whether two contexts are equivalent, i.e. whether they
1827  * have both been cloned from the same version of the same context
1828  * and they both have the same number of enabled events.
1829  * If the number of enabled events is the same, then the set
1830  * of enabled events should be the same, because these are both
1831  * inherited contexts, therefore we can't access individual events
1832  * in them directly with an fd; we can only enable/disable all
1833  * events via prctl, or enable/disable all events in a family
1834  * via ioctl, which will have the same effect on both contexts.
1835  */
1836 static int context_equiv(struct perf_event_context *ctx1,
1837                          struct perf_event_context *ctx2)
1838 {
1839         return ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx
1840                 && ctx1->parent_gen == ctx2->parent_gen
1841                 && !ctx1->pin_count && !ctx2->pin_count;
1842 }
1843 
1844 static void __perf_event_sync_stat(struct perf_event *event,
1845                                      struct perf_event *next_event)
1846 {
1847         u64 value;
1848 
1849         if (!event->attr.inherit_stat)
1850                 return;
1851 
1852         /*
1853          * Update the event value, we cannot use perf_event_read()
1854          * because we're in the middle of a context switch and have IRQs
1855          * disabled, which upsets smp_call_function_single(), however
1856          * we know the event must be on the current CPU, therefore we
1857          * don't need to use it.
1858          */
1859         switch (event->state) {
1860         case PERF_EVENT_STATE_ACTIVE:
1861                 event->pmu->read(event);
1862                 /* fall-through */
1863 
1864         case PERF_EVENT_STATE_INACTIVE:
1865                 update_event_times(event);
1866                 break;
1867 
1868         default:
1869                 break;
1870         }
1871 
1872         /*
1873          * In order to keep per-task stats reliable we need to flip the event
1874          * values when we flip the contexts.
1875          */
1876         value = local64_read(&next_event->count);
1877         value = local64_xchg(&event->count, value);
1878         local64_set(&next_event->count, value);
1879 
1880         swap(event->total_time_enabled, next_event->total_time_enabled);
1881         swap(event->total_time_running, next_event->total_time_running);
1882 
1883         /*
1884          * Since we swizzled the values, update the user visible data too.
1885          */
1886         perf_event_update_userpage(event);
1887         perf_event_update_userpage(next_event);
1888 }
1889 
1890 #define list_next_entry(pos, member) \
1891         list_entry(pos->member.next, typeof(*pos), member)
1892 
1893 static void perf_event_sync_stat(struct perf_event_context *ctx,
1894                                    struct perf_event_context *next_ctx)
1895 {
1896         struct perf_event *event, *next_event;
1897 
1898         if (!ctx->nr_stat)
1899                 return;
1900 
1901         update_context_time(ctx);
1902 
1903         event = list_first_entry(&ctx->event_list,
1904                                    struct perf_event, event_entry);
1905 
1906         next_event = list_first_entry(&next_ctx->event_list,
1907                                         struct perf_event, event_entry);
1908 
1909         while (&event->event_entry != &ctx->event_list &&
1910                &next_event->event_entry != &next_ctx->event_list) {
1911 
1912                 __perf_event_sync_stat(event, next_event);
1913 
1914                 event = list_next_entry(event, event_entry);
1915                 next_event = list_next_entry(next_event, event_entry);
1916         }
1917 }
1918 
1919 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
1920                                          struct task_struct *next)
1921 {
1922         struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
1923         struct perf_event_context *next_ctx;
1924         struct perf_event_context *parent;
1925         struct perf_cpu_context *cpuctx;
1926         int do_switch = 1;
1927 
1928         if (likely(!ctx))
1929                 return;
1930 
1931         cpuctx = __get_cpu_context(ctx);
1932         if (!cpuctx->task_ctx)
1933                 return;
1934 
1935         rcu_read_lock();
1936         parent = rcu_dereference(ctx->parent_ctx);
1937         next_ctx = next->perf_event_ctxp[ctxn];
1938         if (parent && next_ctx &&
1939             rcu_dereference(next_ctx->parent_ctx) == parent) {
1940                 /*
1941                  * Looks like the two contexts are clones, so we might be
1942                  * able to optimize the context switch.  We lock both
1943                  * contexts and check that they are clones under the
1944                  * lock (including re-checking that neither has been
1945                  * uncloned in the meantime).  It doesn't matter which
1946                  * order we take the locks because no other cpu could
1947                  * be trying to lock both of these tasks.
1948                  */
1949                 raw_spin_lock(&ctx->lock);
1950                 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
1951                 if (context_equiv(ctx, next_ctx)) {
1952                         /*
1953                          * XXX do we need a memory barrier of sorts
1954                          * wrt to rcu_dereference() of perf_event_ctxp
1955                          */
1956                         task->perf_event_ctxp[ctxn] = next_ctx;
1957                         next->perf_event_ctxp[ctxn] = ctx;
1958                         ctx->task = next;
1959                         next_ctx->task = task;
1960                         do_switch = 0;
1961 
1962                         perf_event_sync_stat(ctx, next_ctx);
1963                 }
1964                 raw_spin_unlock(&next_ctx->lock);
1965                 raw_spin_unlock(&ctx->lock);
1966         }
1967         rcu_read_unlock();
1968 
1969         if (do_switch) {
1970                 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
1971                 cpuctx->task_ctx = NULL;
1972         }
1973 }
1974 
1975 #define for_each_task_context_nr(ctxn)                                  \
1976         for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
1977 
1978 /*
1979  * Called from scheduler to remove the events of the current task,
1980  * with interrupts disabled.
1981  *
1982  * We stop each event and update the event value in event->count.
1983  *
1984  * This does not protect us against NMI, but disable()
1985  * sets the disabled bit in the control field of event _before_
1986  * accessing the event control register. If a NMI hits, then it will
1987  * not restart the event.
1988  */
1989 void __perf_event_task_sched_out(struct task_struct *task,
1990                                  struct task_struct *next)
1991 {
1992         int ctxn;
1993 
1994         for_each_task_context_nr(ctxn)
1995                 perf_event_context_sched_out(task, ctxn, next);
1996 
1997         /*
1998          * if cgroup events exist on this CPU, then we need
1999          * to check if we have to switch out PMU state.
2000          * cgroup event are system-wide mode only
2001          */
2002         if (atomic_read(&__get_cpu_var(perf_cgroup_events)))
2003                 perf_cgroup_sched_out(task);
2004 }
2005 
2006 static void task_ctx_sched_out(struct perf_event_context *ctx,
2007                                enum event_type_t event_type)
2008 {
2009         struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2010 
2011         if (!cpuctx->task_ctx)
2012                 return;
2013 
2014         if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2015                 return;
2016 
2017         ctx_sched_out(ctx, cpuctx, event_type);
2018         cpuctx->task_ctx = NULL;
2019 }
2020 
2021 /*
2022  * Called with IRQs disabled
2023  */
2024 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
2025                               enum event_type_t event_type)
2026 {
2027         ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
2028 }
2029 
2030 static void
2031 ctx_pinned_sched_in(struct perf_event_context *ctx,
2032                     struct perf_cpu_context *cpuctx)
2033 {
2034         struct perf_event *event;
2035 
2036         list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
2037                 if (event->state <= PERF_EVENT_STATE_OFF)
2038                         continue;
2039                 if (!event_filter_match(event))
2040                         continue;
2041 
2042                 /* may need to reset tstamp_enabled */
2043                 if (is_cgroup_event(event))
2044                         perf_cgroup_mark_enabled(event, ctx);
2045 
2046                 if (group_can_go_on(event, cpuctx, 1))
2047                         group_sched_in(event, cpuctx, ctx);
2048 
2049                 /*
2050                  * If this pinned group hasn't been scheduled,
2051                  * put it in error state.
2052                  */
2053                 if (event->state == PERF_EVENT_STATE_INACTIVE) {
2054                         update_group_times(event);
2055                         event->state = PERF_EVENT_STATE_ERROR;
2056                 }
2057         }
2058 }
2059 
2060 static void
2061 ctx_flexible_sched_in(struct perf_event_context *ctx,
2062                       struct perf_cpu_context *cpuctx)
2063 {
2064         struct perf_event *event;
2065         int can_add_hw = 1;
2066 
2067         list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
2068                 /* Ignore events in OFF or ERROR state */
2069                 if (event->state <= PERF_EVENT_STATE_OFF)
2070                         continue;
2071                 /*
2072                  * Listen to the 'cpu' scheduling filter constraint
2073                  * of events:
2074                  */
2075                 if (!event_filter_match(event))
2076                         continue;
2077 
2078                 /* may need to reset tstamp_enabled */
2079                 if (is_cgroup_event(event))
2080                         perf_cgroup_mark_enabled(event, ctx);
2081 
2082                 if (group_can_go_on(event, cpuctx, can_add_hw)) {
2083                         if (group_sched_in(event, cpuctx, ctx))
2084                                 can_add_hw = 0;
2085                 }
2086         }
2087 }
2088 
2089 static void
2090 ctx_sched_in(struct perf_event_context *ctx,
2091              struct perf_cpu_context *cpuctx,
2092              enum event_type_t event_type,
2093              struct task_struct *task)
2094 {
2095         u64 now;
2096 
2097         raw_spin_lock(&ctx->lock);
2098         ctx->is_active = 1;
2099         if (likely(!ctx->nr_events))
2100                 goto out;
2101 
2102         now = perf_clock();
2103         ctx->timestamp = now;
2104         perf_cgroup_set_timestamp(task, ctx);
2105         /*
2106          * First go through the list and put on any pinned groups
2107          * in order to give them the best chance of going on.
2108          */
2109         if (event_type & EVENT_PINNED)
2110                 ctx_pinned_sched_in(ctx, cpuctx);
2111 
2112         /* Then walk through the lower prio flexible groups */
2113         if (event_type & EVENT_FLEXIBLE)
2114                 ctx_flexible_sched_in(ctx, cpuctx);
2115 
2116 out:
2117         raw_spin_unlock(&ctx->lock);
2118 }
2119 
2120 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
2121                              enum event_type_t event_type,
2122                              struct task_struct *task)
2123 {
2124         struct perf_event_context *ctx = &cpuctx->ctx;
2125 
2126         ctx_sched_in(ctx, cpuctx, event_type, task);
2127 }
2128 
2129 static void task_ctx_sched_in(struct perf_event_context *ctx,
2130                               enum event_type_t event_type)
2131 {
2132         struct perf_cpu_context *cpuctx;
2133 
2134         cpuctx = __get_cpu_context(ctx);
2135         if (cpuctx->task_ctx == ctx)
2136                 return;
2137 
2138         ctx_sched_in(ctx, cpuctx, event_type, NULL);
2139         cpuctx->task_ctx = ctx;
2140 }
2141 
2142 static void perf_event_context_sched_in(struct perf_event_context *ctx,
2143                                         struct task_struct *task)
2144 {
2145         struct perf_cpu_context *cpuctx;
2146 
2147         cpuctx = __get_cpu_context(ctx);
2148         if (cpuctx->task_ctx == ctx)
2149                 return;
2150 
2151         perf_pmu_disable(ctx->pmu);
2152         /*
2153          * We want to keep the following priority order:
2154          * cpu pinned (that don't need to move), task pinned,
2155          * cpu flexible, task flexible.
2156          */
2157         cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2158 
2159         ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
2160         cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
2161         ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
2162 
2163         cpuctx->task_ctx = ctx;
2164 
2165         /*
2166          * Since these rotations are per-cpu, we need to ensure the
2167          * cpu-context we got scheduled on is actually rotating.
2168          */
2169         perf_pmu_rotate_start(ctx->pmu);
2170         perf_pmu_enable(ctx->pmu);
2171 }
2172 
2173 /*
2174  * Called from scheduler to add the events of the current task
2175  * with interrupts disabled.
2176  *
2177  * We restore the event value and then enable it.
2178  *
2179  * This does not protect us against NMI, but enable()
2180  * sets the enabled bit in the control field of event _before_
2181  * accessing the event control register. If a NMI hits, then it will
2182  * keep the event running.
2183  */
2184 void __perf_event_task_sched_in(struct task_struct *task)
2185 {
2186         struct perf_event_context *ctx;
2187         int ctxn;
2188 
2189         for_each_task_context_nr(ctxn) {
2190                 ctx = task->perf_event_ctxp[ctxn];
2191                 if (likely(!ctx))
2192                         continue;
2193 
2194                 perf_event_context_sched_in(ctx, task);
2195         }
2196         /*
2197          * if cgroup events exist on this CPU, then we need
2198          * to check if we have to switch in PMU state.
2199          * cgroup event are system-wide mode only
2200          */
2201         if (atomic_read(&__get_cpu_var(perf_cgroup_events)))
2202                 perf_cgroup_sched_in(task);
2203 }
2204 
2205 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
2206 {
2207         u64 frequency = event->attr.sample_freq;
2208         u64 sec = NSEC_PER_SEC;
2209         u64 divisor, dividend;
2210 
2211         int count_fls, nsec_fls, frequency_fls, sec_fls;
2212 
2213         count_fls = fls64(count);
2214         nsec_fls = fls64(nsec);
2215         frequency_fls = fls64(frequency);
2216         sec_fls = 30;
2217 
2218         /*
2219          * We got @count in @nsec, with a target of sample_freq HZ
2220          * the target period becomes:
2221          *
2222          *             @count * 10^9
2223          * period = -------------------
2224          *          @nsec * sample_freq
2225          *
2226          */
2227 
2228         /*
2229          * Reduce accuracy by one bit such that @a and @b converge
2230          * to a similar magnitude.
2231          */
2232 #define REDUCE_FLS(a, b)                \
2233 do {                                    \
2234         if (a##_fls > b##_fls) {        \
2235                 a >>= 1;                \
2236                 a##_fls--;              \
2237         } else {                        \
2238                 b >>= 1;                \
2239                 b##_fls--;              \
2240         }                               \
2241 } while (0)
2242 
2243         /*
2244          * Reduce accuracy until either term fits in a u64, then proceed with
2245          * the other, so that finally we can do a u64/u64 division.
2246          */
2247         while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
2248                 REDUCE_FLS(nsec, frequency);
2249                 REDUCE_FLS(sec, count);
2250         }
2251 
2252         if (count_fls + sec_fls > 64) {
2253                 divisor = nsec * frequency;
2254 
2255                 while (count_fls + sec_fls > 64) {
2256                         REDUCE_FLS(count, sec);
2257                         divisor >>= 1;
2258                 }
2259 
2260                 dividend = count * sec;
2261         } else {
2262                 dividend = count * sec;
2263 
2264                 while (nsec_fls + frequency_fls > 64) {
2265                         REDUCE_FLS(nsec, frequency);
2266                         dividend >>= 1;
2267                 }
2268 
2269                 divisor = nsec * frequency;
2270         }
2271 
2272         if (!divisor)
2273                 return dividend;
2274 
2275         return div64_u64(dividend, divisor);
2276 }
2277 
2278 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count)
2279 {
2280         struct hw_perf_event *hwc = &event->hw;
2281         s64 period, sample_period;
2282         s64 delta;
2283 
2284         period = perf_calculate_period(event, nsec, count);
2285 
2286         delta = (s64)(period - hwc->sample_period);
2287         delta = (delta + 7) / 8; /* low pass filter */
2288 
2289         sample_period = hwc->sample_period + delta;
2290 
2291         if (!sample_period)
2292                 sample_period = 1;
2293 
2294         hwc->sample_period = sample_period;
2295 
2296         if (local64_read(&hwc->period_left) > 8*sample_period) {
2297                 event->pmu->stop(event, PERF_EF_UPDATE);
2298                 local64_set(&hwc->period_left, 0);
2299                 event->pmu->start(event, PERF_EF_RELOAD);
2300         }
2301 }
2302 
2303 static void perf_ctx_adjust_freq(struct perf_event_context *ctx, u64 period)
2304 {
2305         struct perf_event *event;
2306         struct hw_perf_event *hwc;
2307         u64 interrupts, now;
2308         s64 delta;
2309 
2310         raw_spin_lock(&ctx->lock);
2311         list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
2312                 if (event->state != PERF_EVENT_STATE_ACTIVE)
2313                         continue;
2314 
2315                 if (!event_filter_match(event))
2316                         continue;
2317 
2318                 hwc = &event->hw;
2319 
2320                 interrupts = hwc->interrupts;
2321                 hwc->interrupts = 0;
2322 
2323                 /*
2324                  * unthrottle events on the tick
2325                  */
2326                 if (interrupts == MAX_INTERRUPTS) {
2327                         perf_log_throttle(event, 1);
2328                         event->pmu->start(event, 0);
2329                 }
2330 
2331                 if (!event->attr.freq || !event->attr.sample_freq)
2332                         continue;
2333 
2334                 event->pmu->read(event);
2335                 now = local64_read(&event->count);
2336                 delta = now - hwc->freq_count_stamp;
2337                 hwc->freq_count_stamp = now;
2338 
2339                 if (delta > 0)
2340                         perf_adjust_period(event, period, delta);
2341         }
2342         raw_spin_unlock(&ctx->lock);
2343 }
2344 
2345 /*
2346  * Round-robin a context's events:
2347  */
2348 static void rotate_ctx(struct perf_event_context *ctx)
2349 {
2350         raw_spin_lock(&ctx->lock);
2351 
2352         /*
2353          * Rotate the first entry last of non-pinned groups. Rotation might be
2354          * disabled by the inheritance code.
2355          */
2356         if (!ctx->rotate_disable)
2357                 list_rotate_left(&ctx->flexible_groups);
2358 
2359         raw_spin_unlock(&ctx->lock);
2360 }
2361 
2362 /*
2363  * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized
2364  * because they're strictly cpu affine and rotate_start is called with IRQs
2365  * disabled, while rotate_context is called from IRQ context.
2366  */
2367 static void perf_rotate_context(struct perf_cpu_context *cpuctx)
2368 {
2369         u64 interval = (u64)cpuctx->jiffies_interval * TICK_NSEC;
2370         struct perf_event_context *ctx = NULL;
2371         int rotate = 0, remove = 1;
2372 
2373         if (cpuctx->ctx.nr_events) {
2374                 remove = 0;
2375                 if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
2376                         rotate = 1;
2377         }
2378 
2379         ctx = cpuctx->task_ctx;
2380         if (ctx && ctx->nr_events) {
2381                 remove = 0;
2382                 if (ctx->nr_events != ctx->nr_active)
2383                         rotate = 1;
2384         }
2385 
2386         perf_pmu_disable(cpuctx->ctx.pmu);
2387         perf_ctx_adjust_freq(&cpuctx->ctx, interval);
2388         if (ctx)
2389                 perf_ctx_adjust_freq(ctx, interval);
2390 
2391         if (!rotate)
2392                 goto done;
2393 
2394         cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2395         if (ctx)
2396                 task_ctx_sched_out(ctx, EVENT_FLEXIBLE);
2397 
2398         rotate_ctx(&cpuctx->ctx);
2399         if (ctx)
2400                 rotate_ctx(ctx);
2401 
2402         cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, current);
2403         if (ctx)
2404                 task_ctx_sched_in(ctx, EVENT_FLEXIBLE);
2405 
2406 done:
2407         if (remove)
2408                 list_del_init(&cpuctx->rotation_list);
2409 
2410         perf_pmu_enable(cpuctx->ctx.pmu);
2411 }
2412 
2413 void perf_event_task_tick(void)
2414 {
2415         struct list_head *head = &__get_cpu_var(rotation_list);
2416         struct perf_cpu_context *cpuctx, *tmp;
2417 
2418         WARN_ON(!irqs_disabled());
2419 
2420         list_for_each_entry_safe(cpuctx, tmp, head, rotation_list) {
2421                 if (cpuctx->jiffies_interval == 1 ||
2422                                 !(jiffies % cpuctx->jiffies_interval))
2423                         perf_rotate_context(cpuctx);
2424         }
2425 }
2426 
2427 static int event_enable_on_exec(struct perf_event *event,
2428                                 struct perf_event_context *ctx)
2429 {
2430         if (!event->attr.enable_on_exec)
2431                 return 0;
2432 
2433         event->attr.enable_on_exec = 0;
2434         if (event->state >= PERF_EVENT_STATE_INACTIVE)
2435                 return 0;
2436 
2437         __perf_event_mark_enabled(event, ctx);
2438 
2439         return 1;
2440 }
2441 
2442 /*
2443  * Enable all of a task's events that have been marked enable-on-exec.
2444  * This expects task == current.
2445  */
2446 static void perf_event_enable_on_exec(struct perf_event_context *ctx)
2447 {
2448         struct perf_event *event;
2449         unsigned long flags;
2450         int enabled = 0;
2451         int ret;
2452 
2453         local_irq_save(flags);
2454         if (!ctx || !ctx->nr_events)
2455                 goto out;
2456 
2457         /*
2458          * We must ctxsw out cgroup events to avoid conflict
2459          * when invoking perf_task_event_sched_in() later on
2460          * in this function. Otherwise we end up trying to
2461          * ctxswin cgroup events which are already scheduled
2462          * in.
2463          */
2464         perf_cgroup_sched_out(current);
2465         task_ctx_sched_out(ctx, EVENT_ALL);
2466 
2467         raw_spin_lock(&ctx->lock);
2468 
2469         list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
2470                 ret = event_enable_on_exec(event, ctx);
2471                 if (ret)
2472                         enabled = 1;
2473         }
2474 
2475         list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
2476                 ret = event_enable_on_exec(event, ctx);
2477                 if (ret)
2478                         enabled = 1;
2479         }
2480 
2481         /*
2482          * Unclone this context if we enabled any event.
2483          */
2484         if (enabled)
2485                 unclone_ctx(ctx);
2486 
2487         raw_spin_unlock(&ctx->lock);
2488 
2489         /*
2490          * Also calls ctxswin for cgroup events, if any:
2491          */
2492         perf_event_context_sched_in(ctx, ctx->task);
2493 out:
2494         local_irq_restore(flags);
2495 }
2496 
2497 /*
2498  * Cross CPU call to read the hardware event
2499  */
2500 static void __perf_event_read(void *info)
2501 {
2502         struct perf_event *event = info;
2503         struct perf_event_context *ctx = event->ctx;
2504         struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2505 
2506         /*
2507          * If this is a task context, we need to check whether it is
2508          * the current task context of this cpu.  If not it has been
2509          * scheduled out before the smp call arrived.  In that case
2510          * event->count would have been updated to a recent sample
2511          * when the event was scheduled out.
2512          */
2513         if (ctx->task && cpuctx->task_ctx != ctx)
2514                 return;
2515 
2516         raw_spin_lock(&ctx->lock);
2517         if (ctx->is_active) {
2518                 update_context_time(ctx);
2519                 update_cgrp_time_from_event(event);
2520         }
2521         update_event_times(event);
2522         if (event->state == PERF_EVENT_STATE_ACTIVE)
2523                 event->pmu->read(event);
2524         raw_spin_unlock(&ctx->lock);
2525 }
2526 
2527 static inline u64 perf_event_count(struct perf_event *event)
2528 {
2529         return local64_read(&event->count) + atomic64_read(&event->child_count);
2530 }
2531 
2532 static u64 perf_event_read(struct perf_event *event)
2533 {
2534         /*
2535          * If event is enabled and currently active on a CPU, update the
2536          * value in the event structure:
2537          */
2538         if (event->state == PERF_EVENT_STATE_ACTIVE) {
2539                 smp_call_function_single(event->oncpu,
2540                                          __perf_event_read, event, 1);
2541         } else if (event->state == PERF_EVENT_STATE_INACTIVE) {
2542                 struct perf_event_context *ctx = event->ctx;
2543                 unsigned long flags;
2544 
2545                 raw_spin_lock_irqsave(&ctx->lock, flags);
2546                 /*
2547                  * may read while context is not active
2548                  * (e.g., thread is blocked), in that case
2549                  * we cannot update context time
2550                  */
2551                 if (ctx->is_active) {
2552                         update_context_time(ctx);
2553                         update_cgrp_time_from_event(event);
2554                 }
2555                 update_event_times(event);
2556                 raw_spin_unlock_irqrestore(&ctx->lock, flags);
2557         }
2558 
2559         return perf_event_count(event);
2560 }
2561 
2562 /*
2563  * Callchain support
2564  */
2565 
2566 struct callchain_cpus_entries {
2567         struct rcu_head                 rcu_head;
2568         struct perf_callchain_entry     *cpu_entries[0];
2569 };
2570 
2571 static DEFINE_PER_CPU(int, callchain_recursion[PERF_NR_CONTEXTS]);
2572 static atomic_t nr_callchain_events;
2573 static DEFINE_MUTEX(callchain_mutex);
2574 struct callchain_cpus_entries *callchain_cpus_entries;
2575 
2576 
2577 __weak void perf_callchain_kernel(struct perf_callchain_entry *entry,
2578                                   struct pt_regs *regs)
2579 {
2580 }
2581 
2582 __weak void perf_callchain_user(struct perf_callchain_entry *entry,
2583                                 struct pt_regs *regs)
2584 {
2585 }
2586 
2587 static void release_callchain_buffers_rcu(struct rcu_head *head)
2588 {
2589         struct callchain_cpus_entries *entries;
2590         int cpu;
2591 
2592         entries = container_of(head, struct callchain_cpus_entries, rcu_head);
2593 
2594         for_each_possible_cpu(cpu)
2595                 kfree(entries->cpu_entries[cpu]);
2596 
2597         kfree(entries);
2598 }
2599 
2600 static void release_callchain_buffers(void)
2601 {
2602         struct callchain_cpus_entries *entries;
2603 
2604         entries = callchain_cpus_entries;
2605         rcu_assign_pointer(callchain_cpus_entries, NULL);
2606         call_rcu(&entries->rcu_head, release_callchain_buffers_rcu);
2607 }
2608 
2609 static int alloc_callchain_buffers(void)
2610 {
2611         int cpu;
2612         int size;
2613         struct callchain_cpus_entries *entries;
2614 
2615         /*
2616          * We can't use the percpu allocation API for data that can be
2617          * accessed from NMI. Use a temporary manual per cpu allocation
2618          * until that gets sorted out.
2619          */
2620         size = offsetof(struct callchain_cpus_entries, cpu_entries[nr_cpu_ids]);
2621 
2622         entries = kzalloc(size, GFP_KERNEL);
2623         if (!entries)
2624                 return -ENOMEM;
2625 
2626         size = sizeof(struct perf_callchain_entry) * PERF_NR_CONTEXTS;
2627 
2628         for_each_possible_cpu(cpu) {
2629                 entries->cpu_entries[cpu] = kmalloc_node(size, GFP_KERNEL,
2630                                                          cpu_to_node(cpu));
2631                 if (!entries->cpu_entries[cpu])
2632                         goto fail;
2633         }
2634 
2635         rcu_assign_pointer(callchain_cpus_entries, entries);
2636 
2637         return 0;
2638 
2639 fail:
2640         for_each_possible_cpu(cpu)
2641                 kfree(entries->cpu_entries[cpu]);
2642         kfree(entries);
2643 
2644         return -ENOMEM;
2645 }
2646 
2647 static int get_callchain_buffers(void)
2648 {
2649         int err = 0;
2650         int count;
2651 
2652         mutex_lock(&callchain_mutex);
2653 
2654         count = atomic_inc_return(&nr_callchain_events);
2655         if (WARN_ON_ONCE(count < 1)) {
2656                 err = -EINVAL;
2657                 goto exit;
2658         }
2659 
2660         if (count > 1) {
2661                 /* If the allocation failed, give up */
2662                 if (!callchain_cpus_entries)
2663                         err = -ENOMEM;
2664                 goto exit;
2665         }
2666 
2667         err = alloc_callchain_buffers();
2668         if (err)
2669                 release_callchain_buffers();
2670 exit:
2671         mutex_unlock(&callchain_mutex);
2672 
2673         return err;
2674 }
2675 
2676 static void put_callchain_buffers(void)
2677 {
2678         if (atomic_dec_and_mutex_lock(&nr_callchain_events, &callchain_mutex)) {
2679                 release_callchain_buffers();
2680                 mutex_unlock(&callchain_mutex);
2681         }
2682 }
2683 
2684 static int get_recursion_context(int *recursion)
2685 {
2686         int rctx;
2687 
2688         if (in_nmi())
2689                 rctx = 3;
2690         else if (in_irq())
2691                 rctx = 2;
2692         else if (in_softirq())
2693                 rctx = 1;
2694         else
2695                 rctx = 0;
2696 
2697         if (recursion[rctx])
2698                 return -1;
2699 
2700         recursion[rctx]++;
2701         barrier();
2702 
2703         return rctx;
2704 }
2705 
2706 static inline void put_recursion_context(int *recursion, int rctx)
2707 {
2708         barrier();
2709         recursion[rctx]--;
2710 }
2711 
2712 static struct perf_callchain_entry *get_callchain_entry(int *rctx)
2713 {
2714         int cpu;
2715         struct callchain_cpus_entries *entries;
2716 
2717         *rctx = get_recursion_context(__get_cpu_var(callchain_recursion));
2718         if (*rctx == -1)
2719                 return NULL;
2720 
2721         entries = rcu_dereference(callchain_cpus_entries);
2722         if (!entries)
2723                 return NULL;
2724 
2725         cpu = smp_processor_id();
2726 
2727         return &entries->cpu_entries[cpu][*rctx];
2728 }
2729 
2730 static void
2731 put_callchain_entry(int rctx)
2732 {
2733         put_recursion_context(__get_cpu_var(callchain_recursion), rctx);
2734 }
2735 
2736 static struct perf_callchain_entry *perf_callchain(struct pt_regs *regs)
2737 {
2738         int rctx;
2739         struct perf_callchain_entry *entry;
2740 
2741 
2742         entry = get_callchain_entry(&rctx);
2743         if (rctx == -1)
2744                 return NULL;
2745 
2746         if (!entry)
2747                 goto exit_put;
2748 
2749         entry->nr = 0;
2750 
2751         if (!user_mode(regs)) {
2752                 perf_callchain_store(entry, PERF_CONTEXT_KERNEL);
2753                 perf_callchain_kernel(entry, regs);
2754                 if (current->mm)
2755                         regs = task_pt_regs(current);
2756                 else
2757                         regs = NULL;
2758         }
2759 
2760         if (regs) {
2761                 perf_callchain_store(entry, PERF_CONTEXT_USER);
2762                 perf_callchain_user(entry, regs);
2763         }
2764 
2765 exit_put:
2766         put_callchain_entry(rctx);
2767 
2768         return entry;
2769 }
2770 
2771 /*
2772  * Initialize the perf_event context in a task_struct:
2773  */
2774 static void __perf_event_init_context(struct perf_event_context *ctx)
2775 {
2776         raw_spin_lock_init(&ctx->lock);
2777         mutex_init(&ctx->mutex);
2778         INIT_LIST_HEAD(&ctx->pinned_groups);
2779         INIT_LIST_HEAD(&ctx->flexible_groups);
2780         INIT_LIST_HEAD(&ctx->event_list);
2781         atomic_set(&ctx->refcount, 1);
2782 }
2783 
2784 static struct perf_event_context *
2785 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
2786 {
2787         struct perf_event_context *ctx;
2788 
2789         ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
2790         if (!ctx)
2791                 return NULL;
2792 
2793         __perf_event_init_context(ctx);
2794         if (task) {
2795                 ctx->task = task;
2796                 get_task_struct(task);
2797         }
2798         ctx->pmu = pmu;
2799 
2800         return ctx;
2801 }
2802 
2803 static struct task_struct *
2804 find_lively_task_by_vpid(pid_t vpid)
2805 {
2806         struct task_struct *task;
2807         int err;
2808 
2809         rcu_read_lock();
2810         if (!vpid)
2811                 task = current;
2812         else
2813                 task = find_task_by_vpid(vpid);
2814         if (task)
2815                 get_task_struct(task);
2816         rcu_read_unlock();
2817 
2818         if (!task)
2819                 return ERR_PTR(-ESRCH);
2820 
2821         /* Reuse ptrace permission checks for now. */
2822         err = -EACCES;
2823         if (!ptrace_may_access(task, PTRACE_MODE_READ))
2824                 goto errout;
2825 
2826         return task;
2827 errout:
2828         put_task_struct(task);
2829         return ERR_PTR(err);
2830 
2831 }
2832 
2833 /*
2834  * Returns a matching context with refcount and pincount.
2835  */
2836 static struct perf_event_context *
2837 find_get_context(struct pmu *pmu, struct task_struct *task, int cpu)
2838 {
2839         struct perf_event_context *ctx;
2840         struct perf_cpu_context *cpuctx;
2841         unsigned long flags;
2842         int ctxn, err;
2843 
2844         if (!task) {
2845                 /* Must be root to operate on a CPU event: */
2846                 if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
2847                         return ERR_PTR(-EACCES);
2848 
2849                 /*
2850                  * We could be clever and allow to attach a event to an
2851                  * offline CPU and activate it when the CPU comes up, but
2852                  * that's for later.
2853                  */
2854                 if (!cpu_online(cpu))
2855                         return ERR_PTR(-ENODEV);
2856 
2857                 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
2858                 ctx = &cpuctx->ctx;
2859                 get_ctx(ctx);
2860                 ++ctx->pin_count;
2861 
2862                 return ctx;
2863         }
2864 
2865         err = -EINVAL;
2866         ctxn = pmu->task_ctx_nr;
2867         if (ctxn < 0)
2868                 goto errout;
2869 
2870 retry:
2871         ctx = perf_lock_task_context(task, ctxn, &flags);
2872         if (ctx) {
2873                 unclone_ctx(ctx);
2874                 ++ctx->pin_count;
2875                 raw_spin_unlock_irqrestore(&ctx->lock, flags);
2876         }
2877 
2878         if (!ctx) {
2879                 ctx = alloc_perf_context(pmu, task);
2880                 err = -ENOMEM;
2881                 if (!ctx)
2882                         goto errout;
2883 
2884                 get_ctx(ctx);
2885 
2886                 err = 0;
2887                 mutex_lock(&task->perf_event_mutex);
2888                 /*
2889                  * If it has already passed perf_event_exit_task().
2890                  * we must see PF_EXITING, it takes this mutex too.
2891                  */
2892                 if (task->flags & PF_EXITING)
2893                         err = -ESRCH;
2894                 else if (task->perf_event_ctxp[ctxn])
2895                         err = -EAGAIN;
2896                 else {
2897                         ++ctx->pin_count;
2898                         rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
2899                 }
2900                 mutex_unlock(&task->perf_event_mutex);
2901 
2902                 if (unlikely(err)) {
2903                         put_task_struct(task);
2904                         kfree(ctx);
2905 
2906                         if (err == -EAGAIN)
2907                                 goto retry;
2908                         goto errout;
2909                 }
2910         }
2911 
2912         return ctx;
2913 
2914 errout:
2915         return ERR_PTR(err);
2916 }
2917 
2918 static void perf_event_free_filter(struct perf_event *event);
2919 
2920 static void free_event_rcu(struct rcu_head *head)
2921 {
2922         struct perf_event *event;
2923 
2924         event = container_of(head, struct perf_event, rcu_head);
2925         if (event->ns)
2926                 put_pid_ns(event->ns);
2927         perf_event_free_filter(event);
2928         kfree(event);
2929 }
2930 
2931 static void perf_buffer_put(struct perf_buffer *buffer);
2932 
2933 static void free_event(struct perf_event *event)
2934 {
2935         irq_work_sync(&event->pending);
2936 
2937         if (!event->parent) {
2938                 if (event->attach_state & PERF_ATTACH_TASK)
2939                         jump_label_dec(&perf_sched_events);
2940                 if (event->attr.mmap || event->attr.mmap_data)
2941                         atomic_dec(&nr_mmap_events);
2942                 if (event->attr.comm)
2943                         atomic_dec(&nr_comm_events);
2944                 if (event->attr.task)
2945                         atomic_dec(&nr_task_events);
2946                 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
2947                         put_callchain_buffers();
2948                 if (is_cgroup_event(event)) {
2949                         atomic_dec(&per_cpu(perf_cgroup_events, event->cpu));
2950                         jump_label_dec(&perf_sched_events);
2951                 }
2952         }
2953 
2954         if (event->buffer) {
2955                 perf_buffer_put(event->buffer);
2956                 event->buffer = NULL;
2957         }
2958 
2959         if (is_cgroup_event(event))
2960                 perf_detach_cgroup(event);
2961 
2962         if (event->destroy)
2963                 event->destroy(event);
2964 
2965         if (event->ctx)
2966                 put_ctx(event->ctx);
2967 
2968         call_rcu(&event->rcu_head, free_event_rcu);
2969 }
2970 
2971 int perf_event_release_kernel(struct perf_event *event)
2972 {
2973         struct perf_event_context *ctx = event->ctx;
2974 
2975         /*
2976          * Remove from the PMU, can't get re-enabled since we got
2977          * here because the last ref went.
2978          */
2979         perf_event_disable(event);
2980 
2981         WARN_ON_ONCE(ctx->parent_ctx);
2982         /*
2983          * There are two ways this annotation is useful:
2984          *
2985          *  1) there is a lock recursion from perf_event_exit_task
2986          *     see the comment there.
2987          *
2988          *  2) there is a lock-inversion with mmap_sem through
2989          *     perf_event_read_group(), which takes faults while
2990          *     holding ctx->mutex, however this is called after
2991          *     the last filedesc died, so there is no possibility
2992          *     to trigger the AB-BA case.
2993          */
2994         mutex_lock_nested(&ctx->mutex, SINGLE_DEPTH_NESTING);
2995         raw_spin_lock_irq(&ctx->lock);
2996         perf_group_detach(event);
2997         list_del_event(event, ctx);
2998         raw_spin_unlock_irq(&ctx->lock);
2999         mutex_unlock(&ctx->mutex);
3000 
3001         free_event(event);
3002 
3003         return 0;
3004 }
3005 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
3006 
3007 /*
3008  * Called when the last reference to the file is gone.
3009  */
3010 static void put_event(struct perf_event *event)
3011 {
3012         struct task_struct *owner;
3013 
3014         if (!atomic_long_dec_and_test(&event->refcount))
3015                 return;
3016 
3017         rcu_read_lock();
3018         owner = ACCESS_ONCE(event->owner);
3019         /*
3020          * Matches the smp_wmb() in perf_event_exit_task(). If we observe
3021          * !owner it means the list deletion is complete and we can indeed
3022          * free this event, otherwise we need to serialize on
3023          * owner->perf_event_mutex.
3024          */
3025         smp_read_barrier_depends();
3026         if (owner) {
3027                 /*
3028                  * Since delayed_put_task_struct() also drops the last
3029                  * task reference we can safely take a new reference
3030                  * while holding the rcu_read_lock().
3031                  */
3032                 get_task_struct(owner);
3033         }
3034         rcu_read_unlock();
3035 
3036         if (owner) {
3037                 mutex_lock(&owner->perf_event_mutex);
3038                 /*
3039                  * We have to re-check the event->owner field, if it is cleared
3040                  * we raced with perf_event_exit_task(), acquiring the mutex
3041                  * ensured they're done, and we can proceed with freeing the
3042                  * event.
3043                  */
3044                 if (event->owner)
3045                         list_del_init(&event->owner_entry);
3046                 mutex_unlock(&owner->perf_event_mutex);
3047                 put_task_struct(owner);
3048         }
3049 
3050         perf_event_release_kernel(event);
3051 }
3052 
3053 static int perf_release(struct inode *inode, struct file *file)
3054 {
3055         put_event(file->private_data);
3056         return 0;
3057 }
3058 
3059 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
3060 {
3061         struct perf_event *child;
3062         u64 total = 0;
3063 
3064         *enabled = 0;
3065         *running = 0;
3066 
3067         mutex_lock(&event->child_mutex);
3068         total += perf_event_read(event);
3069         *enabled += event->total_time_enabled +
3070                         atomic64_read(&event->child_total_time_enabled);
3071         *running += event->total_time_running +
3072                         atomic64_read(&event->child_total_time_running);
3073 
3074         list_for_each_entry(child, &event->child_list, child_list) {
3075                 total += perf_event_read(child);
3076                 *enabled += child->total_time_enabled;
3077                 *running += child->total_time_running;
3078         }
3079         mutex_unlock(&event->child_mutex);
3080 
3081         return total;
3082 }
3083 EXPORT_SYMBOL_GPL(perf_event_read_value);
3084 
3085 static int perf_event_read_group(struct perf_event *event,
3086                                    u64 read_format, char __user *buf)
3087 {
3088         struct perf_event *leader = event->group_leader, *sub;
3089         int n = 0, size = 0, ret = -EFAULT;
3090         struct perf_event_context *ctx = leader->ctx;
3091         u64 values[5];
3092         u64 count, enabled, running;
3093 
3094         mutex_lock(&ctx->mutex);
3095         count = perf_event_read_value(leader, &enabled, &running);
3096 
3097         values[n++] = 1 + leader->nr_siblings;
3098         if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3099                 values[n++] = enabled;
3100         if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3101                 values[n++] = running;
3102         values[n++] = count;
3103         if (read_format & PERF_FORMAT_ID)
3104                 values[n++] = primary_event_id(leader);
3105 
3106         size = n * sizeof(u64);
3107 
3108         if (copy_to_user(buf, values, size))
3109                 goto unlock;
3110 
3111         ret = size;
3112 
3113         list_for_each_entry(sub, &leader->sibling_list, group_entry) {
3114                 n = 0;
3115 
3116                 values[n++] = perf_event_read_value(sub, &enabled, &running);
3117                 if (read_format & PERF_FORMAT_ID)
3118                         values[n++] = primary_event_id(sub);
3119 
3120                 size = n * sizeof(u64);
3121 
3122                 if (copy_to_user(buf + ret, values, size)) {
3123                         ret = -EFAULT;
3124                         goto unlock;
3125                 }
3126 
3127                 ret += size;
3128         }
3129 unlock:
3130         mutex_unlock(&ctx->mutex);
3131 
3132         return ret;
3133 }
3134 
3135 static int perf_event_read_one(struct perf_event *event,
3136                                  u64 read_format, char __user *buf)
3137 {
3138         u64 enabled, running;
3139         u64 values[4];
3140         int n = 0;
3141 
3142         values[n++] = perf_event_read_value(event, &enabled, &running);
3143         if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3144                 values[n++] = enabled;
3145         if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3146                 values[n++] = running;
3147         if (read_format & PERF_FORMAT_ID)
3148                 values[n++] = primary_event_id(event);
3149 
3150         if (copy_to_user(buf, values, n * sizeof(u64)))
3151                 return -EFAULT;
3152 
3153         return n * sizeof(u64);
3154 }
3155 
3156 /*
3157  * Read the performance event - simple non blocking version for now
3158  */
3159 static ssize_t
3160 perf_read_hw(struct perf_event *event, char __user *buf, size_t count)
3161 {
3162         u64 read_format = event->attr.read_format;
3163         int ret;
3164 
3165         /*
3166          * Return end-of-file for a read on a event that is in
3167          * error state (i.e. because it was pinned but it couldn't be
3168          * scheduled on to the CPU at some point).
3169          */
3170         if (event->state == PERF_EVENT_STATE_ERROR)
3171                 return 0;
3172 
3173         if (count < event->read_size)
3174                 return -ENOSPC;
3175 
3176         WARN_ON_ONCE(event->ctx->parent_ctx);
3177         if (read_format & PERF_FORMAT_GROUP)
3178                 ret = perf_event_read_group(event, read_format, buf);
3179         else
3180                 ret = perf_event_read_one(event, read_format, buf);
3181 
3182         return ret;
3183 }
3184 
3185 static ssize_t
3186 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
3187 {
3188         struct perf_event *event = file->private_data;
3189 
3190         return perf_read_hw(event, buf, count);
3191 }
3192 
3193 static unsigned int perf_poll(struct file *file, poll_table *wait)
3194 {
3195         struct perf_event *event = file->private_data;
3196         struct perf_buffer *buffer;
3197         unsigned int events = POLL_HUP;
3198 
3199         rcu_read_lock();
3200         buffer = rcu_dereference(event->buffer);
3201         if (buffer)
3202                 events = atomic_xchg(&buffer->poll, 0);
3203         rcu_read_unlock();
3204 
3205         poll_wait(file, &event->waitq, wait);
3206 
3207         return events;
3208 }
3209 
3210 static void perf_event_reset(struct perf_event *event)
3211 {
3212         (void)perf_event_read(event);
3213         local64_set(&event->count, 0);
3214         perf_event_update_userpage(event);
3215 }
3216 
3217 /*
3218  * Holding the top-level event's child_mutex means that any
3219  * descendant process that has inherited this event will block
3220  * in sync_child_event if it goes to exit, thus satisfying the
3221  * task existence requirements of perf_event_enable/disable.
3222  */
3223 static void perf_event_for_each_child(struct perf_event *event,
3224                                         void (*func)(struct perf_event *))
3225 {
3226         struct perf_event *child;
3227 
3228         WARN_ON_ONCE(event->ctx->parent_ctx);
3229         mutex_lock(&event->child_mutex);
3230         func(event);
3231         list_for_each_entry(child, &event->child_list, child_list)
3232                 func(child);
3233         mutex_unlock(&event->child_mutex);
3234 }
3235 
3236 static void perf_event_for_each(struct perf_event *event,
3237                                   void (*func)(struct perf_event *))
3238 {
3239         struct perf_event_context *ctx = event->ctx;
3240         struct perf_event *sibling;
3241 
3242         WARN_ON_ONCE(ctx->parent_ctx);
3243         mutex_lock(&ctx->mutex);
3244         event = event->group_leader;
3245 
3246         perf_event_for_each_child(event, func);
3247         func(event);
3248         list_for_each_entry(sibling, &event->sibling_list, group_entry)
3249                 perf_event_for_each_child(event, func);
3250         mutex_unlock(&ctx->mutex);
3251 }
3252 
3253 static int perf_event_period(struct perf_event *event, u64 __user *arg)
3254 {
3255         struct perf_event_context *ctx = event->ctx;
3256         int ret = 0;
3257         u64 value;
3258 
3259         if (!is_sampling_event(event))
3260                 return -EINVAL;
3261 
3262         if (copy_from_user(&value, arg, sizeof(value)))
3263                 return -EFAULT;
3264 
3265         if (!value)
3266                 return -EINVAL;
3267 
3268         raw_spin_lock_irq(&ctx->lock);
3269         if (event->attr.freq) {
3270                 if (value > sysctl_perf_event_sample_rate) {
3271                         ret = -EINVAL;
3272                         goto unlock;
3273                 }
3274 
3275                 event->attr.sample_freq = value;
3276         } else {
3277                 event->attr.sample_period = value;
3278                 event->hw.sample_period = value;
3279         }
3280 unlock:
3281         raw_spin_unlock_irq(&ctx->lock);
3282 
3283         return ret;
3284 }
3285 
3286 static const struct file_operations perf_fops;
3287 
3288 static struct file *perf_fget_light(int fd, int *fput_needed)
3289 {
3290         struct file *file;
3291 
3292         file = fget_light(fd, fput_needed);
3293         if (!file)
3294                 return ERR_PTR(-EBADF);
3295 
3296         if (file->f_op != &perf_fops) {
3297                 fput_light(file, *fput_needed);
3298                 *fput_needed = 0;
3299                 return ERR_PTR(-EBADF);
3300         }
3301 
3302         return file;
3303 }
3304 
3305 static int perf_event_set_output(struct perf_event *event,
3306                                  struct perf_event *output_event);
3307 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
3308 
3309 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
3310 {
3311         struct perf_event *event = file->private_data;
3312         void (*func)(struct perf_event *);
3313         u32 flags = arg;
3314 
3315         switch (cmd) {
3316         case PERF_EVENT_IOC_ENABLE:
3317                 func = perf_event_enable;
3318                 break;
3319         case PERF_EVENT_IOC_DISABLE:
3320                 func = perf_event_disable;
3321                 break;
3322         case PERF_EVENT_IOC_RESET:
3323                 func = perf_event_reset;
3324                 break;
3325 
3326         case PERF_EVENT_IOC_REFRESH:
3327                 return perf_event_refresh(event, arg);
3328 
3329         case PERF_EVENT_IOC_PERIOD:
3330                 return perf_event_period(event, (u64 __user *)arg);
3331 
3332         case PERF_EVENT_IOC_SET_OUTPUT:
3333         {
3334                 struct file *output_file = NULL;
3335                 struct perf_event *output_event = NULL;
3336                 int fput_needed = 0;
3337                 int ret;
3338 
3339                 if (arg != -1) {
3340                         output_file = perf_fget_light(arg, &fput_needed);
3341                         if (IS_ERR(output_file))
3342                                 return PTR_ERR(output_file);
3343                         output_event = output_file->private_data;
3344                 }
3345 
3346                 ret = perf_event_set_output(event, output_event);
3347                 if (output_event)
3348                         fput_light(output_file, fput_needed);
3349 
3350                 return ret;
3351         }
3352 
3353         case PERF_EVENT_IOC_SET_FILTER:
3354                 return perf_event_set_filter(event, (void __user *)arg);
3355 
3356         default:
3357                 return -ENOTTY;
3358         }
3359 
3360         if (flags & PERF_IOC_FLAG_GROUP)
3361                 perf_event_for_each(event, func);
3362         else
3363                 perf_event_for_each_child(event, func);
3364 
3365         return 0;
3366 }
3367 
3368 int perf_event_task_enable(void)
3369 {
3370         struct perf_event *event;
3371 
3372         mutex_lock(&current->perf_event_mutex);
3373         list_for_each_entry(event, &current->perf_event_list, owner_entry)
3374                 perf_event_for_each_child(event, perf_event_enable);
3375         mutex_unlock(&current->perf_event_mutex);
3376 
3377         return 0;
3378 }
3379 
3380 int perf_event_task_disable(void)
3381 {
3382         struct perf_event *event;
3383 
3384         mutex_lock(&current->perf_event_mutex);
3385         list_for_each_entry(event, &current->perf_event_list, owner_entry)
3386                 perf_event_for_each_child(event, perf_event_disable);
3387         mutex_unlock(&current->perf_event_mutex);
3388 
3389         return 0;
3390 }
3391 
3392 #ifndef PERF_EVENT_INDEX_OFFSET
3393 # define PERF_EVENT_INDEX_OFFSET 0
3394 #endif
3395 
3396 static int perf_event_index(struct perf_event *event)
3397 {
3398         if (event->hw.state & PERF_HES_STOPPED)
3399                 return 0;
3400 
3401         if (event->state != PERF_EVENT_STATE_ACTIVE)
3402                 return 0;
3403 
3404         return event->hw.idx + 1 - PERF_EVENT_INDEX_OFFSET;
3405 }
3406 
3407 /*
3408  * Callers need to ensure there can be no nesting of this function, otherwise
3409  * the seqlock logic goes bad. We can not serialize this because the arch
3410  * code calls this from NMI context.
3411  */
3412 void perf_event_update_userpage(struct perf_event *event)
3413 {
3414         struct perf_event_mmap_page *userpg;
3415         struct perf_buffer *buffer;
3416 
3417         rcu_read_lock();
3418         buffer = rcu_dereference(event->buffer);
3419         if (!buffer)
3420                 goto unlock;
3421 
3422         userpg = buffer->user_page;
3423 
3424         /*
3425          * Disable preemption so as to not let the corresponding user-space
3426          * spin too long if we get preempted.
3427          */
3428         preempt_disable();
3429         ++userpg->lock;
3430         barrier();
3431         userpg->index = perf_event_index(event);
3432         userpg->offset = perf_event_count(event);
3433         if (event->state == PERF_EVENT_STATE_ACTIVE)
3434                 userpg->offset -= local64_read(&event->hw.prev_count);
3435 
3436         userpg->time_enabled = event->total_time_enabled +
3437                         atomic64_read(&event->child_total_time_enabled);
3438 
3439         userpg->time_running = event->total_time_running +
3440                         atomic64_read(&event->child_total_time_running);
3441 
3442         barrier();
3443         ++userpg->lock;
3444         preempt_enable();
3445 unlock:
3446         rcu_read_unlock();
3447 }
3448 
3449 static unsigned long perf_data_size(struct perf_buffer *buffer);
3450 
3451 static void
3452 perf_buffer_init(struct perf_buffer *buffer, long watermark, int flags)
3453 {
3454         long max_size = perf_data_size(buffer);
3455 
3456         if (watermark)
3457                 buffer->watermark = min(max_size, watermark);
3458 
3459         if (!buffer->watermark)
3460                 buffer->watermark = max_size / 2;
3461 
3462         if (flags & PERF_BUFFER_WRITABLE)
3463                 buffer->writable = 1;
3464 
3465         atomic_set(&buffer->refcount, 1);
3466 }
3467 
3468 #ifndef CONFIG_PERF_USE_VMALLOC
3469 
3470 /*
3471  * Back perf_mmap() with regular GFP_KERNEL-0 pages.
3472  */
3473 
3474 static struct page *
3475 perf_mmap_to_page(struct perf_buffer *buffer, unsigned long pgoff)
3476 {
3477         if (pgoff > buffer->nr_pages)
3478                 return NULL;
3479 
3480         if (pgoff == 0)
3481                 return virt_to_page(buffer->user_page);
3482 
3483         return virt_to_page(buffer->data_pages[pgoff - 1]);
3484 }
3485 
3486 static void *perf_mmap_alloc_page(int cpu)
3487 {
3488         struct page *page;
3489         int node;
3490 
3491         node = (cpu == -1) ? cpu : cpu_to_node(cpu);
3492         page = alloc_pages_node(node, GFP_KERNEL | __GFP_ZERO, 0);
3493         if (!page)
3494                 return NULL;
3495 
3496         return page_address(page);
3497 }
3498 
3499 static struct perf_buffer *
3500 perf_buffer_alloc(int nr_pages, long watermark, int cpu, int flags)
3501 {
3502         struct perf_buffer *buffer;
3503         unsigned long size;
3504         int i;
3505 
3506         size = sizeof(struct perf_buffer);
3507         size += nr_pages * sizeof(void *);
3508 
3509         buffer = kzalloc(size, GFP_KERNEL);
3510         if (!buffer)
3511                 goto fail;
3512 
3513         buffer->user_page = perf_mmap_alloc_page(cpu);
3514         if (!buffer->user_page)
3515                 goto fail_user_page;
3516 
3517         for (i = 0; i < nr_pages; i++) {
3518                 buffer->data_pages[i] = perf_mmap_alloc_page(cpu);
3519                 if (!buffer->data_pages[i])
3520                         goto fail_data_pages;
3521         }
3522 
3523         buffer->nr_pages = nr_pages;
3524 
3525         perf_buffer_init(buffer, watermark, flags);
3526 
3527         return buffer;
3528 
3529 fail_data_pages:
3530         for (i--; i >= 0; i--)
3531                 free_page((unsigned long)buffer->data_pages[i]);
3532 
3533         free_page((unsigned long)buffer->user_page);
3534 
3535 fail_user_page:
3536         kfree(buffer);
3537 
3538 fail:
3539         return NULL;
3540 }
3541 
3542 static void perf_mmap_free_page(unsigned long addr)
3543 {
3544         struct page *page = virt_to_page((void *)addr);
3545 
3546         page->mapping = NULL;
3547         __free_page(page);
3548 }
3549 
3550 static void perf_buffer_free(struct perf_buffer *buffer)
3551 {
3552         int i;
3553 
3554         perf_mmap_free_page((unsigned long)buffer->user_page);
3555         for (i = 0; i < buffer->nr_pages; i++)
3556                 perf_mmap_free_page((unsigned long)buffer->data_pages[i]);
3557         kfree(buffer);
3558 }
3559 
3560 static inline int page_order(struct perf_buffer *buffer)
3561 {
3562         return 0;
3563 }
3564 
3565 #else
3566 
3567 /*
3568  * Back perf_mmap() with vmalloc memory.
3569  *
3570  * Required for architectures that have d-cache aliasing issues.
3571  */
3572 
3573 static inline int page_order(struct perf_buffer *buffer)
3574 {
3575         return buffer->page_order;
3576 }
3577 
3578 static struct page *
3579 perf_mmap_to_page(struct perf_buffer *buffer, unsigned long pgoff)
3580 {
3581         if (pgoff > (1UL << page_order(buffer)))
3582                 return NULL;
3583 
3584         return vmalloc_to_page((void *)buffer->user_page + pgoff * PAGE_SIZE);
3585 }
3586 
3587 static void perf_mmap_unmark_page(void *addr)
3588 {
3589         struct page *page = vmalloc_to_page(addr);
3590 
3591         page->mapping = NULL;
3592 }
3593 
3594 static void perf_buffer_free_work(struct work_struct *work)
3595 {
3596         struct perf_buffer *buffer;
3597         void *base;
3598         int i, nr;
3599 
3600         buffer = container_of(work, struct perf_buffer, work);
3601         nr = 1 << page_order(buffer);
3602 
3603         base = buffer->user_page;
3604         for (i = 0; i < nr + 1; i++)
3605                 perf_mmap_unmark_page(base + (i * PAGE_SIZE));
3606 
3607         vfree(base);
3608         kfree(buffer);
3609 }
3610 
3611 static void perf_buffer_free(struct perf_buffer *buffer)
3612 {
3613         schedule_work(&buffer->work);
3614 }
3615 
3616 static struct perf_buffer *
3617 perf_buffer_alloc(int nr_pages, long watermark, int cpu, int flags)
3618 {
3619         struct perf_buffer *buffer;
3620         unsigned long size;
3621         void *all_buf;
3622 
3623         size = sizeof(struct perf_buffer);
3624         size += sizeof(void *);
3625 
3626         buffer = kzalloc(size, GFP_KERNEL);
3627         if (!buffer)
3628                 goto fail;
3629 
3630         INIT_WORK(&buffer->work, perf_buffer_free_work);
3631 
3632         all_buf = vmalloc_user((nr_pages + 1) * PAGE_SIZE);
3633         if (!all_buf)
3634                 goto fail_all_buf;
3635 
3636         buffer->user_page = all_buf;
3637         buffer->data_pages[0] = all_buf + PAGE_SIZE;
3638         buffer->page_order = ilog2(nr_pages);
3639         buffer->nr_pages = 1;
3640 
3641         perf_buffer_init(buffer, watermark, flags);
3642 
3643         return buffer;
3644 
3645 fail_all_buf:
3646         kfree(buffer);
3647 
3648 fail:
3649         return NULL;
3650 }
3651 
3652 #endif
3653 
3654 static unsigned long perf_data_size(struct perf_buffer *buffer)
3655 {
3656         return buffer->nr_pages << (PAGE_SHIFT + page_order(buffer));
3657 }
3658 
3659 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
3660 {
3661         struct perf_event *event = vma->vm_file->private_data;
3662         struct perf_buffer *buffer;
3663         int ret = VM_FAULT_SIGBUS;
3664 
3665         if (vmf->flags & FAULT_FLAG_MKWRITE) {
3666                 if (vmf->pgoff == 0)
3667                         ret = 0;
3668                 return ret;
3669         }
3670 
3671         rcu_read_lock();
3672         buffer = rcu_dereference(event->buffer);
3673         if (!buffer)
3674                 goto unlock;
3675 
3676         if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
3677                 goto unlock;
3678 
3679         vmf->page = perf_mmap_to_page(buffer, vmf->pgoff);
3680         if (!vmf->page)
3681                 goto unlock;
3682 
3683         get_page(vmf->page);
3684         vmf->page->mapping = vma->vm_file->f_mapping;
3685         vmf->page->index   = vmf->pgoff;
3686 
3687         ret = 0;
3688 unlock:
3689         rcu_read_unlock();
3690 
3691         return ret;
3692 }
3693 
3694 static void perf_buffer_free_rcu(struct rcu_head *rcu_head)
3695 {
3696         struct perf_buffer *buffer;
3697 
3698         buffer = container_of(rcu_head, struct perf_buffer, rcu_head);
3699         perf_buffer_free(buffer);
3700 }
3701 
3702 static struct perf_buffer *perf_buffer_get(struct perf_event *event)
3703 {
3704         struct perf_buffer *buffer;
3705 
3706         rcu_read_lock();
3707         buffer = rcu_dereference(event->buffer);
3708         if (buffer) {
3709                 if (!atomic_inc_not_zero(&buffer->refcount))
3710                         buffer = NULL;
3711         }
3712         rcu_read_unlock();
3713 
3714         return buffer;
3715 }
3716 
3717 static void perf_buffer_put(struct perf_buffer *buffer)
3718 {
3719         if (!atomic_dec_and_test(&buffer->refcount))
3720                 return;
3721 
3722         call_rcu(&buffer->rcu_head, perf_buffer_free_rcu);
3723 }
3724 
3725 static void perf_mmap_open(struct vm_area_struct *vma)
3726 {
3727         struct perf_event *event = vma->vm_file->private_data;
3728 
3729         atomic_inc(&event->mmap_count);
3730 }
3731 
3732 static void perf_mmap_close(struct vm_area_struct *vma)
3733 {
3734         struct perf_event *event = vma->vm_file->private_data;
3735 
3736         if (atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex)) {
3737                 unsigned long size = perf_data_size(event->buffer);
3738                 struct user_struct *user = event->mmap_user;
3739                 struct perf_buffer *buffer = event->buffer;
3740 
3741                 atomic_long_sub((size >> PAGE_SHIFT) + 1, &user->locked_vm);
3742                 vma->vm_mm->locked_vm -= event->mmap_locked;
3743                 rcu_assign_pointer(event->buffer, NULL);
3744                 mutex_unlock(&event->mmap_mutex);
3745 
3746                 perf_buffer_put(buffer);
3747                 free_uid(user);
3748         }
3749 }
3750 
3751 static const struct vm_operations_struct perf_mmap_vmops = {
3752         .open           = perf_mmap_open,
3753         .close          = perf_mmap_close,
3754         .fault          = perf_mmap_fault,
3755         .page_mkwrite   = perf_mmap_fault,
3756 };
3757 
3758 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
3759 {
3760         struct perf_event *event = file->private_data;
3761         unsigned long user_locked, user_lock_limit;
3762         struct user_struct *user = current_user();
3763         unsigned long locked, lock_limit;
3764         struct perf_buffer *buffer;
3765         unsigned long vma_size;
3766         unsigned long nr_pages;
3767         long user_extra, extra;
3768         int ret = 0, flags = 0;
3769 
3770         /*
3771          * Don't allow mmap() of inherited per-task counters. This would
3772          * create a performance issue due to all children writing to the
3773          * same buffer.
3774          */
3775         if (event->cpu == -1 && event->attr.inherit)
3776                 return -EINVAL;
3777 
3778         if (!(vma->vm_flags & VM_SHARED))
3779                 return -EINVAL;
3780 
3781         vma_size = vma->vm_end - vma->vm_start;
3782         nr_pages = (vma_size / PAGE_SIZE) - 1;
3783 
3784         /*
3785          * If we have buffer pages ensure they're a power-of-two number, so we
3786          * can do bitmasks instead of modulo.
3787          */
3788         if (nr_pages != 0 && !is_power_of_2(nr_pages))
3789                 return -EINVAL;
3790 
3791         if (vma_size != PAGE_SIZE * (1 + nr_pages))
3792                 return -EINVAL;
3793 
3794         if (vma->vm_pgoff != 0)
3795                 return -EINVAL;
3796 
3797         WARN_ON_ONCE(event->ctx->parent_ctx);
3798         mutex_lock(&event->mmap_mutex);
3799         if (event->buffer) {
3800                 if (event->buffer->nr_pages == nr_pages)
3801                         atomic_inc(&event->buffer->refcount);
3802                 else
3803                         ret = -EINVAL;
3804                 goto unlock;
3805         }
3806 
3807         user_extra = nr_pages + 1;
3808         user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
3809 
3810         /*
3811          * Increase the limit linearly with more CPUs:
3812          */
3813         user_lock_limit *= num_online_cpus();
3814 
3815         user_locked = atomic_long_read(&user->locked_vm) + user_extra;
3816 
3817         extra = 0;
3818         if (user_locked > user_lock_limit)
3819                 extra = user_locked - user_lock_limit;
3820 
3821         lock_limit = rlimit(RLIMIT_MEMLOCK);
3822         lock_limit >>= PAGE_SHIFT;
3823         locked = vma->vm_mm->locked_vm + extra;
3824 
3825         if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
3826                 !capable(CAP_IPC_LOCK)) {
3827                 ret = -EPERM;
3828                 goto unlock;
3829         }
3830 
3831         WARN_ON(event->buffer);
3832 
3833         if (vma->vm_flags & VM_WRITE)
3834                 flags |= PERF_BUFFER_WRITABLE;
3835 
3836         buffer = perf_buffer_alloc(nr_pages, event->attr.wakeup_watermark,
3837                                    event->cpu, flags);
3838         if (!buffer) {
3839                 ret = -ENOMEM;
3840                 goto unlock;
3841         }
3842         rcu_assign_pointer(event->buffer, buffer);
3843 
3844         atomic_long_add(user_extra, &user->locked_vm);
3845         event->mmap_locked = extra;
3846         event->mmap_user = get_current_user();
3847         vma->vm_mm->locked_vm += event->mmap_locked;
3848 
3849 unlock:
3850         if (!ret)
3851                 atomic_inc(&event->mmap_count);
3852         mutex_unlock(&event->mmap_mutex);
3853 
3854         vma->vm_flags |= VM_RESERVED;
3855         vma->vm_ops = &perf_mmap_vmops;
3856 
3857         return ret;
3858 }
3859 
3860 static int perf_fasync(int fd, struct file *filp, int on)
3861 {
3862         struct inode *inode = filp->f_path.dentry->d_inode;
3863         struct perf_event *event = filp->private_data;
3864         int retval;
3865 
3866         mutex_lock(&inode->i_mutex);
3867         retval = fasync_helper(fd, filp, on, &event->fasync);
3868         mutex_unlock(&inode->i_mutex);
3869 
3870         if (retval < 0)
3871                 return retval;
3872 
3873         return 0;
3874 }
3875 
3876 static const struct file_operations perf_fops = {
3877         .llseek                 = no_llseek,
3878         .release                = perf_release,
3879         .read                   = perf_read,
3880         .poll                   = perf_poll,
3881         .unlocked_ioctl         = perf_ioctl,
3882         .compat_ioctl           = perf_ioctl,
3883         .mmap                   = perf_mmap,
3884         .fasync                 = perf_fasync,
3885 };
3886 
3887 /*
3888  * Perf event wakeup
3889  *
3890  * If there's data, ensure we set the poll() state and publish everything
3891  * to user-space before waking everybody up.
3892  */
3893 
3894 void perf_event_wakeup(struct perf_event *event)
3895 {
3896         wake_up_all(&event->waitq);
3897 
3898         if (event->pending_kill) {
3899                 kill_fasync(&event->fasync, SIGIO, event->pending_kill);
3900                 event->pending_kill = 0;
3901         }
3902 }
3903 
3904 static void perf_pending_event(struct irq_work *entry)
3905 {
3906         struct perf_event *event = container_of(entry,
3907                         struct perf_event, pending);
3908 
3909         if (event->pending_disable) {
3910                 event->pending_disable = 0;
3911                 __perf_event_disable(event);
3912         }
3913 
3914         if (event->pending_wakeup) {
3915                 event->pending_wakeup = 0;
3916                 perf_event_wakeup(event);
3917         }
3918 }
3919 
3920 /*
3921  * We assume there is only KVM supporting the callbacks.
3922  * Later on, we might change it to a list if there is
3923  * another virtualization implementation supporting the callbacks.
3924  */
3925 struct perf_guest_info_callbacks *perf_guest_cbs;
3926 
3927 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
3928 {
3929         perf_guest_cbs = cbs;
3930         return 0;
3931 }
3932 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
3933 
3934 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
3935 {
3936         perf_guest_cbs = NULL;
3937         return 0;
3938 }
3939 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
3940 
3941 /*
3942  * Output
3943  */
3944 static bool perf_output_space(struct perf_buffer *buffer, unsigned long tail,
3945                               unsigned long offset, unsigned long head)
3946 {
3947         unsigned long mask;
3948 
3949         if (!buffer->writable)
3950                 return true;
3951 
3952         mask = perf_data_size(buffer) - 1;
3953 
3954         offset = (offset - tail) & mask;
3955         head   = (head   - tail) & mask;
3956 
3957         if ((int)(head - offset) < 0)
3958                 return false;
3959 
3960         return true;
3961 }
3962 
3963 static void perf_output_wakeup(struct perf_output_handle *handle)
3964 {
3965         atomic_set(&handle->buffer->poll, POLL_IN);
3966 
3967         if (handle->nmi) {
3968                 handle->event->pending_wakeup = 1;
3969                 irq_work_queue(&handle->event->pending);
3970         } else
3971                 perf_event_wakeup(handle->event);
3972 }
3973 
3974 /*
3975  * We need to ensure a later event_id doesn't publish a head when a former
3976  * event isn't done writing. However since we need to deal with NMIs we
3977  * cannot fully serialize things.
3978  *
3979  * We only publish the head (and generate a wakeup) when the outer-most
3980  * event completes.
3981  */
3982 static void perf_output_get_handle(struct perf_output_handle *handle)
3983 {
3984         struct perf_buffer *buffer = handle->buffer;
3985 
3986         preempt_disable();
3987         local_inc(&buffer->nest);
3988         handle->wakeup = local_read(&buffer->wakeup);
3989 }
3990 
3991 static void perf_output_put_handle(struct perf_output_handle *handle)
3992 {
3993         struct perf_buffer *buffer = handle->buffer;
3994         unsigned long head;
3995 
3996 again:
3997         head = local_read(&buffer->head);
3998 
3999         /*
4000          * IRQ/NMI can happen here, which means we can miss a head update.
4001          */
4002 
4003         if (!local_dec_and_test(&buffer->nest))
4004                 goto out;
4005 
4006         /*
4007          * Publish the known good head. Rely on the full barrier implied
4008          * by atomic_dec_and_test() order the buffer->head read and this
4009          * write.
4010          */
4011         buffer->user_page->data_head = head;
4012 
4013         /*
4014          * Now check if we missed an update, rely on the (compiler)
4015          * barrier in atomic_dec_and_test() to re-read buffer->head.
4016          */
4017         if (unlikely(head != local_read(&buffer->head))) {
4018                 local_inc(&buffer->nest);
4019                 goto again;
4020         }
4021 
4022         if (handle->wakeup != local_read(&buffer->wakeup))
4023                 perf_output_wakeup(handle);
4024 
4025 out:
4026         preempt_enable();
4027 }
4028 
4029 __always_inline void perf_output_copy(struct perf_output_handle *handle,
4030                       const void *buf, unsigned int len)
4031 {
4032         do {
4033                 unsigned long size = min_t(unsigned long, handle->size, len);
4034 
4035                 memcpy(handle->addr, buf, size);
4036 
4037                 len -= size;
4038                 handle->addr += size;
4039                 buf += size;
4040                 handle->size -= size;
4041                 if (!handle->size) {
4042                         struct perf_buffer *buffer = handle->buffer;
4043 
4044                         handle->page++;
4045                         handle->page &= buffer->nr_pages - 1;
4046                         handle->addr = buffer->data_pages[handle->page];
4047                         handle->size = PAGE_SIZE << page_order(buffer);
4048                 }
4049         } while (len);
4050 }
4051 
4052 static void __perf_event_header__init_id(struct perf_event_header *header,
4053                                          struct perf_sample_data *data,
4054                                          struct perf_event *event)
4055 {
4056         u64 sample_type = event->attr.sample_type;
4057 
4058         data->type = sample_type;
4059         header->size += event->id_header_size;
4060 
4061         if (sample_type & PERF_SAMPLE_TID) {
4062                 /* namespace issues */
4063                 data->tid_entry.pid = perf_event_pid(event, current);
4064                 data->tid_entry.tid = perf_event_tid(event, current);
4065         }
4066 
4067         if (sample_type & PERF_SAMPLE_TIME)
4068                 data->time = perf_clock();
4069 
4070         if (sample_type & PERF_SAMPLE_ID)
4071                 data->id = primary_event_id(event);
4072 
4073         if (sample_type & PERF_SAMPLE_STREAM_ID)
4074                 data->stream_id = event->id;
4075 
4076         if (sample_type & PERF_SAMPLE_CPU) {
4077                 data->cpu_entry.cpu      = raw_smp_processor_id();
4078                 data->cpu_entry.reserved = 0;
4079         }
4080 }
4081 
4082 static void perf_event_header__init_id(struct perf_event_header *header,
4083                                        struct perf_sample_data *data,
4084                                        struct perf_event *event)
4085 {
4086         if (event->attr.sample_id_all)
4087                 __perf_event_header__init_id(header, data, event);
4088 }
4089 
4090 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
4091                                            struct perf_sample_data *data)
4092 {
4093         u64 sample_type = data->type;
4094 
4095         if (sample_type & PERF_SAMPLE_TID)
4096                 perf_output_put(handle, data->tid_entry);
4097 
4098         if (sample_type & PERF_SAMPLE_TIME)
4099                 perf_output_put(handle, data->time);
4100 
4101         if (sample_type & PERF_SAMPLE_ID)
4102                 perf_output_put(handle, data->id);
4103 
4104         if (sample_type & PERF_SAMPLE_STREAM_ID)
4105                 perf_output_put(handle, data->stream_id);
4106 
4107         if (sample_type & PERF_SAMPLE_CPU)
4108                 perf_output_put(handle, data->cpu_entry);
4109 }
4110 
4111 static void perf_event__output_id_sample(struct perf_event *event,
4112                                          struct perf_output_handle *handle,
4113                                          struct perf_sample_data *sample)
4114 {
4115         if (event->attr.sample_id_all)
4116                 __perf_event__output_id_sample(handle, sample);
4117 }
4118 
4119 int perf_output_begin(struct perf_output_handle *handle,
4120                       struct perf_event *event, unsigned int size,
4121                       int nmi, int sample)
4122 {
4123         struct perf_buffer *buffer;
4124         unsigned long tail, offset, head;
4125         int have_lost;
4126         struct perf_sample_data sample_data;
4127         struct {
4128                 struct perf_event_header header;
4129                 u64                      id;
4130                 u64                      lost;
4131         } lost_event;
4132 
4133         rcu_read_lock();
4134         /*
4135          * For inherited events we send all the output towards the parent.
4136          */
4137         if (event->parent)
4138                 event = event->parent;
4139 
4140         buffer = rcu_dereference(event->buffer);
4141         if (!buffer)
4142                 goto out;
4143 
4144         handle->buffer  = buffer;
4145         handle->event   = event;
4146         handle->nmi     = nmi;
4147         handle->sample  = sample;
4148 
4149         if (!buffer->nr_pages)
4150                 goto out;
4151 
4152         have_lost = local_read(&buffer->lost);
4153         if (have_lost) {
4154                 lost_event.header.size = sizeof(lost_event);
4155                 perf_event_header__init_id(&lost_event.header, &sample_data,
4156                                            event);
4157                 size += lost_event.header.size;
4158         }
4159 
4160         perf_output_get_handle(handle);
4161 
4162         do {
4163                 /*
4164                  * Userspace could choose to issue a mb() before updating the
4165                  * tail pointer. So that all reads will be completed before the
4166                  * write is issued.
4167                  */
4168                 tail = ACCESS_ONCE(buffer->user_page->data_tail);
4169                 smp_rmb();
4170                 offset = head = local_read(&buffer->head);
4171                 head += size;
4172                 if (unlikely(!perf_output_space(buffer, tail, offset, head)))
4173                         goto fail;
4174         } while (local_cmpxchg(&buffer->head, offset, head) != offset);
4175 
4176         if (head - local_read(&buffer->wakeup) > buffer->watermark)
4177                 local_add(buffer->watermark, &buffer->wakeup);
4178 
4179         handle->page = offset >> (PAGE_SHIFT + page_order(buffer));
4180         handle->page &= buffer->nr_pages - 1;
4181         handle->size = offset & ((PAGE_SIZE << page_order(buffer)) - 1);
4182         handle->addr = buffer->data_pages[handle->page];
4183         handle->addr += handle->size;
4184         handle->size = (PAGE_SIZE << page_order(buffer)) - handle->size;
4185 
4186         if (have_lost) {
4187                 lost_event.header.type = PERF_RECORD_LOST;
4188                 lost_event.header.misc = 0;
4189                 lost_event.id          = event->id;
4190                 lost_event.lost        = local_xchg(&buffer->lost, 0);
4191 
4192                 perf_output_put(handle, lost_event);
4193                 perf_event__output_id_sample(event, handle, &sample_data);
4194         }
4195 
4196         return 0;
4197 
4198 fail:
4199         local_inc(&buffer->lost);
4200         perf_output_put_handle(handle);
4201 out:
4202         rcu_read_unlock();
4203 
4204         return -ENOSPC;
4205 }
4206 
4207 void perf_output_end(struct perf_output_handle *handle)
4208 {
4209         struct perf_event *event = handle->event;
4210         struct perf_buffer *buffer = handle->buffer;
4211 
4212         int wakeup_events = event->attr.wakeup_events;
4213 
4214         if (handle->sample && wakeup_events) {
4215                 int events = local_inc_return(&buffer->events);
4216                 if (events >= wakeup_events) {
4217                         local_sub(wakeup_events, &buffer->events);
4218                         local_inc(&buffer->wakeup);
4219                 }
4220         }
4221 
4222         perf_output_put_handle(handle);
4223         rcu_read_unlock();
4224 }
4225 
4226 static void perf_output_read_one(struct perf_output_handle *handle,
4227                                  struct perf_event *event,
4228                                  u64 enabled, u64 running)
4229 {
4230         u64 read_format = event->attr.read_format;
4231         u64 values[4];
4232         int n = 0;
4233 
4234         values[n++] = perf_event_count(event);
4235         if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
4236                 values[n++] = enabled +
4237                         atomic64_read(&event->child_total_time_enabled);
4238         }
4239         if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
4240                 values[n++] = running +
4241                         atomic64_read(&event->child_total_time_running);
4242         }
4243         if (read_format & PERF_FORMAT_ID)
4244                 values[n++] = primary_event_id(event);
4245 
4246         perf_output_copy(handle, values, n * sizeof(u64));
4247 }
4248 
4249 /*
4250  * XXX PERF_FORMAT_GROUP vs inherited events seems difficult.
4251  */
4252 static void perf_output_read_group(struct perf_output_handle *handle,
4253                             struct perf_event *event,
4254                             u64 enabled, u64 running)
4255 {
4256         struct perf_event *leader = event->group_leader, *sub;
4257         u64 read_format = event->attr.read_format;
4258         u64 values[5];
4259         int n = 0;
4260 
4261         values[n++] = 1 + leader->nr_siblings;
4262 
4263         if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
4264                 values[n++] = enabled;
4265 
4266         if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
4267                 values[n++] = running;
4268 
4269         if (leader != event)
4270                 leader->pmu->read(leader);
4271 
4272         values[n++] = perf_event_count(leader);
4273         if (read_format & PERF_FORMAT_ID)
4274                 values[n++] = primary_event_id(leader);
4275 
4276         perf_output_copy(handle, values, n * sizeof(u64));
4277 
4278         list_for_each_entry(sub, &leader->sibling_list, group_entry) {
4279                 n = 0;
4280 
4281                 if (sub != event)
4282                         sub->pmu->read(sub);
4283 
4284                 values[n++] = perf_event_count(sub);
4285                 if (read_format & PERF_FORMAT_ID)
4286                         values[n++] = primary_event_id(sub);
4287 
4288                 perf_output_copy(handle, values, n * sizeof(u64));
4289         }
4290 }
4291 
4292 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
4293                                  PERF_FORMAT_TOTAL_TIME_RUNNING)
4294 
4295 static void perf_output_read(struct perf_output_handle *handle,
4296                              struct perf_event *event)
4297 {
4298         u64 enabled = 0, running = 0, now, ctx_time;
4299         u64 read_format = event->attr.read_format;
4300 
4301         /*
4302          * compute total_time_enabled, total_time_running
4303          * based on snapshot values taken when the event
4304          * was last scheduled in.
4305          *
4306          * we cannot simply called update_context_time()
4307          * because of locking issue as we are called in
4308          * NMI context
4309          */
4310         if (read_format & PERF_FORMAT_TOTAL_TIMES) {
4311                 now = perf_clock();
4312                 ctx_time = event->shadow_ctx_time + now;
4313                 enabled = ctx_time - event->tstamp_enabled;
4314                 running = ctx_time - event->tstamp_running;
4315         }
4316 
4317         if (event->attr.read_format & PERF_FORMAT_GROUP)
4318                 perf_output_read_group(handle, event, enabled, running);
4319         else
4320                 perf_output_read_one(handle, event, enabled, running);
4321 }
4322 
4323 void perf_output_sample(struct perf_output_handle *handle,
4324                         struct perf_event_header *header,
4325                         struct perf_sample_data *data,
4326                         struct perf_event *event)
4327 {
4328         u64 sample_type = data->type;
4329 
4330         perf_output_put(handle, *header);
4331 
4332         if (sample_type & PERF_SAMPLE_IP)
4333                 perf_output_put(handle, data->ip);
4334 
4335         if (sample_type & PERF_SAMPLE_TID)
4336                 perf_output_put(handle, data->tid_entry);
4337 
4338         if (sample_type & PERF_SAMPLE_TIME)
4339                 perf_output_put(handle, data->time);
4340 
4341         if (sample_type & PERF_SAMPLE_ADDR)
4342                 perf_output_put(handle, data->addr);
4343 
4344         if (sample_type & PERF_SAMPLE_ID)
4345                 perf_output_put(handle, data->id);
4346 
4347         if (sample_type & PERF_SAMPLE_STREAM_ID)
4348                 perf_output_put(handle, data->stream_id);
4349 
4350         if (sample_type & PERF_SAMPLE_CPU)
4351                 perf_output_put(handle, data->cpu_entry);
4352 
4353         if (sample_type & PERF_SAMPLE_PERIOD)
4354                 perf_output_put(handle, data->period);
4355 
4356         if (sample_type & PERF_SAMPLE_READ)
4357                 perf_output_read(handle, event);
4358 
4359         if (sample_type & PERF_SAMPLE_CALLCHAIN) {
4360                 if (data->callchain) {
4361                         int size = 1;
4362 
4363                         if (data->callchain)
4364                                 size += data->callchain->nr;
4365 
4366                         size *= sizeof(u64);
4367 
4368                         perf_output_copy(handle, data->callchain, size);
4369                 } else {
4370                         u64 nr = 0;
4371                         perf_output_put(handle, nr);
4372                 }
4373         }
4374 
4375         if (sample_type & PERF_SAMPLE_RAW) {
4376                 if (data->raw) {
4377                         perf_output_put(handle, data->raw->size);
4378                         perf_output_copy(handle, data->raw->data,
4379                                          data->raw->size);
4380                 } else {
4381                         struct {
4382                                 u32     size;
4383                                 u32     data;
4384                         } raw = {
4385                                 .size = sizeof(u32),
4386                                 .data = 0,
4387                         };
4388                         perf_output_put(handle, raw);
4389                 }
4390         }
4391 }
4392 
4393 void perf_prepare_sample(struct perf_event_header *header,
4394                          struct perf_sample_data *data,
4395                          struct perf_event *event,
4396                          struct pt_regs *regs)
4397 {
4398         u64 sample_type = event->attr.sample_type;
4399 
4400         header->type = PERF_RECORD_SAMPLE;
4401         header->size = sizeof(*header) + event->header_size;
4402 
4403         header->misc = 0;
4404         header->misc |= perf_misc_flags(regs);
4405 
4406         __perf_event_header__init_id(header, data, event);
4407 
4408         if (sample_type & PERF_SAMPLE_IP)
4409                 data->ip = perf_instruction_pointer(regs);
4410 
4411         if (sample_type & PERF_SAMPLE_CALLCHAIN) {
4412                 int size = 1;
4413 
4414                 data->callchain = perf_callchain(regs);
4415 
4416                 if (data->callchain)
4417                         size += data->callchain->nr;
4418 
4419                 header->size += size * sizeof(u64);
4420         }
4421 
4422         if (sample_type & PERF_SAMPLE_RAW) {
4423                 int size = sizeof(u32);
4424 
4425                 if (data->raw)
4426                         size += data->raw->size;
4427                 else
4428                         size += sizeof(u32);
4429 
4430                 WARN_ON_ONCE(size & (sizeof(u64)-1));
4431                 header->size += size;
4432         }
4433 }
4434 
4435 static void perf_event_output(struct perf_event *event, int nmi,
4436                                 struct perf_sample_data *data,
4437                                 struct pt_regs *regs)
4438 {
4439         struct perf_output_handle handle;
4440         struct perf_event_header header;
4441 
4442         /* protect the callchain buffers */
4443         rcu_read_lock();
4444 
4445         perf_prepare_sample(&header, data, event, regs);
4446 
4447         if (perf_output_begin(&handle, event, header.size, nmi, 1))
4448                 goto exit;
4449 
4450         perf_output_sample(&handle, &header, data, event);
4451 
4452         perf_output_end(&handle);
4453 
4454 exit:
4455         rcu_read_unlock();
4456 }
4457 
4458 /*
4459  * read event_id
4460  */
4461 
4462 struct perf_read_event {
4463         struct perf_event_header        header;
4464 
4465         u32                             pid;
4466         u32                             tid;
4467 };
4468 
4469 static void
4470 perf_event_read_event(struct perf_event *event,
4471                         struct task_struct *task)
4472 {
4473         struct perf_output_handle handle;
4474         struct perf_sample_data sample;
4475         struct perf_read_event read_event = {
4476                 .header = {
4477                         .type = PERF_RECORD_READ,
4478                         .misc = 0,
4479                         .size = sizeof(read_event) + event->read_size,
4480                 },
4481                 .pid = perf_event_pid(event, task),
4482                 .tid = perf_event_tid(event, task),
4483         };
4484         int ret;
4485 
4486         perf_event_header__init_id(&read_event.header, &sample, event);
4487         ret = perf_output_begin(&handle, event, read_event.header.size, 0, 0);
4488         if (ret)
4489                 return;
4490 
4491         perf_output_put(&handle, read_event);
4492         perf_output_read(&handle, event);
4493         perf_event__output_id_sample(event, &handle, &sample);
4494 
4495         perf_output_end(&handle);
4496 }
4497 
4498 /*
4499  * task tracking -- fork/exit
4500  *
4501  * enabled by: attr.comm | attr.mmap | attr.mmap_data | attr.task
4502  */
4503 
4504 struct perf_task_event {
4505         struct task_struct              *task;
4506         struct perf_event_context       *task_ctx;
4507 
4508         struct {
4509                 struct perf_event_header        header;
4510 
4511                 u32                             pid;
4512                 u32                             ppid;
4513                 u32                             tid;
4514                 u32                             ptid;
4515                 u64                             time;
4516         } event_id;
4517 };
4518 
4519 static void perf_event_task_output(struct perf_event *event,
4520                                      struct perf_task_event *task_event)
4521 {
4522         struct perf_output_handle handle;
4523         struct perf_sample_data sample;
4524         struct task_struct *task = task_event->task;
4525         int ret, size = task_event->event_id.header.size;
4526 
4527         perf_event_header__init_id(&task_event->event_id.header, &sample, event);
4528 
4529         ret = perf_output_begin(&handle, event,
4530                                 task_event->event_id.header.size, 0, 0);
4531         if (ret)
4532                 goto out;
4533 
4534         task_event->event_id.pid = perf_event_pid(event, task);
4535         task_event->event_id.ppid = perf_event_pid(event, current);
4536 
4537         task_event->event_id.tid = perf_event_tid(event, task);
4538         task_event->event_id.ptid = perf_event_tid(event, current);
4539 
4540         perf_output_put(&handle, task_event->event_id);
4541 
4542         perf_event__output_id_sample(event, &handle, &sample);
4543 
4544         perf_output_end(&handle);
4545 out:
4546         task_event->event_id.header.size = size;
4547 }
4548 
4549 static int perf_event_task_match(struct perf_event *event)
4550 {
4551         if (event->state < PERF_EVENT_STATE_INACTIVE)
4552                 return 0;
4553 
4554         if (!event_filter_match(event))
4555                 return 0;
4556 
4557         if (event->attr.comm || event->attr.mmap ||
4558             event->attr.mmap_data || event->attr.task)
4559                 return 1;
4560 
4561         return 0;
4562 }
4563 
4564 static void perf_event_task_ctx(struct perf_event_context *ctx,
4565                                   struct perf_task_event *task_event)
4566 {
4567         struct perf_event *event;
4568 
4569         list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
4570                 if (perf_event_task_match(event))
4571                         perf_event_task_output(event, task_event);
4572         }
4573 }
4574 
4575 static void perf_event_task_event(struct perf_task_event *task_event)
4576 {
4577         struct perf_cpu_context *cpuctx;
4578         struct perf_event_context *ctx;
4579         struct pmu *pmu;
4580         int ctxn;
4581 
4582         rcu_read_lock();
4583         list_for_each_entry_rcu(pmu, &pmus, entry) {
4584                 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
4585                 if (cpuctx->unique_pmu != pmu)
4586                         goto next;
4587                 perf_event_task_ctx(&cpuctx->ctx, task_event);
4588 
4589                 ctx = task_event->task_ctx;
4590                 if (!ctx) {
4591                         ctxn = pmu->task_ctx_nr;
4592                         if (ctxn < 0)
4593                                 goto next;
4594                         ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
4595                 }
4596                 if (ctx)
4597                         perf_event_task_ctx(ctx, task_event);
4598 next:
4599                 put_cpu_ptr(pmu->pmu_cpu_context);
4600         }
4601         rcu_read_unlock();
4602 }
4603 
4604 static void perf_event_task(struct task_struct *task,
4605                               struct perf_event_context *task_ctx,
4606                               int new)
4607 {
4608         struct perf_task_event task_event;
4609 
4610         if (!atomic_read(&nr_comm_events) &&
4611             !atomic_read(&nr_mmap_events) &&
4612             !atomic_read(&nr_task_events))
4613                 return;
4614 
4615         task_event = (struct perf_task_event){
4616                 .task     = task,
4617                 .task_ctx = task_ctx,
4618                 .event_id    = {
4619                         .header = {
4620                                 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
4621                                 .misc = 0,
4622                                 .size = sizeof(task_event.event_id),
4623                         },
4624                         /* .pid  */
4625                         /* .ppid */
4626                         /* .tid  */
4627                         /* .ptid */
4628                         .time = perf_clock(),
4629                 },
4630         };
4631 
4632         perf_event_task_event(&task_event);
4633 }
4634 
4635 void perf_event_fork(struct task_struct *task)
4636 {
4637         perf_event_task(task, NULL, 1);
4638 }
4639 
4640 /*
4641  * comm tracking
4642  */
4643 
4644 struct perf_comm_event {
4645         struct task_struct      *task;
4646         char                    *comm;
4647         int                     comm_size;
4648 
4649         struct {
4650                 struct perf_event_header        header;
4651 
4652                 u32                             pid;
4653                 u32                             tid;
4654         } event_id;
4655 };
4656 
4657 static void perf_event_comm_output(struct perf_event *event,
4658                                      struct perf_comm_event *comm_event)
4659 {
4660         struct perf_output_handle handle;
4661         struct perf_sample_data sample;
4662         int size = comm_event->event_id.header.size;
4663         int ret;
4664 
4665         perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
4666         ret = perf_output_begin(&handle, event,
4667                                 comm_event->event_id.header.size, 0, 0);
4668 
4669         if (ret)
4670                 goto out;
4671 
4672         comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
4673         comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
4674 
4675         perf_output_put(&handle, comm_event->event_id);
4676         perf_output_copy(&handle, comm_event->comm,
4677                                    comm_event->comm_size);
4678 
4679         perf_event__output_id_sample(event, &handle, &sample);
4680 
4681         perf_output_end(&handle);
4682 out:
4683         comm_event->event_id.header.size = size;
4684 }
4685 
4686 static int perf_event_comm_match(struct perf_event *event)
4687 {
4688         if (event->state < PERF_EVENT_STATE_INACTIVE)
4689                 return 0;
4690 
4691         if (!event_filter_match(event))
4692                 return 0;
4693 
4694         if (event->attr.comm)
4695                 return 1;
4696 
4697         return 0;
4698 }
4699 
4700 static void perf_event_comm_ctx(struct perf_event_context *ctx,
4701                                   struct perf_comm_event *comm_event)
4702 {
4703         struct perf_event *event;
4704 
4705         list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
4706                 if (perf_event_comm_match(event))
4707                         perf_event_comm_output(event, comm_event);
4708         }
4709 }
4710 
4711 static void perf_event_comm_event(struct perf_comm_event *comm_event)
4712 {
4713         struct perf_cpu_context *cpuctx;
4714         struct perf_event_context *ctx;
4715         char comm[TASK_COMM_LEN];
4716         unsigned int size;
4717         struct pmu *pmu;
4718         int ctxn;
4719 
4720         memset(comm, 0, sizeof(comm));
4721         strlcpy(comm, comm_event->task->comm, sizeof(comm));
4722         size = ALIGN(strlen(comm)+1, sizeof(u64));
4723 
4724         comm_event->comm = comm;
4725         comm_event->comm_size = size;
4726 
4727         comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
4728         rcu_read_lock();
4729         list_for_each_entry_rcu(pmu, &pmus, entry) {
4730                 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
4731                 if (cpuctx->unique_pmu != pmu)
4732                         goto next;
4733                 perf_event_comm_ctx(&cpuctx->ctx, comm_event);
4734 
4735                 ctxn = pmu->task_ctx_nr;
4736                 if (ctxn < 0)
4737                         goto next;
4738 
4739                 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
4740                 if (ctx)
4741                         perf_event_comm_ctx(ctx, comm_event);
4742 next:
4743                 put_cpu_ptr(pmu->pmu_cpu_context);
4744         }
4745         rcu_read_unlock();
4746 }
4747 
4748 void perf_event_comm(struct task_struct *task)
4749 {
4750         struct perf_comm_event comm_event;
4751         struct perf_event_context *ctx;
4752         int ctxn;
4753 
4754         for_each_task_context_nr(ctxn) {
4755                 ctx = task->perf_event_ctxp[ctxn];
4756                 if (!ctx)
4757                         continue;
4758 
4759                 perf_event_enable_on_exec(ctx);
4760         }
4761 
4762         if (!atomic_read(&nr_comm_events))
4763                 return;
4764 
4765         comm_event = (struct perf_comm_event){
4766                 .task   = task,
4767                 /* .comm      */
4768                 /* .comm_size */
4769                 .event_id  = {
4770                         .header = {
4771                                 .type = PERF_RECORD_COMM,
4772                                 .misc = 0,
4773                                 /* .size */
4774                         },
4775                         /* .pid */
4776                         /* .tid */
4777                 },
4778         };
4779 
4780         perf_event_comm_event(&comm_event);
4781 }
4782 
4783 /*
4784  * mmap tracking
4785  */
4786 
4787 struct perf_mmap_event {
4788         struct vm_area_struct   *vma;
4789 
4790         const char              *file_name;
4791         int                     file_size;
4792 
4793         struct {
4794                 struct perf_event_header        header;
4795 
4796                 u32                             pid;
4797                 u32                             tid;
4798                 u64                             start;
4799                 u64                             len;
4800                 u64                             pgoff;
4801         } event_id;
4802 };
4803 
4804 static void perf_event_mmap_output(struct perf_event *event,
4805                                      struct perf_mmap_event *mmap_event)
4806 {
4807         struct perf_output_handle handle;
4808         struct perf_sample_data sample;
4809         int size = mmap_event->event_id.header.size;
4810         int ret;
4811 
4812         perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
4813         ret = perf_output_begin(&handle, event,
4814                                 mmap_event->event_id.header.size, 0, 0);
4815         if (ret)
4816                 goto out;
4817 
4818         mmap_event->event_id.pid = perf_event_pid(event, current);
4819         mmap_event->event_id.tid = perf_event_tid(event, current);
4820 
4821         perf_output_put(&handle, mmap_event->event_id);
4822         perf_output_copy(&handle, mmap_event->file_name,
4823                                    mmap_event->file_size);
4824 
4825         perf_event__output_id_sample(event, &handle, &sample);
4826 
4827         perf_output_end(&handle);
4828 out:
4829         mmap_event->event_id.header.size = size;
4830 }
4831 
4832 static int perf_event_mmap_match(struct perf_event *event,
4833                                    struct perf_mmap_event *mmap_event,
4834                                    int executable)
4835 {
4836         if (event->state < PERF_EVENT_STATE_INACTIVE)
4837                 return 0;
4838 
4839         if (!event_filter_match(event))
4840                 return 0;
4841 
4842         if ((!executable && event->attr.mmap_data) ||
4843             (executable && event->attr.mmap))
4844                 return 1;
4845 
4846         return 0;
4847 }
4848 
4849 static void perf_event_mmap_ctx(struct perf_event_context *ctx,
4850                                   struct perf_mmap_event *mmap_event,
4851                                   int executable)
4852 {
4853         struct perf_event *event;
4854 
4855         list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
4856                 if (perf_event_mmap_match(event, mmap_event, executable))
4857                         perf_event_mmap_output(event, mmap_event);
4858         }
4859 }
4860 
4861 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
4862 {
4863         struct perf_cpu_context *cpuctx;
4864         struct perf_event_context *ctx;
4865         struct vm_area_struct *vma = mmap_event->vma;
4866         struct file *file = vma->vm_file;
4867         unsigned int size;
4868         char tmp[16];
4869         char *buf = NULL;
4870         const char *name;
4871         struct pmu *pmu;
4872         int ctxn;
4873 
4874         memset(tmp, 0, sizeof(tmp));
4875 
4876         if (file) {
4877                 /*
4878                  * d_path works from the end of the buffer backwards, so we
4879                  * need to add enough zero bytes after the string to handle
4880                  * the 64bit alignment we do later.
4881                  */
4882                 buf = kzalloc(PATH_MAX + sizeof(u64), GFP_KERNEL);
4883                 if (!buf) {
4884                         name = strncpy(tmp, "//enomem", sizeof(tmp));
4885                         goto got_name;
4886                 }
4887                 name = d_path(&file->f_path, buf, PATH_MAX);
4888                 if (IS_ERR(name)) {
4889                         name = strncpy(tmp, "//toolong", sizeof(tmp));
4890                         goto got_name;
4891                 }
4892         } else {
4893                 if (arch_vma_name(mmap_event->vma)) {
4894                         name = strncpy(tmp, arch_vma_name(mmap_event->vma),
4895                                        sizeof(tmp));
4896                         goto got_name;
4897                 }
4898 
4899                 if (!vma->vm_mm) {
4900                         name = strncpy(tmp, "[vdso]", sizeof(tmp));
4901                         goto got_name;
4902                 } else if (vma->vm_start <= vma->vm_mm->start_brk &&
4903                                 vma->vm_end >= vma->vm_mm->brk) {
4904                         name = strncpy(tmp, "[heap]", sizeof(tmp));
4905                         goto got_name;
4906                 } else if (vma->vm_start <= vma->vm_mm->start_stack &&
4907                                 vma->vm_end >= vma->vm_mm->start_stack) {
4908                         name = strncpy(tmp, "[stack]", sizeof(tmp));
4909                         goto got_name;
4910                 }
4911 
4912                 name = strncpy(tmp, "//anon", sizeof(tmp));
4913                 goto got_name;
4914         }
4915 
4916 got_name:
4917         size = ALIGN(strlen(name)+1, sizeof(u64));
4918 
4919         mmap_event->file_name = name;
4920         mmap_event->file_size = size;
4921 
4922         mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
4923 
4924         rcu_read_lock();
4925         list_for_each_entry_rcu(pmu, &pmus, entry) {
4926                 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
4927                 if (cpuctx->unique_pmu != pmu)
4928                         goto next;
4929                 perf_event_mmap_ctx(&cpuctx->ctx, mmap_event,
4930                                         vma->vm_flags & VM_EXEC);
4931 
4932                 ctxn = pmu->task_ctx_nr;
4933                 if (ctxn < 0)
4934                         goto next;
4935 
4936                 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
4937                 if (ctx) {
4938                         perf_event_mmap_ctx(ctx, mmap_event,
4939                                         vma->vm_flags & VM_EXEC);
4940                 }
4941 next:
4942                 put_cpu_ptr(pmu->pmu_cpu_context);
4943         }
4944         rcu_read_unlock();
4945 
4946         kfree(buf);
4947 }
4948 
4949 void perf_event_mmap(struct vm_area_struct *vma)
4950 {
4951         struct perf_mmap_event mmap_event;
4952 
4953         if (!atomic_read(&nr_mmap_events))
4954                 return;
4955 
4956         mmap_event = (struct perf_mmap_event){
4957                 .vma    = vma,
4958                 /* .file_name */
4959                 /* .file_size */
4960                 .event_id  = {
4961                         .header = {
4962                                 .type = PERF_RECORD_MMAP,
4963                                 .misc = PERF_RECORD_MISC_USER,
4964                                 /* .size */
4965                         },
4966                         /* .pid */
4967                         /* .tid */
4968                         .start  = vma->vm_start,
4969                         .len    = vma->vm_end - vma->vm_start,
4970                         .pgoff  = (u64)vma->vm_pgoff << PAGE_SHIFT,
4971                 },
4972         };
4973 
4974         perf_event_mmap_event(&mmap_event);
4975 }
4976 
4977 /*
4978  * IRQ throttle logging
4979  */
4980 
4981 static void perf_log_throttle(struct perf_event *event, int enable)
4982 {
4983         struct perf_output_handle handle;
4984         struct perf_sample_data sample;
4985         int ret;
4986 
4987         struct {
4988                 struct perf_event_header        header;
4989                 u64                             time;
4990                 u64                             id;
4991                 u64                             stream_id;
4992         } throttle_event = {
4993                 .header = {
4994                         .type = PERF_RECORD_THROTTLE,
4995                         .misc = 0,
4996                         .size = sizeof(throttle_event),
4997                 },
4998                 .time           = perf_clock(),
4999                 .id             = primary_event_id(event),
5000                 .stream_id      = event->id,
5001         };
5002 
5003         if (enable)
5004                 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
5005 
5006         perf_event_header__init_id(&throttle_event.header, &sample, event);
5007 
5008         ret = perf_output_begin(&handle, event,
5009                                 throttle_event.header.size, 1, 0);
5010         if (ret)
5011                 return;
5012 
5013         perf_output_put(&handle, throttle_event);
5014         perf_event__output_id_sample(event, &handle, &sample);
5015         perf_output_end(&handle);
5016 }
5017 
5018 /*
5019  * Generic event overflow handling, sampling.
5020  */
5021 
5022 static int __perf_event_overflow(struct perf_event *event, int nmi,
5023                                    int throttle, struct perf_sample_data *data,
5024                                    struct pt_regs *regs)
5025 {
5026         int events = atomic_read(&event->event_limit);
5027         struct hw_perf_event *hwc = &event->hw;
5028         int ret = 0;
5029 
5030         /*
5031          * Non-sampling counters might still use the PMI to fold short
5032          * hardware counters, ignore those.
5033          */
5034         if (unlikely(!is_sampling_event(event)))
5035                 return 0;
5036 
5037         if (unlikely(hwc->interrupts >= max_samples_per_tick)) {
5038                 if (throttle) {
5039                         hwc->interrupts = MAX_INTERRUPTS;
5040                         perf_log_throttle(event, 0);
5041                         ret = 1;
5042                 }
5043         } else
5044                 hwc->interrupts++;
5045 
5046         if (event->attr.freq) {
5047                 u64 now = perf_clock();
5048                 s64 delta = now - hwc->freq_time_stamp;
5049 
5050                 hwc->freq_time_stamp = now;
5051 
5052                 if (delta > 0 && delta < 2*TICK_NSEC)
5053                         perf_adjust_period(event, delta, hwc->last_period);
5054         }
5055 
5056         /*
5057          * XXX event_limit might not quite work as expected on inherited
5058          * events
5059          */
5060 
5061         event->pending_kill = POLL_IN;
5062         if (events && atomic_dec_and_test(&event->event_limit)) {
5063                 ret = 1;
5064                 event->pending_kill = POLL_HUP;
5065                 event->pending_disable = 1;
5066                 irq_work_queue(&event->pending);
5067         }
5068 
5069         if (event->overflow_handler)
5070                 event->overflow_handler(event, nmi, data, regs);
5071         else
5072                 perf_event_output(event, nmi, data, regs);
5073 
5074         if (event->fasync && event->pending_kill) {
5075                 if (nmi) {
5076                         event->pending_wakeup = 1;
5077                         irq_work_queue(&event->pending);
5078                 } else
5079                         perf_event_wakeup(event);
5080         }
5081 
5082         return ret;
5083 }
5084 
5085 int perf_event_overflow(struct perf_event *event, int nmi,
5086                           struct perf_sample_data *data,
5087                           struct pt_regs *regs)
5088 {
5089         return __perf_event_overflow(event, nmi, 1, data, regs);
5090 }
5091 
5092 /*
5093  * Generic software event infrastructure
5094  */
5095 
5096 struct swevent_htable {
5097         struct swevent_hlist            *swevent_hlist;
5098         struct mutex                    hlist_mutex;
5099         int                             hlist_refcount;
5100 
5101         /* Recursion avoidance in each contexts */
5102         int                             recursion[PERF_NR_CONTEXTS];
5103 };
5104 
5105 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
5106 
5107 /*
5108  * We directly increment event->count and keep a second value in
5109  * event->hw.period_left to count intervals. This period event
5110  * is kept in the range [-sample_period, 0] so that we can use the
5111  * sign as trigger.
5112  */
5113 
5114 static u64 perf_swevent_set_period(struct perf_event *event)
5115 {
5116         struct hw_perf_event *hwc = &event->hw;
5117         u64 period = hwc->last_period;
5118         u64 nr, offset;
5119         s64 old, val;
5120 
5121         hwc->last_period = hwc->sample_period;
5122 
5123 again:
5124         old = val = local64_read(&hwc->period_left);
5125         if (val < 0)
5126                 return 0;
5127 
5128         nr = div64_u64(period + val, period);
5129         offset = nr * period;
5130         val -= offset;
5131         if (local64_cmpxchg(&hwc->period_left, old, val) != old)
5132                 goto again;
5133 
5134         return nr;
5135 }
5136 
5137 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
5138                                     int nmi, struct perf_sample_data *data,
5139                                     struct pt_regs *regs)
5140 {
5141         struct hw_perf_event *hwc = &event->hw;
5142         int throttle = 0;
5143 
5144         data->period = event->hw.last_period;
5145         if (!overflow)
5146                 overflow = perf_swevent_set_period(event);
5147 
5148         if (hwc->interrupts == MAX_INTERRUPTS)
5149                 return;
5150 
5151         for (; overflow; overflow--) {
5152                 if (__perf_event_overflow(event, nmi, throttle,
5153                                             data, regs)) {
5154                         /*
5155                          * We inhibit the overflow from happening when
5156                          * hwc->interrupts == MAX_INTERRUPTS.
5157                          */
5158                         break;
5159                 }
5160                 throttle = 1;
5161         }
5162 }
5163 
5164 static void perf_swevent_event(struct perf_event *event, u64 nr,
5165                                int nmi, struct perf_sample_data *data,
5166                                struct pt_regs *regs)
5167 {
5168         struct hw_perf_event *hwc = &event->hw;
5169 
5170         local64_add(nr, &event->count);
5171 
5172         if (!regs)
5173                 return;
5174 
5175         if (!is_sampling_event(event))
5176                 return;
5177 
5178         if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
5179                 return perf_swevent_overflow(event, 1, nmi, data, regs);
5180 
5181         if (local64_add_negative(nr, &hwc->period_left))
5182                 return;
5183 
5184         perf_swevent_overflow(event, 0, nmi, data, regs);
5185 }
5186 
5187 static int perf_exclude_event(struct perf_event *event,
5188                               struct pt_regs *regs)
5189 {
5190         if (event->hw.state & PERF_HES_STOPPED)
5191                 return 1;
5192 
5193         if (regs) {
5194                 if (event->attr.exclude_user && user_mode(regs))
5195                         return 1;
5196 
5197                 if (event->attr.exclude_kernel && !user_mode(regs))
5198                         return 1;
5199         }
5200 
5201         return 0;
5202 }
5203 
5204 static int perf_swevent_match(struct perf_event *event,
5205                                 enum perf_type_id type,
5206                                 u32 event_id,
5207                                 struct perf_sample_data *data,
5208                                 struct pt_regs *regs)
5209 {
5210         if (event->attr.type != type)
5211                 return 0;
5212 
5213         if (event->attr.config != event_id)
5214                 return 0;
5215 
5216         if (perf_exclude_event(event, regs))
5217                 return 0;
5218 
5219         return 1;
5220 }
5221 
5222 static inline u64 swevent_hash(u64 type, u32 event_id)
5223 {
5224         u64 val = event_id | (type << 32);
5225 
5226         return hash_64(val, SWEVENT_HLIST_BITS);
5227 }
5228 
5229 static inline struct hlist_head *
5230 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
5231 {
5232         u64 hash = swevent_hash(type, event_id);
5233 
5234         return &hlist->heads[hash];
5235 }
5236 
5237 /* For the read side: events when they trigger */
5238 static inline struct hlist_head *
5239 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
5240 {
5241         struct swevent_hlist *hlist;
5242 
5243         hlist = rcu_dereference(swhash->swevent_hlist);
5244         if (!hlist)
5245                 return NULL;
5246 
5247         return __find_swevent_head(hlist, type, event_id);
5248 }
5249 
5250 /* For the event head insertion and removal in the hlist */
5251 static inline struct hlist_head *
5252 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
5253 {
5254         struct swevent_hlist *hlist;
5255         u32 event_id = event->attr.config;
5256         u64 type = event->attr.type;
5257 
5258         /*
5259          * Event scheduling is always serialized against hlist allocation
5260          * and release. Which makes the protected version suitable here.
5261          * The context lock guarantees that.
5262          */
5263         hlist = rcu_dereference_protected(swhash->swevent_hlist,
5264                                           lockdep_is_held(&event->ctx->lock));
5265         if (!hlist)
5266                 return NULL;
5267 
5268         return __find_swevent_head(hlist, type, event_id);
5269 }
5270 
5271 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
5272                                     u64 nr, int nmi,
5273                                     struct perf_sample_data *data,
5274                                     struct pt_regs *regs)
5275 {
5276         struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5277         struct perf_event *event;
5278         struct hlist_node *node;
5279         struct hlist_head *head;
5280 
5281         rcu_read_lock();
5282         head = find_swevent_head_rcu(swhash, type, event_id);
5283         if (!head)
5284                 goto end;
5285 
5286         hlist_for_each_entry_rcu(event, node, head, hlist_entry) {
5287                 if (perf_swevent_match(event, type, event_id, data, regs))
5288                         perf_swevent_event(event, nr, nmi, data, regs);
5289         }
5290 end:
5291         rcu_read_unlock();
5292 }
5293 
5294 int perf_swevent_get_recursion_context(void)
5295 {
5296         struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5297 
5298         return get_recursion_context(swhash->recursion);
5299 }
5300 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
5301 
5302 inline void perf_swevent_put_recursion_context(int rctx)
5303 {
5304         struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5305 
5306         put_recursion_context(swhash->recursion, rctx);
5307 }
5308 
5309 void __perf_sw_event(u32 event_id, u64 nr, int nmi,
5310                             struct pt_regs *regs, u64 addr)
5311 {
5312         struct perf_sample_data data;
5313         int rctx;
5314 
5315         preempt_disable_notrace();
5316         rctx = perf_swevent_get_recursion_context();
5317         if (rctx < 0)
5318                 return;
5319 
5320         perf_sample_data_init(&data, addr);
5321 
5322         do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, nmi, &data, regs);
5323 
5324         perf_swevent_put_recursion_context(rctx);
5325         preempt_enable_notrace();
5326 }
5327 
5328 static void perf_swevent_read(struct perf_event *event)
5329 {
5330 }
5331 
5332 static int perf_swevent_add(struct perf_event *event, int flags)
5333 {
5334         struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
5335         struct hw_perf_event *hwc = &event->hw;
5336         struct hlist_head *head;
5337 
5338         if (is_sampling_event(event)) {
5339                 hwc->last_period = hwc->sample_period;
5340                 perf_swevent_set_period(event);
5341         }
5342 
5343         hwc->state = !(flags & PERF_EF_START);
5344 
5345         head = find_swevent_head(swhash, event);
5346         if (WARN_ON_ONCE(!head))
5347                 return -EINVAL;
5348 
5349         hlist_add_head_rcu(&event->hlist_entry, head);
5350 
5351         return 0;
5352 }
5353 
5354 static void perf_swevent_del(struct perf_event *event, int flags)
5355 {
5356         hlist_del_rcu(&event->hlist_entry);
5357 }
5358 
5359 static void perf_swevent_start(struct perf_event *event, int flags)
5360 {
5361         event->hw.state = 0;
5362 }
5363 
5364 static void perf_swevent_stop(struct perf_event *event, int flags)
5365 {
5366         event->hw.state = PERF_HES_STOPPED;
5367 }
5368 
5369 /* Deref the hlist from the update side */
5370 static inline struct swevent_hlist *
5371 swevent_hlist_deref(struct swevent_htable *swhash)
5372 {
5373         return rcu_dereference_protected(swhash->swevent_hlist,
5374                                          lockdep_is_held(&swhash->hlist_mutex));
5375 }
5376 
5377 static void swevent_hlist_release(struct swevent_htable *swhash)
5378 {
5379         struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
5380 
5381         if (!hlist)
5382                 return;
5383 
5384         rcu_assign_pointer(swhash->swevent_hlist, NULL);
5385         kfree_rcu(hlist, rcu_head);
5386 }
5387 
5388 static void swevent_hlist_put_cpu(struct perf_event *event, int cpu)
5389 {
5390         struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
5391 
5392         mutex_lock(&swhash->hlist_mutex);
5393 
5394         if (!--swhash->hlist_refcount)
5395                 swevent_hlist_release(swhash);
5396 
5397         mutex_unlock(&swhash->hlist_mutex);
5398 }
5399 
5400 static void swevent_hlist_put(struct perf_event *event)
5401 {
5402         int cpu;
5403 
5404         if (event->cpu != -1) {
5405                 swevent_hlist_put_cpu(event, event->cpu);
5406                 return;
5407         }
5408 
5409         for_each_possible_cpu(cpu)
5410                 swevent_hlist_put_cpu(event, cpu);
5411 }
5412 
5413 static int swevent_hlist_get_cpu(struct perf_event *event, int cpu)
5414 {
5415         struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
5416         int err = 0;
5417 
5418         mutex_lock(&swhash->hlist_mutex);
5419 
5420         if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
5421                 struct swevent_hlist *hlist;
5422 
5423                 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
5424                 if (!hlist) {
5425                         err = -ENOMEM;
5426                         goto exit;
5427                 }
5428                 rcu_assign_pointer(swhash->swevent_hlist, hlist);
5429         }
5430         swhash->hlist_refcount++;
5431 exit:
5432         mutex_unlock(&swhash->hlist_mutex);
5433 
5434         return err;
5435 }
5436 
5437 static int swevent_hlist_get(struct perf_event *event)
5438 {
5439         int err;
5440         int cpu, failed_cpu;
5441 
5442         if (event->cpu != -1)
5443                 return swevent_hlist_get_cpu(event, event->cpu);
5444 
5445         get_online_cpus();
5446         for_each_possible_cpu(cpu) {
5447                 err = swevent_hlist_get_cpu(event, cpu);
5448                 if (err) {
5449                         failed_cpu = cpu;
5450                         goto fail;
5451                 }
5452         }
5453         put_online_cpus();
5454 
5455         return 0;
5456 fail:
5457         for_each_possible_cpu(cpu) {
5458                 if (cpu == failed_cpu)
5459                         break;
5460                 swevent_hlist_put_cpu(event, cpu);
5461         }
5462 
5463         put_online_cpus();
5464         return err;
5465 }
5466 
5467 struct jump_label_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
5468 
5469 static void sw_perf_event_destroy(struct perf_event *event)
5470 {
5471         u64 event_id = event->attr.config;
5472 
5473         WARN_ON(event->parent);
5474 
5475         jump_label_dec(&perf_swevent_enabled[event_id]);
5476         swevent_hlist_put(event);
5477 }
5478 
5479 static int perf_swevent_init(struct perf_event *event)
5480 {
5481         u64 event_id = event->attr.config;
5482 
5483         if (event->attr.type != PERF_TYPE_SOFTWARE)
5484                 return -ENOENT;
5485 
5486         switch (event_id) {
5487         case PERF_COUNT_SW_CPU_CLOCK:
5488         case PERF_COUNT_SW_TASK_CLOCK:
5489                 return -ENOENT;
5490 
5491         default:
5492                 break;
5493         }
5494 
5495         if (event_id >= PERF_COUNT_SW_MAX)
5496                 return -ENOENT;
5497 
5498         if (!event->parent) {
5499                 int err;
5500 
5501                 err = swevent_hlist_get(event);
5502                 if (err)
5503                         return err;
5504 
5505                 jump_label_inc(&perf_swevent_enabled[event_id]);
5506                 event->destroy = sw_perf_event_destroy;
5507         }
5508 
5509         return 0;
5510 }
5511 
5512 static struct pmu perf_swevent = {
5513         .task_ctx_nr    = perf_sw_context,
5514 
5515         .event_init     = perf_swevent_init,
5516         .add            = perf_swevent_add,
5517         .del            = perf_swevent_del,
5518         .start          = perf_swevent_start,
5519         .stop           = perf_swevent_stop,
5520         .read           = perf_swevent_read,
5521 };
5522 
5523 #ifdef CONFIG_EVENT_TRACING
5524 
5525 static int perf_tp_filter_match(struct perf_event *event,
5526                                 struct perf_sample_data *data)
5527 {
5528         void *record = data->raw->data;
5529 
5530         if (likely(!event->filter) || filter_match_preds(event->filter, record))
5531                 return 1;
5532         return 0;
5533 }
5534 
5535 static int perf_tp_event_match(struct perf_event *event,
5536                                 struct perf_sample_data *data,
5537                                 struct pt_regs *regs)
5538 {
5539         if (event->hw.state & PERF_HES_STOPPED)
5540                 return 0;
5541         /*
5542          * All tracepoints are from kernel-space.
5543          */
5544         if (event->attr.exclude_kernel)
5545                 return 0;
5546 
5547         if (!perf_tp_filter_match(event, data))
5548                 return 0;
5549 
5550         return 1;
5551 }
5552 
5553 void perf_tp_event(u64 addr, u64 count, void *record, int entry_size,
5554                    struct pt_regs *regs, struct hlist_head *head, int rctx)
5555 {
5556         struct perf_sample_data data;
5557         struct perf_event *event;
5558         struct hlist_node *node;
5559 
5560         struct perf_raw_record raw = {
5561                 .size = entry_size,
5562                 .data = record,
5563         };
5564 
5565         perf_sample_data_init(&data, addr);
5566         data.raw = &raw;
5567 
5568         hlist_for_each_entry_rcu(event, node, head, hlist_entry) {
5569                 if (perf_tp_event_match(event, &data, regs))
5570                         perf_swevent_event(event, count, 1, &data, regs);
5571         }
5572 
5573         perf_swevent_put_recursion_context(rctx);
5574 }
5575 EXPORT_SYMBOL_GPL(perf_tp_event);
5576 
5577 static void tp_perf_event_destroy(struct perf_event *event)
5578 {
5579         perf_trace_destroy(event);
5580 }
5581 
5582 static int perf_tp_event_init(struct perf_event *event)
5583 {
5584         int err;
5585 
5586         if (event->attr.type != PERF_TYPE_TRACEPOINT)
5587                 return -ENOENT;
5588 
5589         err = perf_trace_init(event);
5590         if (err)
5591                 return err;
5592 
5593         event->destroy = tp_perf_event_destroy;
5594 
5595         return 0;
5596 }
5597 
5598 static struct pmu perf_tracepoint = {
5599         .task_ctx_nr    = perf_sw_context,
5600 
5601         .event_init     = perf_tp_event_init,
5602         .add            = perf_trace_add,
5603         .del            = perf_trace_del,
5604         .start          = perf_swevent_start,
5605         .stop           = perf_swevent_stop,
5606         .read           = perf_swevent_read,
5607 };
5608 
5609 static inline void perf_tp_register(void)
5610 {
5611         perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
5612 }
5613 
5614 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
5615 {
5616         char *filter_str;
5617         int ret;
5618 
5619         if (event->attr.type != PERF_TYPE_TRACEPOINT)
5620                 return -EINVAL;
5621 
5622         filter_str = strndup_user(arg, PAGE_SIZE);
5623         if (IS_ERR(filter_str))
5624                 return PTR_ERR(filter_str);
5625 
5626         ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
5627 
5628         kfree(filter_str);
5629         return ret;
5630 }
5631 
5632 static void perf_event_free_filter(struct perf_event *event)
5633 {
5634         ftrace_profile_free_filter(event);
5635 }
5636 
5637 #else
5638 
5639 static inline void perf_tp_register(void)
5640 {
5641 }
5642 
5643 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
5644 {
5645         return -ENOENT;
5646 }
5647 
5648 static void perf_event_free_filter(struct perf_event *event)
5649 {
5650 }
5651 
5652 #endif /* CONFIG_EVENT_TRACING */
5653 
5654 #ifdef CONFIG_HAVE_HW_BREAKPOINT
5655 void perf_bp_event(struct perf_event *bp, void *data)
5656 {
5657         struct perf_sample_data sample;
5658         struct pt_regs *regs = data;
5659 
5660         perf_sample_data_init(&sample, bp->attr.bp_addr);
5661 
5662         if (!bp->hw.state && !perf_exclude_event(bp, regs))
5663                 perf_swevent_event(bp, 1, 1, &sample, regs);
5664 }
5665 #endif
5666 
5667 /*
5668  * hrtimer based swevent callback
5669  */
5670 
5671 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
5672 {
5673         enum hrtimer_restart ret = HRTIMER_RESTART;
5674         struct perf_sample_data data;
5675         struct pt_regs *regs;
5676         struct perf_event *event;
5677         u64 period;
5678 
5679         event = container_of(hrtimer, struct perf_event, hw.hrtimer);
5680 
5681         if (event->state != PERF_EVENT_STATE_ACTIVE)
5682                 return HRTIMER_NORESTART;
5683 
5684         event->pmu->read(event);
5685 
5686         perf_sample_data_init(&data, 0);
5687         data.period = event->hw.last_period;
5688         regs = get_irq_regs();
5689 
5690         if (regs && !perf_exclude_event(event, regs)) {
5691                 if (!(event->attr.exclude_idle && current->pid == 0))
5692                         if (perf_event_overflow(event, 0, &data, regs))
5693                                 ret = HRTIMER_NORESTART;
5694         }
5695 
5696         period = max_t(u64, 10000, event->hw.sample_period);
5697         hrtimer_forward_now(hrtimer, ns_to_ktime(period));
5698 
5699         return ret;
5700 }
5701 
5702 static void perf_swevent_start_hrtimer(struct perf_event *event)
5703 {
5704         struct hw_perf_event *hwc = &event->hw;
5705         s64 period;
5706 
5707         if (!is_sampling_event(event))
5708                 return;
5709 
5710         period = local64_read(&hwc->period_left);
5711         if (period) {
5712                 if (period < 0)
5713                         period = 10000;
5714 
5715                 local64_set(&hwc->period_left, 0);
5716         } else {
5717                 period = max_t(u64, 10000, hwc->sample_period);
5718         }
5719         __hrtimer_start_range_ns(&hwc->hrtimer,
5720                                 ns_to_ktime(period), 0,
5721                                 HRTIMER_MODE_REL_PINNED, 0);
5722 }
5723 
5724 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
5725 {
5726         struct hw_perf_event *hwc = &event->hw;
5727 
5728         if (is_sampling_event(event)) {
5729                 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
5730                 local64_set(&hwc->period_left, ktime_to_ns(remaining));
5731 
5732                 hrtimer_cancel(&hwc->hrtimer);
5733         }
5734 }
5735 
5736 static void perf_swevent_init_hrtimer(struct perf_event *event)
5737 {
5738         struct hw_perf_event *hwc = &event->hw;
5739 
5740         if (!is_sampling_event(event))
5741                 return;
5742 
5743         hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
5744         hwc->hrtimer.function = perf_swevent_hrtimer;
5745 
5746         /*
5747          * Since hrtimers have a fixed rate, we can do a static freq->period
5748          * mapping and avoid the whole period adjust feedback stuff.
5749          */
5750         if (event->attr.freq) {
5751                 long freq = event->attr.sample_freq;
5752 
5753                 event->attr.sample_period = NSEC_PER_SEC / freq;
5754                 hwc->sample_period = event->attr.sample_period;
5755                 local64_set(&hwc->period_left, hwc->sample_period);
5756                 event->attr.freq = 0;
5757         }
5758 }
5759 
5760 /*
5761  * Software event: cpu wall time clock
5762  */
5763 
5764 static void cpu_clock_event_update(struct perf_event *event)
5765 {
5766         s64 prev;
5767         u64 now;
5768 
5769         now = local_clock();
5770         prev = local64_xchg(&event->hw.prev_count, now);
5771         local64_add(now - prev, &event->count);
5772 }
5773 
5774 static void cpu_clock_event_start(struct perf_event *event, int flags)
5775 {
5776         local64_set(&event->hw.prev_count, local_clock());
5777         perf_swevent_start_hrtimer(event);
5778 }
5779 
5780 static void cpu_clock_event_stop(struct perf_event *event, int flags)
5781 {
5782         perf_swevent_cancel_hrtimer(event);
5783         cpu_clock_event_update(event);
5784 }
5785 
5786 static int cpu_clock_event_add(struct perf_event *event, int flags)
5787 {
5788         if (flags & PERF_EF_START)
5789                 cpu_clock_event_start(event, flags);
5790 
5791         return 0;
5792 }
5793 
5794 static void cpu_clock_event_del(struct perf_event *event, int flags)
5795 {
5796         cpu_clock_event_stop(event, flags);
5797 }
5798 
5799 static void cpu_clock_event_read(struct perf_event *event)
5800 {
5801         cpu_clock_event_update(event);
5802 }
5803 
5804 static int cpu_clock_event_init(struct perf_event *event)
5805 {
5806         if (event->attr.type != PERF_TYPE_SOFTWARE)
5807                 return -ENOENT;
5808 
5809         if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
5810                 return -ENOENT;
5811 
5812         perf_swevent_init_hrtimer(event);
5813 
5814         return 0;
5815 }
5816 
5817 static struct pmu perf_cpu_clock = {
5818         .task_ctx_nr    = perf_sw_context,
5819 
5820         .event_init     = cpu_clock_event_init,
5821         .add            = cpu_clock_event_add,
5822         .del            = cpu_clock_event_del,
5823         .start          = cpu_clock_event_start,
5824         .stop           = cpu_clock_event_stop,
5825         .read           = cpu_clock_event_read,
5826 };
5827 
5828 /*
5829  * Software event: task time clock
5830  */
5831 
5832 static void task_clock_event_update(struct perf_event *event, u64 now)
5833 {
5834         u64 prev;
5835         s64 delta;
5836 
5837         prev = local64_xchg(&event->hw.prev_count, now);
5838         delta = now - prev;
5839         local64_add(delta, &event->count);
5840 }
5841 
5842 static void task_clock_event_start(struct perf_event *event, int flags)
5843 {
5844         local64_set(&event->hw.prev_count, event->ctx->time);
5845         perf_swevent_start_hrtimer(event);
5846 }
5847 
5848 static void task_clock_event_stop(struct perf_event *event, int flags)
5849 {
5850         perf_swevent_cancel_hrtimer(event);
5851         task_clock_event_update(event, event->ctx->time);
5852 }
5853 
5854 static int task_clock_event_add(struct perf_event *event, int flags)
5855 {
5856         if (flags & PERF_EF_START)
5857                 task_clock_event_start(event, flags);
5858 
5859         return 0;
5860 }
5861 
5862 static void task_clock_event_del(struct perf_event *event, int flags)
5863 {
5864         task_clock_event_stop(event, PERF_EF_UPDATE);
5865 }
5866 
5867 static void task_clock_event_read(struct perf_event *event)
5868 {
5869         u64 now = perf_clock();
5870         u64 delta = now - event->ctx->timestamp;
5871         u64 time = event->ctx->time + delta;
5872 
5873         task_clock_event_update(event, time);
5874 }
5875 
5876 static int task_clock_event_init(struct perf_event *event)
5877 {
5878         if (event->attr.type != PERF_TYPE_SOFTWARE)
5879                 return -ENOENT;
5880 
5881         if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
5882                 return -ENOENT;
5883 
5884         perf_swevent_init_hrtimer(event);
5885 
5886         return 0;
5887 }
5888 
5889 static struct pmu perf_task_clock = {
5890         .task_ctx_nr    = perf_sw_context,
5891 
5892         .event_init     = task_clock_event_init,
5893         .add            = task_clock_event_add,
5894         .del            = task_clock_event_del,
5895         .start          = task_clock_event_start,
5896         .stop           = task_clock_event_stop,
5897         .read           = task_clock_event_read,
5898 };
5899 
5900 static void perf_pmu_nop_void(struct pmu *pmu)
5901 {
5902 }
5903 
5904 static int perf_pmu_nop_int(struct pmu *pmu)
5905 {
5906         return 0;
5907 }
5908 
5909 static void perf_pmu_start_txn(struct pmu *pmu)
5910 {
5911         perf_pmu_disable(pmu);
5912 }
5913 
5914 static int perf_pmu_commit_txn(struct pmu *pmu)
5915 {
5916         perf_pmu_enable(pmu);
5917         return 0;
5918 }
5919 
5920 static void perf_pmu_cancel_txn(struct pmu *pmu)
5921 {
5922         perf_pmu_enable(pmu);
5923 }
5924 
5925 /*
5926  * Ensures all contexts with the same task_ctx_nr have the same
5927  * pmu_cpu_context too.
5928  */
5929 static void *find_pmu_context(int ctxn)
5930 {
5931         struct pmu *pmu;
5932 
5933         if (ctxn < 0)
5934                 return NULL;
5935 
5936         list_for_each_entry(pmu, &pmus, entry) {
5937                 if (pmu->task_ctx_nr == ctxn)
5938                         return pmu->pmu_cpu_context;
5939         }
5940 
5941         return NULL;
5942 }
5943 
5944 static void update_pmu_context(struct pmu *pmu, struct pmu *old_pmu)
5945 {
5946         int cpu;
5947 
5948         for_each_possible_cpu(cpu) {
5949                 struct perf_cpu_context *cpuctx;
5950 
5951                 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
5952 
5953                 if (cpuctx->unique_pmu == old_pmu)
5954                         cpuctx->unique_pmu = pmu;
5955         }
5956 }
5957 
5958 static void free_pmu_context(struct pmu *pmu)
5959 {
5960         struct pmu *i;
5961 
5962         mutex_lock(&pmus_lock);
5963         /*
5964          * Like a real lame refcount.
5965          */
5966         list_for_each_entry(i, &pmus, entry) {
5967                 if (i->pmu_cpu_context == pmu->pmu_cpu_context) {
5968                         update_pmu_context(i, pmu);
5969                         goto out;
5970                 }
5971         }
5972 
5973         free_percpu(pmu->pmu_cpu_context);
5974 out:
5975         mutex_unlock(&pmus_lock);
5976 }
5977 static struct idr pmu_idr;
5978 
5979 static ssize_t
5980 type_show(struct device *dev, struct device_attribute *attr, char *page)
5981 {
5982         struct pmu *pmu = dev_get_drvdata(dev);
5983 
5984         return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
5985 }
5986 
5987 static struct device_attribute pmu_dev_attrs[] = {
5988        __ATTR_RO(type),
5989        __ATTR_NULL,
5990 };
5991 
5992 static int pmu_bus_running;
5993 static struct bus_type pmu_bus = {
5994         .name           = "event_source",
5995         .dev_attrs      = pmu_dev_attrs,
5996 };
5997 
5998 static void pmu_dev_release(struct device *dev)
5999 {
6000         kfree(dev);
6001 }
6002 
6003 static int pmu_dev_alloc(struct pmu *pmu)
6004 {
6005         int ret = -ENOMEM;
6006 
6007         pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
6008         if (!pmu->dev)
6009                 goto out;
6010 
6011         device_initialize(pmu->dev);
6012         ret = dev_set_name(pmu->dev, "%s", pmu->name);
6013         if (ret)
6014                 goto free_dev;
6015 
6016         dev_set_drvdata(pmu->dev, pmu);
6017         pmu->dev->bus = &pmu_bus;
6018         pmu->dev->release = pmu_dev_release;
6019         ret = device_add(pmu->dev);
6020         if (ret)
6021                 goto free_dev;
6022 
6023 out:
6024         return ret;
6025 
6026 free_dev:
6027         put_device(pmu->dev);
6028         goto out;
6029 }
6030 
6031 static struct lock_class_key cpuctx_mutex;
6032 
6033 int perf_pmu_register(struct pmu *pmu, char *name, int type)
6034 {
6035         int cpu, ret;
6036 
6037         mutex_lock(&pmus_lock);
6038         ret = -ENOMEM;
6039         pmu->pmu_disable_count = alloc_percpu(int);
6040         if (!pmu->pmu_disable_count)
6041                 goto unlock;
6042 
6043         pmu->type = -1;
6044         if (!name)
6045                 goto skip_type;
6046         pmu->name = name;
6047 
6048         if (type < 0) {
6049                 int err = idr_pre_get(&pmu_idr, GFP_KERNEL);
6050                 if (!err)
6051                         goto free_pdc;
6052 
6053                 err = idr_get_new_above(&pmu_idr, pmu, PERF_TYPE_MAX, &type);
6054                 if (err) {
6055                         ret = err;
6056                         goto free_pdc;
6057                 }
6058         }
6059         pmu->type = type;
6060 
6061         if (pmu_bus_running) {
6062                 ret = pmu_dev_alloc(pmu);
6063                 if (ret)
6064                         goto free_idr;
6065         }
6066 
6067 skip_type:
6068         pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
6069         if (pmu->pmu_cpu_context)
6070                 goto got_cpu_context;
6071 
6072         pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
6073         if (!pmu->pmu_cpu_context)
6074                 goto free_dev;
6075 
6076         for_each_possible_cpu(cpu) {
6077                 struct perf_cpu_context *cpuctx;
6078 
6079                 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6080                 __perf_event_init_context(&cpuctx->ctx);
6081                 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
6082                 cpuctx->ctx.type = cpu_context;
6083                 cpuctx->ctx.pmu = pmu;
6084                 cpuctx->jiffies_interval = 1;
6085                 INIT_LIST_HEAD(&cpuctx->rotation_list);
6086                 cpuctx->unique_pmu = pmu;
6087         }
6088 
6089 got_cpu_context:
6090         if (!pmu->start_txn) {
6091                 if (pmu->pmu_enable) {
6092                         /*
6093                          * If we have pmu_enable/pmu_disable calls, install
6094                          * transaction stubs that use that to try and batch
6095                          * hardware accesses.
6096                          */
6097                         pmu->start_txn  = perf_pmu_start_txn;
6098                         pmu->commit_txn = perf_pmu_commit_txn;
6099                         pmu->cancel_txn = perf_pmu_cancel_txn;
6100                 } else {
6101                         pmu->start_txn  = perf_pmu_nop_void;
6102                         pmu->commit_txn = perf_pmu_nop_int;
6103                         pmu->cancel_txn = perf_pmu_nop_void;
6104                 }
6105         }
6106 
6107         if (!pmu->pmu_enable) {
6108                 pmu->pmu_enable  = perf_pmu_nop_void;
6109                 pmu->pmu_disable = perf_pmu_nop_void;
6110         }
6111 
6112         list_add_rcu(&pmu->entry, &pmus);
6113         ret = 0;
6114 unlock:
6115         mutex_unlock(&pmus_lock);
6116 
6117         return ret;
6118 
6119 free_dev:
6120         device_del(pmu->dev);
6121         put_device(pmu->dev);
6122 
6123 free_idr:
6124         if (pmu->type >= PERF_TYPE_MAX)
6125                 idr_remove(&pmu_idr, pmu->type);
6126 
6127 free_pdc:
6128         free_percpu(pmu->pmu_disable_count);
6129         goto unlock;
6130 }
6131 
6132 void perf_pmu_unregister(struct pmu *pmu)
6133 {
6134         mutex_lock(&pmus_lock);
6135         list_del_rcu(&pmu->entry);
6136         mutex_unlock(&pmus_lock);
6137 
6138         /*
6139          * We dereference the pmu list under both SRCU and regular RCU, so
6140          * synchronize against both of those.
6141          */
6142         synchronize_srcu(&pmus_srcu);
6143         synchronize_rcu();
6144 
6145         free_percpu(pmu->pmu_disable_count);
6146         if (pmu->type >= PERF_TYPE_MAX)
6147                 idr_remove(&pmu_idr, pmu->type);
6148         device_del(pmu->dev);
6149         put_device(pmu->dev);
6150         free_pmu_context(pmu);
6151 }
6152 
6153 struct pmu *perf_init_event(struct perf_event *event)
6154 {
6155         struct pmu *pmu = NULL;
6156         int idx;
6157         int ret;
6158 
6159         idx = srcu_read_lock(&pmus_srcu);
6160 
6161         rcu_read_lock();
6162         pmu = idr_find(&pmu_idr, event->attr.type);
6163         rcu_read_unlock();
6164         if (pmu) {
6165                 ret = pmu->event_init(event);
6166                 if (ret)
6167                         pmu = ERR_PTR(ret);
6168                 goto unlock;
6169         }
6170 
6171         list_for_each_entry_rcu(pmu, &pmus, entry) {
6172                 ret = pmu->event_init(event);
6173                 if (!ret)
6174                         goto unlock;
6175 
6176                 if (ret != -ENOENT) {
6177                         pmu = ERR_PTR(ret);
6178                         goto unlock;
6179                 }
6180         }
6181         pmu = ERR_PTR(-ENOENT);
6182 unlock:
6183         srcu_read_unlock(&pmus_srcu, idx);
6184 
6185         return pmu;
6186 }
6187 
6188 /*
6189  * Allocate and initialize a event structure
6190  */
6191 static struct perf_event *
6192 perf_event_alloc(struct perf_event_attr *attr, int cpu,
6193                  struct task_struct *task,
6194                  struct perf_event *group_leader,
6195                  struct perf_event *parent_event,
6196                  perf_overflow_handler_t overflow_handler)
6197 {
6198         struct pmu *pmu;
6199         struct perf_event *event;
6200         struct hw_perf_event *hwc;
6201         long err;
6202 
6203         if ((unsigned)cpu >= nr_cpu_ids) {
6204                 if (!task || cpu != -1)
6205                         return ERR_PTR(-EINVAL);
6206         }
6207 
6208         event = kzalloc(sizeof(*event), GFP_KERNEL);
6209         if (!event)
6210                 return ERR_PTR(-ENOMEM);
6211 
6212         /*
6213          * Single events are their own group leaders, with an
6214          * empty sibling list:
6215          */
6216         if (!group_leader)
6217                 group_leader = event;
6218 
6219         mutex_init(&event->child_mutex);
6220         INIT_LIST_HEAD(&event->child_list);
6221 
6222         INIT_LIST_HEAD(&event->group_entry);
6223         INIT_LIST_HEAD(&event->event_entry);
6224         INIT_LIST_HEAD(&event->sibling_list);
6225         init_waitqueue_head(&event->waitq);
6226         init_irq_work(&event->pending, perf_pending_event);
6227 
6228         mutex_init(&event->mmap_mutex);
6229 
6230         atomic_long_set(&event->refcount, 1);
6231         event->cpu              = cpu;
6232         event->attr             = *attr;
6233         event->group_leader     = group_leader;
6234         event->pmu              = NULL;
6235         event->oncpu            = -1;
6236 
6237         event->parent           = parent_event;
6238 
6239         event->ns               = get_pid_ns(current->nsproxy->pid_ns);
6240         event->id               = atomic64_inc_return(&perf_event_id);
6241 
6242         event->state            = PERF_EVENT_STATE_INACTIVE;
6243 
6244         if (task) {
6245                 event->attach_state = PERF_ATTACH_TASK;
6246 #ifdef CONFIG_HAVE_HW_BREAKPOINT
6247                 /*
6248                  * hw_breakpoint is a bit difficult here..
6249                  */
6250                 if (attr->type == PERF_TYPE_BREAKPOINT)
6251                         event->hw.bp_target = task;
6252 #endif
6253         }
6254 
6255         if (!overflow_handler && parent_event)
6256                 overflow_handler = parent_event->overflow_handler;
6257 
6258         event->overflow_handler = overflow_handler;
6259 
6260         perf_event__state_init(event);
6261 
6262         pmu = NULL;
6263 
6264         hwc = &event->hw;
6265         hwc->sample_period = attr->sample_period;
6266         if (attr->freq && attr->sample_freq)
6267                 hwc->sample_period = 1;
6268         hwc->last_period = hwc->sample_period;
6269 
6270         local64_set(&hwc->period_left, hwc->sample_period);
6271 
6272         /*
6273          * we currently do not support PERF_FORMAT_GROUP on inherited events
6274          */
6275         if (attr->inherit && (attr->read_format & PERF_FORMAT_GROUP))
6276                 goto done;
6277 
6278         pmu = perf_init_event(event);
6279 
6280 done:
6281         err = 0;
6282         if (!pmu)
6283                 err = -EINVAL;
6284         else if (IS_ERR(pmu))
6285                 err = PTR_ERR(pmu);
6286 
6287         if (err) {
6288                 if (event->ns)
6289                         put_pid_ns(event->ns);
6290                 kfree(event);
6291                 return ERR_PTR(err);
6292         }
6293 
6294         event->pmu = pmu;
6295 
6296         if (!event->parent) {
6297                 if (event->attach_state & PERF_ATTACH_TASK)
6298                         jump_label_inc(&perf_sched_events);
6299                 if (event->attr.mmap || event->attr.mmap_data)
6300                         atomic_inc(&nr_mmap_events);
6301                 if (event->attr.comm)
6302                         atomic_inc(&nr_comm_events);
6303                 if (event->attr.task)
6304                         atomic_inc(&nr_task_events);
6305                 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
6306                         err = get_callchain_buffers();
6307                         if (err) {
6308                                 free_event(event);
6309                                 return ERR_PTR(err);
6310                         }
6311                 }
6312         }
6313 
6314         return event;
6315 }
6316 
6317 static int perf_copy_attr(struct perf_event_attr __user *uattr,
6318                           struct perf_event_attr *attr)
6319 {
6320         u32 size;
6321         int ret;
6322 
6323         if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
6324                 return -EFAULT;
6325 
6326         /*
6327          * zero the full structure, so that a short copy will be nice.
6328          */
6329         memset(attr, 0, sizeof(*attr));
6330 
6331         ret = get_user(size, &uattr->size);
6332         if (ret)
6333                 return ret;
6334 
6335         if (size > PAGE_SIZE)   /* silly large */
6336                 goto err_size;
6337 
6338         if (!size)              /* abi compat */
6339                 size = PERF_ATTR_SIZE_VER0;
6340 
6341         if (size < PERF_ATTR_SIZE_VER0)
6342                 goto err_size;
6343 
6344         /*
6345          * If we're handed a bigger struct than we know of,
6346          * ensure all the unknown bits are 0 - i.e. new
6347          * user-space does not rely on any kernel feature
6348          * extensions we dont know about yet.
6349          */
6350         if (size > sizeof(*attr)) {
6351                 unsigned char __user *addr;
6352                 unsigned char __user *end;
6353                 unsigned char val;
6354 
6355                 addr = (void __user *)uattr + sizeof(*attr);
6356                 end  = (void __user *)uattr + size;
6357 
6358                 for (; addr < end; addr++) {
6359                         ret = get_user(val, addr);
6360                         if (ret)
6361                                 return ret;
6362                         if (val)
6363                                 goto err_size;
6364                 }
6365                 size = sizeof(*attr);
6366         }
6367 
6368         ret = copy_from_user(attr, uattr, size);
6369         if (ret)
6370                 return -EFAULT;
6371 
6372         /*
6373          * If the type exists, the corresponding creation will verify
6374          * the attr->config.
6375          */
6376         if (attr->type >= PERF_TYPE_MAX)
6377                 return -EINVAL;
6378 
6379         if (attr->__reserved_1)
6380                 return -EINVAL;
6381 
6382         if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
6383                 return -EINVAL;
6384 
6385         if (attr->read_format & ~(PERF_FORMAT_MAX-1))
6386                 return -EINVAL;
6387 
6388 out:
6389         return ret;
6390 
6391 err_size:
6392         put_user(sizeof(*attr), &uattr->size);
6393         ret = -E2BIG;
6394         goto out;
6395 }
6396 
6397 static int
6398 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
6399 {
6400         struct perf_buffer *buffer = NULL, *old_buffer = NULL;
6401         int ret = -EINVAL;
6402 
6403         if (!output_event)
6404                 goto set;
6405 
6406         /* don't allow circular references */
6407         if (event == output_event)
6408                 goto out;
6409 
6410         /*
6411          * Don't allow cross-cpu buffers
6412          */
6413         if (output_event->cpu != event->cpu)
6414                 goto out;
6415 
6416         /*
6417          * If its not a per-cpu buffer, it must be the same task.
6418          */
6419         if (output_event->cpu == -1 && output_event->ctx != event->ctx)
6420                 goto out;
6421 
6422 set:
6423         mutex_lock(&event->mmap_mutex);
6424         /* Can't redirect output if we've got an active mmap() */
6425         if (atomic_read(&event->mmap_count))
6426                 goto unlock;
6427 
6428         if (output_event) {
6429                 /* get the buffer we want to redirect to */
6430                 buffer = perf_buffer_get(output_event);
6431                 if (!buffer)
6432                         goto unlock;
6433         }
6434 
6435         old_buffer = event->buffer;
6436         rcu_assign_pointer(event->buffer, buffer);
6437         ret = 0;
6438 unlock:
6439         mutex_unlock(&event->mmap_mutex);
6440 
6441         if (old_buffer)
6442                 perf_buffer_put(old_buffer);
6443 out:
6444         return ret;
6445 }
6446 
6447 /**
6448  * sys_perf_event_open - open a performance event, associate it to a task/cpu
6449  *
6450  * @attr_uptr:  event_id type attributes for monitoring/sampling
6451  * @pid:                target pid
6452  * @cpu:                target cpu
6453  * @group_fd:           group leader event fd
6454  */
6455 SYSCALL_DEFINE5(perf_event_open,
6456                 struct perf_event_attr __user *, attr_uptr,
6457                 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
6458 {
6459         struct perf_event *group_leader = NULL, *output_event = NULL;
6460         struct perf_event *event, *sibling;
6461         struct perf_event_attr attr;
6462         struct perf_event_context *ctx;
6463         struct file *event_file = NULL;
6464         struct file *group_file = NULL;
6465         struct task_struct *task = NULL;
6466         struct pmu *pmu;
6467         int event_fd;
6468         int move_group = 0;
6469         int fput_needed = 0;
6470         int err;
6471 
6472         /* for future expandability... */
6473         if (flags & ~PERF_FLAG_ALL)
6474                 return -EINVAL;
6475 
6476         err = perf_copy_attr(attr_uptr, &attr);