1 // SPDX-License-Identifier: GPL-2.0
3 * Performance event support for the System z CPU-measurement Sampling Facility
5 * Copyright IBM Corp. 2013, 2018
6 * Author(s): Hendrik Brueckner <brueckner@linux.vnet.ibm.com>
8 #define KMSG_COMPONENT "cpum_sf"
9 #define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
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>
20 #include <linux/moduleparam.h>
21 #include <asm/cpu_mf.h>
23 #include <asm/debug.h>
24 #include <asm/timex.h>
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.
30 #define CPUM_SF_MIN_SDBT 1
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.
36 #define CPUM_SF_SDB_PER_TABLE ((PAGE_SIZE - 8) / 8)
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
42 #define CPUM_SF_SDBT_TL_OFFSET (CPUM_SF_SDB_PER_TABLE * 8)
43 static inline int require_table_link(const void *sdbt)
45 return ((unsigned long) sdbt & ~PAGE_MASK) == CPUM_SF_SDBT_TL_OFFSET;
48 /* Minimum and maximum sampling buffer sizes:
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.
56 * Sampling buffer size Buffer characteristics
57 * ---------------------------------------------------
58 * 64KB == 16 pages (4KB per page)
59 * 1 page for SDB-tables
62 * 32MB == 8192 pages (4KB per page)
63 * 16 pages for SDB-tables
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;
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 */
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 */
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 */
97 static DEFINE_PER_CPU(struct cpu_hw_sf, cpu_hw_sf);
100 static debug_info_t *sfdbg;
103 * sf_disable() - Switch off sampling facility
105 static int sf_disable(void)
107 struct hws_lsctl_request_block sreq;
109 memset(&sreq, 0, sizeof(sreq));
114 * sf_buffer_available() - Check for an allocated sampling buffer
116 static int sf_buffer_available(struct cpu_hw_sf *cpuhw)
118 return !!cpuhw->sfb.sdbt;
122 * deallocate sampling facility buffer
124 static void free_sampling_buffer(struct sf_buffer *sfb)
126 unsigned long *sdbt, *curr;
134 /* Free the SDBT after all SDBs are processed... */
139 /* Process table-link entries */
140 if (is_link_entry(curr)) {
141 curr = get_next_sdbt(curr);
143 free_page((unsigned long) sdbt);
145 /* If the origin is reached, sampling buffer is freed */
146 if (curr == sfb->sdbt)
151 /* Process SDB pointer */
159 debug_sprintf_event(sfdbg, 5,
160 "free_sampling_buffer: freed sdbt=%p\n", sfb->sdbt);
161 memset(sfb, 0, sizeof(*sfb));
164 static int alloc_sample_data_block(unsigned long *sdbt, gfp_t gfp_flags)
166 unsigned long sdb, *trailer;
168 /* Allocate and initialize sample-data-block */
169 sdb = get_zeroed_page(gfp_flags);
172 trailer = trailer_entry_ptr(sdb);
173 *trailer = SDB_TE_ALERT_REQ_MASK;
175 /* Link SDB into the sample-data-block-table */
182 * realloc_sampling_buffer() - extend sampler memory
184 * Allocates new sample-data-blocks and adds them to the specified sampling
187 * Important: This modifies the sampling buffer and must be called when the
188 * sampling facility is disabled.
190 * Returns zero on success, non-zero otherwise.
192 static int realloc_sampling_buffer(struct sf_buffer *sfb,
193 unsigned long num_sdb, gfp_t gfp_flags)
196 unsigned long *new, *tail, *tail_prev = NULL;
198 if (!sfb->sdbt || !sfb->tail)
201 if (!is_link_entry(sfb->tail))
204 /* Append to the existing sampling buffer, overwriting the table-link
206 * The tail variables always points to the "tail" (last and table-link)
207 * entry in an SDB-table.
211 /* Do a sanity check whether the table-link entry points to
212 * the sampling buffer origin.
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"
218 (void *) sfb->sdbt, (void *) tail);
222 /* Allocate remaining SDBs */
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);
233 /* Link current page to tail of chain */
234 *tail = (unsigned long)(void *) new + 1;
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.
244 rc = alloc_sample_data_block(tail, gfp_flags);
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.
253 free_page((unsigned long) new);
260 tail_prev = new = NULL; /* Allocated at least one SBD */
263 /* Link sampling buffer to its origin */
264 *tail = (unsigned long) sfb->sdbt + 1;
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);
274 * allocate_sampling_buffer() - allocate sampler memory
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.
282 * Returns zero on success, non-zero otherwise.
284 static int alloc_sampling_buffer(struct sf_buffer *sfb, unsigned long num_sdb)
291 /* Allocate the sample-data-block-table origin */
292 sfb->sdbt = (unsigned long *) get_zeroed_page(GFP_KERNEL);
298 /* Link the table origin to point to itself to prepare for
299 * realloc_sampling_buffer() invocation.
301 sfb->tail = sfb->sdbt;
302 *sfb->tail = (unsigned long)(void *) sfb->sdbt + 1;
304 /* Allocate requested number of sample-data-blocks */
305 rc = realloc_sampling_buffer(sfb, num_sdb, GFP_KERNEL);
307 free_sampling_buffer(sfb);
308 debug_sprintf_event(sfdbg, 4, "alloc_sampling_buffer: "
309 "realloc_sampling_buffer failed with rc=%i\n", rc);
311 debug_sprintf_event(sfdbg, 4,
312 "alloc_sampling_buffer: tear=%p dear=%p\n",
313 sfb->sdbt, (void *) *sfb->sdbt);
317 static void sfb_set_limits(unsigned long min, unsigned long max)
319 struct hws_qsi_info_block si;
321 CPUM_SF_MIN_SDB = min;
322 CPUM_SF_MAX_SDB = max;
324 memset(&si, 0, sizeof(si));
326 CPUM_SF_SDB_DIAG_FACTOR = DIV_ROUND_UP(si.dsdes, si.bsdes);
329 static unsigned long sfb_max_limit(struct hw_perf_event *hwc)
331 return SAMPL_DIAG_MODE(hwc) ? CPUM_SF_MAX_SDB * CPUM_SF_SDB_DIAG_FACTOR
335 static unsigned long sfb_pending_allocs(struct sf_buffer *sfb,
336 struct hw_perf_event *hwc)
339 return SFB_ALLOC_REG(hwc);
340 if (SFB_ALLOC_REG(hwc) > sfb->num_sdb)
341 return SFB_ALLOC_REG(hwc) - sfb->num_sdb;
345 static int sfb_has_pending_allocs(struct sf_buffer *sfb,
346 struct hw_perf_event *hwc)
348 return sfb_pending_allocs(sfb, hwc) > 0;
351 static void sfb_account_allocs(unsigned long num, struct hw_perf_event *hwc)
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));
356 SFB_ALLOC_REG(hwc) += num;
359 static void sfb_init_allocs(unsigned long num, struct hw_perf_event *hwc)
361 SFB_ALLOC_REG(hwc) = 0;
362 sfb_account_allocs(num, hwc);
365 static void deallocate_buffers(struct cpu_hw_sf *cpuhw)
368 free_sampling_buffer(&cpuhw->sfb);
371 static int allocate_buffers(struct cpu_hw_sf *cpuhw, struct hw_perf_event *hwc)
373 unsigned long n_sdb, freq, factor;
376 /* Calculate sampling buffers using 4K pages
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.
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).
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.
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
400 sample_size = sizeof(struct hws_basic_entry);
401 freq = sample_rate_to_freq(&cpuhw->qsi, SAMPL_RATE(hwc));
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;
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.
415 sfb_init_allocs(n_sdb, hwc);
416 if (sf_buffer_available(cpuhw))
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),
425 return alloc_sampling_buffer(&cpuhw->sfb,
426 sfb_pending_allocs(&cpuhw->sfb, hwc));
429 static unsigned long min_percent(unsigned int percent, unsigned long base,
432 return min_t(unsigned long, min, DIV_ROUND_UP(percent * base, 100));
435 static unsigned long compute_sfb_extent(unsigned long ratio, unsigned long base)
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.
445 return min_percent(1, base, 1);
447 return min_percent(1, base, 1);
449 return min_percent(2, base, 2);
451 return min_percent(3, base, 3);
453 return min_percent(4, base, 4);
455 return min_percent(5, base, 8);
458 static void sfb_account_overflows(struct cpu_hw_sf *cpuhw,
459 struct hw_perf_event *hwc)
461 unsigned long ratio, num;
463 if (!OVERFLOW_REG(hwc))
466 /* The sample_overflow contains the average number of sample data
467 * that has been lost because sample-data-blocks were full.
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.
473 ratio = DIV_ROUND_UP(100 * OVERFLOW_REG(hwc) * cpuhw->sfb.num_sdb,
474 sample_rate_to_freq(&cpuhw->qsi, SAMPL_RATE(hwc)));
476 /* Compute number of sample-data-blocks */
477 num = compute_sfb_extent(ratio, cpuhw->sfb.num_sdb);
479 sfb_account_allocs(num, hwc);
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;
486 /* extend_sampling_buffer() - Extend sampling buffer
487 * @sfb: Sampling buffer structure (for local CPU)
488 * @hwc: Perf event hardware structure
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.
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.
497 static void extend_sampling_buffer(struct sf_buffer *sfb,
498 struct hw_perf_event *hwc)
500 unsigned long num, num_old;
503 num = sfb_pending_allocs(sfb, hwc);
506 num_old = sfb->num_sdb;
508 /* Disable the sampling facility to reset any states and also
509 * clear pending measurement alerts.
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.
518 rc = realloc_sampling_buffer(sfb, num, GFP_ATOMIC);
520 debug_sprintf_event(sfdbg, 5, "sfb: extend: realloc "
521 "failed with rc=%i\n", rc);
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));
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);
536 #define PMC_RELEASE 1
537 #define PMC_FAILURE 2
538 static void setup_pmc_cpu(void *flags)
541 struct cpu_hw_sf *cpusf = this_cpu_ptr(&cpu_hw_sf);
544 switch (*((int *) flags)) {
546 memset(cpusf, 0, sizeof(*cpusf));
547 err = qsi(&cpusf->qsi);
550 cpusf->flags |= PMU_F_RESERVED;
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);
559 cpusf->flags &= ~PMU_F_RESERVED;
562 pr_err("Switching off the sampling facility failed "
563 "with rc=%i\n", err);
565 deallocate_buffers(cpusf);
566 debug_sprintf_event(sfdbg, 5,
567 "setup_pmc_cpu: released: cpuhw=%p\n", cpusf);
571 *((int *) flags) |= PMC_FAILURE;
574 static void release_pmc_hardware(void)
576 int flags = PMC_RELEASE;
578 irq_subclass_unregister(IRQ_SUBCLASS_MEASUREMENT_ALERT);
579 on_each_cpu(setup_pmc_cpu, &flags, 1);
582 static int reserve_pmc_hardware(void)
584 int flags = PMC_INIT;
586 on_each_cpu(setup_pmc_cpu, &flags, 1);
587 if (flags & PMC_FAILURE) {
588 release_pmc_hardware();
591 irq_subclass_register(IRQ_SUBCLASS_MEASUREMENT_ALERT);
596 static void hw_perf_event_destroy(struct perf_event *event)
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);
607 static void hw_init_period(struct hw_perf_event *hwc, u64 period)
609 hwc->sample_period = period;
610 hwc->last_period = hwc->sample_period;
611 local64_set(&hwc->period_left, hwc->sample_period);
614 static void hw_reset_registers(struct hw_perf_event *hwc,
615 unsigned long *sdbt_origin)
617 /* (Re)set to first sample-data-block-table */
618 TEAR_REG(hwc) = (unsigned long) sdbt_origin;
621 static unsigned long hw_limit_rate(const struct hws_qsi_info_block *si,
624 return clamp_t(unsigned long, rate,
625 si->min_sampl_rate, si->max_sampl_rate);
628 static u32 cpumsf_pid_type(struct perf_event *event,
629 u32 pid, enum pid_type type)
631 struct task_struct *tsk;
637 tsk = find_task_by_pid_ns(pid, &init_pid_ns);
641 * Only top level events contain the pid namespace in which
645 event = event->parent;
646 pid = __task_pid_nr_ns(tsk, type, event->ns);
648 * See also 1d953111b648
649 * "perf/core: Don't report zero PIDs for exiting tasks".
651 if (!pid && !pid_alive(tsk))
658 static void cpumsf_output_event_pid(struct perf_event *event,
659 struct perf_sample_data *data,
660 struct pt_regs *regs)
663 struct perf_event_header header;
664 struct perf_output_handle handle;
667 * Obtain the PID from the basic-sampling data entry and
668 * correct the data->tid_entry.pid value.
670 pid = data->tid_entry.pid;
672 /* Protect callchain buffers, tasks */
675 perf_prepare_sample(&header, data, event, regs);
676 if (perf_output_begin(&handle, event, header.size))
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);
683 perf_output_sample(&handle, &header, data, event);
684 perf_output_end(&handle);
689 static unsigned long getrate(bool freq, unsigned long sample,
690 struct hws_qsi_info_block *si)
695 rate = freq_to_sample_rate(si, sample);
696 rate = hw_limit_rate(si, rate);
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.
702 rate = hw_limit_rate(si, sample);
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().
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");
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
726 * Since the CPU Measurement sampling facility can not handle frequency
727 * calculate the sampling interval when frequency is specified using
729 * interval := cpu_speed * 1000000 / sample_freq
731 * Returns errno on bad input and zero on success with parameter interval
732 * set to the correct sampling rate.
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.
738 static int __hw_perf_event_init_rate(struct perf_event *event,
739 struct hws_qsi_info_block *si)
741 struct perf_event_attr *attr = &event->attr;
742 struct hw_perf_event *hwc = &event->hw;
746 if (!attr->sample_freq)
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;
752 rate = getrate(attr->freq, attr->sample_period, si);
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));
766 static int __hw_perf_event_init(struct perf_event *event)
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;
774 /* Reserve CPU-measurement sampling facility */
776 if (!atomic_inc_not_zero(&num_events)) {
777 mutex_lock(&pmc_reserve_mutex);
778 if (atomic_read(&num_events) == 0 && reserve_pmc_hardware())
781 atomic_inc(&num_events);
782 mutex_unlock(&pmc_reserve_mutex);
784 event->destroy = hw_perf_event_destroy;
789 /* Access per-CPU sampling information (query sampling info) */
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).
798 memset(&si, 0, sizeof(si));
800 if (event->cpu == -1)
803 /* Event is pinned to a particular CPU, retrieve the per-CPU
804 * sampling structure for accessing the CPU-specific QSI.
806 cpuhw = &per_cpu(cpu_hw_sf, event->cpu);
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.
819 if (si.ribm & CPU_MF_SF_RIBM_NOTAV) {
820 pr_warn("CPU Measurement Facility sampling is temporarily not available\n");
825 /* Always enable basic sampling */
826 SAMPL_FLAGS(hwc) = PERF_CPUM_SF_BASIC_MODE;
828 /* Check if diagnostic sampling is requested. Deny if the required
829 * sampling authorization is missing.
831 if (attr->config == PERF_EVENT_CPUM_SF_DIAG) {
836 SAMPL_FLAGS(hwc) |= PERF_CPUM_SF_DIAG_MODE;
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;
843 err = __hw_perf_event_init_rate(event, &si);
847 /* Initialize sample data overflow accounting */
848 hwc->extra_reg.reg = REG_OVERFLOW;
849 OVERFLOW_REG(hwc) = 0;
851 /* Use AUX buffer. No need to allocate it by ourself */
852 if (attr->config == PERF_EVENT_CPUM_SF_DIAG)
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.
861 /* Event is pinned to a particular CPU */
862 err = allocate_buffers(cpuhw, hwc);
864 /* Event is not pinned, allocate sampling buffer on
867 for_each_online_cpu(cpu) {
868 cpuhw = &per_cpu(cpu_hw_sf, cpu);
869 err = allocate_buffers(cpuhw, hwc);
875 /* If PID/TID sampling is active, replace the default overflow
876 * handler to extract and resolve the PIDs from the basic-sampling
879 if (event->attr.sample_type & PERF_SAMPLE_TID)
880 if (is_default_overflow_handler(event))
881 event->overflow_handler = cpumsf_output_event_pid;
886 static int cpumsf_pmu_event_init(struct perf_event *event)
890 /* No support for taken branch sampling */
891 if (has_branch_stack(event))
894 switch (event->attr.type) {
896 if ((event->attr.config != PERF_EVENT_CPUM_SF) &&
897 (event->attr.config != PERF_EVENT_CPUM_SF_DIAG))
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.
906 if (event->attr.config != PERF_COUNT_HW_CPU_CYCLES)
908 if (!is_sampling_event(event))
915 /* Check online status of the CPU to which the event is pinned */
916 if (event->cpu >= 0 && !cpu_online(event->cpu))
919 /* Force reset of idle/hv excludes regardless of what the
922 if (event->attr.exclude_hv)
923 event->attr.exclude_hv = 0;
924 if (event->attr.exclude_idle)
925 event->attr.exclude_idle = 0;
927 err = __hw_perf_event_init(event);
930 event->destroy(event);
934 static void cpumsf_pmu_enable(struct pmu *pmu)
936 struct cpu_hw_sf *cpuhw = this_cpu_ptr(&cpu_hw_sf);
937 struct hw_perf_event *hwc;
940 if (cpuhw->flags & PMU_F_ENABLED)
943 if (cpuhw->flags & PMU_F_ERR_MASK)
946 /* Check whether to extent the sampling buffer.
948 * Two conditions trigger an increase of the sampling buffer for a
950 * 1. Postponed buffer allocations from the event initialization.
951 * 2. Sampling overflows that contribute to pending allocations.
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().
958 hwc = &cpuhw->event->hw;
959 if (!(SAMPL_DIAG_MODE(hwc))) {
961 * Account number of overflow-designated
964 sfb_account_overflows(cpuhw, hwc);
965 if (sfb_has_pending_allocs(&cpuhw->sfb, hwc))
966 extend_sampling_buffer(&cpuhw->sfb, hwc);
968 /* Rate may be adjusted with ioctl() */
969 cpuhw->lsctl.interval = SAMPL_RATE(&cpuhw->event->hw);
972 /* (Re)enable the PMU and sampling facility */
973 cpuhw->flags |= PMU_F_ENABLED;
976 err = lsctl(&cpuhw->lsctl);
978 cpuhw->flags &= ~PMU_F_ENABLED;
979 pr_err("Loading sampling controls failed: op=%i err=%i\n",
984 /* Load current program parameter */
985 lpp(&S390_lowcore.lpp);
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);
995 static void cpumsf_pmu_disable(struct pmu *pmu)
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;
1002 if (!(cpuhw->flags & PMU_F_ENABLED))
1005 if (cpuhw->flags & PMU_F_ERR_MASK)
1008 /* Switch off sampling activation control */
1009 inactive = cpuhw->lsctl;
1013 err = lsctl(&inactive);
1015 pr_err("Loading sampling controls failed: op=%i err=%i\n",
1020 /* Save state of TEAR and DEAR register contents */
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.
1028 cpuhw->lsctl.tear = si.tear;
1029 cpuhw->lsctl.dear = si.dear;
1032 debug_sprintf_event(sfdbg, 3, "cpumsf_pmu_disable: "
1033 "qsi() failed with err=%i\n", err);
1035 cpuhw->flags &= ~PMU_F_ENABLED;
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
1043 * Filter perf events according to their exclude specification.
1045 * Return non-zero if the event shall be excluded.
1047 static int perf_exclude_event(struct perf_event *event, struct pt_regs *regs,
1048 struct perf_sf_sde_regs *sde_regs)
1050 if (event->attr.exclude_user && user_mode(regs))
1052 if (event->attr.exclude_kernel && !user_mode(regs))
1054 if (event->attr.exclude_guest && sde_regs->in_guest)
1056 if (event->attr.exclude_host && !sde_regs->in_guest)
1061 /* perf_push_sample() - Push samples to perf
1062 * @event: The perf event
1063 * @sample: Hardware sample data
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
1070 * Return non-zero if an event overflow occurred.
1072 static int perf_push_sample(struct perf_event *event,
1073 struct hws_basic_entry *basic)
1076 struct pt_regs regs;
1077 struct perf_sf_sde_regs *sde_regs;
1078 struct perf_sample_data data;
1080 /* Setup perf sample */
1081 perf_sample_data_init(&data, 0, event->hw.last_period);
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
1088 memset(®s, 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 *) ®s.int_parm_long;
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;
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
1110 switch (basic->CL) {
1111 case 1: /* logical partition */
1112 sde_regs->in_guest = 0;
1114 case 2: /* virtual machine */
1115 sde_regs->in_guest = 1;
1117 default: /* old machine, use heuristics */
1118 if (basic->gpp || basic->prim_asn != 0xffff)
1119 sde_regs->in_guest = 1;
1124 * Store the PID value from the sample-data-entry to be
1125 * processed and resolved by cpumsf_output_event_pid().
1127 data.tid_entry.pid = basic->hpp & LPP_PID_MASK;
1130 if (perf_exclude_event(event, ®s, sde_regs))
1132 if (perf_event_overflow(event, &data, ®s)) {
1134 event->pmu->stop(event, 0);
1136 perf_event_update_userpage(event);
1141 static void perf_event_count_update(struct perf_event *event, u64 count)
1143 local64_add(count, &event->count);
1146 static void debug_sample_entry(struct hws_basic_entry *sample,
1147 struct hws_trailer_entry *te)
1149 debug_sprintf_event(sfdbg, 4, "hw_collect_samples: Found unknown "
1150 "sampling data entry: te->f=%i basic.def=%04x "
1152 te->f, sample->def, sample);
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
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.
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
1172 * The overflow variables counts the number of samples that has been discarded
1173 * due to a perf event overflow.
1175 static void hw_collect_samples(struct perf_event *event, unsigned long *sdbt,
1176 unsigned long long *overflow)
1178 struct hws_trailer_entry *te;
1179 struct hws_basic_entry *sample;
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 */
1188 /* Update perf event period */
1189 perf_event_count_update(event, SAMPL_RATE(&event->hw));
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
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,
1205 /* Count discarded samples */
1208 debug_sample_entry(sample, te);
1209 /* Sample slot is not yet written or other record.
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.
1223 /* Reset sample slot and advance to next sample */
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
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.
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).
1243 static void hw_perf_event_update(struct perf_event *event, int flush_all)
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;
1252 * AUX buffer is used when in diagnostic sampling mode.
1253 * No perf events/samples are created.
1255 if (SAMPL_DIAG_MODE(&event->hw))
1258 if (flush_all && SDB_FULL_BLOCKS(hwc))
1261 sdbt = (unsigned long *) TEAR_REG(hwc);
1262 done = event_overflow = sampl_overflow = num_sdb = 0;
1264 /* Get the trailer entry of the sample-data-block */
1265 te = (struct hws_trailer_entry *) trailer_entry_ptr(*sdbt);
1267 /* Leave loop if no more work to do (block full indicator) */
1274 /* Check the sample overflow count */
1276 /* Account sample overflows and, if a particular limit
1277 * is reached, extend the sampling buffer.
1278 * For details, see sfb_account_overflows().
1280 sampl_overflow += te->overflow;
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",
1286 (te->f) ? trailer_timestamp(te) : 0ULL);
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.
1292 hw_collect_samples(event, sdbt, &event_overflow);
1295 /* Reset trailer (using compare-double-and-swap) */
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,
1303 /* Advance to next sample-data-block */
1305 if (is_link_entry(sdbt))
1306 sdbt = get_next_sdbt(sdbt);
1308 /* Update event hardware registers */
1309 TEAR_REG(hwc) = (unsigned long) sdbt;
1311 /* Stop processing sample-data if all samples of the current
1312 * sample-data-block were flushed even if it was not full.
1314 if (flush_all && done)
1318 /* Account sample overflows in the event hardware structure */
1320 OVERFLOW_REG(hwc) = DIV_ROUND_UP(OVERFLOW_REG(hwc) +
1321 sampl_overflow, 1 + num_sdb);
1323 /* Perf_event_overflow() and perf_event_account_interrupt() limit
1324 * the interrupt rate to an upper limit. Roughly 1000 samples per
1326 * Hitting this limit results in a large number
1327 * of throttled REF_REPORT_THROTTLE entries and the samples
1329 * Slightly increase the interval to avoid hitting this limit.
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",
1335 DIV_ROUND_UP(SAMPL_RATE(hwc), 10));
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);
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)
1350 * Get trailer entry by index of SDB.
1352 static struct hws_trailer_entry *aux_sdb_trailer(struct aux_buffer *aux,
1353 unsigned long index)
1357 index = AUX_SDB_INDEX(aux, index);
1358 sdb = aux->sdb_index[index];
1359 return (struct hws_trailer_entry *)trailer_entry_ptr(sdb);
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
1368 * 1. Scan SDBs to see how much data is there and consume them.
1369 * 2. Remove alert indicator in the buffer.
1371 static void aux_output_end(struct perf_output_handle *handle)
1373 unsigned long i, range_scan, idx;
1374 struct aux_buffer *aux;
1375 struct hws_trailer_entry *te;
1377 aux = perf_get_aux(handle);
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))
1387 /* i is num of SDBs which are full */
1388 perf_aux_output_end(handle, i << PAGE_SHIFT);
1390 /* Remove alert indicators in the buffer */
1391 te = aux_sdb_trailer(aux, aux->alert_mark);
1392 te->flags &= ~SDB_TE_ALERT_REQ_MASK;
1394 debug_sprintf_event(sfdbg, 6, "aux_output_end: collect %lx SDBs\n", i);
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.
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
1406 static int aux_output_begin(struct perf_output_handle *handle,
1407 struct aux_buffer *aux,
1408 struct cpu_hw_sf *cpuhw)
1410 unsigned long range;
1411 unsigned long i, range_scan, idx;
1412 unsigned long head, base, offset;
1413 struct hws_trailer_entry *te;
1415 if (WARN_ON_ONCE(handle->head & ~PAGE_MASK))
1418 aux->head = handle->head >> PAGE_SHIFT;
1419 range = (handle->size + 1) >> PAGE_SHIFT;
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.
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);
1436 /* Save the position of empty SDBs */
1437 aux->empty_mark = aux->head + range - 1;
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;
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];
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,
1466 * Set alert indicator on SDB at index @alert_index while sampler is running.
1468 * Return true if successfully.
1469 * Return false if full indicator is already set by hardware sampler.
1471 static bool aux_set_alert(struct aux_buffer *aux, unsigned long alert_index,
1472 unsigned long long *overflow)
1474 unsigned long long orig_overflow, orig_flags, new_flags;
1475 struct hws_trailer_entry *te;
1477 te = aux_sdb_trailer(aux, alert_index);
1479 orig_flags = te->flags;
1480 *overflow = orig_overflow = te->overflow;
1481 if (orig_flags & SDB_TE_BUFFER_FULL_MASK) {
1483 * SDB is already set by hardware.
1484 * Abort and try to set somewhere
1489 new_flags = orig_flags | SDB_TE_ALERT_REQ_MASK;
1490 } while (!cmpxchg_double(&te->flags, &te->overflow,
1491 orig_flags, orig_overflow,
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
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.
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.
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.
1516 * Return true if alert indicator is set successfully and false if not.
1518 static bool aux_reset_buffer(struct aux_buffer *aux, unsigned long range,
1519 unsigned long long *overflow)
1521 unsigned long long orig_overflow, orig_flags, new_flags;
1522 unsigned long i, range_scan, idx;
1523 struct hws_trailer_entry *te;
1525 if (range <= AUX_SDB_NUM_EMPTY(aux))
1527 * No need to scan. All SDBs in range are marked as empty.
1528 * Just set alert indicator. Should check race with hardware
1531 return aux_set_alert(aux, aux->alert_mark, overflow);
1533 if (aux->alert_mark <= aux->empty_mark)
1535 * Set alert indicator on empty SDB. Should check race
1536 * with hardware sampler.
1538 if (!aux_set_alert(aux, aux->alert_mark, overflow))
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.
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);
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;
1557 new_flags &= ~SDB_TE_ALERT_REQ_MASK;
1558 } while (!cmpxchg_double(&te->flags, &te->overflow,
1559 orig_flags, orig_overflow,
1561 *overflow += orig_overflow;
1564 /* Update empty_mark to new position */
1565 aux->empty_mark = aux->head + range - 1;
1571 * Measurement alert handler for diagnostic mode sampling.
1573 static void hw_collect_aux(struct cpu_hw_sf *cpuhw)
1575 struct aux_buffer *aux;
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;
1582 aux = perf_get_aux(handle);
1583 if (WARN_ON_ONCE(!aux))
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;
1591 num_sdb = aux->sfb.num_sdb;
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",
1599 debug_sprintf_event(sfdbg, 1, "AUX buffer used up\n");
1602 if (WARN_ON_ONCE(!aux))
1605 /* Update head and alert_mark to new position */
1606 aux->head = handle->head >> PAGE_SHIFT;
1607 range = (handle->size + 1) >> PAGE_SHIFT;
1609 aux->alert_mark = aux->head;
1611 aux->alert_mark = aux->head + range/2 - 1;
1613 if (aux_reset_buffer(aux, range, &overflow)) {
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 "
1624 aux->head, range, overflow);
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);
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);
1642 * Callback when freeing AUX buffers.
1644 static void aux_buffer_free(void *data)
1646 struct aux_buffer *aux = data;
1647 unsigned long i, num_sdbt;
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]);
1657 kfree(aux->sdbt_index);
1658 kfree(aux->sdb_index);
1661 debug_sprintf_event(sfdbg, 4, "aux_buffer_free: free "
1662 "%lu SDBTs\n", num_sdbt);
1665 static void aux_sdb_init(unsigned long sdb)
1667 struct hws_trailer_entry *te;
1669 te = (struct hws_trailer_entry *)trailer_entry_ptr(sdb);
1671 /* Save clock base */
1673 memcpy(&te->progusage2, &tod_clock_base[1], 8);
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
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.
1688 * Return the private AUX buffer structure if success or NULL if fails.
1690 static void *aux_buffer_setup(struct perf_event *event, void **pages,
1691 int nr_pages, bool snapshot)
1693 struct sf_buffer *sfb;
1694 struct aux_buffer *aux;
1695 unsigned long *new, *tail;
1698 if (!nr_pages || !pages)
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",
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",
1713 /* Allocate aux_buffer struct for the event */
1714 aux = kzalloc(sizeof(struct aux_buffer), GFP_KERNEL);
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)
1725 /* Allocate sdb_index for fast reference */
1726 aux->sdb_index = kmalloc_array(nr_pages, sizeof(void *), GFP_KERNEL);
1727 if (!aux->sdb_index)
1730 /* Allocate the first SDBT */
1732 sfb->sdbt = (unsigned long *) get_zeroed_page(GFP_KERNEL);
1735 aux->sdbt_index[sfb->num_sdbt++] = (unsigned long)sfb->sdbt;
1736 tail = sfb->tail = sfb->sdbt;
1739 * Link the provided pages of AUX buffer to SDBT.
1740 * Allocate SDBT if needed.
1742 for (i = 0; i < nr_pages; i++, tail++) {
1743 if (require_table_link(tail)) {
1744 new = (unsigned long *) get_zeroed_page(GFP_KERNEL);
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;
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]);
1757 sfb->num_sdb = nr_pages;
1759 /* Link the last entry in the SDBT to the first SDBT */
1760 *tail = (unsigned long) sfb->sdbt + 1;
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.
1768 aux->empty_mark = sfb->num_sdb - 1;
1770 debug_sprintf_event(sfdbg, 4, "aux_buffer_setup: setup %lu SDBTs"
1772 sfb->num_sdbt, sfb->num_sdb);
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);
1782 kfree(aux->sdbt_index);
1789 static void cpumsf_pmu_read(struct perf_event *event)
1791 /* Nothing to do ... updates are interrupt-driven */
1794 /* Check if the new sampling period/freqeuncy is appropriate.
1796 * Return non-zero on error and zero on passed checks.
1798 static int cpumsf_pmu_check_period(struct perf_event *event, u64 value)
1800 struct hws_qsi_info_block si;
1804 memset(&si, 0, sizeof(si));
1805 if (event->cpu == -1) {
1809 /* Event is pinned to a particular CPU, retrieve the per-CPU
1810 * sampling structure for accessing the CPU-specific QSI.
1812 struct cpu_hw_sf *cpuhw = &per_cpu(cpu_hw_sf, event->cpu);
1817 do_freq = !!SAMPLE_FREQ_MODE(&event->hw);
1818 rate = getrate(do_freq, value, &si);
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",
1828 event->attr.sample_period, do_freq);
1832 /* Activate sampling control.
1833 * Next call of pmu_enable() starts sampling.
1835 static void cpumsf_pmu_start(struct perf_event *event, int flags)
1837 struct cpu_hw_sf *cpuhw = this_cpu_ptr(&cpu_hw_sf);
1839 if (WARN_ON_ONCE(!(event->hw.state & PERF_HES_STOPPED)))
1842 if (flags & PERF_EF_RELOAD)
1843 WARN_ON_ONCE(!(event->hw.state & PERF_HES_UPTODATE));
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);
1853 /* Deactivate sampling control.
1854 * Next call of pmu_enable() stops sampling.
1856 static void cpumsf_pmu_stop(struct perf_event *event, int flags)
1858 struct cpu_hw_sf *cpuhw = this_cpu_ptr(&cpu_hw_sf);
1860 if (event->hw.state & PERF_HES_STOPPED)
1863 perf_pmu_disable(event->pmu);
1864 cpuhw->lsctl.cs = 0;
1865 cpuhw->lsctl.cd = 0;
1866 event->hw.state |= PERF_HES_STOPPED;
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;
1872 perf_pmu_enable(event->pmu);
1875 static int cpumsf_pmu_add(struct perf_event *event, int flags)
1877 struct cpu_hw_sf *cpuhw = this_cpu_ptr(&cpu_hw_sf);
1878 struct aux_buffer *aux;
1881 if (cpuhw->flags & PMU_F_IN_USE)
1884 if (!SAMPL_DIAG_MODE(&event->hw) && !cpuhw->sfb.sdbt)
1888 perf_pmu_disable(event->pmu);
1890 event->hw.state = PERF_HES_UPTODATE | PERF_HES_STOPPED;
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.
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);
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)) {
1912 if (SAMPL_DIAG_MODE(&event->hw)) {
1913 aux = perf_aux_output_begin(&cpuhw->handle, event);
1918 err = aux_output_begin(&cpuhw->handle, aux, cpuhw);
1921 cpuhw->lsctl.ed = 1;
1923 cpuhw->lsctl.es = 1;
1925 /* Set in_use flag and store event */
1926 cpuhw->event = event;
1927 cpuhw->flags |= PMU_F_IN_USE;
1929 if (flags & PERF_EF_START)
1930 cpumsf_pmu_start(event, PERF_EF_RELOAD);
1932 perf_event_update_userpage(event);
1933 perf_pmu_enable(event->pmu);
1937 static void cpumsf_pmu_del(struct perf_event *event, int flags)
1939 struct cpu_hw_sf *cpuhw = this_cpu_ptr(&cpu_hw_sf);
1941 perf_pmu_disable(event->pmu);
1942 cpumsf_pmu_stop(event, PERF_EF_UPDATE);
1944 cpuhw->lsctl.es = 0;
1945 cpuhw->lsctl.ed = 0;
1946 cpuhw->flags &= ~PMU_F_IN_USE;
1947 cpuhw->event = NULL;
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);
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);
1958 /* Attribute list for CPU_SF.
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.
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.
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.
1975 SF_CYCLES_BASIC_ATTR_IDX = 0,
1976 SF_CYCLES_BASIC_DIAG_ATTR_IDX,
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)
1984 PMU_FORMAT_ATTR(event, "config:0-63");
1986 static struct attribute *cpumsf_pmu_format_attr[] = {
1987 &format_attr_event.attr,
1991 static struct attribute_group cpumsf_pmu_events_group = {
1993 .attrs = cpumsf_pmu_events_attr,
1996 static struct attribute_group cpumsf_pmu_format_group = {
1998 .attrs = cpumsf_pmu_format_attr,
2001 static const struct attribute_group *cpumsf_pmu_attr_groups[] = {
2002 &cpumsf_pmu_events_group,
2003 &cpumsf_pmu_format_group,
2007 static struct pmu cpumf_sampling = {
2008 .pmu_enable = cpumsf_pmu_enable,
2009 .pmu_disable = cpumsf_pmu_disable,
2011 .event_init = cpumsf_pmu_event_init,
2012 .add = cpumsf_pmu_add,
2013 .del = cpumsf_pmu_del,
2015 .start = cpumsf_pmu_start,
2016 .stop = cpumsf_pmu_stop,
2017 .read = cpumsf_pmu_read,
2019 .attr_groups = cpumsf_pmu_attr_groups,
2021 .setup_aux = aux_buffer_setup,
2022 .free_aux = aux_buffer_free,
2024 .check_period = cpumsf_pmu_check_period,
2027 static void cpumf_measurement_alert(struct ext_code ext_code,
2028 unsigned int alert, unsigned long unused)
2030 struct cpu_hw_sf *cpuhw;
2032 if (!(alert & CPU_MF_INT_SF_MASK))
2034 inc_irq_stat(IRQEXT_CMS);
2035 cpuhw = this_cpu_ptr(&cpu_hw_sf);
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))
2042 /* The processing below must take care of multiple alert events that
2043 * might be indicated concurrently. */
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);
2051 hw_perf_event_update(cpuhw->event, 0);
2053 WARN_ON_ONCE(!(cpuhw->flags & PMU_F_IN_USE));
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",
2061 /* Sampling authorization change request */
2062 if (alert & CPU_MF_INT_SF_SACA)
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;
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",
2076 cpuhw->flags |= PMU_F_ERR_IBE;
2081 static int cpusf_pmu_setup(unsigned int cpu, int flags)
2083 /* Ignore the notification if no events are scheduled on the PMU.
2084 * This might be racy...
2086 if (!atomic_read(&num_events))
2089 local_irq_disable();
2090 setup_pmc_cpu(&flags);
2095 static int s390_pmu_sf_online_cpu(unsigned int cpu)
2097 return cpusf_pmu_setup(cpu, PMC_INIT);
2100 static int s390_pmu_sf_offline_cpu(unsigned int cpu)
2102 return cpusf_pmu_setup(cpu, PMC_RELEASE);
2105 static int param_get_sfb_size(char *buffer, const struct kernel_param *kp)
2107 if (!cpum_sf_avail())
2109 return sprintf(buffer, "%lu,%lu", CPUM_SF_MIN_SDB, CPUM_SF_MAX_SDB);
2112 static int param_set_sfb_size(const char *val, const struct kernel_param *kp)
2115 unsigned long min, max;
2117 if (!cpum_sf_avail())
2119 if (!val || !strlen(val))
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;
2128 rc = kstrtoul(val, 10, &max);
2130 if (min < 2 || min >= max || max > get_num_physpages())
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);
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,
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)
2154 pr_err("Sampling facility support for perf is not available: "
2155 "reason=%04x\n", reason);
2158 static int __init init_cpum_sampling_pmu(void)
2160 struct hws_qsi_info_block si;
2163 if (!cpum_sf_avail())
2166 memset(&si, 0, sizeof(si));
2168 pr_cpumsf_err(RS_INIT_FAILURE_QSI);
2172 if (!si.as && !si.ad)
2175 if (si.bsdes != sizeof(struct hws_basic_entry)) {
2176 pr_cpumsf_err(RS_INIT_FAILURE_BSDES);
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.
2185 cpumsf_pmu_events_attr[SF_CYCLES_BASIC_DIAG_ATTR_IDX] =
2186 CPUMF_EVENT_PTR(SF, SF_CYCLES_BASIC_DIAG);
2189 sfdbg = debug_register(KMSG_COMPONENT, 2, 1, 80);
2191 pr_err("Registering for s390dbf failed\n");
2194 debug_register_view(sfdbg, &debug_sprintf_view);
2196 err = register_external_irq(EXT_IRQ_MEASURE_ALERT,
2197 cpumf_measurement_alert);
2199 pr_cpumsf_err(RS_INIT_FAILURE_ALRT);
2200 debug_unregister(sfdbg);
2204 err = perf_pmu_register(&cpumf_sampling, "cpum_sf", PERF_TYPE_RAW);
2206 pr_cpumsf_err(RS_INIT_FAILURE_PERF);
2207 unregister_external_irq(EXT_IRQ_MEASURE_ALERT,
2208 cpumf_measurement_alert);
2209 debug_unregister(sfdbg);
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);
2219 arch_initcall(init_cpum_sampling_pmu);
2220 core_param(cpum_sfb_size, CPUM_SF_MAX_SDB, sfb_size, 0644);