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

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

Version: ~ [ linux-6.11.5 ] ~ [ linux-6.10.14 ] ~ [ linux-6.9.12 ] ~ [ linux-6.8.12 ] ~ [ linux-6.7.12 ] ~ [ linux-6.6.58 ] ~ [ linux-6.5.13 ] ~ [ linux-6.4.16 ] ~ [ linux-6.3.13 ] ~ [ linux-6.2.16 ] ~ [ linux-6.1.114 ] ~ [ linux-6.0.19 ] ~ [ linux-5.19.17 ] ~ [ linux-5.18.19 ] ~ [ linux-5.17.15 ] ~ [ linux-5.16.20 ] ~ [ linux-5.15.169 ] ~ [ linux-5.14.21 ] ~ [ linux-5.13.19 ] ~ [ linux-5.12.19 ] ~ [ linux-5.11.22 ] ~ [ linux-5.10.228 ] ~ [ linux-5.9.16 ] ~ [ linux-5.8.18 ] ~ [ linux-5.7.19 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.284 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.322 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.336 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.337 ] ~ [ linux-4.4.302 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.9 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

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

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

kernel.org | git.kernel.org | LWN.net | Project Home | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

sflogo.php