perf: Fix wrong comment about default event_idx
[platform/kernel/linux-starfive.git] / include / linux / perf_event.h
1 /*
2  * Performance events:
3  *
4  *    Copyright (C) 2008-2009, Thomas Gleixner <tglx@linutronix.de>
5  *    Copyright (C) 2008-2011, Red Hat, Inc., Ingo Molnar
6  *    Copyright (C) 2008-2011, Red Hat, Inc., Peter Zijlstra
7  *
8  * Data type definitions, declarations, prototypes.
9  *
10  *    Started by: Thomas Gleixner and Ingo Molnar
11  *
12  * For licencing details see kernel-base/COPYING
13  */
14 #ifndef _LINUX_PERF_EVENT_H
15 #define _LINUX_PERF_EVENT_H
16
17 #include <uapi/linux/perf_event.h>
18 #include <uapi/linux/bpf_perf_event.h>
19
20 /*
21  * Kernel-internal data types and definitions:
22  */
23
24 #ifdef CONFIG_PERF_EVENTS
25 # include <asm/perf_event.h>
26 # include <asm/local64.h>
27 #endif
28
29 #define PERF_GUEST_ACTIVE       0x01
30 #define PERF_GUEST_USER 0x02
31
32 struct perf_guest_info_callbacks {
33         unsigned int                    (*state)(void);
34         unsigned long                   (*get_ip)(void);
35         unsigned int                    (*handle_intel_pt_intr)(void);
36 };
37
38 #ifdef CONFIG_HAVE_HW_BREAKPOINT
39 #include <linux/rhashtable-types.h>
40 #include <asm/hw_breakpoint.h>
41 #endif
42
43 #include <linux/list.h>
44 #include <linux/mutex.h>
45 #include <linux/rculist.h>
46 #include <linux/rcupdate.h>
47 #include <linux/spinlock.h>
48 #include <linux/hrtimer.h>
49 #include <linux/fs.h>
50 #include <linux/pid_namespace.h>
51 #include <linux/workqueue.h>
52 #include <linux/ftrace.h>
53 #include <linux/cpu.h>
54 #include <linux/irq_work.h>
55 #include <linux/static_key.h>
56 #include <linux/jump_label_ratelimit.h>
57 #include <linux/atomic.h>
58 #include <linux/sysfs.h>
59 #include <linux/perf_regs.h>
60 #include <linux/cgroup.h>
61 #include <linux/refcount.h>
62 #include <linux/security.h>
63 #include <linux/static_call.h>
64 #include <linux/lockdep.h>
65 #include <asm/local.h>
66
67 struct perf_callchain_entry {
68         __u64                           nr;
69         __u64                           ip[]; /* /proc/sys/kernel/perf_event_max_stack */
70 };
71
72 struct perf_callchain_entry_ctx {
73         struct perf_callchain_entry *entry;
74         u32                         max_stack;
75         u32                         nr;
76         short                       contexts;
77         bool                        contexts_maxed;
78 };
79
80 typedef unsigned long (*perf_copy_f)(void *dst, const void *src,
81                                      unsigned long off, unsigned long len);
82
83 struct perf_raw_frag {
84         union {
85                 struct perf_raw_frag    *next;
86                 unsigned long           pad;
87         };
88         perf_copy_f                     copy;
89         void                            *data;
90         u32                             size;
91 } __packed;
92
93 struct perf_raw_record {
94         struct perf_raw_frag            frag;
95         u32                             size;
96 };
97
98 static __always_inline bool perf_raw_frag_last(const struct perf_raw_frag *frag)
99 {
100         return frag->pad < sizeof(u64);
101 }
102
103 /*
104  * branch stack layout:
105  *  nr: number of taken branches stored in entries[]
106  *  hw_idx: The low level index of raw branch records
107  *          for the most recent branch.
108  *          -1ULL means invalid/unknown.
109  *
110  * Note that nr can vary from sample to sample
111  * branches (to, from) are stored from most recent
112  * to least recent, i.e., entries[0] contains the most
113  * recent branch.
114  * The entries[] is an abstraction of raw branch records,
115  * which may not be stored in age order in HW, e.g. Intel LBR.
116  * The hw_idx is to expose the low level index of raw
117  * branch record for the most recent branch aka entries[0].
118  * The hw_idx index is between -1 (unknown) and max depth,
119  * which can be retrieved in /sys/devices/cpu/caps/branches.
120  * For the architectures whose raw branch records are
121  * already stored in age order, the hw_idx should be 0.
122  */
123 struct perf_branch_stack {
124         __u64                           nr;
125         __u64                           hw_idx;
126         struct perf_branch_entry        entries[];
127 };
128
129 struct task_struct;
130
131 /*
132  * extra PMU register associated with an event
133  */
134 struct hw_perf_event_extra {
135         u64             config; /* register value */
136         unsigned int    reg;    /* register address or index */
137         int             alloc;  /* extra register already allocated */
138         int             idx;    /* index in shared_regs->regs[] */
139 };
140
141 /**
142  * hw_perf_event::flag values
143  *
144  * PERF_EVENT_FLAG_ARCH bits are reserved for architecture-specific
145  * usage.
146  */
147 #define PERF_EVENT_FLAG_ARCH                    0x000fffff
148 #define PERF_EVENT_FLAG_USER_READ_CNT           0x80000000
149
150 static_assert((PERF_EVENT_FLAG_USER_READ_CNT & PERF_EVENT_FLAG_ARCH) == 0);
151
152 /**
153  * struct hw_perf_event - performance event hardware details:
154  */
155 struct hw_perf_event {
156 #ifdef CONFIG_PERF_EVENTS
157         union {
158                 struct { /* hardware */
159                         u64             config;
160                         u64             last_tag;
161                         unsigned long   config_base;
162                         unsigned long   event_base;
163                         int             event_base_rdpmc;
164                         int             idx;
165                         int             last_cpu;
166                         int             flags;
167
168                         struct hw_perf_event_extra extra_reg;
169                         struct hw_perf_event_extra branch_reg;
170                 };
171                 struct { /* software */
172                         struct hrtimer  hrtimer;
173                 };
174                 struct { /* tracepoint */
175                         /* for tp_event->class */
176                         struct list_head        tp_list;
177                 };
178                 struct { /* amd_power */
179                         u64     pwr_acc;
180                         u64     ptsc;
181                 };
182 #ifdef CONFIG_HAVE_HW_BREAKPOINT
183                 struct { /* breakpoint */
184                         /*
185                          * Crufty hack to avoid the chicken and egg
186                          * problem hw_breakpoint has with context
187                          * creation and event initalization.
188                          */
189                         struct arch_hw_breakpoint       info;
190                         struct rhlist_head              bp_list;
191                 };
192 #endif
193                 struct { /* amd_iommu */
194                         u8      iommu_bank;
195                         u8      iommu_cntr;
196                         u16     padding;
197                         u64     conf;
198                         u64     conf1;
199                 };
200         };
201         /*
202          * If the event is a per task event, this will point to the task in
203          * question. See the comment in perf_event_alloc().
204          */
205         struct task_struct              *target;
206
207         /*
208          * PMU would store hardware filter configuration
209          * here.
210          */
211         void                            *addr_filters;
212
213         /* Last sync'ed generation of filters */
214         unsigned long                   addr_filters_gen;
215
216 /*
217  * hw_perf_event::state flags; used to track the PERF_EF_* state.
218  */
219 #define PERF_HES_STOPPED        0x01 /* the counter is stopped */
220 #define PERF_HES_UPTODATE       0x02 /* event->count up-to-date */
221 #define PERF_HES_ARCH           0x04
222
223         int                             state;
224
225         /*
226          * The last observed hardware counter value, updated with a
227          * local64_cmpxchg() such that pmu::read() can be called nested.
228          */
229         local64_t                       prev_count;
230
231         /*
232          * The period to start the next sample with.
233          */
234         u64                             sample_period;
235
236         union {
237                 struct { /* Sampling */
238                         /*
239                          * The period we started this sample with.
240                          */
241                         u64                             last_period;
242
243                         /*
244                          * However much is left of the current period;
245                          * note that this is a full 64bit value and
246                          * allows for generation of periods longer
247                          * than hardware might allow.
248                          */
249                         local64_t                       period_left;
250                 };
251                 struct { /* Topdown events counting for context switch */
252                         u64                             saved_metric;
253                         u64                             saved_slots;
254                 };
255         };
256
257         /*
258          * State for throttling the event, see __perf_event_overflow() and
259          * perf_adjust_freq_unthr_context().
260          */
261         u64                             interrupts_seq;
262         u64                             interrupts;
263
264         /*
265          * State for freq target events, see __perf_event_overflow() and
266          * perf_adjust_freq_unthr_context().
267          */
268         u64                             freq_time_stamp;
269         u64                             freq_count_stamp;
270 #endif
271 };
272
273 struct perf_event;
274 struct perf_event_pmu_context;
275
276 /*
277  * Common implementation detail of pmu::{start,commit,cancel}_txn
278  */
279 #define PERF_PMU_TXN_ADD  0x1           /* txn to add/schedule event on PMU */
280 #define PERF_PMU_TXN_READ 0x2           /* txn to read event group from PMU */
281
282 /**
283  * pmu::capabilities flags
284  */
285 #define PERF_PMU_CAP_NO_INTERRUPT               0x0001
286 #define PERF_PMU_CAP_NO_NMI                     0x0002
287 #define PERF_PMU_CAP_AUX_NO_SG                  0x0004
288 #define PERF_PMU_CAP_EXTENDED_REGS              0x0008
289 #define PERF_PMU_CAP_EXCLUSIVE                  0x0010
290 #define PERF_PMU_CAP_ITRACE                     0x0020
291 #define PERF_PMU_CAP_HETEROGENEOUS_CPUS         0x0040
292 #define PERF_PMU_CAP_NO_EXCLUDE                 0x0080
293 #define PERF_PMU_CAP_AUX_OUTPUT                 0x0100
294 #define PERF_PMU_CAP_EXTENDED_HW_TYPE           0x0200
295
296 struct perf_output_handle;
297
298 #define PMU_NULL_DEV    ((void *)(~0UL))
299
300 /**
301  * struct pmu - generic performance monitoring unit
302  */
303 struct pmu {
304         struct list_head                entry;
305
306         struct module                   *module;
307         struct device                   *dev;
308         struct device                   *parent;
309         const struct attribute_group    **attr_groups;
310         const struct attribute_group    **attr_update;
311         const char                      *name;
312         int                             type;
313
314         /*
315          * various common per-pmu feature flags
316          */
317         int                             capabilities;
318
319         int __percpu                    *pmu_disable_count;
320         struct perf_cpu_pmu_context __percpu *cpu_pmu_context;
321         atomic_t                        exclusive_cnt; /* < 0: cpu; > 0: tsk */
322         int                             task_ctx_nr;
323         int                             hrtimer_interval_ms;
324
325         /* number of address filters this PMU can do */
326         unsigned int                    nr_addr_filters;
327
328         /*
329          * Fully disable/enable this PMU, can be used to protect from the PMI
330          * as well as for lazy/batch writing of the MSRs.
331          */
332         void (*pmu_enable)              (struct pmu *pmu); /* optional */
333         void (*pmu_disable)             (struct pmu *pmu); /* optional */
334
335         /*
336          * Try and initialize the event for this PMU.
337          *
338          * Returns:
339          *  -ENOENT     -- @event is not for this PMU
340          *
341          *  -ENODEV     -- @event is for this PMU but PMU not present
342          *  -EBUSY      -- @event is for this PMU but PMU temporarily unavailable
343          *  -EINVAL     -- @event is for this PMU but @event is not valid
344          *  -EOPNOTSUPP -- @event is for this PMU, @event is valid, but not supported
345          *  -EACCES     -- @event is for this PMU, @event is valid, but no privileges
346          *
347          *  0           -- @event is for this PMU and valid
348          *
349          * Other error return values are allowed.
350          */
351         int (*event_init)               (struct perf_event *event);
352
353         /*
354          * Notification that the event was mapped or unmapped.  Called
355          * in the context of the mapping task.
356          */
357         void (*event_mapped)            (struct perf_event *event, struct mm_struct *mm); /* optional */
358         void (*event_unmapped)          (struct perf_event *event, struct mm_struct *mm); /* optional */
359
360         /*
361          * Flags for ->add()/->del()/ ->start()/->stop(). There are
362          * matching hw_perf_event::state flags.
363          */
364 #define PERF_EF_START   0x01            /* start the counter when adding    */
365 #define PERF_EF_RELOAD  0x02            /* reload the counter when starting */
366 #define PERF_EF_UPDATE  0x04            /* update the counter when stopping */
367
368         /*
369          * Adds/Removes a counter to/from the PMU, can be done inside a
370          * transaction, see the ->*_txn() methods.
371          *
372          * The add/del callbacks will reserve all hardware resources required
373          * to service the event, this includes any counter constraint
374          * scheduling etc.
375          *
376          * Called with IRQs disabled and the PMU disabled on the CPU the event
377          * is on.
378          *
379          * ->add() called without PERF_EF_START should result in the same state
380          *  as ->add() followed by ->stop().
381          *
382          * ->del() must always PERF_EF_UPDATE stop an event. If it calls
383          *  ->stop() that must deal with already being stopped without
384          *  PERF_EF_UPDATE.
385          */
386         int  (*add)                     (struct perf_event *event, int flags);
387         void (*del)                     (struct perf_event *event, int flags);
388
389         /*
390          * Starts/Stops a counter present on the PMU.
391          *
392          * The PMI handler should stop the counter when perf_event_overflow()
393          * returns !0. ->start() will be used to continue.
394          *
395          * Also used to change the sample period.
396          *
397          * Called with IRQs disabled and the PMU disabled on the CPU the event
398          * is on -- will be called from NMI context with the PMU generates
399          * NMIs.
400          *
401          * ->stop() with PERF_EF_UPDATE will read the counter and update
402          *  period/count values like ->read() would.
403          *
404          * ->start() with PERF_EF_RELOAD will reprogram the counter
405          *  value, must be preceded by a ->stop() with PERF_EF_UPDATE.
406          */
407         void (*start)                   (struct perf_event *event, int flags);
408         void (*stop)                    (struct perf_event *event, int flags);
409
410         /*
411          * Updates the counter value of the event.
412          *
413          * For sampling capable PMUs this will also update the software period
414          * hw_perf_event::period_left field.
415          */
416         void (*read)                    (struct perf_event *event);
417
418         /*
419          * Group events scheduling is treated as a transaction, add
420          * group events as a whole and perform one schedulability test.
421          * If the test fails, roll back the whole group
422          *
423          * Start the transaction, after this ->add() doesn't need to
424          * do schedulability tests.
425          *
426          * Optional.
427          */
428         void (*start_txn)               (struct pmu *pmu, unsigned int txn_flags);
429         /*
430          * If ->start_txn() disabled the ->add() schedulability test
431          * then ->commit_txn() is required to perform one. On success
432          * the transaction is closed. On error the transaction is kept
433          * open until ->cancel_txn() is called.
434          *
435          * Optional.
436          */
437         int  (*commit_txn)              (struct pmu *pmu);
438         /*
439          * Will cancel the transaction, assumes ->del() is called
440          * for each successful ->add() during the transaction.
441          *
442          * Optional.
443          */
444         void (*cancel_txn)              (struct pmu *pmu);
445
446         /*
447          * Will return the value for perf_event_mmap_page::index for this event,
448          * if no implementation is provided it will default to 0 (see
449          * perf_event_idx_default).
450          */
451         int (*event_idx)                (struct perf_event *event); /*optional */
452
453         /*
454          * context-switches callback
455          */
456         void (*sched_task)              (struct perf_event_pmu_context *pmu_ctx,
457                                         bool sched_in);
458
459         /*
460          * Kmem cache of PMU specific data
461          */
462         struct kmem_cache               *task_ctx_cache;
463
464         /*
465          * PMU specific parts of task perf event context (i.e. ctx->task_ctx_data)
466          * can be synchronized using this function. See Intel LBR callstack support
467          * implementation and Perf core context switch handling callbacks for usage
468          * examples.
469          */
470         void (*swap_task_ctx)           (struct perf_event_pmu_context *prev_epc,
471                                          struct perf_event_pmu_context *next_epc);
472                                         /* optional */
473
474         /*
475          * Set up pmu-private data structures for an AUX area
476          */
477         void *(*setup_aux)              (struct perf_event *event, void **pages,
478                                          int nr_pages, bool overwrite);
479                                         /* optional */
480
481         /*
482          * Free pmu-private AUX data structures
483          */
484         void (*free_aux)                (void *aux); /* optional */
485
486         /*
487          * Take a snapshot of the AUX buffer without touching the event
488          * state, so that preempting ->start()/->stop() callbacks does
489          * not interfere with their logic. Called in PMI context.
490          *
491          * Returns the size of AUX data copied to the output handle.
492          *
493          * Optional.
494          */
495         long (*snapshot_aux)            (struct perf_event *event,
496                                          struct perf_output_handle *handle,
497                                          unsigned long size);
498
499         /*
500          * Validate address range filters: make sure the HW supports the
501          * requested configuration and number of filters; return 0 if the
502          * supplied filters are valid, -errno otherwise.
503          *
504          * Runs in the context of the ioctl()ing process and is not serialized
505          * with the rest of the PMU callbacks.
506          */
507         int (*addr_filters_validate)    (struct list_head *filters);
508                                         /* optional */
509
510         /*
511          * Synchronize address range filter configuration:
512          * translate hw-agnostic filters into hardware configuration in
513          * event::hw::addr_filters.
514          *
515          * Runs as a part of filter sync sequence that is done in ->start()
516          * callback by calling perf_event_addr_filters_sync().
517          *
518          * May (and should) traverse event::addr_filters::list, for which its
519          * caller provides necessary serialization.
520          */
521         void (*addr_filters_sync)       (struct perf_event *event);
522                                         /* optional */
523
524         /*
525          * Check if event can be used for aux_output purposes for
526          * events of this PMU.
527          *
528          * Runs from perf_event_open(). Should return 0 for "no match"
529          * or non-zero for "match".
530          */
531         int (*aux_output_match)         (struct perf_event *event);
532                                         /* optional */
533
534         /*
535          * Skip programming this PMU on the given CPU. Typically needed for
536          * big.LITTLE things.
537          */
538         bool (*filter)                  (struct pmu *pmu, int cpu); /* optional */
539
540         /*
541          * Check period value for PERF_EVENT_IOC_PERIOD ioctl.
542          */
543         int (*check_period)             (struct perf_event *event, u64 value); /* optional */
544 };
545
546 enum perf_addr_filter_action_t {
547         PERF_ADDR_FILTER_ACTION_STOP = 0,
548         PERF_ADDR_FILTER_ACTION_START,
549         PERF_ADDR_FILTER_ACTION_FILTER,
550 };
551
552 /**
553  * struct perf_addr_filter - address range filter definition
554  * @entry:      event's filter list linkage
555  * @path:       object file's path for file-based filters
556  * @offset:     filter range offset
557  * @size:       filter range size (size==0 means single address trigger)
558  * @action:     filter/start/stop
559  *
560  * This is a hardware-agnostic filter configuration as specified by the user.
561  */
562 struct perf_addr_filter {
563         struct list_head        entry;
564         struct path             path;
565         unsigned long           offset;
566         unsigned long           size;
567         enum perf_addr_filter_action_t  action;
568 };
569
570 /**
571  * struct perf_addr_filters_head - container for address range filters
572  * @list:       list of filters for this event
573  * @lock:       spinlock that serializes accesses to the @list and event's
574  *              (and its children's) filter generations.
575  * @nr_file_filters:    number of file-based filters
576  *
577  * A child event will use parent's @list (and therefore @lock), so they are
578  * bundled together; see perf_event_addr_filters().
579  */
580 struct perf_addr_filters_head {
581         struct list_head        list;
582         raw_spinlock_t          lock;
583         unsigned int            nr_file_filters;
584 };
585
586 struct perf_addr_filter_range {
587         unsigned long           start;
588         unsigned long           size;
589 };
590
591 /**
592  * enum perf_event_state - the states of an event:
593  */
594 enum perf_event_state {
595         PERF_EVENT_STATE_DEAD           = -4,
596         PERF_EVENT_STATE_EXIT           = -3,
597         PERF_EVENT_STATE_ERROR          = -2,
598         PERF_EVENT_STATE_OFF            = -1,
599         PERF_EVENT_STATE_INACTIVE       =  0,
600         PERF_EVENT_STATE_ACTIVE         =  1,
601 };
602
603 struct file;
604 struct perf_sample_data;
605
606 typedef void (*perf_overflow_handler_t)(struct perf_event *,
607                                         struct perf_sample_data *,
608                                         struct pt_regs *regs);
609
610 /*
611  * Event capabilities. For event_caps and groups caps.
612  *
613  * PERF_EV_CAP_SOFTWARE: Is a software event.
614  * PERF_EV_CAP_READ_ACTIVE_PKG: A CPU event (or cgroup event) that can be read
615  * from any CPU in the package where it is active.
616  * PERF_EV_CAP_SIBLING: An event with this flag must be a group sibling and
617  * cannot be a group leader. If an event with this flag is detached from the
618  * group it is scheduled out and moved into an unrecoverable ERROR state.
619  */
620 #define PERF_EV_CAP_SOFTWARE            BIT(0)
621 #define PERF_EV_CAP_READ_ACTIVE_PKG     BIT(1)
622 #define PERF_EV_CAP_SIBLING             BIT(2)
623
624 #define SWEVENT_HLIST_BITS              8
625 #define SWEVENT_HLIST_SIZE              (1 << SWEVENT_HLIST_BITS)
626
627 struct swevent_hlist {
628         struct hlist_head               heads[SWEVENT_HLIST_SIZE];
629         struct rcu_head                 rcu_head;
630 };
631
632 #define PERF_ATTACH_CONTEXT     0x01
633 #define PERF_ATTACH_GROUP       0x02
634 #define PERF_ATTACH_TASK        0x04
635 #define PERF_ATTACH_TASK_DATA   0x08
636 #define PERF_ATTACH_ITRACE      0x10
637 #define PERF_ATTACH_SCHED_CB    0x20
638 #define PERF_ATTACH_CHILD       0x40
639
640 struct bpf_prog;
641 struct perf_cgroup;
642 struct perf_buffer;
643
644 struct pmu_event_list {
645         raw_spinlock_t          lock;
646         struct list_head        list;
647 };
648
649 /*
650  * event->sibling_list is modified whole holding both ctx->lock and ctx->mutex
651  * as such iteration must hold either lock. However, since ctx->lock is an IRQ
652  * safe lock, and is only held by the CPU doing the modification, having IRQs
653  * disabled is sufficient since it will hold-off the IPIs.
654  */
655 #ifdef CONFIG_PROVE_LOCKING
656 #define lockdep_assert_event_ctx(event)                         \
657         WARN_ON_ONCE(__lockdep_enabled &&                       \
658                      (this_cpu_read(hardirqs_enabled) &&        \
659                       lockdep_is_held(&(event)->ctx->mutex) != LOCK_STATE_HELD))
660 #else
661 #define lockdep_assert_event_ctx(event)
662 #endif
663
664 #define for_each_sibling_event(sibling, event)                  \
665         lockdep_assert_event_ctx(event);                        \
666         if ((event)->group_leader == (event))                   \
667                 list_for_each_entry((sibling), &(event)->sibling_list, sibling_list)
668
669 /**
670  * struct perf_event - performance event kernel representation:
671  */
672 struct perf_event {
673 #ifdef CONFIG_PERF_EVENTS
674         /*
675          * entry onto perf_event_context::event_list;
676          *   modifications require ctx->lock
677          *   RCU safe iterations.
678          */
679         struct list_head                event_entry;
680
681         /*
682          * Locked for modification by both ctx->mutex and ctx->lock; holding
683          * either sufficies for read.
684          */
685         struct list_head                sibling_list;
686         struct list_head                active_list;
687         /*
688          * Node on the pinned or flexible tree located at the event context;
689          */
690         struct rb_node                  group_node;
691         u64                             group_index;
692         /*
693          * We need storage to track the entries in perf_pmu_migrate_context; we
694          * cannot use the event_entry because of RCU and we want to keep the
695          * group in tact which avoids us using the other two entries.
696          */
697         struct list_head                migrate_entry;
698
699         struct hlist_node               hlist_entry;
700         struct list_head                active_entry;
701         int                             nr_siblings;
702
703         /* Not serialized. Only written during event initialization. */
704         int                             event_caps;
705         /* The cumulative AND of all event_caps for events in this group. */
706         int                             group_caps;
707
708         struct perf_event               *group_leader;
709         /*
710          * event->pmu will always point to pmu in which this event belongs.
711          * Whereas event->pmu_ctx->pmu may point to other pmu when group of
712          * different pmu events is created.
713          */
714         struct pmu                      *pmu;
715         void                            *pmu_private;
716
717         enum perf_event_state           state;
718         unsigned int                    attach_state;
719         local64_t                       count;
720         atomic64_t                      child_count;
721
722         /*
723          * These are the total time in nanoseconds that the event
724          * has been enabled (i.e. eligible to run, and the task has
725          * been scheduled in, if this is a per-task event)
726          * and running (scheduled onto the CPU), respectively.
727          */
728         u64                             total_time_enabled;
729         u64                             total_time_running;
730         u64                             tstamp;
731
732         struct perf_event_attr          attr;
733         u16                             header_size;
734         u16                             id_header_size;
735         u16                             read_size;
736         struct hw_perf_event            hw;
737
738         struct perf_event_context       *ctx;
739         /*
740          * event->pmu_ctx points to perf_event_pmu_context in which the event
741          * is added. This pmu_ctx can be of other pmu for sw event when that
742          * sw event is part of a group which also contains non-sw events.
743          */
744         struct perf_event_pmu_context   *pmu_ctx;
745         atomic_long_t                   refcount;
746
747         /*
748          * These accumulate total time (in nanoseconds) that children
749          * events have been enabled and running, respectively.
750          */
751         atomic64_t                      child_total_time_enabled;
752         atomic64_t                      child_total_time_running;
753
754         /*
755          * Protect attach/detach and child_list:
756          */
757         struct mutex                    child_mutex;
758         struct list_head                child_list;
759         struct perf_event               *parent;
760
761         int                             oncpu;
762         int                             cpu;
763
764         struct list_head                owner_entry;
765         struct task_struct              *owner;
766
767         /* mmap bits */
768         struct mutex                    mmap_mutex;
769         atomic_t                        mmap_count;
770
771         struct perf_buffer              *rb;
772         struct list_head                rb_entry;
773         unsigned long                   rcu_batches;
774         int                             rcu_pending;
775
776         /* poll related */
777         wait_queue_head_t               waitq;
778         struct fasync_struct            *fasync;
779
780         /* delayed work for NMIs and such */
781         unsigned int                    pending_wakeup;
782         unsigned int                    pending_kill;
783         unsigned int                    pending_disable;
784         unsigned int                    pending_sigtrap;
785         unsigned long                   pending_addr;   /* SIGTRAP */
786         struct irq_work                 pending_irq;
787         struct callback_head            pending_task;
788         unsigned int                    pending_work;
789
790         atomic_t                        event_limit;
791
792         /* address range filters */
793         struct perf_addr_filters_head   addr_filters;
794         /* vma address array for file-based filders */
795         struct perf_addr_filter_range   *addr_filter_ranges;
796         unsigned long                   addr_filters_gen;
797
798         /* for aux_output events */
799         struct perf_event               *aux_event;
800
801         void (*destroy)(struct perf_event *);
802         struct rcu_head                 rcu_head;
803
804         struct pid_namespace            *ns;
805         u64                             id;
806
807         atomic64_t                      lost_samples;
808
809         u64                             (*clock)(void);
810         perf_overflow_handler_t         overflow_handler;
811         void                            *overflow_handler_context;
812 #ifdef CONFIG_BPF_SYSCALL
813         perf_overflow_handler_t         orig_overflow_handler;
814         struct bpf_prog                 *prog;
815         u64                             bpf_cookie;
816 #endif
817
818 #ifdef CONFIG_EVENT_TRACING
819         struct trace_event_call         *tp_event;
820         struct event_filter             *filter;
821 #ifdef CONFIG_FUNCTION_TRACER
822         struct ftrace_ops               ftrace_ops;
823 #endif
824 #endif
825
826 #ifdef CONFIG_CGROUP_PERF
827         struct perf_cgroup              *cgrp; /* cgroup event is attach to */
828 #endif
829
830 #ifdef CONFIG_SECURITY
831         void *security;
832 #endif
833         struct list_head                sb_list;
834
835         /*
836          * Certain events gets forwarded to another pmu internally by over-
837          * writing kernel copy of event->attr.type without user being aware
838          * of it. event->orig_type contains original 'type' requested by
839          * user.
840          */
841         __u32                           orig_type;
842 #endif /* CONFIG_PERF_EVENTS */
843 };
844
845 /*
846  *           ,-----------------------[1:n]----------------------.
847  *           V                                                  V
848  * perf_event_context <-[1:n]-> perf_event_pmu_context <--- perf_event
849  *           ^                      ^     |                     |
850  *           `--------[1:n]---------'     `-[n:1]-> pmu <-[1:n]-'
851  *
852  *
853  * struct perf_event_pmu_context  lifetime is refcount based and RCU freed
854  * (similar to perf_event_context). Locking is as if it were a member of
855  * perf_event_context; specifically:
856  *
857  *   modification, both: ctx->mutex && ctx->lock
858  *   reading, either:    ctx->mutex || ctx->lock
859  *
860  * There is one exception to this; namely put_pmu_ctx() isn't always called
861  * with ctx->mutex held; this means that as long as we can guarantee the epc
862  * has events the above rules hold.
863  *
864  * Specificially, sys_perf_event_open()'s group_leader case depends on
865  * ctx->mutex pinning the configuration. Since we hold a reference on
866  * group_leader (through the filedesc) it can't go away, therefore it's
867  * associated pmu_ctx must exist and cannot change due to ctx->mutex.
868  */
869 struct perf_event_pmu_context {
870         struct pmu                      *pmu;
871         struct perf_event_context       *ctx;
872
873         struct list_head                pmu_ctx_entry;
874
875         struct list_head                pinned_active;
876         struct list_head                flexible_active;
877
878         /* Used to avoid freeing per-cpu perf_event_pmu_context */
879         unsigned int                    embedded : 1;
880
881         unsigned int                    nr_events;
882
883         atomic_t                        refcount; /* event <-> epc */
884         struct rcu_head                 rcu_head;
885
886         void                            *task_ctx_data; /* pmu specific data */
887         /*
888          * Set when one or more (plausibly active) event can't be scheduled
889          * due to pmu overcommit or pmu constraints, except tolerant to
890          * events not necessary to be active due to scheduling constraints,
891          * such as cgroups.
892          */
893         int                             rotate_necessary;
894 };
895
896 struct perf_event_groups {
897         struct rb_root  tree;
898         u64             index;
899 };
900
901
902 /**
903  * struct perf_event_context - event context structure
904  *
905  * Used as a container for task events and CPU events as well:
906  */
907 struct perf_event_context {
908         /*
909          * Protect the states of the events in the list,
910          * nr_active, and the list:
911          */
912         raw_spinlock_t                  lock;
913         /*
914          * Protect the list of events.  Locking either mutex or lock
915          * is sufficient to ensure the list doesn't change; to change
916          * the list you need to lock both the mutex and the spinlock.
917          */
918         struct mutex                    mutex;
919
920         struct list_head                pmu_ctx_list;
921         struct perf_event_groups        pinned_groups;
922         struct perf_event_groups        flexible_groups;
923         struct list_head                event_list;
924
925         int                             nr_events;
926         int                             nr_user;
927         int                             is_active;
928
929         int                             nr_task_data;
930         int                             nr_stat;
931         int                             nr_freq;
932         int                             rotate_disable;
933
934         refcount_t                      refcount; /* event <-> ctx */
935         struct task_struct              *task;
936
937         /*
938          * Context clock, runs when context enabled.
939          */
940         u64                             time;
941         u64                             timestamp;
942         u64                             timeoffset;
943
944         /*
945          * These fields let us detect when two contexts have both
946          * been cloned (inherited) from a common ancestor.
947          */
948         struct perf_event_context       *parent_ctx;
949         u64                             parent_gen;
950         u64                             generation;
951         int                             pin_count;
952 #ifdef CONFIG_CGROUP_PERF
953         int                             nr_cgroups;      /* cgroup evts */
954 #endif
955         struct rcu_head                 rcu_head;
956
957         /*
958          * Sum (event->pending_sigtrap + event->pending_work)
959          *
960          * The SIGTRAP is targeted at ctx->task, as such it won't do changing
961          * that until the signal is delivered.
962          */
963         local_t                         nr_pending;
964 };
965
966 /*
967  * Number of contexts where an event can trigger:
968  *      task, softirq, hardirq, nmi.
969  */
970 #define PERF_NR_CONTEXTS        4
971
972 struct perf_cpu_pmu_context {
973         struct perf_event_pmu_context   epc;
974         struct perf_event_pmu_context   *task_epc;
975
976         struct list_head                sched_cb_entry;
977         int                             sched_cb_usage;
978
979         int                             active_oncpu;
980         int                             exclusive;
981
982         raw_spinlock_t                  hrtimer_lock;
983         struct hrtimer                  hrtimer;
984         ktime_t                         hrtimer_interval;
985         unsigned int                    hrtimer_active;
986 };
987
988 /**
989  * struct perf_event_cpu_context - per cpu event context structure
990  */
991 struct perf_cpu_context {
992         struct perf_event_context       ctx;
993         struct perf_event_context       *task_ctx;
994         int                             online;
995
996 #ifdef CONFIG_CGROUP_PERF
997         struct perf_cgroup              *cgrp;
998 #endif
999
1000         /*
1001          * Per-CPU storage for iterators used in visit_groups_merge. The default
1002          * storage is of size 2 to hold the CPU and any CPU event iterators.
1003          */
1004         int                             heap_size;
1005         struct perf_event               **heap;
1006         struct perf_event               *heap_default[2];
1007 };
1008
1009 struct perf_output_handle {
1010         struct perf_event               *event;
1011         struct perf_buffer              *rb;
1012         unsigned long                   wakeup;
1013         unsigned long                   size;
1014         u64                             aux_flags;
1015         union {
1016                 void                    *addr;
1017                 unsigned long           head;
1018         };
1019         int                             page;
1020 };
1021
1022 struct bpf_perf_event_data_kern {
1023         bpf_user_pt_regs_t *regs;
1024         struct perf_sample_data *data;
1025         struct perf_event *event;
1026 };
1027
1028 #ifdef CONFIG_CGROUP_PERF
1029
1030 /*
1031  * perf_cgroup_info keeps track of time_enabled for a cgroup.
1032  * This is a per-cpu dynamically allocated data structure.
1033  */
1034 struct perf_cgroup_info {
1035         u64                             time;
1036         u64                             timestamp;
1037         u64                             timeoffset;
1038         int                             active;
1039 };
1040
1041 struct perf_cgroup {
1042         struct cgroup_subsys_state      css;
1043         struct perf_cgroup_info __percpu *info;
1044 };
1045
1046 /*
1047  * Must ensure cgroup is pinned (css_get) before calling
1048  * this function. In other words, we cannot call this function
1049  * if there is no cgroup event for the current CPU context.
1050  */
1051 static inline struct perf_cgroup *
1052 perf_cgroup_from_task(struct task_struct *task, struct perf_event_context *ctx)
1053 {
1054         return container_of(task_css_check(task, perf_event_cgrp_id,
1055                                            ctx ? lockdep_is_held(&ctx->lock)
1056                                                : true),
1057                             struct perf_cgroup, css);
1058 }
1059 #endif /* CONFIG_CGROUP_PERF */
1060
1061 #ifdef CONFIG_PERF_EVENTS
1062
1063 extern struct perf_event_context *perf_cpu_task_ctx(void);
1064
1065 extern void *perf_aux_output_begin(struct perf_output_handle *handle,
1066                                    struct perf_event *event);
1067 extern void perf_aux_output_end(struct perf_output_handle *handle,
1068                                 unsigned long size);
1069 extern int perf_aux_output_skip(struct perf_output_handle *handle,
1070                                 unsigned long size);
1071 extern void *perf_get_aux(struct perf_output_handle *handle);
1072 extern void perf_aux_output_flag(struct perf_output_handle *handle, u64 flags);
1073 extern void perf_event_itrace_started(struct perf_event *event);
1074
1075 extern int perf_pmu_register(struct pmu *pmu, const char *name, int type);
1076 extern void perf_pmu_unregister(struct pmu *pmu);
1077
1078 extern void __perf_event_task_sched_in(struct task_struct *prev,
1079                                        struct task_struct *task);
1080 extern void __perf_event_task_sched_out(struct task_struct *prev,
1081                                         struct task_struct *next);
1082 extern int perf_event_init_task(struct task_struct *child, u64 clone_flags);
1083 extern void perf_event_exit_task(struct task_struct *child);
1084 extern void perf_event_free_task(struct task_struct *task);
1085 extern void perf_event_delayed_put(struct task_struct *task);
1086 extern struct file *perf_event_get(unsigned int fd);
1087 extern const struct perf_event *perf_get_event(struct file *file);
1088 extern const struct perf_event_attr *perf_event_attrs(struct perf_event *event);
1089 extern void perf_event_print_debug(void);
1090 extern void perf_pmu_disable(struct pmu *pmu);
1091 extern void perf_pmu_enable(struct pmu *pmu);
1092 extern void perf_sched_cb_dec(struct pmu *pmu);
1093 extern void perf_sched_cb_inc(struct pmu *pmu);
1094 extern int perf_event_task_disable(void);
1095 extern int perf_event_task_enable(void);
1096
1097 extern void perf_pmu_resched(struct pmu *pmu);
1098
1099 extern int perf_event_refresh(struct perf_event *event, int refresh);
1100 extern void perf_event_update_userpage(struct perf_event *event);
1101 extern int perf_event_release_kernel(struct perf_event *event);
1102 extern struct perf_event *
1103 perf_event_create_kernel_counter(struct perf_event_attr *attr,
1104                                 int cpu,
1105                                 struct task_struct *task,
1106                                 perf_overflow_handler_t callback,
1107                                 void *context);
1108 extern void perf_pmu_migrate_context(struct pmu *pmu,
1109                                 int src_cpu, int dst_cpu);
1110 int perf_event_read_local(struct perf_event *event, u64 *value,
1111                           u64 *enabled, u64 *running);
1112 extern u64 perf_event_read_value(struct perf_event *event,
1113                                  u64 *enabled, u64 *running);
1114
1115 extern struct perf_callchain_entry *perf_callchain(struct perf_event *event, struct pt_regs *regs);
1116
1117 static inline bool branch_sample_no_flags(const struct perf_event *event)
1118 {
1119         return event->attr.branch_sample_type & PERF_SAMPLE_BRANCH_NO_FLAGS;
1120 }
1121
1122 static inline bool branch_sample_no_cycles(const struct perf_event *event)
1123 {
1124         return event->attr.branch_sample_type & PERF_SAMPLE_BRANCH_NO_CYCLES;
1125 }
1126
1127 static inline bool branch_sample_type(const struct perf_event *event)
1128 {
1129         return event->attr.branch_sample_type & PERF_SAMPLE_BRANCH_TYPE_SAVE;
1130 }
1131
1132 static inline bool branch_sample_hw_index(const struct perf_event *event)
1133 {
1134         return event->attr.branch_sample_type & PERF_SAMPLE_BRANCH_HW_INDEX;
1135 }
1136
1137 static inline bool branch_sample_priv(const struct perf_event *event)
1138 {
1139         return event->attr.branch_sample_type & PERF_SAMPLE_BRANCH_PRIV_SAVE;
1140 }
1141
1142
1143 struct perf_sample_data {
1144         /*
1145          * Fields set by perf_sample_data_init() unconditionally,
1146          * group so as to minimize the cachelines touched.
1147          */
1148         u64                             sample_flags;
1149         u64                             period;
1150         u64                             dyn_size;
1151
1152         /*
1153          * Fields commonly set by __perf_event_header__init_id(),
1154          * group so as to minimize the cachelines touched.
1155          */
1156         u64                             type;
1157         struct {
1158                 u32     pid;
1159                 u32     tid;
1160         }                               tid_entry;
1161         u64                             time;
1162         u64                             id;
1163         struct {
1164                 u32     cpu;
1165                 u32     reserved;
1166         }                               cpu_entry;
1167
1168         /*
1169          * The other fields, optionally {set,used} by
1170          * perf_{prepare,output}_sample().
1171          */
1172         u64                             ip;
1173         struct perf_callchain_entry     *callchain;
1174         struct perf_raw_record          *raw;
1175         struct perf_branch_stack        *br_stack;
1176         union perf_sample_weight        weight;
1177         union  perf_mem_data_src        data_src;
1178         u64                             txn;
1179
1180         struct perf_regs                regs_user;
1181         struct perf_regs                regs_intr;
1182         u64                             stack_user_size;
1183
1184         u64                             stream_id;
1185         u64                             cgroup;
1186         u64                             addr;
1187         u64                             phys_addr;
1188         u64                             data_page_size;
1189         u64                             code_page_size;
1190         u64                             aux_size;
1191 } ____cacheline_aligned;
1192
1193 /* default value for data source */
1194 #define PERF_MEM_NA (PERF_MEM_S(OP, NA)   |\
1195                     PERF_MEM_S(LVL, NA)   |\
1196                     PERF_MEM_S(SNOOP, NA) |\
1197                     PERF_MEM_S(LOCK, NA)  |\
1198                     PERF_MEM_S(TLB, NA))
1199
1200 static inline void perf_sample_data_init(struct perf_sample_data *data,
1201                                          u64 addr, u64 period)
1202 {
1203         /* remaining struct members initialized in perf_prepare_sample() */
1204         data->sample_flags = PERF_SAMPLE_PERIOD;
1205         data->period = period;
1206         data->dyn_size = 0;
1207
1208         if (addr) {
1209                 data->addr = addr;
1210                 data->sample_flags |= PERF_SAMPLE_ADDR;
1211         }
1212 }
1213
1214 static inline void perf_sample_save_callchain(struct perf_sample_data *data,
1215                                               struct perf_event *event,
1216                                               struct pt_regs *regs)
1217 {
1218         int size = 1;
1219
1220         data->callchain = perf_callchain(event, regs);
1221         size += data->callchain->nr;
1222
1223         data->dyn_size += size * sizeof(u64);
1224         data->sample_flags |= PERF_SAMPLE_CALLCHAIN;
1225 }
1226
1227 static inline void perf_sample_save_raw_data(struct perf_sample_data *data,
1228                                              struct perf_raw_record *raw)
1229 {
1230         struct perf_raw_frag *frag = &raw->frag;
1231         u32 sum = 0;
1232         int size;
1233
1234         do {
1235                 sum += frag->size;
1236                 if (perf_raw_frag_last(frag))
1237                         break;
1238                 frag = frag->next;
1239         } while (1);
1240
1241         size = round_up(sum + sizeof(u32), sizeof(u64));
1242         raw->size = size - sizeof(u32);
1243         frag->pad = raw->size - sum;
1244
1245         data->raw = raw;
1246         data->dyn_size += size;
1247         data->sample_flags |= PERF_SAMPLE_RAW;
1248 }
1249
1250 static inline void perf_sample_save_brstack(struct perf_sample_data *data,
1251                                             struct perf_event *event,
1252                                             struct perf_branch_stack *brs)
1253 {
1254         int size = sizeof(u64); /* nr */
1255
1256         if (branch_sample_hw_index(event))
1257                 size += sizeof(u64);
1258         size += brs->nr * sizeof(struct perf_branch_entry);
1259
1260         data->br_stack = brs;
1261         data->dyn_size += size;
1262         data->sample_flags |= PERF_SAMPLE_BRANCH_STACK;
1263 }
1264
1265 static inline u32 perf_sample_data_size(struct perf_sample_data *data,
1266                                         struct perf_event *event)
1267 {
1268         u32 size = sizeof(struct perf_event_header);
1269
1270         size += event->header_size + event->id_header_size;
1271         size += data->dyn_size;
1272
1273         return size;
1274 }
1275
1276 /*
1277  * Clear all bitfields in the perf_branch_entry.
1278  * The to and from fields are not cleared because they are
1279  * systematically modified by caller.
1280  */
1281 static inline void perf_clear_branch_entry_bitfields(struct perf_branch_entry *br)
1282 {
1283         br->mispred = 0;
1284         br->predicted = 0;
1285         br->in_tx = 0;
1286         br->abort = 0;
1287         br->cycles = 0;
1288         br->type = 0;
1289         br->spec = PERF_BR_SPEC_NA;
1290         br->reserved = 0;
1291 }
1292
1293 extern void perf_output_sample(struct perf_output_handle *handle,
1294                                struct perf_event_header *header,
1295                                struct perf_sample_data *data,
1296                                struct perf_event *event);
1297 extern void perf_prepare_sample(struct perf_sample_data *data,
1298                                 struct perf_event *event,
1299                                 struct pt_regs *regs);
1300 extern void perf_prepare_header(struct perf_event_header *header,
1301                                 struct perf_sample_data *data,
1302                                 struct perf_event *event,
1303                                 struct pt_regs *regs);
1304
1305 extern int perf_event_overflow(struct perf_event *event,
1306                                  struct perf_sample_data *data,
1307                                  struct pt_regs *regs);
1308
1309 extern void perf_event_output_forward(struct perf_event *event,
1310                                      struct perf_sample_data *data,
1311                                      struct pt_regs *regs);
1312 extern void perf_event_output_backward(struct perf_event *event,
1313                                        struct perf_sample_data *data,
1314                                        struct pt_regs *regs);
1315 extern int perf_event_output(struct perf_event *event,
1316                              struct perf_sample_data *data,
1317                              struct pt_regs *regs);
1318
1319 static inline bool
1320 is_default_overflow_handler(struct perf_event *event)
1321 {
1322         if (likely(event->overflow_handler == perf_event_output_forward))
1323                 return true;
1324         if (unlikely(event->overflow_handler == perf_event_output_backward))
1325                 return true;
1326         return false;
1327 }
1328
1329 extern void
1330 perf_event_header__init_id(struct perf_event_header *header,
1331                            struct perf_sample_data *data,
1332                            struct perf_event *event);
1333 extern void
1334 perf_event__output_id_sample(struct perf_event *event,
1335                              struct perf_output_handle *handle,
1336                              struct perf_sample_data *sample);
1337
1338 extern void
1339 perf_log_lost_samples(struct perf_event *event, u64 lost);
1340
1341 static inline bool event_has_any_exclude_flag(struct perf_event *event)
1342 {
1343         struct perf_event_attr *attr = &event->attr;
1344
1345         return attr->exclude_idle || attr->exclude_user ||
1346                attr->exclude_kernel || attr->exclude_hv ||
1347                attr->exclude_guest || attr->exclude_host;
1348 }
1349
1350 static inline bool is_sampling_event(struct perf_event *event)
1351 {
1352         return event->attr.sample_period != 0;
1353 }
1354
1355 /*
1356  * Return 1 for a software event, 0 for a hardware event
1357  */
1358 static inline int is_software_event(struct perf_event *event)
1359 {
1360         return event->event_caps & PERF_EV_CAP_SOFTWARE;
1361 }
1362
1363 /*
1364  * Return 1 for event in sw context, 0 for event in hw context
1365  */
1366 static inline int in_software_context(struct perf_event *event)
1367 {
1368         return event->pmu_ctx->pmu->task_ctx_nr == perf_sw_context;
1369 }
1370
1371 static inline int is_exclusive_pmu(struct pmu *pmu)
1372 {
1373         return pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE;
1374 }
1375
1376 extern struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
1377
1378 extern void ___perf_sw_event(u32, u64, struct pt_regs *, u64);
1379 extern void __perf_sw_event(u32, u64, struct pt_regs *, u64);
1380
1381 #ifndef perf_arch_fetch_caller_regs
1382 static inline void perf_arch_fetch_caller_regs(struct pt_regs *regs, unsigned long ip) { }
1383 #endif
1384
1385 /*
1386  * When generating a perf sample in-line, instead of from an interrupt /
1387  * exception, we lack a pt_regs. This is typically used from software events
1388  * like: SW_CONTEXT_SWITCHES, SW_MIGRATIONS and the tie-in with tracepoints.
1389  *
1390  * We typically don't need a full set, but (for x86) do require:
1391  * - ip for PERF_SAMPLE_IP
1392  * - cs for user_mode() tests
1393  * - sp for PERF_SAMPLE_CALLCHAIN
1394  * - eflags for MISC bits and CALLCHAIN (see: perf_hw_regs())
1395  *
1396  * NOTE: assumes @regs is otherwise already 0 filled; this is important for
1397  * things like PERF_SAMPLE_REGS_INTR.
1398  */
1399 static inline void perf_fetch_caller_regs(struct pt_regs *regs)
1400 {
1401         perf_arch_fetch_caller_regs(regs, CALLER_ADDR0);
1402 }
1403
1404 static __always_inline void
1405 perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
1406 {
1407         if (static_key_false(&perf_swevent_enabled[event_id]))
1408                 __perf_sw_event(event_id, nr, regs, addr);
1409 }
1410
1411 DECLARE_PER_CPU(struct pt_regs, __perf_regs[4]);
1412
1413 /*
1414  * 'Special' version for the scheduler, it hard assumes no recursion,
1415  * which is guaranteed by us not actually scheduling inside other swevents
1416  * because those disable preemption.
1417  */
1418 static __always_inline void __perf_sw_event_sched(u32 event_id, u64 nr, u64 addr)
1419 {
1420         struct pt_regs *regs = this_cpu_ptr(&__perf_regs[0]);
1421
1422         perf_fetch_caller_regs(regs);
1423         ___perf_sw_event(event_id, nr, regs, addr);
1424 }
1425
1426 extern struct static_key_false perf_sched_events;
1427
1428 static __always_inline bool __perf_sw_enabled(int swevt)
1429 {
1430         return static_key_false(&perf_swevent_enabled[swevt]);
1431 }
1432
1433 static inline void perf_event_task_migrate(struct task_struct *task)
1434 {
1435         if (__perf_sw_enabled(PERF_COUNT_SW_CPU_MIGRATIONS))
1436                 task->sched_migrated = 1;
1437 }
1438
1439 static inline void perf_event_task_sched_in(struct task_struct *prev,
1440                                             struct task_struct *task)
1441 {
1442         if (static_branch_unlikely(&perf_sched_events))
1443                 __perf_event_task_sched_in(prev, task);
1444
1445         if (__perf_sw_enabled(PERF_COUNT_SW_CPU_MIGRATIONS) &&
1446             task->sched_migrated) {
1447                 __perf_sw_event_sched(PERF_COUNT_SW_CPU_MIGRATIONS, 1, 0);
1448                 task->sched_migrated = 0;
1449         }
1450 }
1451
1452 static inline void perf_event_task_sched_out(struct task_struct *prev,
1453                                              struct task_struct *next)
1454 {
1455         if (__perf_sw_enabled(PERF_COUNT_SW_CONTEXT_SWITCHES))
1456                 __perf_sw_event_sched(PERF_COUNT_SW_CONTEXT_SWITCHES, 1, 0);
1457
1458 #ifdef CONFIG_CGROUP_PERF
1459         if (__perf_sw_enabled(PERF_COUNT_SW_CGROUP_SWITCHES) &&
1460             perf_cgroup_from_task(prev, NULL) !=
1461             perf_cgroup_from_task(next, NULL))
1462                 __perf_sw_event_sched(PERF_COUNT_SW_CGROUP_SWITCHES, 1, 0);
1463 #endif
1464
1465         if (static_branch_unlikely(&perf_sched_events))
1466                 __perf_event_task_sched_out(prev, next);
1467 }
1468
1469 extern void perf_event_mmap(struct vm_area_struct *vma);
1470
1471 extern void perf_event_ksymbol(u16 ksym_type, u64 addr, u32 len,
1472                                bool unregister, const char *sym);
1473 extern void perf_event_bpf_event(struct bpf_prog *prog,
1474                                  enum perf_bpf_event_type type,
1475                                  u16 flags);
1476
1477 #ifdef CONFIG_GUEST_PERF_EVENTS
1478 extern struct perf_guest_info_callbacks __rcu *perf_guest_cbs;
1479
1480 DECLARE_STATIC_CALL(__perf_guest_state, *perf_guest_cbs->state);
1481 DECLARE_STATIC_CALL(__perf_guest_get_ip, *perf_guest_cbs->get_ip);
1482 DECLARE_STATIC_CALL(__perf_guest_handle_intel_pt_intr, *perf_guest_cbs->handle_intel_pt_intr);
1483
1484 static inline unsigned int perf_guest_state(void)
1485 {
1486         return static_call(__perf_guest_state)();
1487 }
1488 static inline unsigned long perf_guest_get_ip(void)
1489 {
1490         return static_call(__perf_guest_get_ip)();
1491 }
1492 static inline unsigned int perf_guest_handle_intel_pt_intr(void)
1493 {
1494         return static_call(__perf_guest_handle_intel_pt_intr)();
1495 }
1496 extern void perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs);
1497 extern void perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs);
1498 #else
1499 static inline unsigned int perf_guest_state(void)                { return 0; }
1500 static inline unsigned long perf_guest_get_ip(void)              { return 0; }
1501 static inline unsigned int perf_guest_handle_intel_pt_intr(void) { return 0; }
1502 #endif /* CONFIG_GUEST_PERF_EVENTS */
1503
1504 extern void perf_event_exec(void);
1505 extern void perf_event_comm(struct task_struct *tsk, bool exec);
1506 extern void perf_event_namespaces(struct task_struct *tsk);
1507 extern void perf_event_fork(struct task_struct *tsk);
1508 extern void perf_event_text_poke(const void *addr,
1509                                  const void *old_bytes, size_t old_len,
1510                                  const void *new_bytes, size_t new_len);
1511
1512 /* Callchains */
1513 DECLARE_PER_CPU(struct perf_callchain_entry, perf_callchain_entry);
1514
1515 extern void perf_callchain_user(struct perf_callchain_entry_ctx *entry, struct pt_regs *regs);
1516 extern void perf_callchain_kernel(struct perf_callchain_entry_ctx *entry, struct pt_regs *regs);
1517 extern struct perf_callchain_entry *
1518 get_perf_callchain(struct pt_regs *regs, u32 init_nr, bool kernel, bool user,
1519                    u32 max_stack, bool crosstask, bool add_mark);
1520 extern int get_callchain_buffers(int max_stack);
1521 extern void put_callchain_buffers(void);
1522 extern struct perf_callchain_entry *get_callchain_entry(int *rctx);
1523 extern void put_callchain_entry(int rctx);
1524
1525 extern int sysctl_perf_event_max_stack;
1526 extern int sysctl_perf_event_max_contexts_per_stack;
1527
1528 static inline int perf_callchain_store_context(struct perf_callchain_entry_ctx *ctx, u64 ip)
1529 {
1530         if (ctx->contexts < sysctl_perf_event_max_contexts_per_stack) {
1531                 struct perf_callchain_entry *entry = ctx->entry;
1532                 entry->ip[entry->nr++] = ip;
1533                 ++ctx->contexts;
1534                 return 0;
1535         } else {
1536                 ctx->contexts_maxed = true;
1537                 return -1; /* no more room, stop walking the stack */
1538         }
1539 }
1540
1541 static inline int perf_callchain_store(struct perf_callchain_entry_ctx *ctx, u64 ip)
1542 {
1543         if (ctx->nr < ctx->max_stack && !ctx->contexts_maxed) {
1544                 struct perf_callchain_entry *entry = ctx->entry;
1545                 entry->ip[entry->nr++] = ip;
1546                 ++ctx->nr;
1547                 return 0;
1548         } else {
1549                 return -1; /* no more room, stop walking the stack */
1550         }
1551 }
1552
1553 extern int sysctl_perf_event_paranoid;
1554 extern int sysctl_perf_event_mlock;
1555 extern int sysctl_perf_event_sample_rate;
1556 extern int sysctl_perf_cpu_time_max_percent;
1557
1558 extern void perf_sample_event_took(u64 sample_len_ns);
1559
1560 int perf_proc_update_handler(struct ctl_table *table, int write,
1561                 void *buffer, size_t *lenp, loff_t *ppos);
1562 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
1563                 void *buffer, size_t *lenp, loff_t *ppos);
1564 int perf_event_max_stack_handler(struct ctl_table *table, int write,
1565                 void *buffer, size_t *lenp, loff_t *ppos);
1566
1567 /* Access to perf_event_open(2) syscall. */
1568 #define PERF_SECURITY_OPEN              0
1569
1570 /* Finer grained perf_event_open(2) access control. */
1571 #define PERF_SECURITY_CPU               1
1572 #define PERF_SECURITY_KERNEL            2
1573 #define PERF_SECURITY_TRACEPOINT        3
1574
1575 static inline int perf_is_paranoid(void)
1576 {
1577         return sysctl_perf_event_paranoid > -1;
1578 }
1579
1580 static inline int perf_allow_kernel(struct perf_event_attr *attr)
1581 {
1582         if (sysctl_perf_event_paranoid > 1 && !perfmon_capable())
1583                 return -EACCES;
1584
1585         return security_perf_event_open(attr, PERF_SECURITY_KERNEL);
1586 }
1587
1588 static inline int perf_allow_cpu(struct perf_event_attr *attr)
1589 {
1590         if (sysctl_perf_event_paranoid > 0 && !perfmon_capable())
1591                 return -EACCES;
1592
1593         return security_perf_event_open(attr, PERF_SECURITY_CPU);
1594 }
1595
1596 static inline int perf_allow_tracepoint(struct perf_event_attr *attr)
1597 {
1598         if (sysctl_perf_event_paranoid > -1 && !perfmon_capable())
1599                 return -EPERM;
1600
1601         return security_perf_event_open(attr, PERF_SECURITY_TRACEPOINT);
1602 }
1603
1604 extern void perf_event_init(void);
1605 extern void perf_tp_event(u16 event_type, u64 count, void *record,
1606                           int entry_size, struct pt_regs *regs,
1607                           struct hlist_head *head, int rctx,
1608                           struct task_struct *task);
1609 extern void perf_bp_event(struct perf_event *event, void *data);
1610
1611 #ifndef perf_misc_flags
1612 # define perf_misc_flags(regs) \
1613                 (user_mode(regs) ? PERF_RECORD_MISC_USER : PERF_RECORD_MISC_KERNEL)
1614 # define perf_instruction_pointer(regs) instruction_pointer(regs)
1615 #endif
1616 #ifndef perf_arch_bpf_user_pt_regs
1617 # define perf_arch_bpf_user_pt_regs(regs) regs
1618 #endif
1619
1620 static inline bool has_branch_stack(struct perf_event *event)
1621 {
1622         return event->attr.sample_type & PERF_SAMPLE_BRANCH_STACK;
1623 }
1624
1625 static inline bool needs_branch_stack(struct perf_event *event)
1626 {
1627         return event->attr.branch_sample_type != 0;
1628 }
1629
1630 static inline bool has_aux(struct perf_event *event)
1631 {
1632         return event->pmu->setup_aux;
1633 }
1634
1635 static inline bool is_write_backward(struct perf_event *event)
1636 {
1637         return !!event->attr.write_backward;
1638 }
1639
1640 static inline bool has_addr_filter(struct perf_event *event)
1641 {
1642         return event->pmu->nr_addr_filters;
1643 }
1644
1645 /*
1646  * An inherited event uses parent's filters
1647  */
1648 static inline struct perf_addr_filters_head *
1649 perf_event_addr_filters(struct perf_event *event)
1650 {
1651         struct perf_addr_filters_head *ifh = &event->addr_filters;
1652
1653         if (event->parent)
1654                 ifh = &event->parent->addr_filters;
1655
1656         return ifh;
1657 }
1658
1659 extern void perf_event_addr_filters_sync(struct perf_event *event);
1660 extern void perf_report_aux_output_id(struct perf_event *event, u64 hw_id);
1661
1662 extern int perf_output_begin(struct perf_output_handle *handle,
1663                              struct perf_sample_data *data,
1664                              struct perf_event *event, unsigned int size);
1665 extern int perf_output_begin_forward(struct perf_output_handle *handle,
1666                                      struct perf_sample_data *data,
1667                                      struct perf_event *event,
1668                                      unsigned int size);
1669 extern int perf_output_begin_backward(struct perf_output_handle *handle,
1670                                       struct perf_sample_data *data,
1671                                       struct perf_event *event,
1672                                       unsigned int size);
1673
1674 extern void perf_output_end(struct perf_output_handle *handle);
1675 extern unsigned int perf_output_copy(struct perf_output_handle *handle,
1676                              const void *buf, unsigned int len);
1677 extern unsigned int perf_output_skip(struct perf_output_handle *handle,
1678                                      unsigned int len);
1679 extern long perf_output_copy_aux(struct perf_output_handle *aux_handle,
1680                                  struct perf_output_handle *handle,
1681                                  unsigned long from, unsigned long to);
1682 extern int perf_swevent_get_recursion_context(void);
1683 extern void perf_swevent_put_recursion_context(int rctx);
1684 extern u64 perf_swevent_set_period(struct perf_event *event);
1685 extern void perf_event_enable(struct perf_event *event);
1686 extern void perf_event_disable(struct perf_event *event);
1687 extern void perf_event_disable_local(struct perf_event *event);
1688 extern void perf_event_disable_inatomic(struct perf_event *event);
1689 extern void perf_event_task_tick(void);
1690 extern int perf_event_account_interrupt(struct perf_event *event);
1691 extern int perf_event_period(struct perf_event *event, u64 value);
1692 extern u64 perf_event_pause(struct perf_event *event, bool reset);
1693 #else /* !CONFIG_PERF_EVENTS: */
1694 static inline void *
1695 perf_aux_output_begin(struct perf_output_handle *handle,
1696                       struct perf_event *event)                         { return NULL; }
1697 static inline void
1698 perf_aux_output_end(struct perf_output_handle *handle, unsigned long size)
1699                                                                         { }
1700 static inline int
1701 perf_aux_output_skip(struct perf_output_handle *handle,
1702                      unsigned long size)                                { return -EINVAL; }
1703 static inline void *
1704 perf_get_aux(struct perf_output_handle *handle)                         { return NULL; }
1705 static inline void
1706 perf_event_task_migrate(struct task_struct *task)                       { }
1707 static inline void
1708 perf_event_task_sched_in(struct task_struct *prev,
1709                          struct task_struct *task)                      { }
1710 static inline void
1711 perf_event_task_sched_out(struct task_struct *prev,
1712                           struct task_struct *next)                     { }
1713 static inline int perf_event_init_task(struct task_struct *child,
1714                                        u64 clone_flags)                 { return 0; }
1715 static inline void perf_event_exit_task(struct task_struct *child)      { }
1716 static inline void perf_event_free_task(struct task_struct *task)       { }
1717 static inline void perf_event_delayed_put(struct task_struct *task)     { }
1718 static inline struct file *perf_event_get(unsigned int fd)      { return ERR_PTR(-EINVAL); }
1719 static inline const struct perf_event *perf_get_event(struct file *file)
1720 {
1721         return ERR_PTR(-EINVAL);
1722 }
1723 static inline const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
1724 {
1725         return ERR_PTR(-EINVAL);
1726 }
1727 static inline int perf_event_read_local(struct perf_event *event, u64 *value,
1728                                         u64 *enabled, u64 *running)
1729 {
1730         return -EINVAL;
1731 }
1732 static inline void perf_event_print_debug(void)                         { }
1733 static inline int perf_event_task_disable(void)                         { return -EINVAL; }
1734 static inline int perf_event_task_enable(void)                          { return -EINVAL; }
1735 static inline int perf_event_refresh(struct perf_event *event, int refresh)
1736 {
1737         return -EINVAL;
1738 }
1739
1740 static inline void
1741 perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)     { }
1742 static inline void
1743 perf_bp_event(struct perf_event *event, void *data)                     { }
1744
1745 static inline void perf_event_mmap(struct vm_area_struct *vma)          { }
1746
1747 typedef int (perf_ksymbol_get_name_f)(char *name, int name_len, void *data);
1748 static inline void perf_event_ksymbol(u16 ksym_type, u64 addr, u32 len,
1749                                       bool unregister, const char *sym) { }
1750 static inline void perf_event_bpf_event(struct bpf_prog *prog,
1751                                         enum perf_bpf_event_type type,
1752                                         u16 flags)                      { }
1753 static inline void perf_event_exec(void)                                { }
1754 static inline void perf_event_comm(struct task_struct *tsk, bool exec)  { }
1755 static inline void perf_event_namespaces(struct task_struct *tsk)       { }
1756 static inline void perf_event_fork(struct task_struct *tsk)             { }
1757 static inline void perf_event_text_poke(const void *addr,
1758                                         const void *old_bytes,
1759                                         size_t old_len,
1760                                         const void *new_bytes,
1761                                         size_t new_len)                 { }
1762 static inline void perf_event_init(void)                                { }
1763 static inline int  perf_swevent_get_recursion_context(void)             { return -1; }
1764 static inline void perf_swevent_put_recursion_context(int rctx)         { }
1765 static inline u64 perf_swevent_set_period(struct perf_event *event)     { return 0; }
1766 static inline void perf_event_enable(struct perf_event *event)          { }
1767 static inline void perf_event_disable(struct perf_event *event)         { }
1768 static inline int __perf_event_disable(void *info)                      { return -1; }
1769 static inline void perf_event_task_tick(void)                           { }
1770 static inline int perf_event_release_kernel(struct perf_event *event)   { return 0; }
1771 static inline int perf_event_period(struct perf_event *event, u64 value)
1772 {
1773         return -EINVAL;
1774 }
1775 static inline u64 perf_event_pause(struct perf_event *event, bool reset)
1776 {
1777         return 0;
1778 }
1779 #endif
1780
1781 #if defined(CONFIG_PERF_EVENTS) && defined(CONFIG_CPU_SUP_INTEL)
1782 extern void perf_restore_debug_store(void);
1783 #else
1784 static inline void perf_restore_debug_store(void)                       { }
1785 #endif
1786
1787 #define perf_output_put(handle, x) perf_output_copy((handle), &(x), sizeof(x))
1788
1789 struct perf_pmu_events_attr {
1790         struct device_attribute attr;
1791         u64 id;
1792         const char *event_str;
1793 };
1794
1795 struct perf_pmu_events_ht_attr {
1796         struct device_attribute                 attr;
1797         u64                                     id;
1798         const char                              *event_str_ht;
1799         const char                              *event_str_noht;
1800 };
1801
1802 struct perf_pmu_events_hybrid_attr {
1803         struct device_attribute                 attr;
1804         u64                                     id;
1805         const char                              *event_str;
1806         u64                                     pmu_type;
1807 };
1808
1809 struct perf_pmu_format_hybrid_attr {
1810         struct device_attribute                 attr;
1811         u64                                     pmu_type;
1812 };
1813
1814 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
1815                               char *page);
1816
1817 #define PMU_EVENT_ATTR(_name, _var, _id, _show)                         \
1818 static struct perf_pmu_events_attr _var = {                             \
1819         .attr = __ATTR(_name, 0444, _show, NULL),                       \
1820         .id   =  _id,                                                   \
1821 };
1822
1823 #define PMU_EVENT_ATTR_STRING(_name, _var, _str)                            \
1824 static struct perf_pmu_events_attr _var = {                                 \
1825         .attr           = __ATTR(_name, 0444, perf_event_sysfs_show, NULL), \
1826         .id             = 0,                                                \
1827         .event_str      = _str,                                             \
1828 };
1829
1830 #define PMU_EVENT_ATTR_ID(_name, _show, _id)                            \
1831         (&((struct perf_pmu_events_attr[]) {                            \
1832                 { .attr = __ATTR(_name, 0444, _show, NULL),             \
1833                   .id = _id, }                                          \
1834         })[0].attr.attr)
1835
1836 #define PMU_FORMAT_ATTR_SHOW(_name, _format)                            \
1837 static ssize_t                                                          \
1838 _name##_show(struct device *dev,                                        \
1839                                struct device_attribute *attr,           \
1840                                char *page)                              \
1841 {                                                                       \
1842         BUILD_BUG_ON(sizeof(_format) >= PAGE_SIZE);                     \
1843         return sprintf(page, _format "\n");                             \
1844 }                                                                       \
1845
1846 #define PMU_FORMAT_ATTR(_name, _format)                                 \
1847         PMU_FORMAT_ATTR_SHOW(_name, _format)                            \
1848                                                                         \
1849 static struct device_attribute format_attr_##_name = __ATTR_RO(_name)
1850
1851 /* Performance counter hotplug functions */
1852 #ifdef CONFIG_PERF_EVENTS
1853 int perf_event_init_cpu(unsigned int cpu);
1854 int perf_event_exit_cpu(unsigned int cpu);
1855 #else
1856 #define perf_event_init_cpu     NULL
1857 #define perf_event_exit_cpu     NULL
1858 #endif
1859
1860 extern void arch_perf_update_userpage(struct perf_event *event,
1861                                       struct perf_event_mmap_page *userpg,
1862                                       u64 now);
1863
1864 #ifdef CONFIG_MMU
1865 extern __weak u64 arch_perf_get_page_size(struct mm_struct *mm, unsigned long addr);
1866 #endif
1867
1868 /*
1869  * Snapshot branch stack on software events.
1870  *
1871  * Branch stack can be very useful in understanding software events. For
1872  * example, when a long function, e.g. sys_perf_event_open, returns an
1873  * errno, it is not obvious why the function failed. Branch stack could
1874  * provide very helpful information in this type of scenarios.
1875  *
1876  * On software event, it is necessary to stop the hardware branch recorder
1877  * fast. Otherwise, the hardware register/buffer will be flushed with
1878  * entries of the triggering event. Therefore, static call is used to
1879  * stop the hardware recorder.
1880  */
1881
1882 /*
1883  * cnt is the number of entries allocated for entries.
1884  * Return number of entries copied to .
1885  */
1886 typedef int (perf_snapshot_branch_stack_t)(struct perf_branch_entry *entries,
1887                                            unsigned int cnt);
1888 DECLARE_STATIC_CALL(perf_snapshot_branch_stack, perf_snapshot_branch_stack_t);
1889
1890 #ifndef PERF_NEEDS_LOPWR_CB
1891 static inline void perf_lopwr_cb(bool mode)
1892 {
1893 }
1894 #endif
1895
1896 #endif /* _LINUX_PERF_EVENT_H */