GNU Linux-libre 4.19.245-gnu1
[releases.git] / arch / s390 / kernel / perf_cpum_sf.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Performance event support for the System z CPU-measurement Sampling Facility
4  *
5  * Copyright IBM Corp. 2013, 2018
6  * Author(s): Hendrik Brueckner <brueckner@linux.vnet.ibm.com>
7  */
8 #define KMSG_COMPONENT  "cpum_sf"
9 #define pr_fmt(fmt)     KMSG_COMPONENT ": " fmt
10
11 #include <linux/kernel.h>
12 #include <linux/kernel_stat.h>
13 #include <linux/perf_event.h>
14 #include <linux/percpu.h>
15 #include <linux/pid.h>
16 #include <linux/notifier.h>
17 #include <linux/export.h>
18 #include <linux/slab.h>
19 #include <linux/mm.h>
20 #include <linux/moduleparam.h>
21 #include <asm/cpu_mf.h>
22 #include <asm/irq.h>
23 #include <asm/debug.h>
24 #include <asm/timex.h>
25
26 /* Minimum number of sample-data-block-tables:
27  * At least one table is required for the sampling buffer structure.
28  * A single table contains up to 511 pointers to sample-data-blocks.
29  */
30 #define CPUM_SF_MIN_SDBT        1
31
32 /* Number of sample-data-blocks per sample-data-block-table (SDBT):
33  * A table contains SDB pointers (8 bytes) and one table-link entry
34  * that points to the origin of the next SDBT.
35  */
36 #define CPUM_SF_SDB_PER_TABLE   ((PAGE_SIZE - 8) / 8)
37
38 /* Maximum page offset for an SDBT table-link entry:
39  * If this page offset is reached, a table-link entry to the next SDBT
40  * must be added.
41  */
42 #define CPUM_SF_SDBT_TL_OFFSET  (CPUM_SF_SDB_PER_TABLE * 8)
43 static inline int require_table_link(const void *sdbt)
44 {
45         return ((unsigned long) sdbt & ~PAGE_MASK) == CPUM_SF_SDBT_TL_OFFSET;
46 }
47
48 /* Minimum and maximum sampling buffer sizes:
49  *
50  * This number represents the maximum size of the sampling buffer taking
51  * the number of sample-data-block-tables into account.  Note that these
52  * numbers apply to the basic-sampling function only.
53  * The maximum number of SDBs is increased by CPUM_SF_SDB_DIAG_FACTOR if
54  * the diagnostic-sampling function is active.
55  *
56  * Sampling buffer size         Buffer characteristics
57  * ---------------------------------------------------
58  *       64KB               ==    16 pages (4KB per page)
59  *                                 1 page  for SDB-tables
60  *                                15 pages for SDBs
61  *
62  *  32MB                    ==  8192 pages (4KB per page)
63  *                                16 pages for SDB-tables
64  *                              8176 pages for SDBs
65  */
66 static unsigned long __read_mostly CPUM_SF_MIN_SDB = 15;
67 static unsigned long __read_mostly CPUM_SF_MAX_SDB = 8176;
68 static unsigned long __read_mostly CPUM_SF_SDB_DIAG_FACTOR = 1;
69
70 struct sf_buffer {
71         unsigned long    *sdbt;     /* Sample-data-block-table origin */
72         /* buffer characteristics (required for buffer increments) */
73         unsigned long  num_sdb;     /* Number of sample-data-blocks */
74         unsigned long num_sdbt;     /* Number of sample-data-block-tables */
75         unsigned long    *tail;     /* last sample-data-block-table */
76 };
77
78 struct aux_buffer {
79         struct sf_buffer sfb;
80         unsigned long head;        /* index of SDB of buffer head */
81         unsigned long alert_mark;  /* index of SDB of alert request position */
82         unsigned long empty_mark;  /* mark of SDB not marked full */
83         unsigned long *sdb_index;  /* SDB address for fast lookup */
84         unsigned long *sdbt_index; /* SDBT address for fast lookup */
85 };
86
87 struct cpu_hw_sf {
88         /* CPU-measurement sampling information block */
89         struct hws_qsi_info_block qsi;
90         /* CPU-measurement sampling control block */
91         struct hws_lsctl_request_block lsctl;
92         struct sf_buffer sfb;       /* Sampling buffer */
93         unsigned int flags;         /* Status flags */
94         struct perf_event *event;   /* Scheduled perf event */
95         struct perf_output_handle handle; /* AUX buffer output handle */
96 };
97 static DEFINE_PER_CPU(struct cpu_hw_sf, cpu_hw_sf);
98
99 /* Debug feature */
100 static debug_info_t *sfdbg;
101
102 /*
103  * sf_disable() - Switch off sampling facility
104  */
105 static int sf_disable(void)
106 {
107         struct hws_lsctl_request_block sreq;
108
109         memset(&sreq, 0, sizeof(sreq));
110         return lsctl(&sreq);
111 }
112
113 /*
114  * sf_buffer_available() - Check for an allocated sampling buffer
115  */
116 static int sf_buffer_available(struct cpu_hw_sf *cpuhw)
117 {
118         return !!cpuhw->sfb.sdbt;
119 }
120
121 /*
122  * deallocate sampling facility buffer
123  */
124 static void free_sampling_buffer(struct sf_buffer *sfb)
125 {
126         unsigned long *sdbt, *curr;
127
128         if (!sfb->sdbt)
129                 return;
130
131         sdbt = sfb->sdbt;
132         curr = sdbt;
133
134         /* Free the SDBT after all SDBs are processed... */
135         while (1) {
136                 if (!*curr || !sdbt)
137                         break;
138
139                 /* Process table-link entries */
140                 if (is_link_entry(curr)) {
141                         curr = get_next_sdbt(curr);
142                         if (sdbt)
143                                 free_page((unsigned long) sdbt);
144
145                         /* If the origin is reached, sampling buffer is freed */
146                         if (curr == sfb->sdbt)
147                                 break;
148                         else
149                                 sdbt = curr;
150                 } else {
151                         /* Process SDB pointer */
152                         if (*curr) {
153                                 free_page(*curr);
154                                 curr++;
155                         }
156                 }
157         }
158
159         debug_sprintf_event(sfdbg, 5,
160                             "free_sampling_buffer: freed sdbt=%p\n", sfb->sdbt);
161         memset(sfb, 0, sizeof(*sfb));
162 }
163
164 static int alloc_sample_data_block(unsigned long *sdbt, gfp_t gfp_flags)
165 {
166         unsigned long sdb, *trailer;
167
168         /* Allocate and initialize sample-data-block */
169         sdb = get_zeroed_page(gfp_flags);
170         if (!sdb)
171                 return -ENOMEM;
172         trailer = trailer_entry_ptr(sdb);
173         *trailer = SDB_TE_ALERT_REQ_MASK;
174
175         /* Link SDB into the sample-data-block-table */
176         *sdbt = sdb;
177
178         return 0;
179 }
180
181 /*
182  * realloc_sampling_buffer() - extend sampler memory
183  *
184  * Allocates new sample-data-blocks and adds them to the specified sampling
185  * buffer memory.
186  *
187  * Important: This modifies the sampling buffer and must be called when the
188  *            sampling facility is disabled.
189  *
190  * Returns zero on success, non-zero otherwise.
191  */
192 static int realloc_sampling_buffer(struct sf_buffer *sfb,
193                                    unsigned long num_sdb, gfp_t gfp_flags)
194 {
195         int i, rc;
196         unsigned long *new, *tail, *tail_prev = NULL;
197
198         if (!sfb->sdbt || !sfb->tail)
199                 return -EINVAL;
200
201         if (!is_link_entry(sfb->tail))
202                 return -EINVAL;
203
204         /* Append to the existing sampling buffer, overwriting the table-link
205          * register.
206          * The tail variables always points to the "tail" (last and table-link)
207          * entry in an SDB-table.
208          */
209         tail = sfb->tail;
210
211         /* Do a sanity check whether the table-link entry points to
212          * the sampling buffer origin.
213          */
214         if (sfb->sdbt != get_next_sdbt(tail)) {
215                 debug_sprintf_event(sfdbg, 3, "realloc_sampling_buffer: "
216                                     "sampling buffer is not linked: origin=%p"
217                                     "tail=%p\n",
218                                     (void *) sfb->sdbt, (void *) tail);
219                 return -EINVAL;
220         }
221
222         /* Allocate remaining SDBs */
223         rc = 0;
224         for (i = 0; i < num_sdb; i++) {
225                 /* Allocate a new SDB-table if it is full. */
226                 if (require_table_link(tail)) {
227                         new = (unsigned long *) get_zeroed_page(gfp_flags);
228                         if (!new) {
229                                 rc = -ENOMEM;
230                                 break;
231                         }
232                         sfb->num_sdbt++;
233                         /* Link current page to tail of chain */
234                         *tail = (unsigned long)(void *) new + 1;
235                         tail_prev = tail;
236                         tail = new;
237                 }
238
239                 /* Allocate a new sample-data-block.
240                  * If there is not enough memory, stop the realloc process
241                  * and simply use what was allocated.  If this is a temporary
242                  * issue, a new realloc call (if required) might succeed.
243                  */
244                 rc = alloc_sample_data_block(tail, gfp_flags);
245                 if (rc) {
246                         /* Undo last SDBT. An SDBT with no SDB at its first
247                          * entry but with an SDBT entry instead can not be
248                          * handled by the interrupt handler code.
249                          * Avoid this situation.
250                          */
251                         if (tail_prev) {
252                                 sfb->num_sdbt--;
253                                 free_page((unsigned long) new);
254                                 tail = tail_prev;
255                         }
256                         break;
257                 }
258                 sfb->num_sdb++;
259                 tail++;
260                 tail_prev = new = NULL; /* Allocated at least one SBD */
261         }
262
263         /* Link sampling buffer to its origin */
264         *tail = (unsigned long) sfb->sdbt + 1;
265         sfb->tail = tail;
266
267         debug_sprintf_event(sfdbg, 4, "realloc_sampling_buffer: new buffer"
268                             " settings: sdbt=%lu sdb=%lu\n",
269                             sfb->num_sdbt, sfb->num_sdb);
270         return rc;
271 }
272
273 /*
274  * allocate_sampling_buffer() - allocate sampler memory
275  *
276  * Allocates and initializes a sampling buffer structure using the
277  * specified number of sample-data-blocks (SDB).  For each allocation,
278  * a 4K page is used.  The number of sample-data-block-tables (SDBT)
279  * are calculated from SDBs.
280  * Also set the ALERT_REQ mask in each SDBs trailer.
281  *
282  * Returns zero on success, non-zero otherwise.
283  */
284 static int alloc_sampling_buffer(struct sf_buffer *sfb, unsigned long num_sdb)
285 {
286         int rc;
287
288         if (sfb->sdbt)
289                 return -EINVAL;
290
291         /* Allocate the sample-data-block-table origin */
292         sfb->sdbt = (unsigned long *) get_zeroed_page(GFP_KERNEL);
293         if (!sfb->sdbt)
294                 return -ENOMEM;
295         sfb->num_sdb = 0;
296         sfb->num_sdbt = 1;
297
298         /* Link the table origin to point to itself to prepare for
299          * realloc_sampling_buffer() invocation.
300          */
301         sfb->tail = sfb->sdbt;
302         *sfb->tail = (unsigned long)(void *) sfb->sdbt + 1;
303
304         /* Allocate requested number of sample-data-blocks */
305         rc = realloc_sampling_buffer(sfb, num_sdb, GFP_KERNEL);
306         if (rc) {
307                 free_sampling_buffer(sfb);
308                 debug_sprintf_event(sfdbg, 4, "alloc_sampling_buffer: "
309                         "realloc_sampling_buffer failed with rc=%i\n", rc);
310         } else
311                 debug_sprintf_event(sfdbg, 4,
312                         "alloc_sampling_buffer: tear=%p dear=%p\n",
313                         sfb->sdbt, (void *) *sfb->sdbt);
314         return rc;
315 }
316
317 static void sfb_set_limits(unsigned long min, unsigned long max)
318 {
319         struct hws_qsi_info_block si;
320
321         CPUM_SF_MIN_SDB = min;
322         CPUM_SF_MAX_SDB = max;
323
324         memset(&si, 0, sizeof(si));
325         if (!qsi(&si))
326                 CPUM_SF_SDB_DIAG_FACTOR = DIV_ROUND_UP(si.dsdes, si.bsdes);
327 }
328
329 static unsigned long sfb_max_limit(struct hw_perf_event *hwc)
330 {
331         return SAMPL_DIAG_MODE(hwc) ? CPUM_SF_MAX_SDB * CPUM_SF_SDB_DIAG_FACTOR
332                                     : CPUM_SF_MAX_SDB;
333 }
334
335 static unsigned long sfb_pending_allocs(struct sf_buffer *sfb,
336                                         struct hw_perf_event *hwc)
337 {
338         if (!sfb->sdbt)
339                 return SFB_ALLOC_REG(hwc);
340         if (SFB_ALLOC_REG(hwc) > sfb->num_sdb)
341                 return SFB_ALLOC_REG(hwc) - sfb->num_sdb;
342         return 0;
343 }
344
345 static int sfb_has_pending_allocs(struct sf_buffer *sfb,
346                                    struct hw_perf_event *hwc)
347 {
348         return sfb_pending_allocs(sfb, hwc) > 0;
349 }
350
351 static void sfb_account_allocs(unsigned long num, struct hw_perf_event *hwc)
352 {
353         /* Limit the number of SDBs to not exceed the maximum */
354         num = min_t(unsigned long, num, sfb_max_limit(hwc) - SFB_ALLOC_REG(hwc));
355         if (num)
356                 SFB_ALLOC_REG(hwc) += num;
357 }
358
359 static void sfb_init_allocs(unsigned long num, struct hw_perf_event *hwc)
360 {
361         SFB_ALLOC_REG(hwc) = 0;
362         sfb_account_allocs(num, hwc);
363 }
364
365 static void deallocate_buffers(struct cpu_hw_sf *cpuhw)
366 {
367         if (cpuhw->sfb.sdbt)
368                 free_sampling_buffer(&cpuhw->sfb);
369 }
370
371 static int allocate_buffers(struct cpu_hw_sf *cpuhw, struct hw_perf_event *hwc)
372 {
373         unsigned long n_sdb, freq, factor;
374         size_t sample_size;
375
376         /* Calculate sampling buffers using 4K pages
377          *
378          *    1. Determine the sample data size which depends on the used
379          *       sampling functions, for example, basic-sampling or
380          *       basic-sampling with diagnostic-sampling.
381          *
382          *    2. Use the sampling frequency as input.  The sampling buffer is
383          *       designed for almost one second.  This can be adjusted through
384          *       the "factor" variable.
385          *       In any case, alloc_sampling_buffer() sets the Alert Request
386          *       Control indicator to trigger a measurement-alert to harvest
387          *       sample-data-blocks (sdb).
388          *
389          *    3. Compute the number of sample-data-blocks and ensure a minimum
390          *       of CPUM_SF_MIN_SDB.  Also ensure the upper limit does not
391          *       exceed a "calculated" maximum.  The symbolic maximum is
392          *       designed for basic-sampling only and needs to be increased if
393          *       diagnostic-sampling is active.
394          *       See also the remarks for these symbolic constants.
395          *
396          *    4. Compute the number of sample-data-block-tables (SDBT) and
397          *       ensure a minimum of CPUM_SF_MIN_SDBT (one table can manage up
398          *       to 511 SDBs).
399          */
400         sample_size = sizeof(struct hws_basic_entry);
401         freq = sample_rate_to_freq(&cpuhw->qsi, SAMPL_RATE(hwc));
402         factor = 1;
403         n_sdb = DIV_ROUND_UP(freq, factor * ((PAGE_SIZE-64) / sample_size));
404         if (n_sdb < CPUM_SF_MIN_SDB)
405                 n_sdb = CPUM_SF_MIN_SDB;
406
407         /* If there is already a sampling buffer allocated, it is very likely
408          * that the sampling facility is enabled too.  If the event to be
409          * initialized requires a greater sampling buffer, the allocation must
410          * be postponed.  Changing the sampling buffer requires the sampling
411          * facility to be in the disabled state.  So, account the number of
412          * required SDBs and let cpumsf_pmu_enable() resize the buffer just
413          * before the event is started.
414          */
415         sfb_init_allocs(n_sdb, hwc);
416         if (sf_buffer_available(cpuhw))
417                 return 0;
418
419         debug_sprintf_event(sfdbg, 3,
420                             "allocate_buffers: rate=%lu f=%lu sdb=%lu/%lu"
421                             " sample_size=%lu cpuhw=%p\n",
422                             SAMPL_RATE(hwc), freq, n_sdb, sfb_max_limit(hwc),
423                             sample_size, cpuhw);
424
425         return alloc_sampling_buffer(&cpuhw->sfb,
426                                      sfb_pending_allocs(&cpuhw->sfb, hwc));
427 }
428
429 static unsigned long min_percent(unsigned int percent, unsigned long base,
430                                  unsigned long min)
431 {
432         return min_t(unsigned long, min, DIV_ROUND_UP(percent * base, 100));
433 }
434
435 static unsigned long compute_sfb_extent(unsigned long ratio, unsigned long base)
436 {
437         /* Use a percentage-based approach to extend the sampling facility
438          * buffer.  Accept up to 5% sample data loss.
439          * Vary the extents between 1% to 5% of the current number of
440          * sample-data-blocks.
441          */
442         if (ratio <= 5)
443                 return 0;
444         if (ratio <= 25)
445                 return min_percent(1, base, 1);
446         if (ratio <= 50)
447                 return min_percent(1, base, 1);
448         if (ratio <= 75)
449                 return min_percent(2, base, 2);
450         if (ratio <= 100)
451                 return min_percent(3, base, 3);
452         if (ratio <= 250)
453                 return min_percent(4, base, 4);
454
455         return min_percent(5, base, 8);
456 }
457
458 static void sfb_account_overflows(struct cpu_hw_sf *cpuhw,
459                                   struct hw_perf_event *hwc)
460 {
461         unsigned long ratio, num;
462
463         if (!OVERFLOW_REG(hwc))
464                 return;
465
466         /* The sample_overflow contains the average number of sample data
467          * that has been lost because sample-data-blocks were full.
468          *
469          * Calculate the total number of sample data entries that has been
470          * discarded.  Then calculate the ratio of lost samples to total samples
471          * per second in percent.
472          */
473         ratio = DIV_ROUND_UP(100 * OVERFLOW_REG(hwc) * cpuhw->sfb.num_sdb,
474                              sample_rate_to_freq(&cpuhw->qsi, SAMPL_RATE(hwc)));
475
476         /* Compute number of sample-data-blocks */
477         num = compute_sfb_extent(ratio, cpuhw->sfb.num_sdb);
478         if (num)
479                 sfb_account_allocs(num, hwc);
480
481         debug_sprintf_event(sfdbg, 5, "sfb: overflow: overflow=%llu ratio=%lu"
482                             " num=%lu\n", OVERFLOW_REG(hwc), ratio, num);
483         OVERFLOW_REG(hwc) = 0;
484 }
485
486 /* extend_sampling_buffer() - Extend sampling buffer
487  * @sfb:        Sampling buffer structure (for local CPU)
488  * @hwc:        Perf event hardware structure
489  *
490  * Use this function to extend the sampling buffer based on the overflow counter
491  * and postponed allocation extents stored in the specified Perf event hardware.
492  *
493  * Important: This function disables the sampling facility in order to safely
494  *            change the sampling buffer structure.  Do not call this function
495  *            when the PMU is active.
496  */
497 static void extend_sampling_buffer(struct sf_buffer *sfb,
498                                    struct hw_perf_event *hwc)
499 {
500         unsigned long num, num_old;
501         int rc;
502
503         num = sfb_pending_allocs(sfb, hwc);
504         if (!num)
505                 return;
506         num_old = sfb->num_sdb;
507
508         /* Disable the sampling facility to reset any states and also
509          * clear pending measurement alerts.
510          */
511         sf_disable();
512
513         /* Extend the sampling buffer.
514          * This memory allocation typically happens in an atomic context when
515          * called by perf.  Because this is a reallocation, it is fine if the
516          * new SDB-request cannot be satisfied immediately.
517          */
518         rc = realloc_sampling_buffer(sfb, num, GFP_ATOMIC);
519         if (rc)
520                 debug_sprintf_event(sfdbg, 5, "sfb: extend: realloc "
521                                     "failed with rc=%i\n", rc);
522
523         if (sfb_has_pending_allocs(sfb, hwc))
524                 debug_sprintf_event(sfdbg, 5, "sfb: extend: "
525                                     "req=%lu alloc=%lu remaining=%lu\n",
526                                     num, sfb->num_sdb - num_old,
527                                     sfb_pending_allocs(sfb, hwc));
528 }
529
530
531 /* Number of perf events counting hardware events */
532 static atomic_t num_events;
533 /* Used to avoid races in calling reserve/release_cpumf_hardware */
534 static DEFINE_MUTEX(pmc_reserve_mutex);
535
536 #define PMC_INIT      0
537 #define PMC_RELEASE   1
538 #define PMC_FAILURE   2
539 static void setup_pmc_cpu(void *flags)
540 {
541         int err;
542         struct cpu_hw_sf *cpusf = this_cpu_ptr(&cpu_hw_sf);
543
544         err = 0;
545         switch (*((int *) flags)) {
546         case PMC_INIT:
547                 memset(cpusf, 0, sizeof(*cpusf));
548                 err = qsi(&cpusf->qsi);
549                 if (err)
550                         break;
551                 cpusf->flags |= PMU_F_RESERVED;
552                 err = sf_disable();
553                 if (err)
554                         pr_err("Switching off the sampling facility failed "
555                                "with rc=%i\n", err);
556                 debug_sprintf_event(sfdbg, 5,
557                                     "setup_pmc_cpu: initialized: cpuhw=%p\n", cpusf);
558                 break;
559         case PMC_RELEASE:
560                 cpusf->flags &= ~PMU_F_RESERVED;
561                 err = sf_disable();
562                 if (err) {
563                         pr_err("Switching off the sampling facility failed "
564                                "with rc=%i\n", err);
565                 } else
566                         deallocate_buffers(cpusf);
567                 debug_sprintf_event(sfdbg, 5,
568                                     "setup_pmc_cpu: released: cpuhw=%p\n", cpusf);
569                 break;
570         }
571         if (err)
572                 *((int *) flags) |= PMC_FAILURE;
573 }
574
575 static void release_pmc_hardware(void)
576 {
577         int flags = PMC_RELEASE;
578
579         irq_subclass_unregister(IRQ_SUBCLASS_MEASUREMENT_ALERT);
580         on_each_cpu(setup_pmc_cpu, &flags, 1);
581 }
582
583 static int reserve_pmc_hardware(void)
584 {
585         int flags = PMC_INIT;
586
587         on_each_cpu(setup_pmc_cpu, &flags, 1);
588         if (flags & PMC_FAILURE) {
589                 release_pmc_hardware();
590                 return -ENODEV;
591         }
592         irq_subclass_register(IRQ_SUBCLASS_MEASUREMENT_ALERT);
593
594         return 0;
595 }
596
597 static void hw_perf_event_destroy(struct perf_event *event)
598 {
599         /* Release PMC if this is the last perf event */
600         if (!atomic_add_unless(&num_events, -1, 1)) {
601                 mutex_lock(&pmc_reserve_mutex);
602                 if (atomic_dec_return(&num_events) == 0)
603                         release_pmc_hardware();
604                 mutex_unlock(&pmc_reserve_mutex);
605         }
606 }
607
608 static void hw_init_period(struct hw_perf_event *hwc, u64 period)
609 {
610         hwc->sample_period = period;
611         hwc->last_period = hwc->sample_period;
612         local64_set(&hwc->period_left, hwc->sample_period);
613 }
614
615 static void hw_reset_registers(struct hw_perf_event *hwc,
616                                unsigned long *sdbt_origin)
617 {
618         /* (Re)set to first sample-data-block-table */
619         TEAR_REG(hwc) = (unsigned long) sdbt_origin;
620 }
621
622 static unsigned long hw_limit_rate(const struct hws_qsi_info_block *si,
623                                    unsigned long rate)
624 {
625         return clamp_t(unsigned long, rate,
626                        si->min_sampl_rate, si->max_sampl_rate);
627 }
628
629 static u32 cpumsf_pid_type(struct perf_event *event,
630                            u32 pid, enum pid_type type)
631 {
632         struct task_struct *tsk;
633
634         /* Idle process */
635         if (!pid)
636                 goto out;
637
638         tsk = find_task_by_pid_ns(pid, &init_pid_ns);
639         pid = -1;
640         if (tsk) {
641                 /*
642                  * Only top level events contain the pid namespace in which
643                  * they are created.
644                  */
645                 if (event->parent)
646                         event = event->parent;
647                 pid = __task_pid_nr_ns(tsk, type, event->ns);
648                 /*
649                  * See also 1d953111b648
650                  * "perf/core: Don't report zero PIDs for exiting tasks".
651                  */
652                 if (!pid && !pid_alive(tsk))
653                         pid = -1;
654         }
655 out:
656         return pid;
657 }
658
659 static void cpumsf_output_event_pid(struct perf_event *event,
660                                     struct perf_sample_data *data,
661                                     struct pt_regs *regs)
662 {
663         u32 pid;
664         struct perf_event_header header;
665         struct perf_output_handle handle;
666
667         /*
668          * Obtain the PID from the basic-sampling data entry and
669          * correct the data->tid_entry.pid value.
670          */
671         pid = data->tid_entry.pid;
672
673         /* Protect callchain buffers, tasks */
674         rcu_read_lock();
675
676         perf_prepare_sample(&header, data, event, regs);
677         if (perf_output_begin(&handle, event, header.size))
678                 goto out;
679
680         /* Update the process ID (see also kernel/events/core.c) */
681         data->tid_entry.pid = cpumsf_pid_type(event, pid, PIDTYPE_TGID);
682         data->tid_entry.tid = cpumsf_pid_type(event, pid, PIDTYPE_PID);
683
684         perf_output_sample(&handle, &header, data, event);
685         perf_output_end(&handle);
686 out:
687         rcu_read_unlock();
688 }
689
690 static int __hw_perf_event_init(struct perf_event *event)
691 {
692         struct cpu_hw_sf *cpuhw;
693         struct hws_qsi_info_block si;
694         struct perf_event_attr *attr = &event->attr;
695         struct hw_perf_event *hwc = &event->hw;
696         unsigned long rate;
697         int cpu, err;
698
699         /* Reserve CPU-measurement sampling facility */
700         err = 0;
701         if (!atomic_inc_not_zero(&num_events)) {
702                 mutex_lock(&pmc_reserve_mutex);
703                 if (atomic_read(&num_events) == 0 && reserve_pmc_hardware())
704                         err = -EBUSY;
705                 else
706                         atomic_inc(&num_events);
707                 mutex_unlock(&pmc_reserve_mutex);
708         }
709         event->destroy = hw_perf_event_destroy;
710
711         if (err)
712                 goto out;
713
714         /* Access per-CPU sampling information (query sampling info) */
715         /*
716          * The event->cpu value can be -1 to count on every CPU, for example,
717          * when attaching to a task.  If this is specified, use the query
718          * sampling info from the current CPU, otherwise use event->cpu to
719          * retrieve the per-CPU information.
720          * Later, cpuhw indicates whether to allocate sampling buffers for a
721          * particular CPU (cpuhw!=NULL) or each online CPU (cpuw==NULL).
722          */
723         memset(&si, 0, sizeof(si));
724         cpuhw = NULL;
725         if (event->cpu == -1)
726                 qsi(&si);
727         else {
728                 /* Event is pinned to a particular CPU, retrieve the per-CPU
729                  * sampling structure for accessing the CPU-specific QSI.
730                  */
731                 cpuhw = &per_cpu(cpu_hw_sf, event->cpu);
732                 si = cpuhw->qsi;
733         }
734
735         /* Check sampling facility authorization and, if not authorized,
736          * fall back to other PMUs.  It is safe to check any CPU because
737          * the authorization is identical for all configured CPUs.
738          */
739         if (!si.as) {
740                 err = -ENOENT;
741                 goto out;
742         }
743
744         /* Always enable basic sampling */
745         SAMPL_FLAGS(hwc) = PERF_CPUM_SF_BASIC_MODE;
746
747         /* Check if diagnostic sampling is requested.  Deny if the required
748          * sampling authorization is missing.
749          */
750         if (attr->config == PERF_EVENT_CPUM_SF_DIAG) {
751                 if (!si.ad) {
752                         err = -EPERM;
753                         goto out;
754                 }
755                 SAMPL_FLAGS(hwc) |= PERF_CPUM_SF_DIAG_MODE;
756         }
757
758         /* Check and set other sampling flags */
759         if (attr->config1 & PERF_CPUM_SF_FULL_BLOCKS)
760                 SAMPL_FLAGS(hwc) |= PERF_CPUM_SF_FULL_BLOCKS;
761
762         /* The sampling information (si) contains information about the
763          * min/max sampling intervals and the CPU speed.  So calculate the
764          * correct sampling interval and avoid the whole period adjust
765          * feedback loop.
766          */
767         rate = 0;
768         if (attr->freq) {
769                 if (!attr->sample_freq) {
770                         err = -EINVAL;
771                         goto out;
772                 }
773                 rate = freq_to_sample_rate(&si, attr->sample_freq);
774                 rate = hw_limit_rate(&si, rate);
775                 attr->freq = 0;
776                 attr->sample_period = rate;
777         } else {
778                 /* The min/max sampling rates specifies the valid range
779                  * of sample periods.  If the specified sample period is
780                  * out of range, limit the period to the range boundary.
781                  */
782                 rate = hw_limit_rate(&si, hwc->sample_period);
783
784                 /* The perf core maintains a maximum sample rate that is
785                  * configurable through the sysctl interface.  Ensure the
786                  * sampling rate does not exceed this value.  This also helps
787                  * to avoid throttling when pushing samples with
788                  * perf_event_overflow().
789                  */
790                 if (sample_rate_to_freq(&si, rate) >
791                       sysctl_perf_event_sample_rate) {
792                         err = -EINVAL;
793                         debug_sprintf_event(sfdbg, 1, "Sampling rate exceeds maximum perf sample rate\n");
794                         goto out;
795                 }
796         }
797         SAMPL_RATE(hwc) = rate;
798         hw_init_period(hwc, SAMPL_RATE(hwc));
799
800         /* Initialize sample data overflow accounting */
801         hwc->extra_reg.reg = REG_OVERFLOW;
802         OVERFLOW_REG(hwc) = 0;
803
804         /* Use AUX buffer. No need to allocate it by ourself */
805         if (attr->config == PERF_EVENT_CPUM_SF_DIAG)
806                 return 0;
807
808         /* Allocate the per-CPU sampling buffer using the CPU information
809          * from the event.  If the event is not pinned to a particular
810          * CPU (event->cpu == -1; or cpuhw == NULL), allocate sampling
811          * buffers for each online CPU.
812          */
813         if (cpuhw)
814                 /* Event is pinned to a particular CPU */
815                 err = allocate_buffers(cpuhw, hwc);
816         else {
817                 /* Event is not pinned, allocate sampling buffer on
818                  * each online CPU
819                  */
820                 for_each_online_cpu(cpu) {
821                         cpuhw = &per_cpu(cpu_hw_sf, cpu);
822                         err = allocate_buffers(cpuhw, hwc);
823                         if (err)
824                                 break;
825                 }
826         }
827
828         /* If PID/TID sampling is active, replace the default overflow
829          * handler to extract and resolve the PIDs from the basic-sampling
830          * data entries.
831          */
832         if (event->attr.sample_type & PERF_SAMPLE_TID)
833                 if (is_default_overflow_handler(event))
834                         event->overflow_handler = cpumsf_output_event_pid;
835 out:
836         return err;
837 }
838
839 static int cpumsf_pmu_event_init(struct perf_event *event)
840 {
841         int err;
842
843         /* No support for taken branch sampling */
844         if (has_branch_stack(event))
845                 return -EOPNOTSUPP;
846
847         switch (event->attr.type) {
848         case PERF_TYPE_RAW:
849                 if ((event->attr.config != PERF_EVENT_CPUM_SF) &&
850                     (event->attr.config != PERF_EVENT_CPUM_SF_DIAG))
851                         return -ENOENT;
852                 break;
853         case PERF_TYPE_HARDWARE:
854                 /* Support sampling of CPU cycles in addition to the
855                  * counter facility.  However, the counter facility
856                  * is more precise and, hence, restrict this PMU to
857                  * sampling events only.
858                  */
859                 if (event->attr.config != PERF_COUNT_HW_CPU_CYCLES)
860                         return -ENOENT;
861                 if (!is_sampling_event(event))
862                         return -ENOENT;
863                 break;
864         default:
865                 return -ENOENT;
866         }
867
868         /* Check online status of the CPU to which the event is pinned */
869         if (event->cpu >= 0 && !cpu_online(event->cpu))
870                         return -ENODEV;
871
872         /* Force reset of idle/hv excludes regardless of what the
873          * user requested.
874          */
875         if (event->attr.exclude_hv)
876                 event->attr.exclude_hv = 0;
877         if (event->attr.exclude_idle)
878                 event->attr.exclude_idle = 0;
879
880         err = __hw_perf_event_init(event);
881         if (unlikely(err))
882                 if (event->destroy)
883                         event->destroy(event);
884         return err;
885 }
886
887 static void cpumsf_pmu_enable(struct pmu *pmu)
888 {
889         struct cpu_hw_sf *cpuhw = this_cpu_ptr(&cpu_hw_sf);
890         struct hw_perf_event *hwc;
891         int err;
892
893         if (cpuhw->flags & PMU_F_ENABLED)
894                 return;
895
896         if (cpuhw->flags & PMU_F_ERR_MASK)
897                 return;
898
899         /* Check whether to extent the sampling buffer.
900          *
901          * Two conditions trigger an increase of the sampling buffer for a
902          * perf event:
903          *    1. Postponed buffer allocations from the event initialization.
904          *    2. Sampling overflows that contribute to pending allocations.
905          *
906          * Note that the extend_sampling_buffer() function disables the sampling
907          * facility, but it can be fully re-enabled using sampling controls that
908          * have been saved in cpumsf_pmu_disable().
909          */
910         if (cpuhw->event) {
911                 hwc = &cpuhw->event->hw;
912                 if (!(SAMPL_DIAG_MODE(hwc))) {
913                         /*
914                          * Account number of overflow-designated
915                          * buffer extents
916                          */
917                         sfb_account_overflows(cpuhw, hwc);
918                         if (sfb_has_pending_allocs(&cpuhw->sfb, hwc))
919                                 extend_sampling_buffer(&cpuhw->sfb, hwc);
920                 }
921         }
922
923         /* (Re)enable the PMU and sampling facility */
924         cpuhw->flags |= PMU_F_ENABLED;
925         barrier();
926
927         err = lsctl(&cpuhw->lsctl);
928         if (err) {
929                 cpuhw->flags &= ~PMU_F_ENABLED;
930                 pr_err("Loading sampling controls failed: op=%i err=%i\n",
931                         1, err);
932                 return;
933         }
934
935         /* Load current program parameter */
936         lpp(&S390_lowcore.lpp);
937
938         debug_sprintf_event(sfdbg, 6, "pmu_enable: es=%i cs=%i ed=%i cd=%i "
939                             "tear=%p dear=%p\n", cpuhw->lsctl.es, cpuhw->lsctl.cs,
940                             cpuhw->lsctl.ed, cpuhw->lsctl.cd,
941                             (void *) cpuhw->lsctl.tear, (void *) cpuhw->lsctl.dear);
942 }
943
944 static void cpumsf_pmu_disable(struct pmu *pmu)
945 {
946         struct cpu_hw_sf *cpuhw = this_cpu_ptr(&cpu_hw_sf);
947         struct hws_lsctl_request_block inactive;
948         struct hws_qsi_info_block si;
949         int err;
950
951         if (!(cpuhw->flags & PMU_F_ENABLED))
952                 return;
953
954         if (cpuhw->flags & PMU_F_ERR_MASK)
955                 return;
956
957         /* Switch off sampling activation control */
958         inactive = cpuhw->lsctl;
959         inactive.cs = 0;
960         inactive.cd = 0;
961
962         err = lsctl(&inactive);
963         if (err) {
964                 pr_err("Loading sampling controls failed: op=%i err=%i\n",
965                         2, err);
966                 return;
967         }
968
969         /* Save state of TEAR and DEAR register contents */
970         if (!qsi(&si)) {
971                 /* TEAR/DEAR values are valid only if the sampling facility is
972                  * enabled.  Note that cpumsf_pmu_disable() might be called even
973                  * for a disabled sampling facility because cpumsf_pmu_enable()
974                  * controls the enable/disable state.
975                  */
976                 if (si.es) {
977                         cpuhw->lsctl.tear = si.tear;
978                         cpuhw->lsctl.dear = si.dear;
979                 }
980         } else
981                 debug_sprintf_event(sfdbg, 3, "cpumsf_pmu_disable: "
982                                     "qsi() failed with err=%i\n", err);
983
984         cpuhw->flags &= ~PMU_F_ENABLED;
985 }
986
987 /* perf_exclude_event() - Filter event
988  * @event:      The perf event
989  * @regs:       pt_regs structure
990  * @sde_regs:   Sample-data-entry (sde) regs structure
991  *
992  * Filter perf events according to their exclude specification.
993  *
994  * Return non-zero if the event shall be excluded.
995  */
996 static int perf_exclude_event(struct perf_event *event, struct pt_regs *regs,
997                               struct perf_sf_sde_regs *sde_regs)
998 {
999         if (event->attr.exclude_user && user_mode(regs))
1000                 return 1;
1001         if (event->attr.exclude_kernel && !user_mode(regs))
1002                 return 1;
1003         if (event->attr.exclude_guest && sde_regs->in_guest)
1004                 return 1;
1005         if (event->attr.exclude_host && !sde_regs->in_guest)
1006                 return 1;
1007         return 0;
1008 }
1009
1010 /* perf_push_sample() - Push samples to perf
1011  * @event:      The perf event
1012  * @sample:     Hardware sample data
1013  *
1014  * Use the hardware sample data to create perf event sample.  The sample
1015  * is the pushed to the event subsystem and the function checks for
1016  * possible event overflows.  If an event overflow occurs, the PMU is
1017  * stopped.
1018  *
1019  * Return non-zero if an event overflow occurred.
1020  */
1021 static int perf_push_sample(struct perf_event *event,
1022                             struct hws_basic_entry *basic)
1023 {
1024         int overflow;
1025         struct pt_regs regs;
1026         struct perf_sf_sde_regs *sde_regs;
1027         struct perf_sample_data data;
1028
1029         /* Setup perf sample */
1030         perf_sample_data_init(&data, 0, event->hw.last_period);
1031
1032         /* Setup pt_regs to look like an CPU-measurement external interrupt
1033          * using the Program Request Alert code.  The regs.int_parm_long
1034          * field which is unused contains additional sample-data-entry related
1035          * indicators.
1036          */
1037         memset(&regs, 0, sizeof(regs));
1038         regs.int_code = 0x1407;
1039         regs.int_parm = CPU_MF_INT_SF_PRA;
1040         sde_regs = (struct perf_sf_sde_regs *) &regs.int_parm_long;
1041
1042         psw_bits(regs.psw).ia   = basic->ia;
1043         psw_bits(regs.psw).dat  = basic->T;
1044         psw_bits(regs.psw).wait = basic->W;
1045         psw_bits(regs.psw).pstate = basic->P;
1046         psw_bits(regs.psw).as   = basic->AS;
1047
1048         /*
1049          * Use the hardware provided configuration level to decide if the
1050          * sample belongs to a guest or host. If that is not available,
1051          * fall back to the following heuristics:
1052          * A non-zero guest program parameter always indicates a guest
1053          * sample. Some early samples or samples from guests without
1054          * lpp usage would be misaccounted to the host. We use the asn
1055          * value as an addon heuristic to detect most of these guest samples.
1056          * If the value differs from 0xffff (the host value), we assume to
1057          * be a KVM guest.
1058          */
1059         switch (basic->CL) {
1060         case 1: /* logical partition */
1061                 sde_regs->in_guest = 0;
1062                 break;
1063         case 2: /* virtual machine */
1064                 sde_regs->in_guest = 1;
1065                 break;
1066         default: /* old machine, use heuristics */
1067                 if (basic->gpp || basic->prim_asn != 0xffff)
1068                         sde_regs->in_guest = 1;
1069                 break;
1070         }
1071
1072         /*
1073          * Store the PID value from the sample-data-entry to be
1074          * processed and resolved by cpumsf_output_event_pid().
1075          */
1076         data.tid_entry.pid = basic->hpp & LPP_PID_MASK;
1077
1078         overflow = 0;
1079         if (perf_exclude_event(event, &regs, sde_regs))
1080                 goto out;
1081         if (perf_event_overflow(event, &data, &regs)) {
1082                 overflow = 1;
1083                 event->pmu->stop(event, 0);
1084         }
1085         perf_event_update_userpage(event);
1086 out:
1087         return overflow;
1088 }
1089
1090 static void perf_event_count_update(struct perf_event *event, u64 count)
1091 {
1092         local64_add(count, &event->count);
1093 }
1094
1095 static void debug_sample_entry(struct hws_basic_entry *sample,
1096                                struct hws_trailer_entry *te)
1097 {
1098         debug_sprintf_event(sfdbg, 4, "hw_collect_samples: Found unknown "
1099                             "sampling data entry: te->f=%i basic.def=%04x (%p)\n",
1100                             te->f, sample->def, sample);
1101 }
1102
1103 /* hw_collect_samples() - Walk through a sample-data-block and collect samples
1104  * @event:      The perf event
1105  * @sdbt:       Sample-data-block table
1106  * @overflow:   Event overflow counter
1107  *
1108  * Walks through a sample-data-block and collects sampling data entries that are
1109  * then pushed to the perf event subsystem.  Depending on the sampling function,
1110  * there can be either basic-sampling or combined-sampling data entries.  A
1111  * combined-sampling data entry consists of a basic- and a diagnostic-sampling
1112  * data entry.  The sampling function is determined by the flags in the perf
1113  * event hardware structure.  The function always works with a combined-sampling
1114  * data entry but ignores the the diagnostic portion if it is not available.
1115  *
1116  * Note that the implementation focuses on basic-sampling data entries and, if
1117  * such an entry is not valid, the entire combined-sampling data entry is
1118  * ignored.
1119  *
1120  * The overflow variables counts the number of samples that has been discarded
1121  * due to a perf event overflow.
1122  */
1123 static void hw_collect_samples(struct perf_event *event, unsigned long *sdbt,
1124                                unsigned long long *overflow)
1125 {
1126         struct hws_trailer_entry *te;
1127         struct hws_basic_entry *sample;
1128
1129         te = (struct hws_trailer_entry *) trailer_entry_ptr(*sdbt);
1130         sample = (struct hws_basic_entry *) *sdbt;
1131         while ((unsigned long *) sample < (unsigned long *) te) {
1132                 /* Check for an empty sample */
1133                 if (!sample->def)
1134                         break;
1135
1136                 /* Update perf event period */
1137                 perf_event_count_update(event, SAMPL_RATE(&event->hw));
1138
1139                 /* Check whether sample is valid */
1140                 if (sample->def == 0x0001) {
1141                         /* If an event overflow occurred, the PMU is stopped to
1142                          * throttle event delivery.  Remaining sample data is
1143                          * discarded.
1144                          */
1145                         if (!*overflow) {
1146                                 /* Check whether sample is consistent */
1147                                 if (sample->I == 0 && sample->W == 0) {
1148                                         /* Deliver sample data to perf */
1149                                         *overflow = perf_push_sample(event,
1150                                                                      sample);
1151                                 }
1152                         } else
1153                                 /* Count discarded samples */
1154                                 *overflow += 1;
1155                 } else {
1156                         debug_sample_entry(sample, te);
1157                         /* Sample slot is not yet written or other record.
1158                          *
1159                          * This condition can occur if the buffer was reused
1160                          * from a combined basic- and diagnostic-sampling.
1161                          * If only basic-sampling is then active, entries are
1162                          * written into the larger diagnostic entries.
1163                          * This is typically the case for sample-data-blocks
1164                          * that are not full.  Stop processing if the first
1165                          * invalid format was detected.
1166                          */
1167                         if (!te->f)
1168                                 break;
1169                 }
1170
1171                 /* Reset sample slot and advance to next sample */
1172                 sample->def = 0;
1173                 sample++;
1174         }
1175 }
1176
1177 /* hw_perf_event_update() - Process sampling buffer
1178  * @event:      The perf event
1179  * @flush_all:  Flag to also flush partially filled sample-data-blocks
1180  *
1181  * Processes the sampling buffer and create perf event samples.
1182  * The sampling buffer position are retrieved and saved in the TEAR_REG
1183  * register of the specified perf event.
1184  *
1185  * Only full sample-data-blocks are processed.  Specify the flash_all flag
1186  * to also walk through partially filled sample-data-blocks.  It is ignored
1187  * if PERF_CPUM_SF_FULL_BLOCKS is set.  The PERF_CPUM_SF_FULL_BLOCKS flag
1188  * enforces the processing of full sample-data-blocks only (trailer entries
1189  * with the block-full-indicator bit set).
1190  */
1191 static void hw_perf_event_update(struct perf_event *event, int flush_all)
1192 {
1193         struct hw_perf_event *hwc = &event->hw;
1194         struct hws_trailer_entry *te;
1195         unsigned long *sdbt;
1196         unsigned long long event_overflow, sampl_overflow, num_sdb, te_flags;
1197         int done;
1198
1199         /*
1200          * AUX buffer is used when in diagnostic sampling mode.
1201          * No perf events/samples are created.
1202          */
1203         if (SAMPL_DIAG_MODE(&event->hw))
1204                 return;
1205
1206         if (flush_all && SDB_FULL_BLOCKS(hwc))
1207                 flush_all = 0;
1208
1209         sdbt = (unsigned long *) TEAR_REG(hwc);
1210         done = event_overflow = sampl_overflow = num_sdb = 0;
1211         while (!done) {
1212                 /* Get the trailer entry of the sample-data-block */
1213                 te = (struct hws_trailer_entry *) trailer_entry_ptr(*sdbt);
1214
1215                 /* Leave loop if no more work to do (block full indicator) */
1216                 if (!te->f) {
1217                         done = 1;
1218                         if (!flush_all)
1219                                 break;
1220                 }
1221
1222                 /* Check the sample overflow count */
1223                 if (te->overflow)
1224                         /* Account sample overflows and, if a particular limit
1225                          * is reached, extend the sampling buffer.
1226                          * For details, see sfb_account_overflows().
1227                          */
1228                         sampl_overflow += te->overflow;
1229
1230                 /* Timestamps are valid for full sample-data-blocks only */
1231                 debug_sprintf_event(sfdbg, 6, "hw_perf_event_update: sdbt=%p "
1232                                     "overflow=%llu timestamp=0x%llx\n",
1233                                     sdbt, te->overflow,
1234                                     (te->f) ? trailer_timestamp(te) : 0ULL);
1235
1236                 /* Collect all samples from a single sample-data-block and
1237                  * flag if an (perf) event overflow happened.  If so, the PMU
1238                  * is stopped and remaining samples will be discarded.
1239                  */
1240                 hw_collect_samples(event, sdbt, &event_overflow);
1241                 num_sdb++;
1242
1243                 /* Reset trailer (using compare-double-and-swap) */
1244                 do {
1245                         te_flags = te->flags & ~SDB_TE_BUFFER_FULL_MASK;
1246                         te_flags |= SDB_TE_ALERT_REQ_MASK;
1247                 } while (!cmpxchg_double(&te->flags, &te->overflow,
1248                                          te->flags, te->overflow,
1249                                          te_flags, 0ULL));
1250
1251                 /* Advance to next sample-data-block */
1252                 sdbt++;
1253                 if (is_link_entry(sdbt))
1254                         sdbt = get_next_sdbt(sdbt);
1255
1256                 /* Update event hardware registers */
1257                 TEAR_REG(hwc) = (unsigned long) sdbt;
1258
1259                 /* Stop processing sample-data if all samples of the current
1260                  * sample-data-block were flushed even if it was not full.
1261                  */
1262                 if (flush_all && done)
1263                         break;
1264         }
1265
1266         /* Account sample overflows in the event hardware structure */
1267         if (sampl_overflow)
1268                 OVERFLOW_REG(hwc) = DIV_ROUND_UP(OVERFLOW_REG(hwc) +
1269                                                  sampl_overflow, 1 + num_sdb);
1270
1271         /* Perf_event_overflow() and perf_event_account_interrupt() limit
1272          * the interrupt rate to an upper limit. Roughly 1000 samples per
1273          * task tick.
1274          * Hitting this limit results in a large number
1275          * of throttled REF_REPORT_THROTTLE entries and the samples
1276          * are dropped.
1277          * Slightly increase the interval to avoid hitting this limit.
1278          */
1279         if (event_overflow) {
1280                 SAMPL_RATE(hwc) += DIV_ROUND_UP(SAMPL_RATE(hwc), 10);
1281                 debug_sprintf_event(sfdbg, 1, "%s: rate adjustment %ld\n",
1282                                     __func__,
1283                                     DIV_ROUND_UP(SAMPL_RATE(hwc), 10));
1284         }
1285
1286         if (sampl_overflow || event_overflow)
1287                 debug_sprintf_event(sfdbg, 4, "hw_perf_event_update: "
1288                                     "overflow stats: sample=%llu event=%llu\n",
1289                                     sampl_overflow, event_overflow);
1290 }
1291
1292 #define AUX_SDB_INDEX(aux, i) ((i) % aux->sfb.num_sdb)
1293 #define AUX_SDB_NUM(aux, start, end) (end >= start ? end - start + 1 : 0)
1294 #define AUX_SDB_NUM_ALERT(aux) AUX_SDB_NUM(aux, aux->head, aux->alert_mark)
1295 #define AUX_SDB_NUM_EMPTY(aux) AUX_SDB_NUM(aux, aux->head, aux->empty_mark)
1296
1297 /*
1298  * Get trailer entry by index of SDB.
1299  */
1300 static struct hws_trailer_entry *aux_sdb_trailer(struct aux_buffer *aux,
1301                                                  unsigned long index)
1302 {
1303         unsigned long sdb;
1304
1305         index = AUX_SDB_INDEX(aux, index);
1306         sdb = aux->sdb_index[index];
1307         return (struct hws_trailer_entry *)trailer_entry_ptr(sdb);
1308 }
1309
1310 /*
1311  * Finish sampling on the cpu. Called by cpumsf_pmu_del() with pmu
1312  * disabled. Collect the full SDBs in AUX buffer which have not reached
1313  * the point of alert indicator. And ignore the SDBs which are not
1314  * full.
1315  *
1316  * 1. Scan SDBs to see how much data is there and consume them.
1317  * 2. Remove alert indicator in the buffer.
1318  */
1319 static void aux_output_end(struct perf_output_handle *handle)
1320 {
1321         unsigned long i, range_scan, idx;
1322         struct aux_buffer *aux;
1323         struct hws_trailer_entry *te;
1324
1325         aux = perf_get_aux(handle);
1326         if (!aux)
1327                 return;
1328
1329         range_scan = AUX_SDB_NUM_ALERT(aux);
1330         for (i = 0, idx = aux->head; i < range_scan; i++, idx++) {
1331                 te = aux_sdb_trailer(aux, idx);
1332                 if (!(te->flags & SDB_TE_BUFFER_FULL_MASK))
1333                         break;
1334         }
1335         /* i is num of SDBs which are full */
1336         perf_aux_output_end(handle, i << PAGE_SHIFT);
1337
1338         /* Remove alert indicators in the buffer */
1339         te = aux_sdb_trailer(aux, aux->alert_mark);
1340         te->flags &= ~SDB_TE_ALERT_REQ_MASK;
1341
1342         debug_sprintf_event(sfdbg, 6, "aux_output_end: collect %lx SDBs\n", i);
1343 }
1344
1345 /*
1346  * Start sampling on the CPU. Called by cpumsf_pmu_add() when an event
1347  * is first added to the CPU or rescheduled again to the CPU. It is called
1348  * with pmu disabled.
1349  *
1350  * 1. Reset the trailer of SDBs to get ready for new data.
1351  * 2. Tell the hardware where to put the data by reset the SDBs buffer
1352  *    head(tear/dear).
1353  */
1354 static int aux_output_begin(struct perf_output_handle *handle,
1355                             struct aux_buffer *aux,
1356                             struct cpu_hw_sf *cpuhw)
1357 {
1358         unsigned long range;
1359         unsigned long i, range_scan, idx;
1360         unsigned long head, base, offset;
1361         struct hws_trailer_entry *te;
1362
1363         if (WARN_ON_ONCE(handle->head & ~PAGE_MASK))
1364                 return -EINVAL;
1365
1366         aux->head = handle->head >> PAGE_SHIFT;
1367         range = (handle->size + 1) >> PAGE_SHIFT;
1368         if (range <= 1)
1369                 return -ENOMEM;
1370
1371         /*
1372          * SDBs between aux->head and aux->empty_mark are already ready
1373          * for new data. range_scan is num of SDBs not within them.
1374          */
1375         if (range > AUX_SDB_NUM_EMPTY(aux)) {
1376                 range_scan = range - AUX_SDB_NUM_EMPTY(aux);
1377                 idx = aux->empty_mark + 1;
1378                 for (i = 0; i < range_scan; i++, idx++) {
1379                         te = aux_sdb_trailer(aux, idx);
1380                         te->flags &= ~(SDB_TE_BUFFER_FULL_MASK |
1381                                        SDB_TE_ALERT_REQ_MASK);
1382                         te->overflow = 0;
1383                 }
1384                 /* Save the position of empty SDBs */
1385                 aux->empty_mark = aux->head + range - 1;
1386         }
1387
1388         /* Set alert indicator */
1389         aux->alert_mark = aux->head + range/2 - 1;
1390         te = aux_sdb_trailer(aux, aux->alert_mark);
1391         te->flags = te->flags | SDB_TE_ALERT_REQ_MASK;
1392
1393         /* Reset hardware buffer head */
1394         head = AUX_SDB_INDEX(aux, aux->head);
1395         base = aux->sdbt_index[head / CPUM_SF_SDB_PER_TABLE];
1396         offset = head % CPUM_SF_SDB_PER_TABLE;
1397         cpuhw->lsctl.tear = base + offset * sizeof(unsigned long);
1398         cpuhw->lsctl.dear = aux->sdb_index[head];
1399
1400         debug_sprintf_event(sfdbg, 6, "aux_output_begin: "
1401                             "head->alert_mark->empty_mark (num_alert, range)"
1402                             "[%lx -> %lx -> %lx] (%lx, %lx) "
1403                             "tear index %lx, tear %lx dear %lx\n",
1404                             aux->head, aux->alert_mark, aux->empty_mark,
1405                             AUX_SDB_NUM_ALERT(aux), range,
1406                             head / CPUM_SF_SDB_PER_TABLE,
1407                             cpuhw->lsctl.tear,
1408                             cpuhw->lsctl.dear);
1409
1410         return 0;
1411 }
1412
1413 /*
1414  * Set alert indicator on SDB at index @alert_index while sampler is running.
1415  *
1416  * Return true if successfully.
1417  * Return false if full indicator is already set by hardware sampler.
1418  */
1419 static bool aux_set_alert(struct aux_buffer *aux, unsigned long alert_index,
1420                           unsigned long long *overflow)
1421 {
1422         unsigned long long orig_overflow, orig_flags, new_flags;
1423         struct hws_trailer_entry *te;
1424
1425         te = aux_sdb_trailer(aux, alert_index);
1426         do {
1427                 orig_flags = te->flags;
1428                 *overflow = orig_overflow = te->overflow;
1429                 if (orig_flags & SDB_TE_BUFFER_FULL_MASK) {
1430                         /*
1431                          * SDB is already set by hardware.
1432                          * Abort and try to set somewhere
1433                          * behind.
1434                          */
1435                         return false;
1436                 }
1437                 new_flags = orig_flags | SDB_TE_ALERT_REQ_MASK;
1438         } while (!cmpxchg_double(&te->flags, &te->overflow,
1439                                  orig_flags, orig_overflow,
1440                                  new_flags, 0ULL));
1441         return true;
1442 }
1443
1444 /*
1445  * aux_reset_buffer() - Scan and setup SDBs for new samples
1446  * @aux:        The AUX buffer to set
1447  * @range:      The range of SDBs to scan started from aux->head
1448  * @overflow:   Set to overflow count
1449  *
1450  * Set alert indicator on the SDB at index of aux->alert_mark. If this SDB is
1451  * marked as empty, check if it is already set full by the hardware sampler.
1452  * If yes, that means new data is already there before we can set an alert
1453  * indicator. Caller should try to set alert indicator to some position behind.
1454  *
1455  * Scan the SDBs in AUX buffer from behind aux->empty_mark. They are used
1456  * previously and have already been consumed by user space. Reset these SDBs
1457  * (clear full indicator and alert indicator) for new data.
1458  * If aux->alert_mark fall in this area, just set it. Overflow count is
1459  * recorded while scanning.
1460  *
1461  * SDBs between aux->head and aux->empty_mark are already reset at last time.
1462  * and ready for new samples. So scanning on this area could be skipped.
1463  *
1464  * Return true if alert indicator is set successfully and false if not.
1465  */
1466 static bool aux_reset_buffer(struct aux_buffer *aux, unsigned long range,
1467                              unsigned long long *overflow)
1468 {
1469         unsigned long long orig_overflow, orig_flags, new_flags;
1470         unsigned long i, range_scan, idx;
1471         struct hws_trailer_entry *te;
1472
1473         if (range <= AUX_SDB_NUM_EMPTY(aux))
1474                 /*
1475                  * No need to scan. All SDBs in range are marked as empty.
1476                  * Just set alert indicator. Should check race with hardware
1477                  * sampler.
1478                  */
1479                 return aux_set_alert(aux, aux->alert_mark, overflow);
1480
1481         if (aux->alert_mark <= aux->empty_mark)
1482                 /*
1483                  * Set alert indicator on empty SDB. Should check race
1484                  * with hardware sampler.
1485                  */
1486                 if (!aux_set_alert(aux, aux->alert_mark, overflow))
1487                         return false;
1488
1489         /*
1490          * Scan the SDBs to clear full and alert indicator used previously.
1491          * Start scanning from one SDB behind empty_mark. If the new alert
1492          * indicator fall into this range, set it.
1493          */
1494         range_scan = range - AUX_SDB_NUM_EMPTY(aux);
1495         idx = aux->empty_mark + 1;
1496         for (i = 0; i < range_scan; i++, idx++) {
1497                 te = aux_sdb_trailer(aux, idx);
1498                 do {
1499                         orig_flags = te->flags;
1500                         orig_overflow = te->overflow;
1501                         new_flags = orig_flags & ~SDB_TE_BUFFER_FULL_MASK;
1502                         if (idx == aux->alert_mark)
1503                                 new_flags |= SDB_TE_ALERT_REQ_MASK;
1504                         else
1505                                 new_flags &= ~SDB_TE_ALERT_REQ_MASK;
1506                 } while (!cmpxchg_double(&te->flags, &te->overflow,
1507                                          orig_flags, orig_overflow,
1508                                          new_flags, 0ULL));
1509                 *overflow += orig_overflow;
1510         }
1511
1512         /* Update empty_mark to new position */
1513         aux->empty_mark = aux->head + range - 1;
1514
1515         return true;
1516 }
1517
1518 /*
1519  * Measurement alert handler for diagnostic mode sampling.
1520  */
1521 static void hw_collect_aux(struct cpu_hw_sf *cpuhw)
1522 {
1523         struct aux_buffer *aux;
1524         int done = 0;
1525         unsigned long range = 0, size;
1526         unsigned long long overflow = 0;
1527         struct perf_output_handle *handle = &cpuhw->handle;
1528         unsigned long num_sdb;
1529
1530         aux = perf_get_aux(handle);
1531         if (WARN_ON_ONCE(!aux))
1532                 return;
1533
1534         /* Inform user space new data arrived */
1535         size = AUX_SDB_NUM_ALERT(aux) << PAGE_SHIFT;
1536         perf_aux_output_end(handle, size);
1537         num_sdb = aux->sfb.num_sdb;
1538
1539         num_sdb = aux->sfb.num_sdb;
1540         while (!done) {
1541                 /* Get an output handle */
1542                 aux = perf_aux_output_begin(handle, cpuhw->event);
1543                 if (handle->size == 0) {
1544                         pr_err("The AUX buffer with %lu pages for the "
1545                                "diagnostic-sampling mode is full\n",
1546                                 num_sdb);
1547                         debug_sprintf_event(sfdbg, 1, "AUX buffer used up\n");
1548                         break;
1549                 }
1550                 if (WARN_ON_ONCE(!aux))
1551                         return;
1552
1553                 /* Update head and alert_mark to new position */
1554                 aux->head = handle->head >> PAGE_SHIFT;
1555                 range = (handle->size + 1) >> PAGE_SHIFT;
1556                 if (range == 1)
1557                         aux->alert_mark = aux->head;
1558                 else
1559                         aux->alert_mark = aux->head + range/2 - 1;
1560
1561                 if (aux_reset_buffer(aux, range, &overflow)) {
1562                         if (!overflow) {
1563                                 done = 1;
1564                                 break;
1565                         }
1566                         size = range << PAGE_SHIFT;
1567                         perf_aux_output_end(&cpuhw->handle, size);
1568                         pr_err("Sample data caused the AUX buffer with %lu "
1569                                "pages to overflow\n", num_sdb);
1570                         debug_sprintf_event(sfdbg, 1, "head %lx range %lx "
1571                                             "overflow %llx\n",
1572                                             aux->head, range, overflow);
1573                 } else {
1574                         size = AUX_SDB_NUM_ALERT(aux) << PAGE_SHIFT;
1575                         perf_aux_output_end(&cpuhw->handle, size);
1576                         debug_sprintf_event(sfdbg, 6, "head %lx alert %lx "
1577                                             "already full, try another\n",
1578                                             aux->head, aux->alert_mark);
1579                 }
1580         }
1581
1582         if (done)
1583                 debug_sprintf_event(sfdbg, 6, "aux_reset_buffer: "
1584                                     "[%lx -> %lx -> %lx] (%lx, %lx)\n",
1585                                     aux->head, aux->alert_mark, aux->empty_mark,
1586                                     AUX_SDB_NUM_ALERT(aux), range);
1587 }
1588
1589 /*
1590  * Callback when freeing AUX buffers.
1591  */
1592 static void aux_buffer_free(void *data)
1593 {
1594         struct aux_buffer *aux = data;
1595         unsigned long i, num_sdbt;
1596
1597         if (!aux)
1598                 return;
1599
1600         /* Free SDBT. SDB is freed by the caller */
1601         num_sdbt = aux->sfb.num_sdbt;
1602         for (i = 0; i < num_sdbt; i++)
1603                 free_page(aux->sdbt_index[i]);
1604
1605         kfree(aux->sdbt_index);
1606         kfree(aux->sdb_index);
1607         kfree(aux);
1608
1609         debug_sprintf_event(sfdbg, 4, "aux_buffer_free: free "
1610                             "%lu SDBTs\n", num_sdbt);
1611 }
1612
1613 static void aux_sdb_init(unsigned long sdb)
1614 {
1615         struct hws_trailer_entry *te;
1616
1617         te = (struct hws_trailer_entry *)trailer_entry_ptr(sdb);
1618
1619         /* Save clock base */
1620         te->clock_base = 1;
1621         memcpy(&te->progusage2, &tod_clock_base[1], 8);
1622 }
1623
1624 /*
1625  * aux_buffer_setup() - Setup AUX buffer for diagnostic mode sampling
1626  * @event:      Event the buffer is setup for, event->cpu == -1 means current
1627  * @pages:      Array of pointers to buffer pages passed from perf core
1628  * @nr_pages:   Total pages
1629  * @snapshot:   Flag for snapshot mode
1630  *
1631  * This is the callback when setup an event using AUX buffer. Perf tool can
1632  * trigger this by an additional mmap() call on the event. Unlike the buffer
1633  * for basic samples, AUX buffer belongs to the event. It is scheduled with
1634  * the task among online cpus when it is a per-thread event.
1635  *
1636  * Return the private AUX buffer structure if success or NULL if fails.
1637  */
1638 static void *aux_buffer_setup(struct perf_event *event, void **pages,
1639                               int nr_pages, bool snapshot)
1640 {
1641         struct sf_buffer *sfb;
1642         struct aux_buffer *aux;
1643         unsigned long *new, *tail;
1644         int i, n_sdbt;
1645
1646         if (!nr_pages || !pages)
1647                 return NULL;
1648
1649         if (nr_pages > CPUM_SF_MAX_SDB * CPUM_SF_SDB_DIAG_FACTOR) {
1650                 pr_err("AUX buffer size (%i pages) is larger than the "
1651                        "maximum sampling buffer limit\n",
1652                        nr_pages);
1653                 return NULL;
1654         } else if (nr_pages < CPUM_SF_MIN_SDB * CPUM_SF_SDB_DIAG_FACTOR) {
1655                 pr_err("AUX buffer size (%i pages) is less than the "
1656                        "minimum sampling buffer limit\n",
1657                        nr_pages);
1658                 return NULL;
1659         }
1660
1661         /* Allocate aux_buffer struct for the event */
1662         aux = kzalloc(sizeof(struct aux_buffer), GFP_KERNEL);
1663         if (!aux)
1664                 goto no_aux;
1665         sfb = &aux->sfb;
1666
1667         /* Allocate sdbt_index for fast reference */
1668         n_sdbt = (nr_pages + CPUM_SF_SDB_PER_TABLE - 1) / CPUM_SF_SDB_PER_TABLE;
1669         aux->sdbt_index = kmalloc_array(n_sdbt, sizeof(void *), GFP_KERNEL);
1670         if (!aux->sdbt_index)
1671                 goto no_sdbt_index;
1672
1673         /* Allocate sdb_index for fast reference */
1674         aux->sdb_index = kmalloc_array(nr_pages, sizeof(void *), GFP_KERNEL);
1675         if (!aux->sdb_index)
1676                 goto no_sdb_index;
1677
1678         /* Allocate the first SDBT */
1679         sfb->num_sdbt = 0;
1680         sfb->sdbt = (unsigned long *) get_zeroed_page(GFP_KERNEL);
1681         if (!sfb->sdbt)
1682                 goto no_sdbt;
1683         aux->sdbt_index[sfb->num_sdbt++] = (unsigned long)sfb->sdbt;
1684         tail = sfb->tail = sfb->sdbt;
1685
1686         /*
1687          * Link the provided pages of AUX buffer to SDBT.
1688          * Allocate SDBT if needed.
1689          */
1690         for (i = 0; i < nr_pages; i++, tail++) {
1691                 if (require_table_link(tail)) {
1692                         new = (unsigned long *) get_zeroed_page(GFP_KERNEL);
1693                         if (!new)
1694                                 goto no_sdbt;
1695                         aux->sdbt_index[sfb->num_sdbt++] = (unsigned long)new;
1696                         /* Link current page to tail of chain */
1697                         *tail = (unsigned long)(void *) new + 1;
1698                         tail = new;
1699                 }
1700                 /* Tail is the entry in a SDBT */
1701                 *tail = (unsigned long)pages[i];
1702                 aux->sdb_index[i] = (unsigned long)pages[i];
1703                 aux_sdb_init((unsigned long)pages[i]);
1704         }
1705         sfb->num_sdb = nr_pages;
1706
1707         /* Link the last entry in the SDBT to the first SDBT */
1708         *tail = (unsigned long) sfb->sdbt + 1;
1709         sfb->tail = tail;
1710
1711         /*
1712          * Initial all SDBs are zeroed. Mark it as empty.
1713          * So there is no need to clear the full indicator
1714          * when this event is first added.
1715          */
1716         aux->empty_mark = sfb->num_sdb - 1;
1717
1718         debug_sprintf_event(sfdbg, 4, "aux_buffer_setup: setup %lu SDBTs"
1719                             " and %lu SDBs\n",
1720                             sfb->num_sdbt, sfb->num_sdb);
1721
1722         return aux;
1723
1724 no_sdbt:
1725         /* SDBs (AUX buffer pages) are freed by caller */
1726         for (i = 0; i < sfb->num_sdbt; i++)
1727                 free_page(aux->sdbt_index[i]);
1728         kfree(aux->sdb_index);
1729 no_sdb_index:
1730         kfree(aux->sdbt_index);
1731 no_sdbt_index:
1732         kfree(aux);
1733 no_aux:
1734         return NULL;
1735 }
1736
1737 static void cpumsf_pmu_read(struct perf_event *event)
1738 {
1739         /* Nothing to do ... updates are interrupt-driven */
1740 }
1741
1742 /* Activate sampling control.
1743  * Next call of pmu_enable() starts sampling.
1744  */
1745 static void cpumsf_pmu_start(struct perf_event *event, int flags)
1746 {
1747         struct cpu_hw_sf *cpuhw = this_cpu_ptr(&cpu_hw_sf);
1748
1749         if (WARN_ON_ONCE(!(event->hw.state & PERF_HES_STOPPED)))
1750                 return;
1751
1752         if (flags & PERF_EF_RELOAD)
1753                 WARN_ON_ONCE(!(event->hw.state & PERF_HES_UPTODATE));
1754
1755         perf_pmu_disable(event->pmu);
1756         event->hw.state = 0;
1757         cpuhw->lsctl.cs = 1;
1758         if (SAMPL_DIAG_MODE(&event->hw))
1759                 cpuhw->lsctl.cd = 1;
1760         perf_pmu_enable(event->pmu);
1761 }
1762
1763 /* Deactivate sampling control.
1764  * Next call of pmu_enable() stops sampling.
1765  */
1766 static void cpumsf_pmu_stop(struct perf_event *event, int flags)
1767 {
1768         struct cpu_hw_sf *cpuhw = this_cpu_ptr(&cpu_hw_sf);
1769
1770         if (event->hw.state & PERF_HES_STOPPED)
1771                 return;
1772
1773         perf_pmu_disable(event->pmu);
1774         cpuhw->lsctl.cs = 0;
1775         cpuhw->lsctl.cd = 0;
1776         event->hw.state |= PERF_HES_STOPPED;
1777
1778         if ((flags & PERF_EF_UPDATE) && !(event->hw.state & PERF_HES_UPTODATE)) {
1779                 hw_perf_event_update(event, 1);
1780                 event->hw.state |= PERF_HES_UPTODATE;
1781         }
1782         perf_pmu_enable(event->pmu);
1783 }
1784
1785 static int cpumsf_pmu_add(struct perf_event *event, int flags)
1786 {
1787         struct cpu_hw_sf *cpuhw = this_cpu_ptr(&cpu_hw_sf);
1788         struct aux_buffer *aux;
1789         int err;
1790
1791         if (cpuhw->flags & PMU_F_IN_USE)
1792                 return -EAGAIN;
1793
1794         if (!SAMPL_DIAG_MODE(&event->hw) && !cpuhw->sfb.sdbt)
1795                 return -EINVAL;
1796
1797         err = 0;
1798         perf_pmu_disable(event->pmu);
1799
1800         event->hw.state = PERF_HES_UPTODATE | PERF_HES_STOPPED;
1801
1802         /* Set up sampling controls.  Always program the sampling register
1803          * using the SDB-table start.  Reset TEAR_REG event hardware register
1804          * that is used by hw_perf_event_update() to store the sampling buffer
1805          * position after samples have been flushed.
1806          */
1807         cpuhw->lsctl.s = 0;
1808         cpuhw->lsctl.h = 1;
1809         cpuhw->lsctl.interval = SAMPL_RATE(&event->hw);
1810         if (!SAMPL_DIAG_MODE(&event->hw)) {
1811                 cpuhw->lsctl.tear = (unsigned long) cpuhw->sfb.sdbt;
1812                 cpuhw->lsctl.dear = *(unsigned long *) cpuhw->sfb.sdbt;
1813                 hw_reset_registers(&event->hw, cpuhw->sfb.sdbt);
1814         }
1815
1816         /* Ensure sampling functions are in the disabled state.  If disabled,
1817          * switch on sampling enable control. */
1818         if (WARN_ON_ONCE(cpuhw->lsctl.es == 1 || cpuhw->lsctl.ed == 1)) {
1819                 err = -EAGAIN;
1820                 goto out;
1821         }
1822         if (SAMPL_DIAG_MODE(&event->hw)) {
1823                 aux = perf_aux_output_begin(&cpuhw->handle, event);
1824                 if (!aux) {
1825                         err = -EINVAL;
1826                         goto out;
1827                 }
1828                 err = aux_output_begin(&cpuhw->handle, aux, cpuhw);
1829                 if (err)
1830                         goto out;
1831                 cpuhw->lsctl.ed = 1;
1832         }
1833         cpuhw->lsctl.es = 1;
1834
1835         /* Set in_use flag and store event */
1836         cpuhw->event = event;
1837         cpuhw->flags |= PMU_F_IN_USE;
1838
1839         if (flags & PERF_EF_START)
1840                 cpumsf_pmu_start(event, PERF_EF_RELOAD);
1841 out:
1842         perf_event_update_userpage(event);
1843         perf_pmu_enable(event->pmu);
1844         return err;
1845 }
1846
1847 static void cpumsf_pmu_del(struct perf_event *event, int flags)
1848 {
1849         struct cpu_hw_sf *cpuhw = this_cpu_ptr(&cpu_hw_sf);
1850
1851         perf_pmu_disable(event->pmu);
1852         cpumsf_pmu_stop(event, PERF_EF_UPDATE);
1853
1854         cpuhw->lsctl.es = 0;
1855         cpuhw->lsctl.ed = 0;
1856         cpuhw->flags &= ~PMU_F_IN_USE;
1857         cpuhw->event = NULL;
1858
1859         if (SAMPL_DIAG_MODE(&event->hw))
1860                 aux_output_end(&cpuhw->handle);
1861         perf_event_update_userpage(event);
1862         perf_pmu_enable(event->pmu);
1863 }
1864
1865 CPUMF_EVENT_ATTR(SF, SF_CYCLES_BASIC, PERF_EVENT_CPUM_SF);
1866 CPUMF_EVENT_ATTR(SF, SF_CYCLES_BASIC_DIAG, PERF_EVENT_CPUM_SF_DIAG);
1867
1868 static struct attribute *cpumsf_pmu_events_attr[] = {
1869         CPUMF_EVENT_PTR(SF, SF_CYCLES_BASIC),
1870         NULL,
1871         NULL,
1872 };
1873
1874 PMU_FORMAT_ATTR(event, "config:0-63");
1875
1876 static struct attribute *cpumsf_pmu_format_attr[] = {
1877         &format_attr_event.attr,
1878         NULL,
1879 };
1880
1881 static struct attribute_group cpumsf_pmu_events_group = {
1882         .name = "events",
1883         .attrs = cpumsf_pmu_events_attr,
1884 };
1885 static struct attribute_group cpumsf_pmu_format_group = {
1886         .name = "format",
1887         .attrs = cpumsf_pmu_format_attr,
1888 };
1889 static const struct attribute_group *cpumsf_pmu_attr_groups[] = {
1890         &cpumsf_pmu_events_group,
1891         &cpumsf_pmu_format_group,
1892         NULL,
1893 };
1894
1895 static struct pmu cpumf_sampling = {
1896         .pmu_enable   = cpumsf_pmu_enable,
1897         .pmu_disable  = cpumsf_pmu_disable,
1898
1899         .event_init   = cpumsf_pmu_event_init,
1900         .add          = cpumsf_pmu_add,
1901         .del          = cpumsf_pmu_del,
1902
1903         .start        = cpumsf_pmu_start,
1904         .stop         = cpumsf_pmu_stop,
1905         .read         = cpumsf_pmu_read,
1906
1907         .attr_groups  = cpumsf_pmu_attr_groups,
1908
1909         .setup_aux    = aux_buffer_setup,
1910         .free_aux     = aux_buffer_free,
1911 };
1912
1913 static void cpumf_measurement_alert(struct ext_code ext_code,
1914                                     unsigned int alert, unsigned long unused)
1915 {
1916         struct cpu_hw_sf *cpuhw;
1917
1918         if (!(alert & CPU_MF_INT_SF_MASK))
1919                 return;
1920         inc_irq_stat(IRQEXT_CMS);
1921         cpuhw = this_cpu_ptr(&cpu_hw_sf);
1922
1923         /* Measurement alerts are shared and might happen when the PMU
1924          * is not reserved.  Ignore these alerts in this case. */
1925         if (!(cpuhw->flags & PMU_F_RESERVED))
1926                 return;
1927
1928         /* The processing below must take care of multiple alert events that
1929          * might be indicated concurrently. */
1930
1931         /* Program alert request */
1932         if (alert & CPU_MF_INT_SF_PRA) {
1933                 if (cpuhw->flags & PMU_F_IN_USE)
1934                         if (SAMPL_DIAG_MODE(&cpuhw->event->hw))
1935                                 hw_collect_aux(cpuhw);
1936                         else
1937                                 hw_perf_event_update(cpuhw->event, 0);
1938                 else
1939                         WARN_ON_ONCE(!(cpuhw->flags & PMU_F_IN_USE));
1940         }
1941
1942         /* Report measurement alerts only for non-PRA codes */
1943         if (alert != CPU_MF_INT_SF_PRA)
1944                 debug_sprintf_event(sfdbg, 6, "measurement alert: 0x%x\n", alert);
1945
1946         /* Sampling authorization change request */
1947         if (alert & CPU_MF_INT_SF_SACA)
1948                 qsi(&cpuhw->qsi);
1949
1950         /* Loss of sample data due to high-priority machine activities */
1951         if (alert & CPU_MF_INT_SF_LSDA) {
1952                 pr_err("Sample data was lost\n");
1953                 cpuhw->flags |= PMU_F_ERR_LSDA;
1954                 sf_disable();
1955         }
1956
1957         /* Invalid sampling buffer entry */
1958         if (alert & (CPU_MF_INT_SF_IAE|CPU_MF_INT_SF_ISE)) {
1959                 pr_err("A sampling buffer entry is incorrect (alert=0x%x)\n",
1960                        alert);
1961                 cpuhw->flags |= PMU_F_ERR_IBE;
1962                 sf_disable();
1963         }
1964 }
1965 static int cpusf_pmu_setup(unsigned int cpu, int flags)
1966 {
1967         /* Ignore the notification if no events are scheduled on the PMU.
1968          * This might be racy...
1969          */
1970         if (!atomic_read(&num_events))
1971                 return 0;
1972
1973         local_irq_disable();
1974         setup_pmc_cpu(&flags);
1975         local_irq_enable();
1976         return 0;
1977 }
1978
1979 static int s390_pmu_sf_online_cpu(unsigned int cpu)
1980 {
1981         return cpusf_pmu_setup(cpu, PMC_INIT);
1982 }
1983
1984 static int s390_pmu_sf_offline_cpu(unsigned int cpu)
1985 {
1986         return cpusf_pmu_setup(cpu, PMC_RELEASE);
1987 }
1988
1989 static int param_get_sfb_size(char *buffer, const struct kernel_param *kp)
1990 {
1991         if (!cpum_sf_avail())
1992                 return -ENODEV;
1993         return sprintf(buffer, "%lu,%lu", CPUM_SF_MIN_SDB, CPUM_SF_MAX_SDB);
1994 }
1995
1996 static int param_set_sfb_size(const char *val, const struct kernel_param *kp)
1997 {
1998         int rc;
1999         unsigned long min, max;
2000
2001         if (!cpum_sf_avail())
2002                 return -ENODEV;
2003         if (!val || !strlen(val))
2004                 return -EINVAL;
2005
2006         /* Valid parameter values: "min,max" or "max" */
2007         min = CPUM_SF_MIN_SDB;
2008         max = CPUM_SF_MAX_SDB;
2009         if (strchr(val, ','))
2010                 rc = (sscanf(val, "%lu,%lu", &min, &max) == 2) ? 0 : -EINVAL;
2011         else
2012                 rc = kstrtoul(val, 10, &max);
2013
2014         if (min < 2 || min >= max || max > get_num_physpages())
2015                 rc = -EINVAL;
2016         if (rc)
2017                 return rc;
2018
2019         sfb_set_limits(min, max);
2020         pr_info("The sampling buffer limits have changed to: "
2021                 "min=%lu max=%lu (diag=x%lu)\n",
2022                 CPUM_SF_MIN_SDB, CPUM_SF_MAX_SDB, CPUM_SF_SDB_DIAG_FACTOR);
2023         return 0;
2024 }
2025
2026 #define param_check_sfb_size(name, p) __param_check(name, p, void)
2027 static const struct kernel_param_ops param_ops_sfb_size = {
2028         .set = param_set_sfb_size,
2029         .get = param_get_sfb_size,
2030 };
2031
2032 #define RS_INIT_FAILURE_QSI       0x0001
2033 #define RS_INIT_FAILURE_BSDES     0x0002
2034 #define RS_INIT_FAILURE_ALRT      0x0003
2035 #define RS_INIT_FAILURE_PERF      0x0004
2036 static void __init pr_cpumsf_err(unsigned int reason)
2037 {
2038         pr_err("Sampling facility support for perf is not available: "
2039                "reason=%04x\n", reason);
2040 }
2041
2042 static int __init init_cpum_sampling_pmu(void)
2043 {
2044         struct hws_qsi_info_block si;
2045         int err;
2046
2047         if (!cpum_sf_avail())
2048                 return -ENODEV;
2049
2050         memset(&si, 0, sizeof(si));
2051         if (qsi(&si)) {
2052                 pr_cpumsf_err(RS_INIT_FAILURE_QSI);
2053                 return -ENODEV;
2054         }
2055
2056         if (!si.as && !si.ad)
2057                 return -ENODEV;
2058
2059         if (si.bsdes != sizeof(struct hws_basic_entry)) {
2060                 pr_cpumsf_err(RS_INIT_FAILURE_BSDES);
2061                 return -EINVAL;
2062         }
2063
2064         if (si.ad) {
2065                 sfb_set_limits(CPUM_SF_MIN_SDB, CPUM_SF_MAX_SDB);
2066                 cpumsf_pmu_events_attr[1] =
2067                         CPUMF_EVENT_PTR(SF, SF_CYCLES_BASIC_DIAG);
2068         }
2069
2070         sfdbg = debug_register(KMSG_COMPONENT, 2, 1, 80);
2071         if (!sfdbg) {
2072                 pr_err("Registering for s390dbf failed\n");
2073                 return -ENOMEM;
2074         }
2075         debug_register_view(sfdbg, &debug_sprintf_view);
2076
2077         err = register_external_irq(EXT_IRQ_MEASURE_ALERT,
2078                                     cpumf_measurement_alert);
2079         if (err) {
2080                 pr_cpumsf_err(RS_INIT_FAILURE_ALRT);
2081                 debug_unregister(sfdbg);
2082                 goto out;
2083         }
2084
2085         err = perf_pmu_register(&cpumf_sampling, "cpum_sf", PERF_TYPE_RAW);
2086         if (err) {
2087                 pr_cpumsf_err(RS_INIT_FAILURE_PERF);
2088                 unregister_external_irq(EXT_IRQ_MEASURE_ALERT,
2089                                         cpumf_measurement_alert);
2090                 debug_unregister(sfdbg);
2091                 goto out;
2092         }
2093
2094         cpuhp_setup_state(CPUHP_AP_PERF_S390_SF_ONLINE, "perf/s390/sf:online",
2095                           s390_pmu_sf_online_cpu, s390_pmu_sf_offline_cpu);
2096 out:
2097         return err;
2098 }
2099 arch_initcall(init_cpum_sampling_pmu);
2100 core_param(cpum_sfb_size, CPUM_SF_MAX_SDB, sfb_size, 0644);