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