1 // SPDX-License-Identifier: GPL-2.0
3 * Performance event support for s390x - CPU-measurement Counter Facility
5 * Copyright IBM Corp. 2012, 2023
6 * Author(s): Hendrik Brueckner <brueckner@linux.ibm.com>
7 * Thomas Richter <tmricht@linux.ibm.com>
9 #define KMSG_COMPONENT "cpum_cf"
10 #define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
12 #include <linux/kernel.h>
13 #include <linux/kernel_stat.h>
14 #include <linux/percpu.h>
15 #include <linux/notifier.h>
16 #include <linux/init.h>
17 #include <linux/export.h>
18 #include <linux/miscdevice.h>
19 #include <linux/perf_event.h>
21 #include <asm/cpu_mf.h>
22 #include <asm/hwctrset.h>
23 #include <asm/debug.h>
26 CPUMF_CTR_SET_BASIC = 0, /* Basic Counter Set */
27 CPUMF_CTR_SET_USER = 1, /* Problem-State Counter Set */
28 CPUMF_CTR_SET_CRYPTO = 2, /* Crypto-Activity Counter Set */
29 CPUMF_CTR_SET_EXT = 3, /* Extended Counter Set */
30 CPUMF_CTR_SET_MT_DIAG = 4, /* MT-diagnostic Counter Set */
32 /* Maximum number of counter sets */
36 #define CPUMF_LCCTL_ENABLE_SHIFT 16
37 #define CPUMF_LCCTL_ACTCTL_SHIFT 0
39 static inline void ctr_set_enable(u64 *state, u64 ctrsets)
41 *state |= ctrsets << CPUMF_LCCTL_ENABLE_SHIFT;
44 static inline void ctr_set_disable(u64 *state, u64 ctrsets)
46 *state &= ~(ctrsets << CPUMF_LCCTL_ENABLE_SHIFT);
49 static inline void ctr_set_start(u64 *state, u64 ctrsets)
51 *state |= ctrsets << CPUMF_LCCTL_ACTCTL_SHIFT;
54 static inline void ctr_set_stop(u64 *state, u64 ctrsets)
56 *state &= ~(ctrsets << CPUMF_LCCTL_ACTCTL_SHIFT);
59 static inline int ctr_stcctm(enum cpumf_ctr_set set, u64 range, u64 *dest)
62 case CPUMF_CTR_SET_BASIC:
63 return stcctm(BASIC, range, dest);
64 case CPUMF_CTR_SET_USER:
65 return stcctm(PROBLEM_STATE, range, dest);
66 case CPUMF_CTR_SET_CRYPTO:
67 return stcctm(CRYPTO_ACTIVITY, range, dest);
68 case CPUMF_CTR_SET_EXT:
69 return stcctm(EXTENDED, range, dest);
70 case CPUMF_CTR_SET_MT_DIAG:
71 return stcctm(MT_DIAG_CLEARING, range, dest);
72 case CPUMF_CTR_SET_MAX:
78 struct cpu_cf_events {
79 refcount_t refcnt; /* Reference count */
80 atomic_t ctr_set[CPUMF_CTR_SET_MAX];
81 u64 state; /* For perf_event_open SVC */
82 u64 dev_state; /* For /dev/hwctr */
84 size_t used; /* Bytes used in data */
85 size_t usedss; /* Bytes used in start/stop */
86 unsigned char start[PAGE_SIZE]; /* Counter set at event add */
87 unsigned char stop[PAGE_SIZE]; /* Counter set at event delete */
88 unsigned char data[PAGE_SIZE]; /* Counter set at /dev/hwctr */
89 unsigned int sets; /* # Counter set saved in memory */
92 static unsigned int cfdiag_cpu_speed; /* CPU speed for CF_DIAG trailer */
93 static debug_info_t *cf_dbg;
96 * The CPU Measurement query counter information instruction contains
97 * information which varies per machine generation, but is constant and
98 * does not change when running on a particular machine, such as counter
99 * first and second version number. This is needed to determine the size
100 * of counter sets. Extract this information at device driver initialization.
102 static struct cpumf_ctr_info cpumf_ctr_info;
105 struct cpu_cf_events *cpucf;
108 static struct cpu_cf_root { /* Anchor to per CPU data */
109 refcount_t refcnt; /* Overall active events */
110 struct cpu_cf_ptr __percpu *cfptr;
114 * Serialize event initialization and event removal. Both are called from
115 * user space in task context with perf_event_open() and close()
118 * This mutex serializes functions cpum_cf_alloc_cpu() called at event
119 * initialization via cpumf_pmu_event_init() and function cpum_cf_free_cpu()
120 * called at event removal via call back function hw_perf_event_destroy()
121 * when the event is deleted. They are serialized to enforce correct
122 * bookkeeping of pointer and reference counts anchored by
123 * struct cpu_cf_root and the access to cpu_cf_root::refcnt and the
124 * per CPU pointers stored in cpu_cf_root::cfptr.
126 static DEFINE_MUTEX(pmc_reserve_mutex);
129 * Get pointer to per-cpu structure.
131 * Function get_cpu_cfhw() is called from
132 * - cfset_copy_all(): This function is protected by cpus_read_lock(), so
133 * CPU hot plug remove can not happen. Event removal requires a close()
136 * Function this_cpu_cfhw() is called from perf common code functions:
137 * - pmu_{en|dis}able(), pmu_{add|del}()and pmu_{start|stop}():
138 * All functions execute with interrupts disabled on that particular CPU.
139 * - cfset_ioctl_{on|off}, cfset_cpu_read(): see comment cfset_copy_all().
141 * Therefore it is safe to access the CPU specific pointer to the event.
143 static struct cpu_cf_events *get_cpu_cfhw(int cpu)
145 struct cpu_cf_ptr __percpu *p = cpu_cf_root.cfptr;
148 struct cpu_cf_ptr *q = per_cpu_ptr(p, cpu);
155 static struct cpu_cf_events *this_cpu_cfhw(void)
157 return get_cpu_cfhw(smp_processor_id());
160 /* Disable counter sets on dedicated CPU */
161 static void cpum_cf_reset_cpu(void *flags)
166 /* Free per CPU data when the last event is removed. */
167 static void cpum_cf_free_root(void)
169 if (!refcount_dec_and_test(&cpu_cf_root.refcnt))
171 free_percpu(cpu_cf_root.cfptr);
172 cpu_cf_root.cfptr = NULL;
173 irq_subclass_unregister(IRQ_SUBCLASS_MEASUREMENT_ALERT);
174 on_each_cpu(cpum_cf_reset_cpu, NULL, 1);
175 debug_sprintf_event(cf_dbg, 4, "%s2 root.refcnt %u cfptr %px\n",
176 __func__, refcount_read(&cpu_cf_root.refcnt),
181 * On initialization of first event also allocate per CPU data dynamically.
182 * Start with an array of pointers, the array size is the maximum number of
183 * CPUs possible, which might be larger than the number of CPUs currently
186 static int cpum_cf_alloc_root(void)
190 if (refcount_inc_not_zero(&cpu_cf_root.refcnt))
193 /* The memory is already zeroed. */
194 cpu_cf_root.cfptr = alloc_percpu(struct cpu_cf_ptr);
195 if (cpu_cf_root.cfptr) {
196 refcount_set(&cpu_cf_root.refcnt, 1);
197 on_each_cpu(cpum_cf_reset_cpu, NULL, 1);
198 irq_subclass_register(IRQ_SUBCLASS_MEASUREMENT_ALERT);
206 /* Free CPU counter data structure for a PMU */
207 static void cpum_cf_free_cpu(int cpu)
209 struct cpu_cf_events *cpuhw;
210 struct cpu_cf_ptr *p;
212 mutex_lock(&pmc_reserve_mutex);
214 * When invoked via CPU hotplug handler, there might be no events
215 * installed or that particular CPU might not have an
216 * event installed. This anchor pointer can be NULL!
218 if (!cpu_cf_root.cfptr)
220 p = per_cpu_ptr(cpu_cf_root.cfptr, cpu);
223 * Might be zero when called from CPU hotplug handler and no event
224 * installed on that CPU, but on different CPUs.
229 if (refcount_dec_and_test(&cpuhw->refcnt)) {
235 mutex_unlock(&pmc_reserve_mutex);
238 /* Allocate CPU counter data structure for a PMU. Called under mutex lock. */
239 static int cpum_cf_alloc_cpu(int cpu)
241 struct cpu_cf_events *cpuhw;
242 struct cpu_cf_ptr *p;
245 mutex_lock(&pmc_reserve_mutex);
246 rc = cpum_cf_alloc_root();
249 p = per_cpu_ptr(cpu_cf_root.cfptr, cpu);
253 cpuhw = kzalloc(sizeof(*cpuhw), GFP_KERNEL);
256 refcount_set(&cpuhw->refcnt, 1);
261 refcount_inc(&cpuhw->refcnt);
265 * Error in allocation of event, decrement anchor. Since
266 * cpu_cf_event in not created, its destroy() function is not
267 * invoked. Adjust the reference counter for the anchor.
272 mutex_unlock(&pmc_reserve_mutex);
277 * Create/delete per CPU data structures for /dev/hwctr interface and events
278 * created by perf_event_open().
279 * If cpu is -1, track task on all available CPUs. This requires
280 * allocation of hardware data structures for all CPUs. This setup handles
281 * perf_event_open() with task context and /dev/hwctr interface.
282 * If cpu is non-zero install event on this CPU only. This setup handles
283 * perf_event_open() with CPU context.
285 static int cpum_cf_alloc(int cpu)
291 if (!zalloc_cpumask_var(&mask, GFP_KERNEL))
293 for_each_online_cpu(cpu) {
294 rc = cpum_cf_alloc_cpu(cpu);
296 for_each_cpu(cpu, mask)
297 cpum_cf_free_cpu(cpu);
300 cpumask_set_cpu(cpu, mask);
302 free_cpumask_var(mask);
304 rc = cpum_cf_alloc_cpu(cpu);
309 static void cpum_cf_free(int cpu)
312 for_each_online_cpu(cpu)
313 cpum_cf_free_cpu(cpu);
315 cpum_cf_free_cpu(cpu);
319 #define CF_DIAG_CTRSET_DEF 0xfeef /* Counter set header mark */
320 /* interval in seconds */
322 /* Counter sets are stored as data stream in a page sized memory buffer and
323 * exported to user space via raw data attached to the event sample data.
324 * Each counter set starts with an eight byte header consisting of:
325 * - a two byte eye catcher (0xfeef)
326 * - a one byte counter set number
327 * - a two byte counter set size (indicates the number of counters in this set)
328 * - a three byte reserved value (must be zero) to make the header the same
329 * size as a counter value.
330 * All counter values are eight byte in size.
332 * All counter sets are followed by a 64 byte trailer.
333 * The trailer consists of a:
334 * - flag field indicating valid fields when corresponding bit set
335 * - the counter facility first and second version number
336 * - the CPU speed if nonzero
337 * - the time stamp the counter sets have been collected
338 * - the time of day (TOD) base value
339 * - the machine type.
341 * The counter sets are saved when the process is prepared to be executed on a
342 * CPU and saved again when the process is going to be removed from a CPU.
343 * The difference of both counter sets are calculated and stored in the event
346 struct cf_ctrset_entry { /* CPU-M CF counter set entry (8 byte) */
347 unsigned int def:16; /* 0-15 Data Entry Format */
348 unsigned int set:16; /* 16-31 Counter set identifier */
349 unsigned int ctr:16; /* 32-47 Number of stored counters */
350 unsigned int res1:16; /* 48-63 Reserved */
353 struct cf_trailer_entry { /* CPU-M CF_DIAG trailer (64 byte) */
357 unsigned int clock_base:1; /* TOD clock base set */
358 unsigned int speed:1; /* CPU speed set */
359 /* Measurement alerts */
360 unsigned int mtda:1; /* Loss of MT ctr. data alert */
361 unsigned int caca:1; /* Counter auth. change alert */
362 unsigned int lcda:1; /* Loss of counter data alert */
364 unsigned long flags; /* 0-63 All indicators */
367 unsigned int cfvn:16; /* 64-79 Ctr First Version */
368 unsigned int csvn:16; /* 80-95 Ctr Second Version */
369 unsigned int cpu_speed:32; /* 96-127 CPU speed */
371 unsigned long timestamp; /* 128-191 Timestamp (TOD) */
375 unsigned long progusage1;
376 unsigned long progusage2;
377 unsigned long progusage3;
378 unsigned long tod_base;
380 unsigned long progusage[4];
383 unsigned int mach_type:16; /* Machine type */
384 unsigned int res1:16; /* Reserved */
385 unsigned int res2:32; /* Reserved */
388 /* Create the trailer data at the end of a page. */
389 static void cfdiag_trailer(struct cf_trailer_entry *te)
393 te->cfvn = cpumf_ctr_info.cfvn; /* Counter version numbers */
394 te->csvn = cpumf_ctr_info.csvn;
396 get_cpu_id(&cpuid); /* Machine type */
397 te->mach_type = cpuid.machine;
398 te->cpu_speed = cfdiag_cpu_speed;
401 te->clock_base = 1; /* Save clock base */
402 te->tod_base = tod_clock_base.tod;
403 te->timestamp = get_tod_clock_fast();
407 * The number of counters per counter set varies between machine generations,
408 * but is constant when running on a particular machine generation.
409 * Determine each counter set size at device driver initialization and
412 static size_t cpumf_ctr_setsizes[CPUMF_CTR_SET_MAX];
413 static void cpum_cf_make_setsize(enum cpumf_ctr_set ctrset)
415 size_t ctrset_size = 0;
418 case CPUMF_CTR_SET_BASIC:
419 if (cpumf_ctr_info.cfvn >= 1)
422 case CPUMF_CTR_SET_USER:
423 if (cpumf_ctr_info.cfvn == 1)
425 else if (cpumf_ctr_info.cfvn >= 3)
428 case CPUMF_CTR_SET_CRYPTO:
429 if (cpumf_ctr_info.csvn >= 1 && cpumf_ctr_info.csvn <= 5)
431 else if (cpumf_ctr_info.csvn == 6 || cpumf_ctr_info.csvn == 7)
434 case CPUMF_CTR_SET_EXT:
435 if (cpumf_ctr_info.csvn == 1)
437 else if (cpumf_ctr_info.csvn == 2)
439 else if (cpumf_ctr_info.csvn >= 3 && cpumf_ctr_info.csvn <= 5)
441 else if (cpumf_ctr_info.csvn == 6 || cpumf_ctr_info.csvn == 7)
444 case CPUMF_CTR_SET_MT_DIAG:
445 if (cpumf_ctr_info.csvn > 3)
448 case CPUMF_CTR_SET_MAX:
451 cpumf_ctr_setsizes[ctrset] = ctrset_size;
455 * Return the maximum possible counter set size (in number of 8 byte counters)
456 * depending on type and model number.
458 static size_t cpum_cf_read_setsize(enum cpumf_ctr_set ctrset)
460 return cpumf_ctr_setsizes[ctrset];
463 /* Read a counter set. The counter set number determines the counter set and
464 * the CPUM-CF first and second version number determine the number of
465 * available counters in each counter set.
466 * Each counter set starts with header containing the counter set number and
467 * the number of eight byte counters.
469 * The functions returns the number of bytes occupied by this counter set
470 * including the header.
471 * If there is no counter in the counter set, this counter set is useless and
472 * zero is returned on this case.
474 * Note that the counter sets may not be enabled or active and the stcctm
475 * instruction might return error 3. Depending on error_ok value this is ok,
476 * for example when called from cpumf_pmu_start() call back function.
478 static size_t cfdiag_getctrset(struct cf_ctrset_entry *ctrdata, int ctrset,
479 size_t room, bool error_ok)
481 size_t ctrset_size, need = 0;
482 int rc = 3; /* Assume write failure */
484 ctrdata->def = CF_DIAG_CTRSET_DEF;
485 ctrdata->set = ctrset;
487 ctrset_size = cpum_cf_read_setsize(ctrset);
489 if (ctrset_size) { /* Save data */
490 need = ctrset_size * sizeof(u64) + sizeof(*ctrdata);
492 rc = ctr_stcctm(ctrset, ctrset_size,
493 (u64 *)(ctrdata + 1));
495 if (rc != 3 || error_ok)
496 ctrdata->ctr = ctrset_size;
504 static const u64 cpumf_ctr_ctl[CPUMF_CTR_SET_MAX] = {
505 [CPUMF_CTR_SET_BASIC] = 0x02,
506 [CPUMF_CTR_SET_USER] = 0x04,
507 [CPUMF_CTR_SET_CRYPTO] = 0x08,
508 [CPUMF_CTR_SET_EXT] = 0x01,
509 [CPUMF_CTR_SET_MT_DIAG] = 0x20,
512 /* Read out all counter sets and save them in the provided data buffer.
513 * The last 64 byte host an artificial trailer entry.
515 static size_t cfdiag_getctr(void *data, size_t sz, unsigned long auth,
518 struct cf_trailer_entry *trailer;
519 size_t offset = 0, done;
523 sz -= sizeof(*trailer); /* Always room for trailer */
524 for (i = CPUMF_CTR_SET_BASIC; i < CPUMF_CTR_SET_MAX; ++i) {
525 struct cf_ctrset_entry *ctrdata = data + offset;
527 if (!(auth & cpumf_ctr_ctl[i]))
528 continue; /* Counter set not authorized */
530 done = cfdiag_getctrset(ctrdata, i, sz - offset, error_ok);
533 trailer = data + offset;
534 cfdiag_trailer(trailer);
535 return offset + sizeof(*trailer);
538 /* Calculate the difference for each counter in a counter set. */
539 static void cfdiag_diffctrset(u64 *pstart, u64 *pstop, int counters)
541 for (; --counters >= 0; ++pstart, ++pstop)
542 if (*pstop >= *pstart)
545 *pstop = *pstart - *pstop + 1;
548 /* Scan the counter sets and calculate the difference of each counter
549 * in each set. The result is the increment of each counter during the
550 * period the counter set has been activated.
552 * Return true on success.
554 static int cfdiag_diffctr(struct cpu_cf_events *cpuhw, unsigned long auth)
556 struct cf_trailer_entry *trailer_start, *trailer_stop;
557 struct cf_ctrset_entry *ctrstart, *ctrstop;
560 auth &= (1 << CPUMF_LCCTL_ENABLE_SHIFT) - 1;
562 ctrstart = (struct cf_ctrset_entry *)(cpuhw->start + offset);
563 ctrstop = (struct cf_ctrset_entry *)(cpuhw->stop + offset);
565 if (memcmp(ctrstop, ctrstart, sizeof(*ctrstop))) {
566 pr_err_once("cpum_cf_diag counter set compare error "
567 "in set %i\n", ctrstart->set);
570 auth &= ~cpumf_ctr_ctl[ctrstart->set];
571 if (ctrstart->def == CF_DIAG_CTRSET_DEF) {
572 cfdiag_diffctrset((u64 *)(ctrstart + 1),
573 (u64 *)(ctrstop + 1), ctrstart->ctr);
574 offset += ctrstart->ctr * sizeof(u64) +
577 } while (ctrstart->def && auth);
579 /* Save time_stamp from start of event in stop's trailer */
580 trailer_start = (struct cf_trailer_entry *)(cpuhw->start + offset);
581 trailer_stop = (struct cf_trailer_entry *)(cpuhw->stop + offset);
582 trailer_stop->progusage[0] = trailer_start->timestamp;
587 static enum cpumf_ctr_set get_counter_set(u64 event)
589 int set = CPUMF_CTR_SET_MAX;
592 set = CPUMF_CTR_SET_BASIC;
594 set = CPUMF_CTR_SET_USER;
595 else if (event < 128)
596 set = CPUMF_CTR_SET_CRYPTO;
597 else if (event < 288)
598 set = CPUMF_CTR_SET_EXT;
599 else if (event >= 448 && event < 496)
600 set = CPUMF_CTR_SET_MT_DIAG;
605 static int validate_ctr_version(const u64 config, enum cpumf_ctr_set set)
610 /* check required version for counter sets */
612 case CPUMF_CTR_SET_BASIC:
613 case CPUMF_CTR_SET_USER:
614 if (cpumf_ctr_info.cfvn < 1)
617 case CPUMF_CTR_SET_CRYPTO:
618 if ((cpumf_ctr_info.csvn >= 1 && cpumf_ctr_info.csvn <= 5 &&
619 config > 79) || (cpumf_ctr_info.csvn >= 6 && config > 83))
622 case CPUMF_CTR_SET_EXT:
623 if (cpumf_ctr_info.csvn < 1)
625 if ((cpumf_ctr_info.csvn == 1 && config > 159) ||
626 (cpumf_ctr_info.csvn == 2 && config > 175) ||
627 (cpumf_ctr_info.csvn >= 3 && cpumf_ctr_info.csvn <= 5 &&
629 (cpumf_ctr_info.csvn >= 6 && config > 287))
632 case CPUMF_CTR_SET_MT_DIAG:
633 if (cpumf_ctr_info.csvn <= 3)
636 * MT-diagnostic counters are read-only. The counter set
637 * is automatically enabled and activated on all CPUs with
638 * multithreading (SMT). Deactivation of multithreading
639 * also disables the counter set. State changes are ignored
640 * by lcctl(). Because Linux controls SMT enablement through
641 * a kernel parameter only, the counter set is either disabled
642 * or enabled and active.
644 * Thus, the counters can only be used if SMT is on and the
645 * counter set is enabled and active.
647 mtdiag_ctl = cpumf_ctr_ctl[CPUMF_CTR_SET_MT_DIAG];
648 if (!((cpumf_ctr_info.auth_ctl & mtdiag_ctl) &&
649 (cpumf_ctr_info.enable_ctl & mtdiag_ctl) &&
650 (cpumf_ctr_info.act_ctl & mtdiag_ctl)))
653 case CPUMF_CTR_SET_MAX:
661 * Change the CPUMF state to active.
662 * Enable and activate the CPU-counter sets according
663 * to the per-cpu control state.
665 static void cpumf_pmu_enable(struct pmu *pmu)
667 struct cpu_cf_events *cpuhw = this_cpu_cfhw();
670 if (!cpuhw || (cpuhw->flags & PMU_F_ENABLED))
673 err = lcctl(cpuhw->state | cpuhw->dev_state);
675 pr_err("Enabling the performance measuring unit failed with rc=%x\n", err);
677 cpuhw->flags |= PMU_F_ENABLED;
681 * Change the CPUMF state to inactive.
682 * Disable and enable (inactive) the CPU-counter sets according
683 * to the per-cpu control state.
685 static void cpumf_pmu_disable(struct pmu *pmu)
687 struct cpu_cf_events *cpuhw = this_cpu_cfhw();
691 if (!cpuhw || !(cpuhw->flags & PMU_F_ENABLED))
694 inactive = cpuhw->state & ~((1 << CPUMF_LCCTL_ENABLE_SHIFT) - 1);
695 inactive |= cpuhw->dev_state;
696 err = lcctl(inactive);
698 pr_err("Disabling the performance measuring unit failed with rc=%x\n", err);
700 cpuhw->flags &= ~PMU_F_ENABLED;
703 /* Release the PMU if event is the last perf event */
704 static void hw_perf_event_destroy(struct perf_event *event)
706 cpum_cf_free(event->cpu);
709 /* CPUMF <-> perf event mappings for kernel+userspace (basic set) */
710 static const int cpumf_generic_events_basic[] = {
711 [PERF_COUNT_HW_CPU_CYCLES] = 0,
712 [PERF_COUNT_HW_INSTRUCTIONS] = 1,
713 [PERF_COUNT_HW_CACHE_REFERENCES] = -1,
714 [PERF_COUNT_HW_CACHE_MISSES] = -1,
715 [PERF_COUNT_HW_BRANCH_INSTRUCTIONS] = -1,
716 [PERF_COUNT_HW_BRANCH_MISSES] = -1,
717 [PERF_COUNT_HW_BUS_CYCLES] = -1,
719 /* CPUMF <-> perf event mappings for userspace (problem-state set) */
720 static const int cpumf_generic_events_user[] = {
721 [PERF_COUNT_HW_CPU_CYCLES] = 32,
722 [PERF_COUNT_HW_INSTRUCTIONS] = 33,
723 [PERF_COUNT_HW_CACHE_REFERENCES] = -1,
724 [PERF_COUNT_HW_CACHE_MISSES] = -1,
725 [PERF_COUNT_HW_BRANCH_INSTRUCTIONS] = -1,
726 [PERF_COUNT_HW_BRANCH_MISSES] = -1,
727 [PERF_COUNT_HW_BUS_CYCLES] = -1,
730 static int is_userspace_event(u64 ev)
732 return cpumf_generic_events_user[PERF_COUNT_HW_CPU_CYCLES] == ev ||
733 cpumf_generic_events_user[PERF_COUNT_HW_INSTRUCTIONS] == ev;
736 static int __hw_perf_event_init(struct perf_event *event, unsigned int type)
738 struct perf_event_attr *attr = &event->attr;
739 struct hw_perf_event *hwc = &event->hw;
740 enum cpumf_ctr_set set;
745 /* Raw events are used to access counters directly,
746 * hence do not permit excludes */
747 if (attr->exclude_kernel || attr->exclude_user ||
753 case PERF_TYPE_HARDWARE:
754 if (is_sampling_event(event)) /* No sampling support */
757 if (!attr->exclude_user && attr->exclude_kernel) {
759 * Count user space (problem-state) only
760 * Handle events 32 and 33 as 0:u and 1:u
762 if (!is_userspace_event(ev)) {
763 if (ev >= ARRAY_SIZE(cpumf_generic_events_user))
765 ev = cpumf_generic_events_user[ev];
767 } else if (!attr->exclude_kernel && attr->exclude_user) {
768 /* No support for kernel space counters only */
771 /* Count user and kernel space, incl. events 32 + 33 */
772 if (!is_userspace_event(ev)) {
773 if (ev >= ARRAY_SIZE(cpumf_generic_events_basic))
775 ev = cpumf_generic_events_basic[ev];
787 if (ev > PERF_CPUM_CF_MAX_CTR)
790 /* Obtain the counter set to which the specified counter belongs */
791 set = get_counter_set(ev);
793 case CPUMF_CTR_SET_BASIC:
794 case CPUMF_CTR_SET_USER:
795 case CPUMF_CTR_SET_CRYPTO:
796 case CPUMF_CTR_SET_EXT:
797 case CPUMF_CTR_SET_MT_DIAG:
799 * Use the hardware perf event structure to store the
800 * counter number in the 'config' member and the counter
801 * set number in the 'config_base' as bit mask.
802 * It is later used to enable/disable the counter(s).
805 hwc->config_base = cpumf_ctr_ctl[set];
807 case CPUMF_CTR_SET_MAX:
808 /* The counter could not be associated to a counter set */
812 /* Initialize for using the CPU-measurement counter facility */
813 if (cpum_cf_alloc(event->cpu))
815 event->destroy = hw_perf_event_destroy;
818 * Finally, validate version and authorization of the counter set.
819 * If the particular CPU counter set is not authorized,
820 * return with -ENOENT in order to fall back to other
821 * PMUs that might suffice the event request.
823 if (!(hwc->config_base & cpumf_ctr_info.auth_ctl))
825 return validate_ctr_version(hwc->config, set);
828 /* Events CPU_CYLCES and INSTRUCTIONS can be submitted with two different
829 * attribute::type values:
830 * - PERF_TYPE_HARDWARE:
832 * Handle both type of invocations identical. They address the same hardware.
833 * The result is different when event modifiers exclude_kernel and/or
834 * exclude_user are also set.
836 static int cpumf_pmu_event_type(struct perf_event *event)
838 u64 ev = event->attr.config;
840 if (cpumf_generic_events_basic[PERF_COUNT_HW_CPU_CYCLES] == ev ||
841 cpumf_generic_events_basic[PERF_COUNT_HW_INSTRUCTIONS] == ev ||
842 cpumf_generic_events_user[PERF_COUNT_HW_CPU_CYCLES] == ev ||
843 cpumf_generic_events_user[PERF_COUNT_HW_INSTRUCTIONS] == ev)
844 return PERF_TYPE_HARDWARE;
845 return PERF_TYPE_RAW;
848 static int cpumf_pmu_event_init(struct perf_event *event)
850 unsigned int type = event->attr.type;
853 if (type == PERF_TYPE_HARDWARE || type == PERF_TYPE_RAW)
854 err = __hw_perf_event_init(event, type);
855 else if (event->pmu->type == type)
856 /* Registered as unknown PMU */
857 err = __hw_perf_event_init(event, cpumf_pmu_event_type(event));
861 if (unlikely(err) && event->destroy)
862 event->destroy(event);
867 static int hw_perf_event_reset(struct perf_event *event)
873 prev = local64_read(&event->hw.prev_count);
874 err = ecctr(event->hw.config, &new);
878 /* The counter is not (yet) available. This
879 * might happen if the counter set to which
880 * this counter belongs is in the disabled
885 } while (local64_cmpxchg(&event->hw.prev_count, prev, new) != prev);
890 static void hw_perf_event_update(struct perf_event *event)
892 u64 prev, new, delta;
896 prev = local64_read(&event->hw.prev_count);
897 err = ecctr(event->hw.config, &new);
900 } while (local64_cmpxchg(&event->hw.prev_count, prev, new) != prev);
902 delta = (prev <= new) ? new - prev
903 : (-1ULL - prev) + new + 1; /* overflow */
904 local64_add(delta, &event->count);
907 static void cpumf_pmu_read(struct perf_event *event)
909 if (event->hw.state & PERF_HES_STOPPED)
912 hw_perf_event_update(event);
915 static void cpumf_pmu_start(struct perf_event *event, int flags)
917 struct cpu_cf_events *cpuhw = this_cpu_cfhw();
918 struct hw_perf_event *hwc = &event->hw;
921 if (!(hwc->state & PERF_HES_STOPPED))
926 /* (Re-)enable and activate the counter set */
927 ctr_set_enable(&cpuhw->state, hwc->config_base);
928 ctr_set_start(&cpuhw->state, hwc->config_base);
930 /* The counter set to which this counter belongs can be already active.
931 * Because all counters in a set are active, the event->hw.prev_count
932 * needs to be synchronized. At this point, the counter set can be in
933 * the inactive or disabled state.
935 if (hwc->config == PERF_EVENT_CPUM_CF_DIAG) {
936 cpuhw->usedss = cfdiag_getctr(cpuhw->start,
937 sizeof(cpuhw->start),
938 hwc->config_base, true);
940 hw_perf_event_reset(event);
943 /* Increment refcount for counter sets */
944 for (i = CPUMF_CTR_SET_BASIC; i < CPUMF_CTR_SET_MAX; ++i)
945 if ((hwc->config_base & cpumf_ctr_ctl[i]))
946 atomic_inc(&cpuhw->ctr_set[i]);
949 /* Create perf event sample with the counter sets as raw data. The sample
950 * is then pushed to the event subsystem and the function checks for
951 * possible event overflows. If an event overflow occurs, the PMU is
954 * Return non-zero if an event overflow occurred.
956 static int cfdiag_push_sample(struct perf_event *event,
957 struct cpu_cf_events *cpuhw)
959 struct perf_sample_data data;
960 struct perf_raw_record raw;
964 /* Setup perf sample */
965 perf_sample_data_init(&data, 0, event->hw.last_period);
966 memset(®s, 0, sizeof(regs));
967 memset(&raw, 0, sizeof(raw));
969 if (event->attr.sample_type & PERF_SAMPLE_CPU)
970 data.cpu_entry.cpu = event->cpu;
971 if (event->attr.sample_type & PERF_SAMPLE_RAW) {
972 raw.frag.size = cpuhw->usedss;
973 raw.frag.data = cpuhw->stop;
974 perf_sample_save_raw_data(&data, &raw);
977 overflow = perf_event_overflow(event, &data, ®s);
978 debug_sprintf_event(cf_dbg, 3,
979 "%s event %#llx sample_type %#llx raw %d ov %d\n",
980 __func__, event->hw.config,
981 event->attr.sample_type, raw.size, overflow);
983 event->pmu->stop(event, 0);
985 perf_event_update_userpage(event);
989 static void cpumf_pmu_stop(struct perf_event *event, int flags)
991 struct cpu_cf_events *cpuhw = this_cpu_cfhw();
992 struct hw_perf_event *hwc = &event->hw;
995 if (!(hwc->state & PERF_HES_STOPPED)) {
996 /* Decrement reference count for this counter set and if this
997 * is the last used counter in the set, clear activation
998 * control and set the counter set state to inactive.
1000 for (i = CPUMF_CTR_SET_BASIC; i < CPUMF_CTR_SET_MAX; ++i) {
1001 if (!(hwc->config_base & cpumf_ctr_ctl[i]))
1003 if (!atomic_dec_return(&cpuhw->ctr_set[i]))
1004 ctr_set_stop(&cpuhw->state, cpumf_ctr_ctl[i]);
1006 hwc->state |= PERF_HES_STOPPED;
1009 if ((flags & PERF_EF_UPDATE) && !(hwc->state & PERF_HES_UPTODATE)) {
1010 if (hwc->config == PERF_EVENT_CPUM_CF_DIAG) {
1011 local64_inc(&event->count);
1012 cpuhw->usedss = cfdiag_getctr(cpuhw->stop,
1013 sizeof(cpuhw->stop),
1014 event->hw.config_base,
1016 if (cfdiag_diffctr(cpuhw, event->hw.config_base))
1017 cfdiag_push_sample(event, cpuhw);
1019 hw_perf_event_update(event);
1021 hwc->state |= PERF_HES_UPTODATE;
1025 static int cpumf_pmu_add(struct perf_event *event, int flags)
1027 struct cpu_cf_events *cpuhw = this_cpu_cfhw();
1029 ctr_set_enable(&cpuhw->state, event->hw.config_base);
1030 event->hw.state = PERF_HES_UPTODATE | PERF_HES_STOPPED;
1032 if (flags & PERF_EF_START)
1033 cpumf_pmu_start(event, PERF_EF_RELOAD);
1038 static void cpumf_pmu_del(struct perf_event *event, int flags)
1040 struct cpu_cf_events *cpuhw = this_cpu_cfhw();
1043 cpumf_pmu_stop(event, PERF_EF_UPDATE);
1045 /* Check if any counter in the counter set is still used. If not used,
1046 * change the counter set to the disabled state. This also clears the
1047 * content of all counters in the set.
1049 * When a new perf event has been added but not yet started, this can
1050 * clear enable control and resets all counters in a set. Therefore,
1051 * cpumf_pmu_start() always has to reenable a counter set.
1053 for (i = CPUMF_CTR_SET_BASIC; i < CPUMF_CTR_SET_MAX; ++i)
1054 if (!atomic_read(&cpuhw->ctr_set[i]))
1055 ctr_set_disable(&cpuhw->state, cpumf_ctr_ctl[i]);
1058 /* Performance monitoring unit for s390x */
1059 static struct pmu cpumf_pmu = {
1060 .task_ctx_nr = perf_sw_context,
1061 .capabilities = PERF_PMU_CAP_NO_INTERRUPT,
1062 .pmu_enable = cpumf_pmu_enable,
1063 .pmu_disable = cpumf_pmu_disable,
1064 .event_init = cpumf_pmu_event_init,
1065 .add = cpumf_pmu_add,
1066 .del = cpumf_pmu_del,
1067 .start = cpumf_pmu_start,
1068 .stop = cpumf_pmu_stop,
1069 .read = cpumf_pmu_read,
1072 static struct cfset_session { /* CPUs and counter set bit mask */
1073 struct list_head head; /* Head of list of active processes */
1075 .head = LIST_HEAD_INIT(cfset_session.head)
1078 static refcount_t cfset_opencnt = REFCOUNT_INIT(0); /* Access count */
1080 * Synchronize access to device /dev/hwc. This mutex protects against
1081 * concurrent access to functions cfset_open() and cfset_release().
1082 * Same for CPU hotplug add and remove events triggering
1083 * cpum_cf_online_cpu() and cpum_cf_offline_cpu().
1084 * It also serializes concurrent device ioctl access from multiple
1085 * processes accessing /dev/hwc.
1087 * The mutex protects concurrent access to the /dev/hwctr session management
1088 * struct cfset_session and reference counting variable cfset_opencnt.
1090 static DEFINE_MUTEX(cfset_ctrset_mutex);
1093 * CPU hotplug handles only /dev/hwctr device.
1094 * For perf_event_open() the CPU hotplug handling is done on kernel common
1096 * - CPU add: Nothing is done since a file descriptor can not be created
1097 * and returned to the user.
1098 * - CPU delete: Handled by common code via pmu_disable(), pmu_stop() and
1099 * pmu_delete(). The event itself is removed when the file descriptor is
1102 static int cfset_online_cpu(unsigned int cpu);
1104 static int cpum_cf_online_cpu(unsigned int cpu)
1108 debug_sprintf_event(cf_dbg, 4, "%s cpu %d root.refcnt %d "
1109 "opencnt %d\n", __func__, cpu,
1110 refcount_read(&cpu_cf_root.refcnt),
1111 refcount_read(&cfset_opencnt));
1113 * Ignore notification for perf_event_open().
1114 * Handle only /dev/hwctr device sessions.
1116 mutex_lock(&cfset_ctrset_mutex);
1117 if (refcount_read(&cfset_opencnt)) {
1118 rc = cpum_cf_alloc_cpu(cpu);
1120 cfset_online_cpu(cpu);
1122 mutex_unlock(&cfset_ctrset_mutex);
1126 static int cfset_offline_cpu(unsigned int cpu);
1128 static int cpum_cf_offline_cpu(unsigned int cpu)
1130 debug_sprintf_event(cf_dbg, 4, "%s cpu %d root.refcnt %d opencnt %d\n",
1131 __func__, cpu, refcount_read(&cpu_cf_root.refcnt),
1132 refcount_read(&cfset_opencnt));
1134 * During task exit processing of grouped perf events triggered by CPU
1135 * hotplug processing, pmu_disable() is called as part of perf context
1136 * removal process. Therefore do not trigger event removal now for
1137 * perf_event_open() created events. Perf common code triggers event
1138 * destruction when the event file descriptor is closed.
1140 * Handle only /dev/hwctr device sessions.
1142 mutex_lock(&cfset_ctrset_mutex);
1143 if (refcount_read(&cfset_opencnt)) {
1144 cfset_offline_cpu(cpu);
1145 cpum_cf_free_cpu(cpu);
1147 mutex_unlock(&cfset_ctrset_mutex);
1151 /* Return true if store counter set multiple instruction is available */
1152 static inline int stccm_avail(void)
1154 return test_facility(142);
1157 /* CPU-measurement alerts for the counter facility */
1158 static void cpumf_measurement_alert(struct ext_code ext_code,
1159 unsigned int alert, unsigned long unused)
1161 struct cpu_cf_events *cpuhw;
1163 if (!(alert & CPU_MF_INT_CF_MASK))
1166 inc_irq_stat(IRQEXT_CMC);
1169 * Measurement alerts are shared and might happen when the PMU
1170 * is not reserved. Ignore these alerts in this case.
1172 cpuhw = this_cpu_cfhw();
1176 /* counter authorization change alert */
1177 if (alert & CPU_MF_INT_CF_CACA)
1178 qctri(&cpumf_ctr_info);
1180 /* loss of counter data alert */
1181 if (alert & CPU_MF_INT_CF_LCDA)
1182 pr_err("CPU[%i] Counter data was lost\n", smp_processor_id());
1184 /* loss of MT counter data alert */
1185 if (alert & CPU_MF_INT_CF_MTDA)
1186 pr_warn("CPU[%i] MT counter data was lost\n",
1187 smp_processor_id());
1190 static int cfset_init(void);
1191 static int __init cpumf_pmu_init(void)
1195 /* Extract counter measurement facility information */
1196 if (!cpum_cf_avail() || qctri(&cpumf_ctr_info))
1199 /* Determine and store counter set sizes for later reference */
1200 for (rc = CPUMF_CTR_SET_BASIC; rc < CPUMF_CTR_SET_MAX; ++rc)
1201 cpum_cf_make_setsize(rc);
1204 * Clear bit 15 of cr0 to unauthorize problem-state to
1205 * extract measurement counters
1207 ctl_clear_bit(0, 48);
1209 /* register handler for measurement-alert interruptions */
1210 rc = register_external_irq(EXT_IRQ_MEASURE_ALERT,
1211 cpumf_measurement_alert);
1213 pr_err("Registering for CPU-measurement alerts failed with rc=%i\n", rc);
1217 /* Setup s390dbf facility */
1218 cf_dbg = debug_register(KMSG_COMPONENT, 2, 1, 128);
1220 pr_err("Registration of s390dbf(cpum_cf) failed\n");
1224 debug_register_view(cf_dbg, &debug_sprintf_view);
1226 cpumf_pmu.attr_groups = cpumf_cf_event_group();
1227 rc = perf_pmu_register(&cpumf_pmu, "cpum_cf", -1);
1229 pr_err("Registering the cpum_cf PMU failed with rc=%i\n", rc);
1231 } else if (stccm_avail()) { /* Setup counter set device */
1235 rc = cpuhp_setup_state(CPUHP_AP_PERF_S390_CF_ONLINE,
1236 "perf/s390/cf:online",
1237 cpum_cf_online_cpu, cpum_cf_offline_cpu);
1241 debug_unregister_view(cf_dbg, &debug_sprintf_view);
1242 debug_unregister(cf_dbg);
1244 unregister_external_irq(EXT_IRQ_MEASURE_ALERT, cpumf_measurement_alert);
1248 /* Support for the CPU Measurement Facility counter set extraction using
1249 * device /dev/hwctr. This allows user space programs to extract complete
1250 * counter set via normal file operations.
1253 struct cfset_call_on_cpu_parm { /* Parm struct for smp_call_on_cpu */
1254 unsigned int sets; /* Counter set bit mask */
1255 atomic_t cpus_ack; /* # CPUs successfully executed func */
1258 struct cfset_request { /* CPUs and counter set bit mask */
1259 unsigned long ctrset; /* Bit mask of counter set to read */
1260 cpumask_t mask; /* CPU mask to read from */
1261 struct list_head node; /* Chain to cfset_session.head */
1264 static void cfset_session_init(void)
1266 INIT_LIST_HEAD(&cfset_session.head);
1269 /* Remove current request from global bookkeeping. Maintain a counter set bit
1270 * mask on a per CPU basis.
1271 * Done in process context under mutex protection.
1273 static void cfset_session_del(struct cfset_request *p)
1278 /* Add current request to global bookkeeping. Maintain a counter set bit mask
1279 * on a per CPU basis.
1280 * Done in process context under mutex protection.
1282 static void cfset_session_add(struct cfset_request *p)
1284 list_add(&p->node, &cfset_session.head);
1287 /* The /dev/hwctr device access uses PMU_F_IN_USE to mark the device access
1288 * path is currently used.
1289 * The cpu_cf_events::dev_state is used to denote counter sets in use by this
1290 * interface. It is always or'ed in. If this interface is not active, its
1291 * value is zero and no additional counter sets will be included.
1293 * The cpu_cf_events::state is used by the perf_event_open SVC and remains
1296 * perf_pmu_enable() and perf_pmu_enable() and its call backs
1297 * cpumf_pmu_enable() and cpumf_pmu_disable() are called by the
1298 * performance measurement subsystem to enable per process
1299 * CPU Measurement counter facility.
1300 * The XXX_enable() and XXX_disable functions are used to turn off
1301 * x86 performance monitoring interrupt (PMI) during scheduling.
1302 * s390 uses these calls to temporarily stop and resume the active CPU
1303 * counters sets during scheduling.
1305 * We do allow concurrent access of perf_event_open() SVC and /dev/hwctr
1306 * device access. The perf_event_open() SVC interface makes a lot of effort
1307 * to only run the counters while the calling process is actively scheduled
1309 * When /dev/hwctr interface is also used at the same time, the counter sets
1310 * will keep running, even when the process is scheduled off a CPU.
1311 * However this is not a problem and does not lead to wrong counter values
1312 * for the perf_event_open() SVC. The current counter value will be recorded
1313 * during schedule-in. At schedule-out time the current counter value is
1314 * extracted again and the delta is calculated and added to the event.
1316 /* Stop all counter sets via ioctl interface */
1317 static void cfset_ioctl_off(void *parm)
1319 struct cpu_cf_events *cpuhw = this_cpu_cfhw();
1320 struct cfset_call_on_cpu_parm *p = parm;
1323 /* Check if any counter set used by /dev/hwctr */
1324 for (rc = CPUMF_CTR_SET_BASIC; rc < CPUMF_CTR_SET_MAX; ++rc)
1325 if ((p->sets & cpumf_ctr_ctl[rc])) {
1326 if (!atomic_dec_return(&cpuhw->ctr_set[rc])) {
1327 ctr_set_disable(&cpuhw->dev_state,
1329 ctr_set_stop(&cpuhw->dev_state,
1333 /* Keep perf_event_open counter sets */
1334 rc = lcctl(cpuhw->dev_state | cpuhw->state);
1336 pr_err("Counter set stop %#llx of /dev/%s failed rc=%i\n",
1337 cpuhw->state, S390_HWCTR_DEVICE, rc);
1338 if (!cpuhw->dev_state)
1339 cpuhw->flags &= ~PMU_F_IN_USE;
1340 debug_sprintf_event(cf_dbg, 4, "%s rc %d state %#llx dev_state %#llx\n",
1341 __func__, rc, cpuhw->state, cpuhw->dev_state);
1344 /* Start counter sets on particular CPU */
1345 static void cfset_ioctl_on(void *parm)
1347 struct cpu_cf_events *cpuhw = this_cpu_cfhw();
1348 struct cfset_call_on_cpu_parm *p = parm;
1351 cpuhw->flags |= PMU_F_IN_USE;
1352 ctr_set_enable(&cpuhw->dev_state, p->sets);
1353 ctr_set_start(&cpuhw->dev_state, p->sets);
1354 for (rc = CPUMF_CTR_SET_BASIC; rc < CPUMF_CTR_SET_MAX; ++rc)
1355 if ((p->sets & cpumf_ctr_ctl[rc]))
1356 atomic_inc(&cpuhw->ctr_set[rc]);
1357 rc = lcctl(cpuhw->dev_state | cpuhw->state); /* Start counter sets */
1359 atomic_inc(&p->cpus_ack);
1361 pr_err("Counter set start %#llx of /dev/%s failed rc=%i\n",
1362 cpuhw->dev_state | cpuhw->state, S390_HWCTR_DEVICE, rc);
1363 debug_sprintf_event(cf_dbg, 4, "%s rc %d state %#llx dev_state %#llx\n",
1364 __func__, rc, cpuhw->state, cpuhw->dev_state);
1367 static void cfset_release_cpu(void *p)
1369 struct cpu_cf_events *cpuhw = this_cpu_cfhw();
1372 debug_sprintf_event(cf_dbg, 4, "%s state %#llx dev_state %#llx\n",
1373 __func__, cpuhw->state, cpuhw->dev_state);
1374 cpuhw->dev_state = 0;
1375 rc = lcctl(cpuhw->state); /* Keep perf_event_open counter sets */
1377 pr_err("Counter set release %#llx of /dev/%s failed rc=%i\n",
1378 cpuhw->state, S390_HWCTR_DEVICE, rc);
1381 /* This modifies the process CPU mask to adopt it to the currently online
1382 * CPUs. Offline CPUs can not be addresses. This call terminates the access
1383 * and is usually followed by close() or a new iotcl(..., START, ...) which
1384 * creates a new request structure.
1386 static void cfset_all_stop(struct cfset_request *req)
1388 struct cfset_call_on_cpu_parm p = {
1389 .sets = req->ctrset,
1392 cpumask_and(&req->mask, &req->mask, cpu_online_mask);
1393 on_each_cpu_mask(&req->mask, cfset_ioctl_off, &p, 1);
1396 /* Release function is also called when application gets terminated without
1397 * doing a proper ioctl(..., S390_HWCTR_STOP, ...) command.
1399 static int cfset_release(struct inode *inode, struct file *file)
1401 mutex_lock(&cfset_ctrset_mutex);
1402 /* Open followed by close/exit has no private_data */
1403 if (file->private_data) {
1404 cfset_all_stop(file->private_data);
1405 cfset_session_del(file->private_data);
1406 kfree(file->private_data);
1407 file->private_data = NULL;
1409 if (refcount_dec_and_test(&cfset_opencnt)) { /* Last close */
1410 on_each_cpu(cfset_release_cpu, NULL, 1);
1413 mutex_unlock(&cfset_ctrset_mutex);
1418 * Open via /dev/hwctr device. Allocate all per CPU resources on the first
1419 * open of the device. The last close releases all per CPU resources.
1420 * Parallel perf_event_open system calls also use per CPU resources.
1421 * These invocations are handled via reference counting on the per CPU data
1424 static int cfset_open(struct inode *inode, struct file *file)
1428 if (!perfmon_capable())
1430 file->private_data = NULL;
1432 mutex_lock(&cfset_ctrset_mutex);
1433 if (!refcount_inc_not_zero(&cfset_opencnt)) { /* First open */
1434 rc = cpum_cf_alloc(-1);
1436 cfset_session_init();
1437 refcount_set(&cfset_opencnt, 1);
1440 mutex_unlock(&cfset_ctrset_mutex);
1442 /* nonseekable_open() never fails */
1443 return rc ?: nonseekable_open(inode, file);
1446 static int cfset_all_start(struct cfset_request *req)
1448 struct cfset_call_on_cpu_parm p = {
1449 .sets = req->ctrset,
1450 .cpus_ack = ATOMIC_INIT(0),
1455 if (!alloc_cpumask_var(&mask, GFP_KERNEL))
1457 cpumask_and(mask, &req->mask, cpu_online_mask);
1458 on_each_cpu_mask(mask, cfset_ioctl_on, &p, 1);
1459 if (atomic_read(&p.cpus_ack) != cpumask_weight(mask)) {
1460 on_each_cpu_mask(mask, cfset_ioctl_off, &p, 1);
1462 debug_sprintf_event(cf_dbg, 4, "%s CPUs missing", __func__);
1464 free_cpumask_var(mask);
1468 /* Return the maximum required space for all possible CPUs in case one
1469 * CPU will be onlined during the START, READ, STOP cycles.
1470 * To find out the size of the counter sets, any one CPU will do. They
1471 * all have the same counter sets.
1473 static size_t cfset_needspace(unsigned int sets)
1478 for (i = CPUMF_CTR_SET_BASIC; i < CPUMF_CTR_SET_MAX; ++i) {
1479 if (!(sets & cpumf_ctr_ctl[i]))
1481 bytes += cpum_cf_read_setsize(i) * sizeof(u64) +
1482 sizeof(((struct s390_ctrset_setdata *)0)->set) +
1483 sizeof(((struct s390_ctrset_setdata *)0)->no_cnts);
1485 bytes = sizeof(((struct s390_ctrset_read *)0)->no_cpus) + nr_cpu_ids *
1486 (bytes + sizeof(((struct s390_ctrset_cpudata *)0)->cpu_nr) +
1487 sizeof(((struct s390_ctrset_cpudata *)0)->no_sets));
1491 static int cfset_all_copy(unsigned long arg, cpumask_t *mask)
1493 struct s390_ctrset_read __user *ctrset_read;
1494 unsigned int cpu, cpus, rc = 0;
1497 ctrset_read = (struct s390_ctrset_read __user *)arg;
1498 uptr = ctrset_read->data;
1499 for_each_cpu(cpu, mask) {
1500 struct cpu_cf_events *cpuhw = get_cpu_cfhw(cpu);
1501 struct s390_ctrset_cpudata __user *ctrset_cpudata;
1503 ctrset_cpudata = uptr;
1504 rc = put_user(cpu, &ctrset_cpudata->cpu_nr);
1505 rc |= put_user(cpuhw->sets, &ctrset_cpudata->no_sets);
1506 rc |= copy_to_user(ctrset_cpudata->data, cpuhw->data,
1512 uptr += sizeof(struct s390_ctrset_cpudata) + cpuhw->used;
1515 cpus = cpumask_weight(mask);
1516 if (put_user(cpus, &ctrset_read->no_cpus))
1519 debug_sprintf_event(cf_dbg, 4, "%s rc %d copied %ld\n", __func__, rc,
1520 uptr - (void __user *)ctrset_read->data);
1524 static size_t cfset_cpuset_read(struct s390_ctrset_setdata *p, int ctrset,
1525 int ctrset_size, size_t room)
1530 need = sizeof(*p) + sizeof(u64) * ctrset_size;
1532 p->set = cpumf_ctr_ctl[ctrset];
1533 p->no_cnts = ctrset_size;
1534 rc = ctr_stcctm(ctrset, ctrset_size, (u64 *)p->cv);
1535 if (rc == 3) /* Nothing stored */
1541 /* Read all counter sets. */
1542 static void cfset_cpu_read(void *parm)
1544 struct cpu_cf_events *cpuhw = this_cpu_cfhw();
1545 struct cfset_call_on_cpu_parm *p = parm;
1549 /* No data saved yet */
1552 memset(cpuhw->data, 0, sizeof(cpuhw->data));
1554 /* Scan the counter sets */
1555 for (set = CPUMF_CTR_SET_BASIC; set < CPUMF_CTR_SET_MAX; ++set) {
1556 struct s390_ctrset_setdata *sp = (void *)cpuhw->data +
1559 if (!(p->sets & cpumf_ctr_ctl[set]))
1560 continue; /* Counter set not in list */
1561 set_size = cpum_cf_read_setsize(set);
1562 space = sizeof(cpuhw->data) - cpuhw->used;
1563 space = cfset_cpuset_read(sp, set, set_size, space);
1565 cpuhw->used += space;
1568 debug_sprintf_event(cf_dbg, 4, "%s sets %d used %zd\n", __func__,
1569 cpuhw->sets, cpuhw->used);
1573 static int cfset_all_read(unsigned long arg, struct cfset_request *req)
1575 struct cfset_call_on_cpu_parm p;
1579 if (!alloc_cpumask_var(&mask, GFP_KERNEL))
1582 p.sets = req->ctrset;
1583 cpumask_and(mask, &req->mask, cpu_online_mask);
1584 on_each_cpu_mask(mask, cfset_cpu_read, &p, 1);
1585 rc = cfset_all_copy(arg, mask);
1586 free_cpumask_var(mask);
1590 static long cfset_ioctl_read(unsigned long arg, struct cfset_request *req)
1594 if (req && req->ctrset)
1595 ret = cfset_all_read(arg, req);
1599 static long cfset_ioctl_stop(struct file *file)
1601 struct cfset_request *req = file->private_data;
1605 cfset_all_stop(req);
1606 cfset_session_del(req);
1608 file->private_data = NULL;
1614 static long cfset_ioctl_start(unsigned long arg, struct file *file)
1616 struct s390_ctrset_start __user *ustart;
1617 struct s390_ctrset_start start;
1618 struct cfset_request *preq;
1624 if (file->private_data)
1626 ustart = (struct s390_ctrset_start __user *)arg;
1627 if (copy_from_user(&start, ustart, sizeof(start)))
1629 if (start.version != S390_HWCTR_START_VERSION)
1631 if (start.counter_sets & ~(cpumf_ctr_ctl[CPUMF_CTR_SET_BASIC] |
1632 cpumf_ctr_ctl[CPUMF_CTR_SET_USER] |
1633 cpumf_ctr_ctl[CPUMF_CTR_SET_CRYPTO] |
1634 cpumf_ctr_ctl[CPUMF_CTR_SET_EXT] |
1635 cpumf_ctr_ctl[CPUMF_CTR_SET_MT_DIAG]))
1636 return -EINVAL; /* Invalid counter set */
1637 if (!start.counter_sets)
1638 return -EINVAL; /* No counter set at all? */
1640 preq = kzalloc(sizeof(*preq), GFP_KERNEL);
1643 cpumask_clear(&preq->mask);
1644 len = min_t(u64, start.cpumask_len, cpumask_size());
1645 umask = (void __user *)start.cpumask;
1646 if (copy_from_user(&preq->mask, umask, len)) {
1650 if (cpumask_empty(&preq->mask)) {
1654 need = cfset_needspace(start.counter_sets);
1655 if (put_user(need, &ustart->data_bytes)) {
1659 preq->ctrset = start.counter_sets;
1660 ret = cfset_all_start(preq);
1662 cfset_session_add(preq);
1663 file->private_data = preq;
1664 debug_sprintf_event(cf_dbg, 4, "%s set %#lx need %ld ret %d\n",
1665 __func__, preq->ctrset, need, ret);
1672 /* Entry point to the /dev/hwctr device interface.
1673 * The ioctl system call supports three subcommands:
1674 * S390_HWCTR_START: Start the specified counter sets on a CPU list. The
1675 * counter set keeps running until explicitly stopped. Returns the number
1676 * of bytes needed to store the counter values. If another S390_HWCTR_START
1677 * ioctl subcommand is called without a previous S390_HWCTR_STOP stop
1678 * command on the same file descriptor, -EBUSY is returned.
1679 * S390_HWCTR_READ: Read the counter set values from specified CPU list given
1680 * with the S390_HWCTR_START command.
1681 * S390_HWCTR_STOP: Stops the counter sets on the CPU list given with the
1682 * previous S390_HWCTR_START subcommand.
1684 static long cfset_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
1689 mutex_lock(&cfset_ctrset_mutex);
1691 case S390_HWCTR_START:
1692 ret = cfset_ioctl_start(arg, file);
1694 case S390_HWCTR_STOP:
1695 ret = cfset_ioctl_stop(file);
1697 case S390_HWCTR_READ:
1698 ret = cfset_ioctl_read(arg, file->private_data);
1704 mutex_unlock(&cfset_ctrset_mutex);
1709 static const struct file_operations cfset_fops = {
1710 .owner = THIS_MODULE,
1712 .release = cfset_release,
1713 .unlocked_ioctl = cfset_ioctl,
1714 .compat_ioctl = cfset_ioctl,
1718 static struct miscdevice cfset_dev = {
1719 .name = S390_HWCTR_DEVICE,
1720 .minor = MISC_DYNAMIC_MINOR,
1721 .fops = &cfset_fops,
1725 /* Hotplug add of a CPU. Scan through all active processes and add
1726 * that CPU to the list of CPUs supplied with ioctl(..., START, ...).
1728 static int cfset_online_cpu(unsigned int cpu)
1730 struct cfset_call_on_cpu_parm p;
1731 struct cfset_request *rp;
1733 if (!list_empty(&cfset_session.head)) {
1734 list_for_each_entry(rp, &cfset_session.head, node) {
1735 p.sets = rp->ctrset;
1737 cpumask_set_cpu(cpu, &rp->mask);
1743 /* Hotplug remove of a CPU. Scan through all active processes and clear
1744 * that CPU from the list of CPUs supplied with ioctl(..., START, ...).
1745 * Adjust reference counts.
1747 static int cfset_offline_cpu(unsigned int cpu)
1749 struct cfset_call_on_cpu_parm p;
1750 struct cfset_request *rp;
1752 if (!list_empty(&cfset_session.head)) {
1753 list_for_each_entry(rp, &cfset_session.head, node) {
1754 p.sets = rp->ctrset;
1755 cfset_ioctl_off(&p);
1756 cpumask_clear_cpu(cpu, &rp->mask);
1762 static void cfdiag_read(struct perf_event *event)
1764 debug_sprintf_event(cf_dbg, 3, "%s event %#llx count %ld\n", __func__,
1765 event->attr.config, local64_read(&event->count));
1768 static int get_authctrsets(void)
1770 unsigned long auth = 0;
1771 enum cpumf_ctr_set i;
1773 for (i = CPUMF_CTR_SET_BASIC; i < CPUMF_CTR_SET_MAX; ++i) {
1774 if (cpumf_ctr_info.auth_ctl & cpumf_ctr_ctl[i])
1775 auth |= cpumf_ctr_ctl[i];
1780 /* Setup the event. Test for authorized counter sets and only include counter
1781 * sets which are authorized at the time of the setup. Including unauthorized
1782 * counter sets result in specification exception (and panic).
1784 static int cfdiag_event_init2(struct perf_event *event)
1786 struct perf_event_attr *attr = &event->attr;
1789 /* Set sample_period to indicate sampling */
1790 event->hw.config = attr->config;
1791 event->hw.sample_period = attr->sample_period;
1792 local64_set(&event->hw.period_left, event->hw.sample_period);
1793 local64_set(&event->count, 0);
1794 event->hw.last_period = event->hw.sample_period;
1796 /* Add all authorized counter sets to config_base. The
1797 * the hardware init function is either called per-cpu or just once
1798 * for all CPUS (event->cpu == -1). This depends on the whether
1799 * counting is started for all CPUs or on a per workload base where
1800 * the perf event moves from one CPU to another CPU.
1801 * Checking the authorization on any CPU is fine as the hardware
1802 * applies the same authorization settings to all CPUs.
1804 event->hw.config_base = get_authctrsets();
1806 /* No authorized counter sets, nothing to count/sample */
1807 if (!event->hw.config_base)
1810 debug_sprintf_event(cf_dbg, 5, "%s err %d config_base %#lx\n",
1811 __func__, err, event->hw.config_base);
1815 static int cfdiag_event_init(struct perf_event *event)
1817 struct perf_event_attr *attr = &event->attr;
1820 if (event->attr.config != PERF_EVENT_CPUM_CF_DIAG ||
1821 event->attr.type != event->pmu->type)
1824 /* Raw events are used to access counters directly,
1825 * hence do not permit excludes.
1826 * This event is useless without PERF_SAMPLE_RAW to return counter set
1827 * values as raw data.
1829 if (attr->exclude_kernel || attr->exclude_user || attr->exclude_hv ||
1830 !(attr->sample_type & (PERF_SAMPLE_CPU | PERF_SAMPLE_RAW))) {
1835 /* Initialize for using the CPU-measurement counter facility */
1836 if (cpum_cf_alloc(event->cpu))
1838 event->destroy = hw_perf_event_destroy;
1840 err = cfdiag_event_init2(event);
1842 event->destroy(event);
1847 /* Create cf_diag/events/CF_DIAG event sysfs file. This counter is used
1848 * to collect the complete counter sets for a scheduled process. Target
1849 * are complete counter sets attached as raw data to the artificial event.
1850 * This results in complete counter sets available when a process is
1851 * scheduled. Contains the delta of every counter while the process was
1854 CPUMF_EVENT_ATTR(CF_DIAG, CF_DIAG, PERF_EVENT_CPUM_CF_DIAG);
1856 static struct attribute *cfdiag_events_attr[] = {
1857 CPUMF_EVENT_PTR(CF_DIAG, CF_DIAG),
1861 PMU_FORMAT_ATTR(event, "config:0-63");
1863 static struct attribute *cfdiag_format_attr[] = {
1864 &format_attr_event.attr,
1868 static struct attribute_group cfdiag_events_group = {
1870 .attrs = cfdiag_events_attr,
1872 static struct attribute_group cfdiag_format_group = {
1874 .attrs = cfdiag_format_attr,
1876 static const struct attribute_group *cfdiag_attr_groups[] = {
1877 &cfdiag_events_group,
1878 &cfdiag_format_group,
1882 /* Performance monitoring unit for event CF_DIAG. Since this event
1883 * is also started and stopped via the perf_event_open() system call, use
1884 * the same event enable/disable call back functions. They do not
1885 * have a pointer to the perf_event strcture as first parameter.
1887 * The functions XXX_add, XXX_del, XXX_start and XXX_stop are also common.
1888 * Reuse them and distinguish the event (always first parameter) via
1891 static struct pmu cf_diag = {
1892 .task_ctx_nr = perf_sw_context,
1893 .event_init = cfdiag_event_init,
1894 .pmu_enable = cpumf_pmu_enable,
1895 .pmu_disable = cpumf_pmu_disable,
1896 .add = cpumf_pmu_add,
1897 .del = cpumf_pmu_del,
1898 .start = cpumf_pmu_start,
1899 .stop = cpumf_pmu_stop,
1900 .read = cfdiag_read,
1902 .attr_groups = cfdiag_attr_groups
1905 /* Calculate memory needed to store all counter sets together with header and
1906 * trailer data. This is independent of the counter set authorization which
1907 * can vary depending on the configuration.
1909 static size_t cfdiag_maxsize(struct cpumf_ctr_info *info)
1911 size_t max_size = sizeof(struct cf_trailer_entry);
1912 enum cpumf_ctr_set i;
1914 for (i = CPUMF_CTR_SET_BASIC; i < CPUMF_CTR_SET_MAX; ++i) {
1915 size_t size = cpum_cf_read_setsize(i);
1918 max_size += size * sizeof(u64) +
1919 sizeof(struct cf_ctrset_entry);
1924 /* Get the CPU speed, try sampling facility first and CPU attributes second. */
1925 static void cfdiag_get_cpu_speed(void)
1929 if (cpum_sf_avail()) { /* Sampling facility first */
1930 struct hws_qsi_info_block si;
1932 memset(&si, 0, sizeof(si));
1934 cfdiag_cpu_speed = si.cpu_speed;
1939 /* Fallback: CPU speed extract static part. Used in case
1940 * CPU Measurement Sampling Facility is turned off.
1942 mhz = __ecag(ECAG_CPU_ATTRIBUTE, 0);
1944 cfdiag_cpu_speed = mhz & 0xffffffff;
1947 static int cfset_init(void)
1952 cfdiag_get_cpu_speed();
1953 /* Make sure the counter set data fits into predefined buffer. */
1954 need = cfdiag_maxsize(&cpumf_ctr_info);
1955 if (need > sizeof(((struct cpu_cf_events *)0)->start)) {
1956 pr_err("Insufficient memory for PMU(cpum_cf_diag) need=%zu\n",
1961 rc = misc_register(&cfset_dev);
1963 pr_err("Registration of /dev/%s failed rc=%i\n",
1964 cfset_dev.name, rc);
1968 rc = perf_pmu_register(&cf_diag, "cpum_cf_diag", -1);
1970 misc_deregister(&cfset_dev);
1971 pr_err("Registration of PMU(cpum_cf_diag) failed with rc=%i\n",
1978 device_initcall(cpumf_pmu_init);