GNU Linux-libre 4.9.317-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 >= nr_cpumask_bits ||
844             (event->cpu >= 0 && !cpu_online(event->cpu)))
845                 return -ENODEV;
846
847         /* Force reset of idle/hv excludes regardless of what the
848          * user requested.
849          */
850         if (event->attr.exclude_hv)
851                 event->attr.exclude_hv = 0;
852         if (event->attr.exclude_idle)
853                 event->attr.exclude_idle = 0;
854
855         err = __hw_perf_event_init(event);
856         if (unlikely(err))
857                 if (event->destroy)
858                         event->destroy(event);
859         return err;
860 }
861
862 static void cpumsf_pmu_enable(struct pmu *pmu)
863 {
864         struct cpu_hw_sf *cpuhw = this_cpu_ptr(&cpu_hw_sf);
865         struct hw_perf_event *hwc;
866         int err;
867
868         if (cpuhw->flags & PMU_F_ENABLED)
869                 return;
870
871         if (cpuhw->flags & PMU_F_ERR_MASK)
872                 return;
873
874         /* Check whether to extent the sampling buffer.
875          *
876          * Two conditions trigger an increase of the sampling buffer for a
877          * perf event:
878          *    1. Postponed buffer allocations from the event initialization.
879          *    2. Sampling overflows that contribute to pending allocations.
880          *
881          * Note that the extend_sampling_buffer() function disables the sampling
882          * facility, but it can be fully re-enabled using sampling controls that
883          * have been saved in cpumsf_pmu_disable().
884          */
885         if (cpuhw->event) {
886                 hwc = &cpuhw->event->hw;
887                 /* Account number of overflow-designated buffer extents */
888                 sfb_account_overflows(cpuhw, hwc);
889                 if (sfb_has_pending_allocs(&cpuhw->sfb, hwc))
890                         extend_sampling_buffer(&cpuhw->sfb, hwc);
891         }
892
893         /* (Re)enable the PMU and sampling facility */
894         cpuhw->flags |= PMU_F_ENABLED;
895         barrier();
896
897         err = lsctl(&cpuhw->lsctl);
898         if (err) {
899                 cpuhw->flags &= ~PMU_F_ENABLED;
900                 pr_err("Loading sampling controls failed: op=%i err=%i\n",
901                         1, err);
902                 return;
903         }
904
905         debug_sprintf_event(sfdbg, 6, "pmu_enable: es=%i cs=%i ed=%i cd=%i "
906                             "tear=%p dear=%p\n", cpuhw->lsctl.es, cpuhw->lsctl.cs,
907                             cpuhw->lsctl.ed, cpuhw->lsctl.cd,
908                             (void *) cpuhw->lsctl.tear, (void *) cpuhw->lsctl.dear);
909 }
910
911 static void cpumsf_pmu_disable(struct pmu *pmu)
912 {
913         struct cpu_hw_sf *cpuhw = this_cpu_ptr(&cpu_hw_sf);
914         struct hws_lsctl_request_block inactive;
915         struct hws_qsi_info_block si;
916         int err;
917
918         if (!(cpuhw->flags & PMU_F_ENABLED))
919                 return;
920
921         if (cpuhw->flags & PMU_F_ERR_MASK)
922                 return;
923
924         /* Switch off sampling activation control */
925         inactive = cpuhw->lsctl;
926         inactive.cs = 0;
927         inactive.cd = 0;
928
929         err = lsctl(&inactive);
930         if (err) {
931                 pr_err("Loading sampling controls failed: op=%i err=%i\n",
932                         2, err);
933                 return;
934         }
935
936         /* Save state of TEAR and DEAR register contents */
937         if (!qsi(&si)) {
938                 /* TEAR/DEAR values are valid only if the sampling facility is
939                  * enabled.  Note that cpumsf_pmu_disable() might be called even
940                  * for a disabled sampling facility because cpumsf_pmu_enable()
941                  * controls the enable/disable state.
942                  */
943                 if (si.es) {
944                         cpuhw->lsctl.tear = si.tear;
945                         cpuhw->lsctl.dear = si.dear;
946                 }
947         } else
948                 debug_sprintf_event(sfdbg, 3, "cpumsf_pmu_disable: "
949                                     "qsi() failed with err=%i\n", err);
950
951         cpuhw->flags &= ~PMU_F_ENABLED;
952 }
953
954 /* perf_exclude_event() - Filter event
955  * @event:      The perf event
956  * @regs:       pt_regs structure
957  * @sde_regs:   Sample-data-entry (sde) regs structure
958  *
959  * Filter perf events according to their exclude specification.
960  *
961  * Return non-zero if the event shall be excluded.
962  */
963 static int perf_exclude_event(struct perf_event *event, struct pt_regs *regs,
964                               struct perf_sf_sde_regs *sde_regs)
965 {
966         if (event->attr.exclude_user && user_mode(regs))
967                 return 1;
968         if (event->attr.exclude_kernel && !user_mode(regs))
969                 return 1;
970         if (event->attr.exclude_guest && sde_regs->in_guest)
971                 return 1;
972         if (event->attr.exclude_host && !sde_regs->in_guest)
973                 return 1;
974         return 0;
975 }
976
977 /* perf_push_sample() - Push samples to perf
978  * @event:      The perf event
979  * @sample:     Hardware sample data
980  *
981  * Use the hardware sample data to create perf event sample.  The sample
982  * is the pushed to the event subsystem and the function checks for
983  * possible event overflows.  If an event overflow occurs, the PMU is
984  * stopped.
985  *
986  * Return non-zero if an event overflow occurred.
987  */
988 static int perf_push_sample(struct perf_event *event, struct sf_raw_sample *sfr)
989 {
990         int overflow;
991         struct pt_regs regs;
992         struct perf_sf_sde_regs *sde_regs;
993         struct perf_sample_data data;
994         struct perf_raw_record raw = {
995                 .frag = {
996                         .size = sfr->size,
997                         .data = sfr,
998                 },
999         };
1000
1001         /* Setup perf sample */
1002         perf_sample_data_init(&data, 0, event->hw.last_period);
1003         data.raw = &raw;
1004
1005         /* Setup pt_regs to look like an CPU-measurement external interrupt
1006          * using the Program Request Alert code.  The regs.int_parm_long
1007          * field which is unused contains additional sample-data-entry related
1008          * indicators.
1009          */
1010         memset(&regs, 0, sizeof(regs));
1011         regs.int_code = 0x1407;
1012         regs.int_parm = CPU_MF_INT_SF_PRA;
1013         sde_regs = (struct perf_sf_sde_regs *) &regs.int_parm_long;
1014
1015         regs.psw.addr = sfr->basic.ia;
1016         if (sfr->basic.T)
1017                 regs.psw.mask |= PSW_MASK_DAT;
1018         if (sfr->basic.W)
1019                 regs.psw.mask |= PSW_MASK_WAIT;
1020         if (sfr->basic.P)
1021                 regs.psw.mask |= PSW_MASK_PSTATE;
1022         switch (sfr->basic.AS) {
1023         case 0x0:
1024                 regs.psw.mask |= PSW_ASC_PRIMARY;
1025                 break;
1026         case 0x1:
1027                 regs.psw.mask |= PSW_ASC_ACCREG;
1028                 break;
1029         case 0x2:
1030                 regs.psw.mask |= PSW_ASC_SECONDARY;
1031                 break;
1032         case 0x3:
1033                 regs.psw.mask |= PSW_ASC_HOME;
1034                 break;
1035         }
1036
1037         /*
1038          * A non-zero guest program parameter indicates a guest
1039          * sample.
1040          * Note that some early samples or samples from guests without
1041          * lpp usage would be misaccounted to the host. We use the asn
1042          * value as a heuristic to detect most of these guest samples.
1043          * If the value differs from the host hpp value, we assume
1044          * it to be a KVM guest.
1045          */
1046         if (sfr->basic.gpp || sfr->basic.prim_asn != (u16) sfr->basic.hpp)
1047                 sde_regs->in_guest = 1;
1048
1049         overflow = 0;
1050         if (perf_exclude_event(event, &regs, sde_regs))
1051                 goto out;
1052         if (perf_event_overflow(event, &data, &regs)) {
1053                 overflow = 1;
1054                 event->pmu->stop(event, 0);
1055         }
1056         perf_event_update_userpage(event);
1057 out:
1058         return overflow;
1059 }
1060
1061 static void perf_event_count_update(struct perf_event *event, u64 count)
1062 {
1063         local64_add(count, &event->count);
1064 }
1065
1066 static int sample_format_is_valid(struct hws_combined_entry *sample,
1067                                    unsigned int flags)
1068 {
1069         if (likely(flags & PERF_CPUM_SF_BASIC_MODE))
1070                 /* Only basic-sampling data entries with data-entry-format
1071                  * version of 0x0001 can be processed.
1072                  */
1073                 if (sample->basic.def != 0x0001)
1074                         return 0;
1075         if (flags & PERF_CPUM_SF_DIAG_MODE)
1076                 /* The data-entry-format number of diagnostic-sampling data
1077                  * entries can vary.  Because diagnostic data is just passed
1078                  * through, do only a sanity check on the DEF.
1079                  */
1080                 if (sample->diag.def < 0x8001)
1081                         return 0;
1082         return 1;
1083 }
1084
1085 static int sample_is_consistent(struct hws_combined_entry *sample,
1086                                 unsigned long flags)
1087 {
1088         /* This check applies only to basic-sampling data entries of potentially
1089          * combined-sampling data entries.  Invalid entries cannot be processed
1090          * by the PMU and, thus, do not deliver an associated
1091          * diagnostic-sampling data entry.
1092          */
1093         if (unlikely(!(flags & PERF_CPUM_SF_BASIC_MODE)))
1094                 return 0;
1095         /*
1096          * Samples are skipped, if they are invalid or for which the
1097          * instruction address is not predictable, i.e., the wait-state bit is
1098          * set.
1099          */
1100         if (sample->basic.I || sample->basic.W)
1101                 return 0;
1102         return 1;
1103 }
1104
1105 static void reset_sample_slot(struct hws_combined_entry *sample,
1106                               unsigned long flags)
1107 {
1108         if (likely(flags & PERF_CPUM_SF_BASIC_MODE))
1109                 sample->basic.def = 0;
1110         if (flags & PERF_CPUM_SF_DIAG_MODE)
1111                 sample->diag.def = 0;
1112 }
1113
1114 static void sfr_store_sample(struct sf_raw_sample *sfr,
1115                              struct hws_combined_entry *sample)
1116 {
1117         if (likely(sfr->format & PERF_CPUM_SF_BASIC_MODE))
1118                 sfr->basic = sample->basic;
1119         if (sfr->format & PERF_CPUM_SF_DIAG_MODE)
1120                 memcpy(&sfr->diag, &sample->diag, sfr->dsdes);
1121 }
1122
1123 static void debug_sample_entry(struct hws_combined_entry *sample,
1124                                struct hws_trailer_entry *te,
1125                                unsigned long flags)
1126 {
1127         debug_sprintf_event(sfdbg, 4, "hw_collect_samples: Found unknown "
1128                             "sampling data entry: te->f=%i basic.def=%04x (%p)"
1129                             " diag.def=%04x (%p)\n", te->f,
1130                             sample->basic.def, &sample->basic,
1131                             (flags & PERF_CPUM_SF_DIAG_MODE)
1132                                         ? sample->diag.def : 0xFFFF,
1133                             (flags & PERF_CPUM_SF_DIAG_MODE)
1134                                         ?  &sample->diag : NULL);
1135 }
1136
1137 /* hw_collect_samples() - Walk through a sample-data-block and collect samples
1138  * @event:      The perf event
1139  * @sdbt:       Sample-data-block table
1140  * @overflow:   Event overflow counter
1141  *
1142  * Walks through a sample-data-block and collects sampling data entries that are
1143  * then pushed to the perf event subsystem.  Depending on the sampling function,
1144  * there can be either basic-sampling or combined-sampling data entries.  A
1145  * combined-sampling data entry consists of a basic- and a diagnostic-sampling
1146  * data entry.  The sampling function is determined by the flags in the perf
1147  * event hardware structure.  The function always works with a combined-sampling
1148  * data entry but ignores the the diagnostic portion if it is not available.
1149  *
1150  * Note that the implementation focuses on basic-sampling data entries and, if
1151  * such an entry is not valid, the entire combined-sampling data entry is
1152  * ignored.
1153  *
1154  * The overflow variables counts the number of samples that has been discarded
1155  * due to a perf event overflow.
1156  */
1157 static void hw_collect_samples(struct perf_event *event, unsigned long *sdbt,
1158                                unsigned long long *overflow)
1159 {
1160         unsigned long flags = SAMPL_FLAGS(&event->hw);
1161         struct hws_combined_entry *sample;
1162         struct hws_trailer_entry *te;
1163         struct sf_raw_sample *sfr;
1164         size_t sample_size;
1165
1166         /* Prepare and initialize raw sample data */
1167         sfr = (struct sf_raw_sample *) RAWSAMPLE_REG(&event->hw);
1168         sfr->format = flags & PERF_CPUM_SF_MODE_MASK;
1169
1170         sample_size = event_sample_size(&event->hw);
1171         te = (struct hws_trailer_entry *) trailer_entry_ptr(*sdbt);
1172         sample = (struct hws_combined_entry *) *sdbt;
1173         while ((unsigned long *) sample < (unsigned long *) te) {
1174                 /* Check for an empty sample */
1175                 if (!sample->basic.def)
1176                         break;
1177
1178                 /* Update perf event period */
1179                 perf_event_count_update(event, SAMPL_RATE(&event->hw));
1180
1181                 /* Check sampling data entry */
1182                 if (sample_format_is_valid(sample, flags)) {
1183                         /* If an event overflow occurred, the PMU is stopped to
1184                          * throttle event delivery.  Remaining sample data is
1185                          * discarded.
1186                          */
1187                         if (!*overflow) {
1188                                 if (sample_is_consistent(sample, flags)) {
1189                                         /* Deliver sample data to perf */
1190                                         sfr_store_sample(sfr, sample);
1191                                         *overflow = perf_push_sample(event, sfr);
1192                                 }
1193                         } else
1194                                 /* Count discarded samples */
1195                                 *overflow += 1;
1196                 } else {
1197                         debug_sample_entry(sample, te, flags);
1198                         /* Sample slot is not yet written or other record.
1199                          *
1200                          * This condition can occur if the buffer was reused
1201                          * from a combined basic- and diagnostic-sampling.
1202                          * If only basic-sampling is then active, entries are
1203                          * written into the larger diagnostic entries.
1204                          * This is typically the case for sample-data-blocks
1205                          * that are not full.  Stop processing if the first
1206                          * invalid format was detected.
1207                          */
1208                         if (!te->f)
1209                                 break;
1210                 }
1211
1212                 /* Reset sample slot and advance to next sample */
1213                 reset_sample_slot(sample, flags);
1214                 sample += sample_size;
1215         }
1216 }
1217
1218 /* hw_perf_event_update() - Process sampling buffer
1219  * @event:      The perf event
1220  * @flush_all:  Flag to also flush partially filled sample-data-blocks
1221  *
1222  * Processes the sampling buffer and create perf event samples.
1223  * The sampling buffer position are retrieved and saved in the TEAR_REG
1224  * register of the specified perf event.
1225  *
1226  * Only full sample-data-blocks are processed.  Specify the flash_all flag
1227  * to also walk through partially filled sample-data-blocks.  It is ignored
1228  * if PERF_CPUM_SF_FULL_BLOCKS is set.  The PERF_CPUM_SF_FULL_BLOCKS flag
1229  * enforces the processing of full sample-data-blocks only (trailer entries
1230  * with the block-full-indicator bit set).
1231  */
1232 static void hw_perf_event_update(struct perf_event *event, int flush_all)
1233 {
1234         struct hw_perf_event *hwc = &event->hw;
1235         struct hws_trailer_entry *te;
1236         unsigned long *sdbt;
1237         unsigned long long event_overflow, sampl_overflow, num_sdb, te_flags;
1238         int done;
1239
1240         if (flush_all && SDB_FULL_BLOCKS(hwc))
1241                 flush_all = 0;
1242
1243         sdbt = (unsigned long *) TEAR_REG(hwc);
1244         done = event_overflow = sampl_overflow = num_sdb = 0;
1245         while (!done) {
1246                 /* Get the trailer entry of the sample-data-block */
1247                 te = (struct hws_trailer_entry *) trailer_entry_ptr(*sdbt);
1248
1249                 /* Leave loop if no more work to do (block full indicator) */
1250                 if (!te->f) {
1251                         done = 1;
1252                         if (!flush_all)
1253                                 break;
1254                 }
1255
1256                 /* Check the sample overflow count */
1257                 if (te->overflow)
1258                         /* Account sample overflows and, if a particular limit
1259                          * is reached, extend the sampling buffer.
1260                          * For details, see sfb_account_overflows().
1261                          */
1262                         sampl_overflow += te->overflow;
1263
1264                 /* Timestamps are valid for full sample-data-blocks only */
1265                 debug_sprintf_event(sfdbg, 6, "hw_perf_event_update: sdbt=%p "
1266                                     "overflow=%llu timestamp=0x%llx\n",
1267                                     sdbt, te->overflow,
1268                                     (te->f) ? trailer_timestamp(te) : 0ULL);
1269
1270                 /* Collect all samples from a single sample-data-block and
1271                  * flag if an (perf) event overflow happened.  If so, the PMU
1272                  * is stopped and remaining samples will be discarded.
1273                  */
1274                 hw_collect_samples(event, sdbt, &event_overflow);
1275                 num_sdb++;
1276
1277                 /* Reset trailer (using compare-double-and-swap) */
1278                 do {
1279                         te_flags = te->flags & ~SDB_TE_BUFFER_FULL_MASK;
1280                         te_flags |= SDB_TE_ALERT_REQ_MASK;
1281                 } while (!cmpxchg_double(&te->flags, &te->overflow,
1282                                          te->flags, te->overflow,
1283                                          te_flags, 0ULL));
1284
1285                 /* Advance to next sample-data-block */
1286                 sdbt++;
1287                 if (is_link_entry(sdbt))
1288                         sdbt = get_next_sdbt(sdbt);
1289
1290                 /* Update event hardware registers */
1291                 TEAR_REG(hwc) = (unsigned long) sdbt;
1292
1293                 /* Stop processing sample-data if all samples of the current
1294                  * sample-data-block were flushed even if it was not full.
1295                  */
1296                 if (flush_all && done)
1297                         break;
1298         }
1299
1300         /* Account sample overflows in the event hardware structure */
1301         if (sampl_overflow)
1302                 OVERFLOW_REG(hwc) = DIV_ROUND_UP(OVERFLOW_REG(hwc) +
1303                                                  sampl_overflow, 1 + num_sdb);
1304
1305         /* Perf_event_overflow() and perf_event_account_interrupt() limit
1306          * the interrupt rate to an upper limit. Roughly 1000 samples per
1307          * task tick.
1308          * Hitting this limit results in a large number
1309          * of throttled REF_REPORT_THROTTLE entries and the samples
1310          * are dropped.
1311          * Slightly increase the interval to avoid hitting this limit.
1312          */
1313         if (event_overflow) {
1314                 SAMPL_RATE(hwc) += DIV_ROUND_UP(SAMPL_RATE(hwc), 10);
1315                 debug_sprintf_event(sfdbg, 1, "%s: rate adjustment %ld\n",
1316                                     __func__,
1317                                     DIV_ROUND_UP(SAMPL_RATE(hwc), 10));
1318         }
1319
1320         if (sampl_overflow || event_overflow)
1321                 debug_sprintf_event(sfdbg, 4, "hw_perf_event_update: "
1322                                     "overflow stats: sample=%llu event=%llu\n",
1323                                     sampl_overflow, event_overflow);
1324 }
1325
1326 static void cpumsf_pmu_read(struct perf_event *event)
1327 {
1328         /* Nothing to do ... updates are interrupt-driven */
1329 }
1330
1331 /* Activate sampling control.
1332  * Next call of pmu_enable() starts sampling.
1333  */
1334 static void cpumsf_pmu_start(struct perf_event *event, int flags)
1335 {
1336         struct cpu_hw_sf *cpuhw = this_cpu_ptr(&cpu_hw_sf);
1337
1338         if (WARN_ON_ONCE(!(event->hw.state & PERF_HES_STOPPED)))
1339                 return;
1340
1341         if (flags & PERF_EF_RELOAD)
1342                 WARN_ON_ONCE(!(event->hw.state & PERF_HES_UPTODATE));
1343
1344         perf_pmu_disable(event->pmu);
1345         event->hw.state = 0;
1346         cpuhw->lsctl.cs = 1;
1347         if (SAMPL_DIAG_MODE(&event->hw))
1348                 cpuhw->lsctl.cd = 1;
1349         perf_pmu_enable(event->pmu);
1350 }
1351
1352 /* Deactivate sampling control.
1353  * Next call of pmu_enable() stops sampling.
1354  */
1355 static void cpumsf_pmu_stop(struct perf_event *event, int flags)
1356 {
1357         struct cpu_hw_sf *cpuhw = this_cpu_ptr(&cpu_hw_sf);
1358
1359         if (event->hw.state & PERF_HES_STOPPED)
1360                 return;
1361
1362         perf_pmu_disable(event->pmu);
1363         cpuhw->lsctl.cs = 0;
1364         cpuhw->lsctl.cd = 0;
1365         event->hw.state |= PERF_HES_STOPPED;
1366
1367         if ((flags & PERF_EF_UPDATE) && !(event->hw.state & PERF_HES_UPTODATE)) {
1368                 hw_perf_event_update(event, 1);
1369                 event->hw.state |= PERF_HES_UPTODATE;
1370         }
1371         perf_pmu_enable(event->pmu);
1372 }
1373
1374 static int cpumsf_pmu_add(struct perf_event *event, int flags)
1375 {
1376         struct cpu_hw_sf *cpuhw = this_cpu_ptr(&cpu_hw_sf);
1377         int err;
1378
1379         if (cpuhw->flags & PMU_F_IN_USE)
1380                 return -EAGAIN;
1381
1382         if (!cpuhw->sfb.sdbt)
1383                 return -EINVAL;
1384
1385         err = 0;
1386         perf_pmu_disable(event->pmu);
1387
1388         event->hw.state = PERF_HES_UPTODATE | PERF_HES_STOPPED;
1389
1390         /* Set up sampling controls.  Always program the sampling register
1391          * using the SDB-table start.  Reset TEAR_REG event hardware register
1392          * that is used by hw_perf_event_update() to store the sampling buffer
1393          * position after samples have been flushed.
1394          */
1395         cpuhw->lsctl.s = 0;
1396         cpuhw->lsctl.h = 1;
1397         cpuhw->lsctl.tear = (unsigned long) cpuhw->sfb.sdbt;
1398         cpuhw->lsctl.dear = *(unsigned long *) cpuhw->sfb.sdbt;
1399         cpuhw->lsctl.interval = SAMPL_RATE(&event->hw);
1400         hw_reset_registers(&event->hw, cpuhw->sfb.sdbt);
1401
1402         /* Ensure sampling functions are in the disabled state.  If disabled,
1403          * switch on sampling enable control. */
1404         if (WARN_ON_ONCE(cpuhw->lsctl.es == 1 || cpuhw->lsctl.ed == 1)) {
1405                 err = -EAGAIN;
1406                 goto out;
1407         }
1408         cpuhw->lsctl.es = 1;
1409         if (SAMPL_DIAG_MODE(&event->hw))
1410                 cpuhw->lsctl.ed = 1;
1411
1412         /* Set in_use flag and store event */
1413         cpuhw->event = event;
1414         cpuhw->flags |= PMU_F_IN_USE;
1415
1416         if (flags & PERF_EF_START)
1417                 cpumsf_pmu_start(event, PERF_EF_RELOAD);
1418 out:
1419         perf_event_update_userpage(event);
1420         perf_pmu_enable(event->pmu);
1421         return err;
1422 }
1423
1424 static void cpumsf_pmu_del(struct perf_event *event, int flags)
1425 {
1426         struct cpu_hw_sf *cpuhw = this_cpu_ptr(&cpu_hw_sf);
1427
1428         perf_pmu_disable(event->pmu);
1429         cpumsf_pmu_stop(event, PERF_EF_UPDATE);
1430
1431         cpuhw->lsctl.es = 0;
1432         cpuhw->lsctl.ed = 0;
1433         cpuhw->flags &= ~PMU_F_IN_USE;
1434         cpuhw->event = NULL;
1435
1436         perf_event_update_userpage(event);
1437         perf_pmu_enable(event->pmu);
1438 }
1439
1440 CPUMF_EVENT_ATTR(SF, SF_CYCLES_BASIC, PERF_EVENT_CPUM_SF);
1441 CPUMF_EVENT_ATTR(SF, SF_CYCLES_BASIC_DIAG, PERF_EVENT_CPUM_SF_DIAG);
1442
1443 static struct attribute *cpumsf_pmu_events_attr[] = {
1444         CPUMF_EVENT_PTR(SF, SF_CYCLES_BASIC),
1445         NULL,
1446         NULL,
1447 };
1448
1449 PMU_FORMAT_ATTR(event, "config:0-63");
1450
1451 static struct attribute *cpumsf_pmu_format_attr[] = {
1452         &format_attr_event.attr,
1453         NULL,
1454 };
1455
1456 static struct attribute_group cpumsf_pmu_events_group = {
1457         .name = "events",
1458         .attrs = cpumsf_pmu_events_attr,
1459 };
1460 static struct attribute_group cpumsf_pmu_format_group = {
1461         .name = "format",
1462         .attrs = cpumsf_pmu_format_attr,
1463 };
1464 static const struct attribute_group *cpumsf_pmu_attr_groups[] = {
1465         &cpumsf_pmu_events_group,
1466         &cpumsf_pmu_format_group,
1467         NULL,
1468 };
1469
1470 static struct pmu cpumf_sampling = {
1471         .pmu_enable   = cpumsf_pmu_enable,
1472         .pmu_disable  = cpumsf_pmu_disable,
1473
1474         .event_init   = cpumsf_pmu_event_init,
1475         .add          = cpumsf_pmu_add,
1476         .del          = cpumsf_pmu_del,
1477
1478         .start        = cpumsf_pmu_start,
1479         .stop         = cpumsf_pmu_stop,
1480         .read         = cpumsf_pmu_read,
1481
1482         .attr_groups  = cpumsf_pmu_attr_groups,
1483 };
1484
1485 static void cpumf_measurement_alert(struct ext_code ext_code,
1486                                     unsigned int alert, unsigned long unused)
1487 {
1488         struct cpu_hw_sf *cpuhw;
1489
1490         if (!(alert & CPU_MF_INT_SF_MASK))
1491                 return;
1492         inc_irq_stat(IRQEXT_CMS);
1493         cpuhw = this_cpu_ptr(&cpu_hw_sf);
1494
1495         /* Measurement alerts are shared and might happen when the PMU
1496          * is not reserved.  Ignore these alerts in this case. */
1497         if (!(cpuhw->flags & PMU_F_RESERVED))
1498                 return;
1499
1500         /* The processing below must take care of multiple alert events that
1501          * might be indicated concurrently. */
1502
1503         /* Program alert request */
1504         if (alert & CPU_MF_INT_SF_PRA) {
1505                 if (cpuhw->flags & PMU_F_IN_USE)
1506                         hw_perf_event_update(cpuhw->event, 0);
1507                 else
1508                         WARN_ON_ONCE(!(cpuhw->flags & PMU_F_IN_USE));
1509         }
1510
1511         /* Report measurement alerts only for non-PRA codes */
1512         if (alert != CPU_MF_INT_SF_PRA)
1513                 debug_sprintf_event(sfdbg, 6, "measurement alert: 0x%x\n", alert);
1514
1515         /* Sampling authorization change request */
1516         if (alert & CPU_MF_INT_SF_SACA)
1517                 qsi(&cpuhw->qsi);
1518
1519         /* Loss of sample data due to high-priority machine activities */
1520         if (alert & CPU_MF_INT_SF_LSDA) {
1521                 pr_err("Sample data was lost\n");
1522                 cpuhw->flags |= PMU_F_ERR_LSDA;
1523                 sf_disable();
1524         }
1525
1526         /* Invalid sampling buffer entry */
1527         if (alert & (CPU_MF_INT_SF_IAE|CPU_MF_INT_SF_ISE)) {
1528                 pr_err("A sampling buffer entry is incorrect (alert=0x%x)\n",
1529                        alert);
1530                 cpuhw->flags |= PMU_F_ERR_IBE;
1531                 sf_disable();
1532         }
1533 }
1534 static int cpusf_pmu_setup(unsigned int cpu, int flags)
1535 {
1536         /* Ignore the notification if no events are scheduled on the PMU.
1537          * This might be racy...
1538          */
1539         if (!atomic_read(&num_events))
1540                 return 0;
1541
1542         local_irq_disable();
1543         setup_pmc_cpu(&flags);
1544         local_irq_enable();
1545         return 0;
1546 }
1547
1548 static int s390_pmu_sf_online_cpu(unsigned int cpu)
1549 {
1550         return cpusf_pmu_setup(cpu, PMC_INIT);
1551 }
1552
1553 static int s390_pmu_sf_offline_cpu(unsigned int cpu)
1554 {
1555         return cpusf_pmu_setup(cpu, PMC_RELEASE);
1556 }
1557
1558 static int param_get_sfb_size(char *buffer, const struct kernel_param *kp)
1559 {
1560         if (!cpum_sf_avail())
1561                 return -ENODEV;
1562         return sprintf(buffer, "%lu,%lu", CPUM_SF_MIN_SDB, CPUM_SF_MAX_SDB);
1563 }
1564
1565 static int param_set_sfb_size(const char *val, const struct kernel_param *kp)
1566 {
1567         int rc;
1568         unsigned long min, max;
1569
1570         if (!cpum_sf_avail())
1571                 return -ENODEV;
1572         if (!val || !strlen(val))
1573                 return -EINVAL;
1574
1575         /* Valid parameter values: "min,max" or "max" */
1576         min = CPUM_SF_MIN_SDB;
1577         max = CPUM_SF_MAX_SDB;
1578         if (strchr(val, ','))
1579                 rc = (sscanf(val, "%lu,%lu", &min, &max) == 2) ? 0 : -EINVAL;
1580         else
1581                 rc = kstrtoul(val, 10, &max);
1582
1583         if (min < 2 || min >= max || max > get_num_physpages())
1584                 rc = -EINVAL;
1585         if (rc)
1586                 return rc;
1587
1588         sfb_set_limits(min, max);
1589         pr_info("The sampling buffer limits have changed to: "
1590                 "min=%lu max=%lu (diag=x%lu)\n",
1591                 CPUM_SF_MIN_SDB, CPUM_SF_MAX_SDB, CPUM_SF_SDB_DIAG_FACTOR);
1592         return 0;
1593 }
1594
1595 #define param_check_sfb_size(name, p) __param_check(name, p, void)
1596 static const struct kernel_param_ops param_ops_sfb_size = {
1597         .set = param_set_sfb_size,
1598         .get = param_get_sfb_size,
1599 };
1600
1601 #define RS_INIT_FAILURE_QSI       0x0001
1602 #define RS_INIT_FAILURE_BSDES     0x0002
1603 #define RS_INIT_FAILURE_ALRT      0x0003
1604 #define RS_INIT_FAILURE_PERF      0x0004
1605 static void __init pr_cpumsf_err(unsigned int reason)
1606 {
1607         pr_err("Sampling facility support for perf is not available: "
1608                "reason=%04x\n", reason);
1609 }
1610
1611 static int __init init_cpum_sampling_pmu(void)
1612 {
1613         struct hws_qsi_info_block si;
1614         int err;
1615
1616         if (!cpum_sf_avail())
1617                 return -ENODEV;
1618
1619         memset(&si, 0, sizeof(si));
1620         if (qsi(&si)) {
1621                 pr_cpumsf_err(RS_INIT_FAILURE_QSI);
1622                 return -ENODEV;
1623         }
1624
1625         if (si.bsdes != sizeof(struct hws_basic_entry)) {
1626                 pr_cpumsf_err(RS_INIT_FAILURE_BSDES);
1627                 return -EINVAL;
1628         }
1629
1630         if (si.ad) {
1631                 sfb_set_limits(CPUM_SF_MIN_SDB, CPUM_SF_MAX_SDB);
1632                 cpumsf_pmu_events_attr[1] =
1633                         CPUMF_EVENT_PTR(SF, SF_CYCLES_BASIC_DIAG);
1634         }
1635
1636         sfdbg = debug_register(KMSG_COMPONENT, 2, 1, 80);
1637         if (!sfdbg) {
1638                 pr_err("Registering for s390dbf failed\n");
1639                 return -ENOMEM;
1640         }
1641         debug_register_view(sfdbg, &debug_sprintf_view);
1642
1643         err = register_external_irq(EXT_IRQ_MEASURE_ALERT,
1644                                     cpumf_measurement_alert);
1645         if (err) {
1646                 pr_cpumsf_err(RS_INIT_FAILURE_ALRT);
1647                 debug_unregister(sfdbg);
1648                 goto out;
1649         }
1650
1651         err = perf_pmu_register(&cpumf_sampling, "cpum_sf", PERF_TYPE_RAW);
1652         if (err) {
1653                 pr_cpumsf_err(RS_INIT_FAILURE_PERF);
1654                 unregister_external_irq(EXT_IRQ_MEASURE_ALERT,
1655                                         cpumf_measurement_alert);
1656                 debug_unregister(sfdbg);
1657                 goto out;
1658         }
1659
1660         cpuhp_setup_state(CPUHP_AP_PERF_S390_SF_ONLINE, "AP_PERF_S390_SF_ONLINE",
1661                           s390_pmu_sf_online_cpu, s390_pmu_sf_offline_cpu);
1662 out:
1663         return err;
1664 }
1665 arch_initcall(init_cpum_sampling_pmu);
1666 core_param(cpum_sfb_size, CPUM_SF_MAX_SDB, sfb_size, 0644);