USB: cdc-wdm: Make wdm_flush() interruptible and add wdm_fsync().
[linux/fpc-iii.git] / arch / s390 / kernel / perf_cpum_sf.c
blob4a76b381d25aa712b957529b5fb5be88fadab541
1 /*
2 * Performance event support for the System z CPU-measurement Sampling Facility
4 * Copyright IBM Corp. 2013
5 * Author(s): Hendrik Brueckner <brueckner@linux.vnet.ibm.com>
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.
11 #define KMSG_COMPONENT "cpum_sf"
12 #define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
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>
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.
32 #define CPUM_SF_MIN_SDBT 1
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.
38 #define CPUM_SF_SDB_PER_TABLE ((PAGE_SIZE - 8) / 8)
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.
44 #define CPUM_SF_SDBT_TL_OFFSET (CPUM_SF_SDB_PER_TABLE * 8)
45 static inline int require_table_link(const void *sdbt)
47 return ((unsigned long) sdbt & ~PAGE_MASK) == CPUM_SF_SDBT_TL_OFFSET;
50 /* Minimum and maximum sampling buffer sizes:
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.
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
64 * 32MB == 8192 pages (4KB per page)
65 * 16 pages for SDB-tables
66 * 8176 pages for SDBs
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;
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 */
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 */
89 static DEFINE_PER_CPU(struct cpu_hw_sf, cpu_hw_sf);
91 /* Debug feature */
92 static debug_info_t *sfdbg;
95 * sf_disable() - Switch off sampling facility
97 static int sf_disable(void)
99 struct hws_lsctl_request_block sreq;
101 memset(&sreq, 0, sizeof(sreq));
102 return lsctl(&sreq);
106 * sf_buffer_available() - Check for an allocated sampling buffer
108 static int sf_buffer_available(struct cpu_hw_sf *cpuhw)
110 return !!cpuhw->sfb.sdbt;
114 * deallocate sampling facility buffer
116 static void free_sampling_buffer(struct sf_buffer *sfb)
118 unsigned long *sdbt, *curr;
120 if (!sfb->sdbt)
121 return;
123 sdbt = sfb->sdbt;
124 curr = sdbt;
126 /* Free the SDBT after all SDBs are processed... */
127 while (1) {
128 if (!*curr || !sdbt)
129 break;
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);
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++;
151 debug_sprintf_event(sfdbg, 5,
152 "free_sampling_buffer: freed sdbt=%p\n", sfb->sdbt);
153 memset(sfb, 0, sizeof(*sfb));
156 static int alloc_sample_data_block(unsigned long *sdbt, gfp_t gfp_flags)
158 unsigned long sdb, *trailer;
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;
167 /* Link SDB into the sample-data-block-table */
168 *sdbt = sdb;
170 return 0;
174 * realloc_sampling_buffer() - extend sampler memory
176 * Allocates new sample-data-blocks and adds them to the specified sampling
177 * buffer memory.
179 * Important: This modifies the sampling buffer and must be called when the
180 * sampling facility is disabled.
182 * Returns zero on success, non-zero otherwise.
184 static int realloc_sampling_buffer(struct sf_buffer *sfb,
185 unsigned long num_sdb, gfp_t gfp_flags)
187 int i, rc;
188 unsigned long *new, *tail, *tail_prev = NULL;
190 if (!sfb->sdbt || !sfb->tail)
191 return -EINVAL;
193 if (!is_link_entry(sfb->tail))
194 return -EINVAL;
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.
201 tail = sfb->tail;
203 /* Do a sanity check whether the table-link entry points to
204 * the sampling buffer origin.
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;
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;
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;
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.
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.
243 if (tail_prev) {
244 sfb->num_sdbt--;
245 free_page((unsigned long) new);
246 tail = tail_prev;
248 break;
250 sfb->num_sdb++;
251 tail++;
252 tail_prev = new = NULL; /* Allocated at least one SBD */
255 /* Link sampling buffer to its origin */
256 *tail = (unsigned long) sfb->sdbt + 1;
257 sfb->tail = tail;
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;
266 * allocate_sampling_buffer() - allocate sampler memory
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.
274 * Returns zero on success, non-zero otherwise.
276 static int alloc_sampling_buffer(struct sf_buffer *sfb, unsigned long num_sdb)
278 int rc;
280 if (sfb->sdbt)
281 return -EINVAL;
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;
290 /* Link the table origin to point to itself to prepare for
291 * realloc_sampling_buffer() invocation.
293 sfb->tail = sfb->sdbt;
294 *sfb->tail = (unsigned long)(void *) sfb->sdbt + 1;
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;
309 static void sfb_set_limits(unsigned long min, unsigned long max)
311 struct hws_qsi_info_block si;
313 CPUM_SF_MIN_SDB = min;
314 CPUM_SF_MAX_SDB = max;
316 memset(&si, 0, sizeof(si));
317 if (!qsi(&si))
318 CPUM_SF_SDB_DIAG_FACTOR = DIV_ROUND_UP(si.dsdes, si.bsdes);
321 static unsigned long sfb_max_limit(struct hw_perf_event *hwc)
323 return SAMPL_DIAG_MODE(hwc) ? CPUM_SF_MAX_SDB * CPUM_SF_SDB_DIAG_FACTOR
324 : CPUM_SF_MAX_SDB;
327 static unsigned long sfb_pending_allocs(struct sf_buffer *sfb,
328 struct hw_perf_event *hwc)
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;
337 static int sfb_has_pending_allocs(struct sf_buffer *sfb,
338 struct hw_perf_event *hwc)
340 return sfb_pending_allocs(sfb, hwc) > 0;
343 static void sfb_account_allocs(unsigned long num, struct hw_perf_event *hwc)
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;
351 static void sfb_init_allocs(unsigned long num, struct hw_perf_event *hwc)
353 SFB_ALLOC_REG(hwc) = 0;
354 sfb_account_allocs(num, hwc);
357 static size_t event_sample_size(struct hw_perf_event *hwc)
359 struct sf_raw_sample *sfr = (struct sf_raw_sample *) RAWSAMPLE_REG(hwc);
360 size_t sample_size;
362 /* The sample size depends on the sampling function: The basic-sampling
363 * function must be always enabled, diagnostic-sampling function is
364 * optional.
366 sample_size = sfr->bsdes;
367 if (SAMPL_DIAG_MODE(hwc))
368 sample_size += sfr->dsdes;
370 return sample_size;
373 static void deallocate_buffers(struct cpu_hw_sf *cpuhw)
375 if (cpuhw->sfb.sdbt)
376 free_sampling_buffer(&cpuhw->sfb);
379 static int allocate_buffers(struct cpu_hw_sf *cpuhw, struct hw_perf_event *hwc)
381 unsigned long n_sdb, freq, factor;
382 size_t sfr_size, sample_size;
383 struct sf_raw_sample *sfr;
385 /* Allocate raw sample buffer
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.
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;
412 /* Calculate sampling buffers using 4K pages
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.
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).
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.
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).
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;
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.
451 sfb_init_allocs(n_sdb, hwc);
452 if (sf_buffer_available(cpuhw))
453 return 0;
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);
461 return alloc_sampling_buffer(&cpuhw->sfb,
462 sfb_pending_allocs(&cpuhw->sfb, hwc));
465 static unsigned long min_percent(unsigned int percent, unsigned long base,
466 unsigned long min)
468 return min_t(unsigned long, min, DIV_ROUND_UP(percent * base, 100));
471 static unsigned long compute_sfb_extent(unsigned long ratio, unsigned long base)
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.
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);
491 return min_percent(5, base, 8);
494 static void sfb_account_overflows(struct cpu_hw_sf *cpuhw,
495 struct hw_perf_event *hwc)
497 unsigned long ratio, num;
499 if (!OVERFLOW_REG(hwc))
500 return;
502 /* The sample_overflow contains the average number of sample data
503 * that has been lost because sample-data-blocks were full.
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.
509 ratio = DIV_ROUND_UP(100 * OVERFLOW_REG(hwc) * cpuhw->sfb.num_sdb,
510 sample_rate_to_freq(&cpuhw->qsi, SAMPL_RATE(hwc)));
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);
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;
522 /* extend_sampling_buffer() - Extend sampling buffer
523 * @sfb: Sampling buffer structure (for local CPU)
524 * @hwc: Perf event hardware structure
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.
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.
533 static void extend_sampling_buffer(struct sf_buffer *sfb,
534 struct hw_perf_event *hwc)
536 unsigned long num, num_old;
537 int rc;
539 num = sfb_pending_allocs(sfb, hwc);
540 if (!num)
541 return;
542 num_old = sfb->num_sdb;
544 /* Disable the sampling facility to reset any states and also
545 * clear pending measurement alerts.
547 sf_disable();
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.
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);
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));
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);
572 #define PMC_INIT 0
573 #define PMC_RELEASE 1
574 #define PMC_FAILURE 2
575 static void setup_pmc_cpu(void *flags)
577 int err;
578 struct cpu_hw_sf *cpusf = this_cpu_ptr(&cpu_hw_sf);
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;
607 if (err)
608 *((int *) flags) |= PMC_FAILURE;
611 static void release_pmc_hardware(void)
613 int flags = PMC_RELEASE;
615 irq_subclass_unregister(IRQ_SUBCLASS_MEASUREMENT_ALERT);
616 on_each_cpu(setup_pmc_cpu, &flags, 1);
617 perf_release_sampling();
620 static int reserve_pmc_hardware(void)
622 int flags = PMC_INIT;
623 int err;
625 err = perf_reserve_sampling();
626 if (err)
627 return err;
628 on_each_cpu(setup_pmc_cpu, &flags, 1);
629 if (flags & PMC_FAILURE) {
630 release_pmc_hardware();
631 return -ENODEV;
633 irq_subclass_register(IRQ_SUBCLASS_MEASUREMENT_ALERT);
635 return 0;
638 static void hw_perf_event_destroy(struct perf_event *event)
640 /* Free raw sample buffer */
641 if (RAWSAMPLE_REG(&event->hw))
642 kfree((void *) RAWSAMPLE_REG(&event->hw));
644 /* Release PMC if this is the last perf event */
645 if (!atomic_add_unless(&num_events, -1, 1)) {
646 mutex_lock(&pmc_reserve_mutex);
647 if (atomic_dec_return(&num_events) == 0)
648 release_pmc_hardware();
649 mutex_unlock(&pmc_reserve_mutex);
653 static void hw_init_period(struct hw_perf_event *hwc, u64 period)
655 hwc->sample_period = period;
656 hwc->last_period = hwc->sample_period;
657 local64_set(&hwc->period_left, hwc->sample_period);
660 static void hw_reset_registers(struct hw_perf_event *hwc,
661 unsigned long *sdbt_origin)
663 struct sf_raw_sample *sfr;
665 /* (Re)set to first sample-data-block-table */
666 TEAR_REG(hwc) = (unsigned long) sdbt_origin;
668 /* (Re)set raw sampling buffer register */
669 sfr = (struct sf_raw_sample *) RAWSAMPLE_REG(hwc);
670 memset(&sfr->basic, 0, sizeof(sfr->basic));
671 memset(&sfr->diag, 0, sfr->dsdes);
674 static unsigned long hw_limit_rate(const struct hws_qsi_info_block *si,
675 unsigned long rate)
677 return clamp_t(unsigned long, rate,
678 si->min_sampl_rate, si->max_sampl_rate);
681 static int __hw_perf_event_init(struct perf_event *event)
683 struct cpu_hw_sf *cpuhw;
684 struct hws_qsi_info_block si;
685 struct perf_event_attr *attr = &event->attr;
686 struct hw_perf_event *hwc = &event->hw;
687 unsigned long rate;
688 int cpu, err;
690 /* Reserve CPU-measurement sampling facility */
691 err = 0;
692 if (!atomic_inc_not_zero(&num_events)) {
693 mutex_lock(&pmc_reserve_mutex);
694 if (atomic_read(&num_events) == 0 && reserve_pmc_hardware())
695 err = -EBUSY;
696 else
697 atomic_inc(&num_events);
698 mutex_unlock(&pmc_reserve_mutex);
700 event->destroy = hw_perf_event_destroy;
702 if (err)
703 goto out;
705 /* Access per-CPU sampling information (query sampling info) */
707 * The event->cpu value can be -1 to count on every CPU, for example,
708 * when attaching to a task. If this is specified, use the query
709 * sampling info from the current CPU, otherwise use event->cpu to
710 * retrieve the per-CPU information.
711 * Later, cpuhw indicates whether to allocate sampling buffers for a
712 * particular CPU (cpuhw!=NULL) or each online CPU (cpuw==NULL).
714 memset(&si, 0, sizeof(si));
715 cpuhw = NULL;
716 if (event->cpu == -1)
717 qsi(&si);
718 else {
719 /* Event is pinned to a particular CPU, retrieve the per-CPU
720 * sampling structure for accessing the CPU-specific QSI.
722 cpuhw = &per_cpu(cpu_hw_sf, event->cpu);
723 si = cpuhw->qsi;
726 /* Check sampling facility authorization and, if not authorized,
727 * fall back to other PMUs. It is safe to check any CPU because
728 * the authorization is identical for all configured CPUs.
730 if (!si.as) {
731 err = -ENOENT;
732 goto out;
735 /* Always enable basic sampling */
736 SAMPL_FLAGS(hwc) = PERF_CPUM_SF_BASIC_MODE;
738 /* Check if diagnostic sampling is requested. Deny if the required
739 * sampling authorization is missing.
741 if (attr->config == PERF_EVENT_CPUM_SF_DIAG) {
742 if (!si.ad) {
743 err = -EPERM;
744 goto out;
746 SAMPL_FLAGS(hwc) |= PERF_CPUM_SF_DIAG_MODE;
749 /* Check and set other sampling flags */
750 if (attr->config1 & PERF_CPUM_SF_FULL_BLOCKS)
751 SAMPL_FLAGS(hwc) |= PERF_CPUM_SF_FULL_BLOCKS;
753 /* The sampling information (si) contains information about the
754 * min/max sampling intervals and the CPU speed. So calculate the
755 * correct sampling interval and avoid the whole period adjust
756 * feedback loop.
758 rate = 0;
759 if (attr->freq) {
760 if (!attr->sample_freq) {
761 err = -EINVAL;
762 goto out;
764 rate = freq_to_sample_rate(&si, attr->sample_freq);
765 rate = hw_limit_rate(&si, rate);
766 attr->freq = 0;
767 attr->sample_period = rate;
768 } else {
769 /* The min/max sampling rates specifies the valid range
770 * of sample periods. If the specified sample period is
771 * out of range, limit the period to the range boundary.
773 rate = hw_limit_rate(&si, hwc->sample_period);
775 /* The perf core maintains a maximum sample rate that is
776 * configurable through the sysctl interface. Ensure the
777 * sampling rate does not exceed this value. This also helps
778 * to avoid throttling when pushing samples with
779 * perf_event_overflow().
781 if (sample_rate_to_freq(&si, rate) >
782 sysctl_perf_event_sample_rate) {
783 err = -EINVAL;
784 debug_sprintf_event(sfdbg, 1, "Sampling rate exceeds maximum perf sample rate\n");
785 goto out;
788 SAMPL_RATE(hwc) = rate;
789 hw_init_period(hwc, SAMPL_RATE(hwc));
791 /* Initialize sample data overflow accounting */
792 hwc->extra_reg.reg = REG_OVERFLOW;
793 OVERFLOW_REG(hwc) = 0;
795 /* Allocate the per-CPU sampling buffer using the CPU information
796 * from the event. If the event is not pinned to a particular
797 * CPU (event->cpu == -1; or cpuhw == NULL), allocate sampling
798 * buffers for each online CPU.
800 if (cpuhw)
801 /* Event is pinned to a particular CPU */
802 err = allocate_buffers(cpuhw, hwc);
803 else {
804 /* Event is not pinned, allocate sampling buffer on
805 * each online CPU
807 for_each_online_cpu(cpu) {
808 cpuhw = &per_cpu(cpu_hw_sf, cpu);
809 err = allocate_buffers(cpuhw, hwc);
810 if (err)
811 break;
814 out:
815 return err;
818 static int cpumsf_pmu_event_init(struct perf_event *event)
820 int err;
822 /* No support for taken branch sampling */
823 if (has_branch_stack(event))
824 return -EOPNOTSUPP;
826 switch (event->attr.type) {
827 case PERF_TYPE_RAW:
828 if ((event->attr.config != PERF_EVENT_CPUM_SF) &&
829 (event->attr.config != PERF_EVENT_CPUM_SF_DIAG))
830 return -ENOENT;
831 break;
832 case PERF_TYPE_HARDWARE:
833 /* Support sampling of CPU cycles in addition to the
834 * counter facility. However, the counter facility
835 * is more precise and, hence, restrict this PMU to
836 * sampling events only.
838 if (event->attr.config != PERF_COUNT_HW_CPU_CYCLES)
839 return -ENOENT;
840 if (!is_sampling_event(event))
841 return -ENOENT;
842 break;
843 default:
844 return -ENOENT;
847 /* Check online status of the CPU to which the event is pinned */
848 if (event->cpu >= nr_cpumask_bits ||
849 (event->cpu >= 0 && !cpu_online(event->cpu)))
850 return -ENODEV;
852 /* Force reset of idle/hv excludes regardless of what the
853 * user requested.
855 if (event->attr.exclude_hv)
856 event->attr.exclude_hv = 0;
857 if (event->attr.exclude_idle)
858 event->attr.exclude_idle = 0;
860 err = __hw_perf_event_init(event);
861 if (unlikely(err))
862 if (event->destroy)
863 event->destroy(event);
864 return err;
867 static void cpumsf_pmu_enable(struct pmu *pmu)
869 struct cpu_hw_sf *cpuhw = this_cpu_ptr(&cpu_hw_sf);
870 struct hw_perf_event *hwc;
871 int err;
873 if (cpuhw->flags & PMU_F_ENABLED)
874 return;
876 if (cpuhw->flags & PMU_F_ERR_MASK)
877 return;
879 /* Check whether to extent the sampling buffer.
881 * Two conditions trigger an increase of the sampling buffer for a
882 * perf event:
883 * 1. Postponed buffer allocations from the event initialization.
884 * 2. Sampling overflows that contribute to pending allocations.
886 * Note that the extend_sampling_buffer() function disables the sampling
887 * facility, but it can be fully re-enabled using sampling controls that
888 * have been saved in cpumsf_pmu_disable().
890 if (cpuhw->event) {
891 hwc = &cpuhw->event->hw;
892 /* Account number of overflow-designated buffer extents */
893 sfb_account_overflows(cpuhw, hwc);
894 if (sfb_has_pending_allocs(&cpuhw->sfb, hwc))
895 extend_sampling_buffer(&cpuhw->sfb, hwc);
898 /* (Re)enable the PMU and sampling facility */
899 cpuhw->flags |= PMU_F_ENABLED;
900 barrier();
902 err = lsctl(&cpuhw->lsctl);
903 if (err) {
904 cpuhw->flags &= ~PMU_F_ENABLED;
905 pr_err("Loading sampling controls failed: op=%i err=%i\n",
906 1, err);
907 return;
910 debug_sprintf_event(sfdbg, 6, "pmu_enable: es=%i cs=%i ed=%i cd=%i "
911 "tear=%p dear=%p\n", cpuhw->lsctl.es, cpuhw->lsctl.cs,
912 cpuhw->lsctl.ed, cpuhw->lsctl.cd,
913 (void *) cpuhw->lsctl.tear, (void *) cpuhw->lsctl.dear);
916 static void cpumsf_pmu_disable(struct pmu *pmu)
918 struct cpu_hw_sf *cpuhw = this_cpu_ptr(&cpu_hw_sf);
919 struct hws_lsctl_request_block inactive;
920 struct hws_qsi_info_block si;
921 int err;
923 if (!(cpuhw->flags & PMU_F_ENABLED))
924 return;
926 if (cpuhw->flags & PMU_F_ERR_MASK)
927 return;
929 /* Switch off sampling activation control */
930 inactive = cpuhw->lsctl;
931 inactive.cs = 0;
932 inactive.cd = 0;
934 err = lsctl(&inactive);
935 if (err) {
936 pr_err("Loading sampling controls failed: op=%i err=%i\n",
937 2, err);
938 return;
941 /* Save state of TEAR and DEAR register contents */
942 if (!qsi(&si)) {
943 /* TEAR/DEAR values are valid only if the sampling facility is
944 * enabled. Note that cpumsf_pmu_disable() might be called even
945 * for a disabled sampling facility because cpumsf_pmu_enable()
946 * controls the enable/disable state.
948 if (si.es) {
949 cpuhw->lsctl.tear = si.tear;
950 cpuhw->lsctl.dear = si.dear;
952 } else
953 debug_sprintf_event(sfdbg, 3, "cpumsf_pmu_disable: "
954 "qsi() failed with err=%i\n", err);
956 cpuhw->flags &= ~PMU_F_ENABLED;
959 /* perf_exclude_event() - Filter event
960 * @event: The perf event
961 * @regs: pt_regs structure
962 * @sde_regs: Sample-data-entry (sde) regs structure
964 * Filter perf events according to their exclude specification.
966 * Return non-zero if the event shall be excluded.
968 static int perf_exclude_event(struct perf_event *event, struct pt_regs *regs,
969 struct perf_sf_sde_regs *sde_regs)
971 if (event->attr.exclude_user && user_mode(regs))
972 return 1;
973 if (event->attr.exclude_kernel && !user_mode(regs))
974 return 1;
975 if (event->attr.exclude_guest && sde_regs->in_guest)
976 return 1;
977 if (event->attr.exclude_host && !sde_regs->in_guest)
978 return 1;
979 return 0;
982 /* perf_push_sample() - Push samples to perf
983 * @event: The perf event
984 * @sample: Hardware sample data
986 * Use the hardware sample data to create perf event sample. The sample
987 * is the pushed to the event subsystem and the function checks for
988 * possible event overflows. If an event overflow occurs, the PMU is
989 * stopped.
991 * Return non-zero if an event overflow occurred.
993 static int perf_push_sample(struct perf_event *event, struct sf_raw_sample *sfr)
995 int overflow;
996 struct pt_regs regs;
997 struct perf_sf_sde_regs *sde_regs;
998 struct perf_sample_data data;
999 struct perf_raw_record raw;
1001 /* Setup perf sample */
1002 perf_sample_data_init(&data, 0, event->hw.last_period);
1003 raw.size = sfr->size;
1004 raw.data = sfr;
1005 data.raw = &raw;
1007 /* Setup pt_regs to look like an CPU-measurement external interrupt
1008 * using the Program Request Alert code. The regs.int_parm_long
1009 * field which is unused contains additional sample-data-entry related
1010 * indicators.
1012 memset(&regs, 0, sizeof(regs));
1013 regs.int_code = 0x1407;
1014 regs.int_parm = CPU_MF_INT_SF_PRA;
1015 sde_regs = (struct perf_sf_sde_regs *) &regs.int_parm_long;
1017 regs.psw.addr = sfr->basic.ia;
1018 if (sfr->basic.T)
1019 regs.psw.mask |= PSW_MASK_DAT;
1020 if (sfr->basic.W)
1021 regs.psw.mask |= PSW_MASK_WAIT;
1022 if (sfr->basic.P)
1023 regs.psw.mask |= PSW_MASK_PSTATE;
1024 switch (sfr->basic.AS) {
1025 case 0x0:
1026 regs.psw.mask |= PSW_ASC_PRIMARY;
1027 break;
1028 case 0x1:
1029 regs.psw.mask |= PSW_ASC_ACCREG;
1030 break;
1031 case 0x2:
1032 regs.psw.mask |= PSW_ASC_SECONDARY;
1033 break;
1034 case 0x3:
1035 regs.psw.mask |= PSW_ASC_HOME;
1036 break;
1040 * A non-zero guest program parameter indicates a guest
1041 * sample.
1042 * Note that some early samples might be misaccounted to
1043 * the host.
1045 if (sfr->basic.gpp)
1046 sde_regs->in_guest = 1;
1048 overflow = 0;
1049 if (perf_exclude_event(event, &regs, sde_regs))
1050 goto out;
1051 if (perf_event_overflow(event, &data, &regs)) {
1052 overflow = 1;
1053 event->pmu->stop(event, 0);
1055 perf_event_update_userpage(event);
1056 out:
1057 return overflow;
1060 static void perf_event_count_update(struct perf_event *event, u64 count)
1062 local64_add(count, &event->count);
1065 static int sample_format_is_valid(struct hws_combined_entry *sample,
1066 unsigned int flags)
1068 if (likely(flags & PERF_CPUM_SF_BASIC_MODE))
1069 /* Only basic-sampling data entries with data-entry-format
1070 * version of 0x0001 can be processed.
1072 if (sample->basic.def != 0x0001)
1073 return 0;
1074 if (flags & PERF_CPUM_SF_DIAG_MODE)
1075 /* The data-entry-format number of diagnostic-sampling data
1076 * entries can vary. Because diagnostic data is just passed
1077 * through, do only a sanity check on the DEF.
1079 if (sample->diag.def < 0x8001)
1080 return 0;
1081 return 1;
1084 static int sample_is_consistent(struct hws_combined_entry *sample,
1085 unsigned long flags)
1087 /* This check applies only to basic-sampling data entries of potentially
1088 * combined-sampling data entries. Invalid entries cannot be processed
1089 * by the PMU and, thus, do not deliver an associated
1090 * diagnostic-sampling data entry.
1092 if (unlikely(!(flags & PERF_CPUM_SF_BASIC_MODE)))
1093 return 0;
1095 * Samples are skipped, if they are invalid or for which the
1096 * instruction address is not predictable, i.e., the wait-state bit is
1097 * set.
1099 if (sample->basic.I || sample->basic.W)
1100 return 0;
1101 return 1;
1104 static void reset_sample_slot(struct hws_combined_entry *sample,
1105 unsigned long flags)
1107 if (likely(flags & PERF_CPUM_SF_BASIC_MODE))
1108 sample->basic.def = 0;
1109 if (flags & PERF_CPUM_SF_DIAG_MODE)
1110 sample->diag.def = 0;
1113 static void sfr_store_sample(struct sf_raw_sample *sfr,
1114 struct hws_combined_entry *sample)
1116 if (likely(sfr->format & PERF_CPUM_SF_BASIC_MODE))
1117 sfr->basic = sample->basic;
1118 if (sfr->format & PERF_CPUM_SF_DIAG_MODE)
1119 memcpy(&sfr->diag, &sample->diag, sfr->dsdes);
1122 static void debug_sample_entry(struct hws_combined_entry *sample,
1123 struct hws_trailer_entry *te,
1124 unsigned long flags)
1126 debug_sprintf_event(sfdbg, 4, "hw_collect_samples: Found unknown "
1127 "sampling data entry: te->f=%i basic.def=%04x (%p)"
1128 " diag.def=%04x (%p)\n", te->f,
1129 sample->basic.def, &sample->basic,
1130 (flags & PERF_CPUM_SF_DIAG_MODE)
1131 ? sample->diag.def : 0xFFFF,
1132 (flags & PERF_CPUM_SF_DIAG_MODE)
1133 ? &sample->diag : NULL);
1136 /* hw_collect_samples() - Walk through a sample-data-block and collect samples
1137 * @event: The perf event
1138 * @sdbt: Sample-data-block table
1139 * @overflow: Event overflow counter
1141 * Walks through a sample-data-block and collects sampling data entries that are
1142 * then pushed to the perf event subsystem. Depending on the sampling function,
1143 * there can be either basic-sampling or combined-sampling data entries. A
1144 * combined-sampling data entry consists of a basic- and a diagnostic-sampling
1145 * data entry. The sampling function is determined by the flags in the perf
1146 * event hardware structure. The function always works with a combined-sampling
1147 * data entry but ignores the the diagnostic portion if it is not available.
1149 * Note that the implementation focuses on basic-sampling data entries and, if
1150 * such an entry is not valid, the entire combined-sampling data entry is
1151 * ignored.
1153 * The overflow variables counts the number of samples that has been discarded
1154 * due to a perf event overflow.
1156 static void hw_collect_samples(struct perf_event *event, unsigned long *sdbt,
1157 unsigned long long *overflow)
1159 unsigned long flags = SAMPL_FLAGS(&event->hw);
1160 struct hws_combined_entry *sample;
1161 struct hws_trailer_entry *te;
1162 struct sf_raw_sample *sfr;
1163 size_t sample_size;
1165 /* Prepare and initialize raw sample data */
1166 sfr = (struct sf_raw_sample *) RAWSAMPLE_REG(&event->hw);
1167 sfr->format = flags & PERF_CPUM_SF_MODE_MASK;
1169 sample_size = event_sample_size(&event->hw);
1170 te = (struct hws_trailer_entry *) trailer_entry_ptr(*sdbt);
1171 sample = (struct hws_combined_entry *) *sdbt;
1172 while ((unsigned long *) sample < (unsigned long *) te) {
1173 /* Check for an empty sample */
1174 if (!sample->basic.def)
1175 break;
1177 /* Update perf event period */
1178 perf_event_count_update(event, SAMPL_RATE(&event->hw));
1180 /* Check sampling data entry */
1181 if (sample_format_is_valid(sample, flags)) {
1182 /* If an event overflow occurred, the PMU is stopped to
1183 * throttle event delivery. Remaining sample data is
1184 * discarded.
1186 if (!*overflow) {
1187 if (sample_is_consistent(sample, flags)) {
1188 /* Deliver sample data to perf */
1189 sfr_store_sample(sfr, sample);
1190 *overflow = perf_push_sample(event, sfr);
1192 } else
1193 /* Count discarded samples */
1194 *overflow += 1;
1195 } else {
1196 debug_sample_entry(sample, te, flags);
1197 /* Sample slot is not yet written or other record.
1199 * This condition can occur if the buffer was reused
1200 * from a combined basic- and diagnostic-sampling.
1201 * If only basic-sampling is then active, entries are
1202 * written into the larger diagnostic entries.
1203 * This is typically the case for sample-data-blocks
1204 * that are not full. Stop processing if the first
1205 * invalid format was detected.
1207 if (!te->f)
1208 break;
1211 /* Reset sample slot and advance to next sample */
1212 reset_sample_slot(sample, flags);
1213 sample += sample_size;
1217 /* hw_perf_event_update() - Process sampling buffer
1218 * @event: The perf event
1219 * @flush_all: Flag to also flush partially filled sample-data-blocks
1221 * Processes the sampling buffer and create perf event samples.
1222 * The sampling buffer position are retrieved and saved in the TEAR_REG
1223 * register of the specified perf event.
1225 * Only full sample-data-blocks are processed. Specify the flash_all flag
1226 * to also walk through partially filled sample-data-blocks. It is ignored
1227 * if PERF_CPUM_SF_FULL_BLOCKS is set. The PERF_CPUM_SF_FULL_BLOCKS flag
1228 * enforces the processing of full sample-data-blocks only (trailer entries
1229 * with the block-full-indicator bit set).
1231 static void hw_perf_event_update(struct perf_event *event, int flush_all)
1233 struct hw_perf_event *hwc = &event->hw;
1234 struct hws_trailer_entry *te;
1235 unsigned long *sdbt;
1236 unsigned long long event_overflow, sampl_overflow, num_sdb, te_flags;
1237 int done;
1239 if (flush_all && SDB_FULL_BLOCKS(hwc))
1240 flush_all = 0;
1242 sdbt = (unsigned long *) TEAR_REG(hwc);
1243 done = event_overflow = sampl_overflow = num_sdb = 0;
1244 while (!done) {
1245 /* Get the trailer entry of the sample-data-block */
1246 te = (struct hws_trailer_entry *) trailer_entry_ptr(*sdbt);
1248 /* Leave loop if no more work to do (block full indicator) */
1249 if (!te->f) {
1250 done = 1;
1251 if (!flush_all)
1252 break;
1255 /* Check the sample overflow count */
1256 if (te->overflow)
1257 /* Account sample overflows and, if a particular limit
1258 * is reached, extend the sampling buffer.
1259 * For details, see sfb_account_overflows().
1261 sampl_overflow += te->overflow;
1263 /* Timestamps are valid for full sample-data-blocks only */
1264 debug_sprintf_event(sfdbg, 6, "hw_perf_event_update: sdbt=%p "
1265 "overflow=%llu timestamp=0x%llx\n",
1266 sdbt, te->overflow,
1267 (te->f) ? trailer_timestamp(te) : 0ULL);
1269 /* Collect all samples from a single sample-data-block and
1270 * flag if an (perf) event overflow happened. If so, the PMU
1271 * is stopped and remaining samples will be discarded.
1273 hw_collect_samples(event, sdbt, &event_overflow);
1274 num_sdb++;
1276 /* Reset trailer (using compare-double-and-swap) */
1277 do {
1278 te_flags = te->flags & ~SDB_TE_BUFFER_FULL_MASK;
1279 te_flags |= SDB_TE_ALERT_REQ_MASK;
1280 } while (!cmpxchg_double(&te->flags, &te->overflow,
1281 te->flags, te->overflow,
1282 te_flags, 0ULL));
1284 /* Advance to next sample-data-block */
1285 sdbt++;
1286 if (is_link_entry(sdbt))
1287 sdbt = get_next_sdbt(sdbt);
1289 /* Update event hardware registers */
1290 TEAR_REG(hwc) = (unsigned long) sdbt;
1292 /* Stop processing sample-data if all samples of the current
1293 * sample-data-block were flushed even if it was not full.
1295 if (flush_all && done)
1296 break;
1299 /* Account sample overflows in the event hardware structure */
1300 if (sampl_overflow)
1301 OVERFLOW_REG(hwc) = DIV_ROUND_UP(OVERFLOW_REG(hwc) +
1302 sampl_overflow, 1 + num_sdb);
1304 /* Perf_event_overflow() and perf_event_account_interrupt() limit
1305 * the interrupt rate to an upper limit. Roughly 1000 samples per
1306 * task tick.
1307 * Hitting this limit results in a large number
1308 * of throttled REF_REPORT_THROTTLE entries and the samples
1309 * are dropped.
1310 * Slightly increase the interval to avoid hitting this limit.
1312 if (event_overflow) {
1313 SAMPL_RATE(hwc) += DIV_ROUND_UP(SAMPL_RATE(hwc), 10);
1314 debug_sprintf_event(sfdbg, 1, "%s: rate adjustment %ld\n",
1315 __func__,
1316 DIV_ROUND_UP(SAMPL_RATE(hwc), 10));
1319 if (sampl_overflow || event_overflow)
1320 debug_sprintf_event(sfdbg, 4, "hw_perf_event_update: "
1321 "overflow stats: sample=%llu event=%llu\n",
1322 sampl_overflow, event_overflow);
1325 static void cpumsf_pmu_read(struct perf_event *event)
1327 /* Nothing to do ... updates are interrupt-driven */
1330 /* Activate sampling control.
1331 * Next call of pmu_enable() starts sampling.
1333 static void cpumsf_pmu_start(struct perf_event *event, int flags)
1335 struct cpu_hw_sf *cpuhw = this_cpu_ptr(&cpu_hw_sf);
1337 if (WARN_ON_ONCE(!(event->hw.state & PERF_HES_STOPPED)))
1338 return;
1340 if (flags & PERF_EF_RELOAD)
1341 WARN_ON_ONCE(!(event->hw.state & PERF_HES_UPTODATE));
1343 perf_pmu_disable(event->pmu);
1344 event->hw.state = 0;
1345 cpuhw->lsctl.cs = 1;
1346 if (SAMPL_DIAG_MODE(&event->hw))
1347 cpuhw->lsctl.cd = 1;
1348 perf_pmu_enable(event->pmu);
1351 /* Deactivate sampling control.
1352 * Next call of pmu_enable() stops sampling.
1354 static void cpumsf_pmu_stop(struct perf_event *event, int flags)
1356 struct cpu_hw_sf *cpuhw = this_cpu_ptr(&cpu_hw_sf);
1358 if (event->hw.state & PERF_HES_STOPPED)
1359 return;
1361 perf_pmu_disable(event->pmu);
1362 cpuhw->lsctl.cs = 0;
1363 cpuhw->lsctl.cd = 0;
1364 event->hw.state |= PERF_HES_STOPPED;
1366 if ((flags & PERF_EF_UPDATE) && !(event->hw.state & PERF_HES_UPTODATE)) {
1367 hw_perf_event_update(event, 1);
1368 event->hw.state |= PERF_HES_UPTODATE;
1370 perf_pmu_enable(event->pmu);
1373 static int cpumsf_pmu_add(struct perf_event *event, int flags)
1375 struct cpu_hw_sf *cpuhw = this_cpu_ptr(&cpu_hw_sf);
1376 int err;
1378 if (cpuhw->flags & PMU_F_IN_USE)
1379 return -EAGAIN;
1381 if (!cpuhw->sfb.sdbt)
1382 return -EINVAL;
1384 err = 0;
1385 perf_pmu_disable(event->pmu);
1387 event->hw.state = PERF_HES_UPTODATE | PERF_HES_STOPPED;
1389 /* Set up sampling controls. Always program the sampling register
1390 * using the SDB-table start. Reset TEAR_REG event hardware register
1391 * that is used by hw_perf_event_update() to store the sampling buffer
1392 * position after samples have been flushed.
1394 cpuhw->lsctl.s = 0;
1395 cpuhw->lsctl.h = 1;
1396 cpuhw->lsctl.tear = (unsigned long) cpuhw->sfb.sdbt;
1397 cpuhw->lsctl.dear = *(unsigned long *) cpuhw->sfb.sdbt;
1398 cpuhw->lsctl.interval = SAMPL_RATE(&event->hw);
1399 hw_reset_registers(&event->hw, cpuhw->sfb.sdbt);
1401 /* Ensure sampling functions are in the disabled state. If disabled,
1402 * switch on sampling enable control. */
1403 if (WARN_ON_ONCE(cpuhw->lsctl.es == 1 || cpuhw->lsctl.ed == 1)) {
1404 err = -EAGAIN;
1405 goto out;
1407 cpuhw->lsctl.es = 1;
1408 if (SAMPL_DIAG_MODE(&event->hw))
1409 cpuhw->lsctl.ed = 1;
1411 /* Set in_use flag and store event */
1412 cpuhw->event = event;
1413 cpuhw->flags |= PMU_F_IN_USE;
1415 if (flags & PERF_EF_START)
1416 cpumsf_pmu_start(event, PERF_EF_RELOAD);
1417 out:
1418 perf_event_update_userpage(event);
1419 perf_pmu_enable(event->pmu);
1420 return err;
1423 static void cpumsf_pmu_del(struct perf_event *event, int flags)
1425 struct cpu_hw_sf *cpuhw = this_cpu_ptr(&cpu_hw_sf);
1427 perf_pmu_disable(event->pmu);
1428 cpumsf_pmu_stop(event, PERF_EF_UPDATE);
1430 cpuhw->lsctl.es = 0;
1431 cpuhw->lsctl.ed = 0;
1432 cpuhw->flags &= ~PMU_F_IN_USE;
1433 cpuhw->event = NULL;
1435 perf_event_update_userpage(event);
1436 perf_pmu_enable(event->pmu);
1439 CPUMF_EVENT_ATTR(SF, SF_CYCLES_BASIC, PERF_EVENT_CPUM_SF);
1440 CPUMF_EVENT_ATTR(SF, SF_CYCLES_BASIC_DIAG, PERF_EVENT_CPUM_SF_DIAG);
1442 static struct attribute *cpumsf_pmu_events_attr[] = {
1443 CPUMF_EVENT_PTR(SF, SF_CYCLES_BASIC),
1444 NULL,
1445 NULL,
1448 PMU_FORMAT_ATTR(event, "config:0-63");
1450 static struct attribute *cpumsf_pmu_format_attr[] = {
1451 &format_attr_event.attr,
1452 NULL,
1455 static struct attribute_group cpumsf_pmu_events_group = {
1456 .name = "events",
1457 .attrs = cpumsf_pmu_events_attr,
1459 static struct attribute_group cpumsf_pmu_format_group = {
1460 .name = "format",
1461 .attrs = cpumsf_pmu_format_attr,
1463 static const struct attribute_group *cpumsf_pmu_attr_groups[] = {
1464 &cpumsf_pmu_events_group,
1465 &cpumsf_pmu_format_group,
1466 NULL,
1469 static struct pmu cpumf_sampling = {
1470 .pmu_enable = cpumsf_pmu_enable,
1471 .pmu_disable = cpumsf_pmu_disable,
1473 .event_init = cpumsf_pmu_event_init,
1474 .add = cpumsf_pmu_add,
1475 .del = cpumsf_pmu_del,
1477 .start = cpumsf_pmu_start,
1478 .stop = cpumsf_pmu_stop,
1479 .read = cpumsf_pmu_read,
1481 .attr_groups = cpumsf_pmu_attr_groups,
1484 static void cpumf_measurement_alert(struct ext_code ext_code,
1485 unsigned int alert, unsigned long unused)
1487 struct cpu_hw_sf *cpuhw;
1489 if (!(alert & CPU_MF_INT_SF_MASK))
1490 return;
1491 inc_irq_stat(IRQEXT_CMS);
1492 cpuhw = this_cpu_ptr(&cpu_hw_sf);
1494 /* Measurement alerts are shared and might happen when the PMU
1495 * is not reserved. Ignore these alerts in this case. */
1496 if (!(cpuhw->flags & PMU_F_RESERVED))
1497 return;
1499 /* The processing below must take care of multiple alert events that
1500 * might be indicated concurrently. */
1502 /* Program alert request */
1503 if (alert & CPU_MF_INT_SF_PRA) {
1504 if (cpuhw->flags & PMU_F_IN_USE)
1505 hw_perf_event_update(cpuhw->event, 0);
1506 else
1507 WARN_ON_ONCE(!(cpuhw->flags & PMU_F_IN_USE));
1510 /* Report measurement alerts only for non-PRA codes */
1511 if (alert != CPU_MF_INT_SF_PRA)
1512 debug_sprintf_event(sfdbg, 6, "measurement alert: 0x%x\n", alert);
1514 /* Sampling authorization change request */
1515 if (alert & CPU_MF_INT_SF_SACA)
1516 qsi(&cpuhw->qsi);
1518 /* Loss of sample data due to high-priority machine activities */
1519 if (alert & CPU_MF_INT_SF_LSDA) {
1520 pr_err("Sample data was lost\n");
1521 cpuhw->flags |= PMU_F_ERR_LSDA;
1522 sf_disable();
1525 /* Invalid sampling buffer entry */
1526 if (alert & (CPU_MF_INT_SF_IAE|CPU_MF_INT_SF_ISE)) {
1527 pr_err("A sampling buffer entry is incorrect (alert=0x%x)\n",
1528 alert);
1529 cpuhw->flags |= PMU_F_ERR_IBE;
1530 sf_disable();
1534 static int cpumf_pmu_notifier(struct notifier_block *self,
1535 unsigned long action, void *hcpu)
1537 unsigned int cpu = (long) hcpu;
1538 int flags;
1540 /* Ignore the notification if no events are scheduled on the PMU.
1541 * This might be racy...
1543 if (!atomic_read(&num_events))
1544 return NOTIFY_OK;
1546 switch (action & ~CPU_TASKS_FROZEN) {
1547 case CPU_ONLINE:
1548 case CPU_ONLINE_FROZEN:
1549 flags = PMC_INIT;
1550 smp_call_function_single(cpu, setup_pmc_cpu, &flags, 1);
1551 break;
1552 case CPU_DOWN_PREPARE:
1553 flags = PMC_RELEASE;
1554 smp_call_function_single(cpu, setup_pmc_cpu, &flags, 1);
1555 break;
1556 default:
1557 break;
1560 return NOTIFY_OK;
1563 static int param_get_sfb_size(char *buffer, const struct kernel_param *kp)
1565 if (!cpum_sf_avail())
1566 return -ENODEV;
1567 return sprintf(buffer, "%lu,%lu", CPUM_SF_MIN_SDB, CPUM_SF_MAX_SDB);
1570 static int param_set_sfb_size(const char *val, const struct kernel_param *kp)
1572 int rc;
1573 unsigned long min, max;
1575 if (!cpum_sf_avail())
1576 return -ENODEV;
1577 if (!val || !strlen(val))
1578 return -EINVAL;
1580 /* Valid parameter values: "min,max" or "max" */
1581 min = CPUM_SF_MIN_SDB;
1582 max = CPUM_SF_MAX_SDB;
1583 if (strchr(val, ','))
1584 rc = (sscanf(val, "%lu,%lu", &min, &max) == 2) ? 0 : -EINVAL;
1585 else
1586 rc = kstrtoul(val, 10, &max);
1588 if (min < 2 || min >= max || max > get_num_physpages())
1589 rc = -EINVAL;
1590 if (rc)
1591 return rc;
1593 sfb_set_limits(min, max);
1594 pr_info("The sampling buffer limits have changed to: "
1595 "min=%lu max=%lu (diag=x%lu)\n",
1596 CPUM_SF_MIN_SDB, CPUM_SF_MAX_SDB, CPUM_SF_SDB_DIAG_FACTOR);
1597 return 0;
1600 #define param_check_sfb_size(name, p) __param_check(name, p, void)
1601 static const struct kernel_param_ops param_ops_sfb_size = {
1602 .set = param_set_sfb_size,
1603 .get = param_get_sfb_size,
1606 #define RS_INIT_FAILURE_QSI 0x0001
1607 #define RS_INIT_FAILURE_BSDES 0x0002
1608 #define RS_INIT_FAILURE_ALRT 0x0003
1609 #define RS_INIT_FAILURE_PERF 0x0004
1610 static void __init pr_cpumsf_err(unsigned int reason)
1612 pr_err("Sampling facility support for perf is not available: "
1613 "reason=%04x\n", reason);
1616 static int __init init_cpum_sampling_pmu(void)
1618 struct hws_qsi_info_block si;
1619 int err;
1621 if (!cpum_sf_avail())
1622 return -ENODEV;
1624 memset(&si, 0, sizeof(si));
1625 if (qsi(&si)) {
1626 pr_cpumsf_err(RS_INIT_FAILURE_QSI);
1627 return -ENODEV;
1630 if (si.bsdes != sizeof(struct hws_basic_entry)) {
1631 pr_cpumsf_err(RS_INIT_FAILURE_BSDES);
1632 return -EINVAL;
1635 if (si.ad) {
1636 sfb_set_limits(CPUM_SF_MIN_SDB, CPUM_SF_MAX_SDB);
1637 cpumsf_pmu_events_attr[1] =
1638 CPUMF_EVENT_PTR(SF, SF_CYCLES_BASIC_DIAG);
1641 sfdbg = debug_register(KMSG_COMPONENT, 2, 1, 80);
1642 if (!sfdbg) {
1643 pr_err("Registering for s390dbf failed\n");
1644 return -ENOMEM;
1646 debug_register_view(sfdbg, &debug_sprintf_view);
1648 err = register_external_irq(EXT_IRQ_MEASURE_ALERT,
1649 cpumf_measurement_alert);
1650 if (err) {
1651 pr_cpumsf_err(RS_INIT_FAILURE_ALRT);
1652 debug_unregister(sfdbg);
1653 goto out;
1656 err = perf_pmu_register(&cpumf_sampling, "cpum_sf", PERF_TYPE_RAW);
1657 if (err) {
1658 pr_cpumsf_err(RS_INIT_FAILURE_PERF);
1659 unregister_external_irq(EXT_IRQ_MEASURE_ALERT,
1660 cpumf_measurement_alert);
1661 debug_unregister(sfdbg);
1662 goto out;
1664 perf_cpu_notifier(cpumf_pmu_notifier);
1665 out:
1666 return err;
1668 arch_initcall(init_cpum_sampling_pmu);
1669 core_param(cpum_sfb_size, CPUM_SF_MAX_SDB, sfb_size, 0640);