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