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