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