xref: /openbmc/linux/arch/s390/kernel/perf_cpum_sf.c (revision 1f8e5072)
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(&header, data, event, regs);
722 	if (perf_output_begin(&handle, data, event, header.size))
723 		goto out;
724 
725 	/* Update the process ID (see also kernel/events/core.c) */
726 	data->tid_entry.pid = cpumsf_pid_type(event, pid, PIDTYPE_TGID);
727 	data->tid_entry.tid = cpumsf_pid_type(event, pid, PIDTYPE_PID);
728 
729 	perf_output_sample(&handle, &header, data, event);
730 	perf_output_end(&handle);
731 out:
732 	rcu_read_unlock();
733 }
734 
735 static unsigned long getrate(bool freq, unsigned long sample,
736 			     struct hws_qsi_info_block *si)
737 {
738 	unsigned long rate;
739 
740 	if (freq) {
741 		rate = freq_to_sample_rate(si, sample);
742 		rate = hw_limit_rate(si, rate);
743 	} else {
744 		/* The min/max sampling rates specifies the valid range
745 		 * of sample periods.  If the specified sample period is
746 		 * out of range, limit the period to the range boundary.
747 		 */
748 		rate = hw_limit_rate(si, sample);
749 
750 		/* The perf core maintains a maximum sample rate that is
751 		 * configurable through the sysctl interface.  Ensure the
752 		 * sampling rate does not exceed this value.  This also helps
753 		 * to avoid throttling when pushing samples with
754 		 * perf_event_overflow().
755 		 */
756 		if (sample_rate_to_freq(si, rate) >
757 		    sysctl_perf_event_sample_rate) {
758 			debug_sprintf_event(sfdbg, 1, "%s: "
759 					    "Sampling rate exceeds maximum "
760 					    "perf sample rate\n", __func__);
761 			rate = 0;
762 		}
763 	}
764 	return rate;
765 }
766 
767 /* The sampling information (si) contains information about the
768  * min/max sampling intervals and the CPU speed.  So calculate the
769  * correct sampling interval and avoid the whole period adjust
770  * feedback loop.
771  *
772  * Since the CPU Measurement sampling facility can not handle frequency
773  * calculate the sampling interval when frequency is specified using
774  * this formula:
775  *	interval := cpu_speed * 1000000 / sample_freq
776  *
777  * Returns errno on bad input and zero on success with parameter interval
778  * set to the correct sampling rate.
779  *
780  * Note: This function turns off freq bit to avoid calling function
781  * perf_adjust_period(). This causes frequency adjustment in the common
782  * code part which causes tremendous variations in the counter values.
783  */
784 static int __hw_perf_event_init_rate(struct perf_event *event,
785 				     struct hws_qsi_info_block *si)
786 {
787 	struct perf_event_attr *attr = &event->attr;
788 	struct hw_perf_event *hwc = &event->hw;
789 	unsigned long rate;
790 
791 	if (attr->freq) {
792 		if (!attr->sample_freq)
793 			return -EINVAL;
794 		rate = getrate(attr->freq, attr->sample_freq, si);
795 		attr->freq = 0;		/* Don't call  perf_adjust_period() */
796 		SAMPL_FLAGS(hwc) |= PERF_CPUM_SF_FREQ_MODE;
797 	} else {
798 		rate = getrate(attr->freq, attr->sample_period, si);
799 		if (!rate)
800 			return -EINVAL;
801 	}
802 	attr->sample_period = rate;
803 	SAMPL_RATE(hwc) = rate;
804 	hw_init_period(hwc, SAMPL_RATE(hwc));
805 	debug_sprintf_event(sfdbg, 4, "%s: cpu %d period %#llx freq %d,%#lx\n",
806 			    __func__, event->cpu, event->attr.sample_period,
807 			    event->attr.freq, SAMPLE_FREQ_MODE(hwc));
808 	return 0;
809 }
810 
811 static int __hw_perf_event_init(struct perf_event *event)
812 {
813 	struct cpu_hw_sf *cpuhw;
814 	struct hws_qsi_info_block si;
815 	struct perf_event_attr *attr = &event->attr;
816 	struct hw_perf_event *hwc = &event->hw;
817 	int cpu, err;
818 
819 	/* Reserve CPU-measurement sampling facility */
820 	err = 0;
821 	if (!atomic_inc_not_zero(&num_events)) {
822 		mutex_lock(&pmc_reserve_mutex);
823 		if (atomic_read(&num_events) == 0 && reserve_pmc_hardware())
824 			err = -EBUSY;
825 		else
826 			atomic_inc(&num_events);
827 		mutex_unlock(&pmc_reserve_mutex);
828 	}
829 	event->destroy = hw_perf_event_destroy;
830 
831 	if (err)
832 		goto out;
833 
834 	/* Access per-CPU sampling information (query sampling info) */
835 	/*
836 	 * The event->cpu value can be -1 to count on every CPU, for example,
837 	 * when attaching to a task.  If this is specified, use the query
838 	 * sampling info from the current CPU, otherwise use event->cpu to
839 	 * retrieve the per-CPU information.
840 	 * Later, cpuhw indicates whether to allocate sampling buffers for a
841 	 * particular CPU (cpuhw!=NULL) or each online CPU (cpuw==NULL).
842 	 */
843 	memset(&si, 0, sizeof(si));
844 	cpuhw = NULL;
845 	if (event->cpu == -1)
846 		qsi(&si);
847 	else {
848 		/* Event is pinned to a particular CPU, retrieve the per-CPU
849 		 * sampling structure for accessing the CPU-specific QSI.
850 		 */
851 		cpuhw = &per_cpu(cpu_hw_sf, event->cpu);
852 		si = cpuhw->qsi;
853 	}
854 
855 	/* Check sampling facility authorization and, if not authorized,
856 	 * fall back to other PMUs.  It is safe to check any CPU because
857 	 * the authorization is identical for all configured CPUs.
858 	 */
859 	if (!si.as) {
860 		err = -ENOENT;
861 		goto out;
862 	}
863 
864 	if (si.ribm & CPU_MF_SF_RIBM_NOTAV) {
865 		pr_warn("CPU Measurement Facility sampling is temporarily not available\n");
866 		err = -EBUSY;
867 		goto out;
868 	}
869 
870 	/* Always enable basic sampling */
871 	SAMPL_FLAGS(hwc) = PERF_CPUM_SF_BASIC_MODE;
872 
873 	/* Check if diagnostic sampling is requested.  Deny if the required
874 	 * sampling authorization is missing.
875 	 */
876 	if (attr->config == PERF_EVENT_CPUM_SF_DIAG) {
877 		if (!si.ad) {
878 			err = -EPERM;
879 			goto out;
880 		}
881 		SAMPL_FLAGS(hwc) |= PERF_CPUM_SF_DIAG_MODE;
882 	}
883 
884 	/* Check and set other sampling flags */
885 	if (attr->config1 & PERF_CPUM_SF_FULL_BLOCKS)
886 		SAMPL_FLAGS(hwc) |= PERF_CPUM_SF_FULL_BLOCKS;
887 
888 	err =  __hw_perf_event_init_rate(event, &si);
889 	if (err)
890 		goto out;
891 
892 	/* Initialize sample data overflow accounting */
893 	hwc->extra_reg.reg = REG_OVERFLOW;
894 	OVERFLOW_REG(hwc) = 0;
895 
896 	/* Use AUX buffer. No need to allocate it by ourself */
897 	if (attr->config == PERF_EVENT_CPUM_SF_DIAG)
898 		return 0;
899 
900 	/* Allocate the per-CPU sampling buffer using the CPU information
901 	 * from the event.  If the event is not pinned to a particular
902 	 * CPU (event->cpu == -1; or cpuhw == NULL), allocate sampling
903 	 * buffers for each online CPU.
904 	 */
905 	if (cpuhw)
906 		/* Event is pinned to a particular CPU */
907 		err = allocate_buffers(cpuhw, hwc);
908 	else {
909 		/* Event is not pinned, allocate sampling buffer on
910 		 * each online CPU
911 		 */
912 		for_each_online_cpu(cpu) {
913 			cpuhw = &per_cpu(cpu_hw_sf, cpu);
914 			err = allocate_buffers(cpuhw, hwc);
915 			if (err)
916 				break;
917 		}
918 	}
919 
920 	/* If PID/TID sampling is active, replace the default overflow
921 	 * handler to extract and resolve the PIDs from the basic-sampling
922 	 * data entries.
923 	 */
924 	if (event->attr.sample_type & PERF_SAMPLE_TID)
925 		if (is_default_overflow_handler(event))
926 			event->overflow_handler = cpumsf_output_event_pid;
927 out:
928 	return err;
929 }
930 
931 static bool is_callchain_event(struct perf_event *event)
932 {
933 	u64 sample_type = event->attr.sample_type;
934 
935 	return sample_type & (PERF_SAMPLE_CALLCHAIN | PERF_SAMPLE_REGS_USER |
936 			      PERF_SAMPLE_STACK_USER);
937 }
938 
939 static int cpumsf_pmu_event_init(struct perf_event *event)
940 {
941 	int err;
942 
943 	/* No support for taken branch sampling */
944 	/* No support for callchain, stacks and registers */
945 	if (has_branch_stack(event) || is_callchain_event(event))
946 		return -EOPNOTSUPP;
947 
948 	switch (event->attr.type) {
949 	case PERF_TYPE_RAW:
950 		if ((event->attr.config != PERF_EVENT_CPUM_SF) &&
951 		    (event->attr.config != PERF_EVENT_CPUM_SF_DIAG))
952 			return -ENOENT;
953 		break;
954 	case PERF_TYPE_HARDWARE:
955 		/* Support sampling of CPU cycles in addition to the
956 		 * counter facility.  However, the counter facility
957 		 * is more precise and, hence, restrict this PMU to
958 		 * sampling events only.
959 		 */
960 		if (event->attr.config != PERF_COUNT_HW_CPU_CYCLES)
961 			return -ENOENT;
962 		if (!is_sampling_event(event))
963 			return -ENOENT;
964 		break;
965 	default:
966 		return -ENOENT;
967 	}
968 
969 	/* Check online status of the CPU to which the event is pinned */
970 	if (event->cpu >= 0 && !cpu_online(event->cpu))
971 		return -ENODEV;
972 
973 	/* Force reset of idle/hv excludes regardless of what the
974 	 * user requested.
975 	 */
976 	if (event->attr.exclude_hv)
977 		event->attr.exclude_hv = 0;
978 	if (event->attr.exclude_idle)
979 		event->attr.exclude_idle = 0;
980 
981 	err = __hw_perf_event_init(event);
982 	if (unlikely(err))
983 		if (event->destroy)
984 			event->destroy(event);
985 	return err;
986 }
987 
988 static void cpumsf_pmu_enable(struct pmu *pmu)
989 {
990 	struct cpu_hw_sf *cpuhw = this_cpu_ptr(&cpu_hw_sf);
991 	struct hw_perf_event *hwc;
992 	int err;
993 
994 	if (cpuhw->flags & PMU_F_ENABLED)
995 		return;
996 
997 	if (cpuhw->flags & PMU_F_ERR_MASK)
998 		return;
999 
1000 	/* Check whether to extent the sampling buffer.
1001 	 *
1002 	 * Two conditions trigger an increase of the sampling buffer for a
1003 	 * perf event:
1004 	 *    1. Postponed buffer allocations from the event initialization.
1005 	 *    2. Sampling overflows that contribute to pending allocations.
1006 	 *
1007 	 * Note that the extend_sampling_buffer() function disables the sampling
1008 	 * facility, but it can be fully re-enabled using sampling controls that
1009 	 * have been saved in cpumsf_pmu_disable().
1010 	 */
1011 	if (cpuhw->event) {
1012 		hwc = &cpuhw->event->hw;
1013 		if (!(SAMPL_DIAG_MODE(hwc))) {
1014 			/*
1015 			 * Account number of overflow-designated
1016 			 * buffer extents
1017 			 */
1018 			sfb_account_overflows(cpuhw, hwc);
1019 			extend_sampling_buffer(&cpuhw->sfb, hwc);
1020 		}
1021 		/* Rate may be adjusted with ioctl() */
1022 		cpuhw->lsctl.interval = SAMPL_RATE(&cpuhw->event->hw);
1023 	}
1024 
1025 	/* (Re)enable the PMU and sampling facility */
1026 	cpuhw->flags |= PMU_F_ENABLED;
1027 	barrier();
1028 
1029 	err = lsctl(&cpuhw->lsctl);
1030 	if (err) {
1031 		cpuhw->flags &= ~PMU_F_ENABLED;
1032 		pr_err("Loading sampling controls failed: op %i err %i\n",
1033 			1, err);
1034 		return;
1035 	}
1036 
1037 	/* Load current program parameter */
1038 	lpp(&S390_lowcore.lpp);
1039 
1040 	debug_sprintf_event(sfdbg, 6, "%s: es %i cs %i ed %i cd %i "
1041 			    "interval %#lx tear %#lx dear %#lx\n", __func__,
1042 			    cpuhw->lsctl.es, cpuhw->lsctl.cs, cpuhw->lsctl.ed,
1043 			    cpuhw->lsctl.cd, cpuhw->lsctl.interval,
1044 			    cpuhw->lsctl.tear, cpuhw->lsctl.dear);
1045 }
1046 
1047 static void cpumsf_pmu_disable(struct pmu *pmu)
1048 {
1049 	struct cpu_hw_sf *cpuhw = this_cpu_ptr(&cpu_hw_sf);
1050 	struct hws_lsctl_request_block inactive;
1051 	struct hws_qsi_info_block si;
1052 	int err;
1053 
1054 	if (!(cpuhw->flags & PMU_F_ENABLED))
1055 		return;
1056 
1057 	if (cpuhw->flags & PMU_F_ERR_MASK)
1058 		return;
1059 
1060 	/* Switch off sampling activation control */
1061 	inactive = cpuhw->lsctl;
1062 	inactive.cs = 0;
1063 	inactive.cd = 0;
1064 
1065 	err = lsctl(&inactive);
1066 	if (err) {
1067 		pr_err("Loading sampling controls failed: op %i err %i\n",
1068 			2, err);
1069 		return;
1070 	}
1071 
1072 	/* Save state of TEAR and DEAR register contents */
1073 	err = qsi(&si);
1074 	if (!err) {
1075 		/* TEAR/DEAR values are valid only if the sampling facility is
1076 		 * enabled.  Note that cpumsf_pmu_disable() might be called even
1077 		 * for a disabled sampling facility because cpumsf_pmu_enable()
1078 		 * controls the enable/disable state.
1079 		 */
1080 		if (si.es) {
1081 			cpuhw->lsctl.tear = si.tear;
1082 			cpuhw->lsctl.dear = si.dear;
1083 		}
1084 	} else
1085 		debug_sprintf_event(sfdbg, 3, "%s: qsi() failed with err %i\n",
1086 				    __func__, err);
1087 
1088 	cpuhw->flags &= ~PMU_F_ENABLED;
1089 }
1090 
1091 /* perf_exclude_event() - Filter event
1092  * @event:	The perf event
1093  * @regs:	pt_regs structure
1094  * @sde_regs:	Sample-data-entry (sde) regs structure
1095  *
1096  * Filter perf events according to their exclude specification.
1097  *
1098  * Return non-zero if the event shall be excluded.
1099  */
1100 static int perf_exclude_event(struct perf_event *event, struct pt_regs *regs,
1101 			      struct perf_sf_sde_regs *sde_regs)
1102 {
1103 	if (event->attr.exclude_user && user_mode(regs))
1104 		return 1;
1105 	if (event->attr.exclude_kernel && !user_mode(regs))
1106 		return 1;
1107 	if (event->attr.exclude_guest && sde_regs->in_guest)
1108 		return 1;
1109 	if (event->attr.exclude_host && !sde_regs->in_guest)
1110 		return 1;
1111 	return 0;
1112 }
1113 
1114 /* perf_push_sample() - Push samples to perf
1115  * @event:	The perf event
1116  * @sample:	Hardware sample data
1117  *
1118  * Use the hardware sample data to create perf event sample.  The sample
1119  * is the pushed to the event subsystem and the function checks for
1120  * possible event overflows.  If an event overflow occurs, the PMU is
1121  * stopped.
1122  *
1123  * Return non-zero if an event overflow occurred.
1124  */
1125 static int perf_push_sample(struct perf_event *event,
1126 			    struct hws_basic_entry *basic)
1127 {
1128 	int overflow;
1129 	struct pt_regs regs;
1130 	struct perf_sf_sde_regs *sde_regs;
1131 	struct perf_sample_data data;
1132 
1133 	/* Setup perf sample */
1134 	perf_sample_data_init(&data, 0, event->hw.last_period);
1135 
1136 	/* Setup pt_regs to look like an CPU-measurement external interrupt
1137 	 * using the Program Request Alert code.  The regs.int_parm_long
1138 	 * field which is unused contains additional sample-data-entry related
1139 	 * indicators.
1140 	 */
1141 	memset(&regs, 0, sizeof(regs));
1142 	regs.int_code = 0x1407;
1143 	regs.int_parm = CPU_MF_INT_SF_PRA;
1144 	sde_regs = (struct perf_sf_sde_regs *) &regs.int_parm_long;
1145 
1146 	psw_bits(regs.psw).ia	= basic->ia;
1147 	psw_bits(regs.psw).dat	= basic->T;
1148 	psw_bits(regs.psw).wait = basic->W;
1149 	psw_bits(regs.psw).pstate = basic->P;
1150 	psw_bits(regs.psw).as	= basic->AS;
1151 
1152 	/*
1153 	 * Use the hardware provided configuration level to decide if the
1154 	 * sample belongs to a guest or host. If that is not available,
1155 	 * fall back to the following heuristics:
1156 	 * A non-zero guest program parameter always indicates a guest
1157 	 * sample. Some early samples or samples from guests without
1158 	 * lpp usage would be misaccounted to the host. We use the asn
1159 	 * value as an addon heuristic to detect most of these guest samples.
1160 	 * If the value differs from 0xffff (the host value), we assume to
1161 	 * be a KVM guest.
1162 	 */
1163 	switch (basic->CL) {
1164 	case 1: /* logical partition */
1165 		sde_regs->in_guest = 0;
1166 		break;
1167 	case 2: /* virtual machine */
1168 		sde_regs->in_guest = 1;
1169 		break;
1170 	default: /* old machine, use heuristics */
1171 		if (basic->gpp || basic->prim_asn != 0xffff)
1172 			sde_regs->in_guest = 1;
1173 		break;
1174 	}
1175 
1176 	/*
1177 	 * Store the PID value from the sample-data-entry to be
1178 	 * processed and resolved by cpumsf_output_event_pid().
1179 	 */
1180 	data.tid_entry.pid = basic->hpp & LPP_PID_MASK;
1181 
1182 	overflow = 0;
1183 	if (perf_exclude_event(event, &regs, sde_regs))
1184 		goto out;
1185 	if (perf_event_overflow(event, &data, &regs)) {
1186 		overflow = 1;
1187 		event->pmu->stop(event, 0);
1188 	}
1189 	perf_event_update_userpage(event);
1190 out:
1191 	return overflow;
1192 }
1193 
1194 static void perf_event_count_update(struct perf_event *event, u64 count)
1195 {
1196 	local64_add(count, &event->count);
1197 }
1198 
1199 /* hw_collect_samples() - Walk through a sample-data-block and collect samples
1200  * @event:	The perf event
1201  * @sdbt:	Sample-data-block table
1202  * @overflow:	Event overflow counter
1203  *
1204  * Walks through a sample-data-block and collects sampling data entries that are
1205  * then pushed to the perf event subsystem.  Depending on the sampling function,
1206  * there can be either basic-sampling or combined-sampling data entries.  A
1207  * combined-sampling data entry consists of a basic- and a diagnostic-sampling
1208  * data entry.	The sampling function is determined by the flags in the perf
1209  * event hardware structure.  The function always works with a combined-sampling
1210  * data entry but ignores the the diagnostic portion if it is not available.
1211  *
1212  * Note that the implementation focuses on basic-sampling data entries and, if
1213  * such an entry is not valid, the entire combined-sampling data entry is
1214  * ignored.
1215  *
1216  * The overflow variables counts the number of samples that has been discarded
1217  * due to a perf event overflow.
1218  */
1219 static void hw_collect_samples(struct perf_event *event, unsigned long *sdbt,
1220 			       unsigned long long *overflow)
1221 {
1222 	struct hws_trailer_entry *te;
1223 	struct hws_basic_entry *sample;
1224 
1225 	te = trailer_entry_ptr((unsigned long)sdbt);
1226 	sample = (struct hws_basic_entry *)sdbt;
1227 	while ((unsigned long *) sample < (unsigned long *) te) {
1228 		/* Check for an empty sample */
1229 		if (!sample->def || sample->LS)
1230 			break;
1231 
1232 		/* Update perf event period */
1233 		perf_event_count_update(event, SAMPL_RATE(&event->hw));
1234 
1235 		/* Check whether sample is valid */
1236 		if (sample->def == 0x0001) {
1237 			/* If an event overflow occurred, the PMU is stopped to
1238 			 * throttle event delivery.  Remaining sample data is
1239 			 * discarded.
1240 			 */
1241 			if (!*overflow) {
1242 				/* Check whether sample is consistent */
1243 				if (sample->I == 0 && sample->W == 0) {
1244 					/* Deliver sample data to perf */
1245 					*overflow = perf_push_sample(event,
1246 								     sample);
1247 				}
1248 			} else
1249 				/* Count discarded samples */
1250 				*overflow += 1;
1251 		} else {
1252 			debug_sprintf_event(sfdbg, 4,
1253 					    "%s: Found unknown"
1254 					    " sampling data entry: te->f %i"
1255 					    " basic.def %#4x (%p)\n", __func__,
1256 					    te->header.f, sample->def, sample);
1257 			/* Sample slot is not yet written or other record.
1258 			 *
1259 			 * This condition can occur if the buffer was reused
1260 			 * from a combined basic- and diagnostic-sampling.
1261 			 * If only basic-sampling is then active, entries are
1262 			 * written into the larger diagnostic entries.
1263 			 * This is typically the case for sample-data-blocks
1264 			 * that are not full.  Stop processing if the first
1265 			 * invalid format was detected.
1266 			 */
1267 			if (!te->header.f)
1268 				break;
1269 		}
1270 
1271 		/* Reset sample slot and advance to next sample */
1272 		sample->def = 0;
1273 		sample++;
1274 	}
1275 }
1276 
1277 static inline __uint128_t __cdsg(__uint128_t *ptr, __uint128_t old, __uint128_t new)
1278 {
1279 	asm volatile(
1280 		"	cdsg	%[old],%[new],%[ptr]\n"
1281 		: [old] "+d" (old), [ptr] "+QS" (*ptr)
1282 		: [new] "d" (new)
1283 		: "memory", "cc");
1284 	return old;
1285 }
1286 
1287 /* hw_perf_event_update() - Process sampling buffer
1288  * @event:	The perf event
1289  * @flush_all:	Flag to also flush partially filled sample-data-blocks
1290  *
1291  * Processes the sampling buffer and create perf event samples.
1292  * The sampling buffer position are retrieved and saved in the TEAR_REG
1293  * register of the specified perf event.
1294  *
1295  * Only full sample-data-blocks are processed.	Specify the flash_all flag
1296  * to also walk through partially filled sample-data-blocks.  It is ignored
1297  * if PERF_CPUM_SF_FULL_BLOCKS is set.	The PERF_CPUM_SF_FULL_BLOCKS flag
1298  * enforces the processing of full sample-data-blocks only (trailer entries
1299  * with the block-full-indicator bit set).
1300  */
1301 static void hw_perf_event_update(struct perf_event *event, int flush_all)
1302 {
1303 	unsigned long long event_overflow, sampl_overflow, num_sdb;
1304 	union hws_trailer_header old, prev, new;
1305 	struct hw_perf_event *hwc = &event->hw;
1306 	struct hws_trailer_entry *te;
1307 	unsigned long *sdbt, sdb;
1308 	int done;
1309 
1310 	/*
1311 	 * AUX buffer is used when in diagnostic sampling mode.
1312 	 * No perf events/samples are created.
1313 	 */
1314 	if (SAMPL_DIAG_MODE(&event->hw))
1315 		return;
1316 
1317 	if (flush_all && SDB_FULL_BLOCKS(hwc))
1318 		flush_all = 0;
1319 
1320 	sdbt = (unsigned long *) TEAR_REG(hwc);
1321 	done = event_overflow = sampl_overflow = num_sdb = 0;
1322 	while (!done) {
1323 		/* Get the trailer entry of the sample-data-block */
1324 		sdb = (unsigned long)phys_to_virt(*sdbt);
1325 		te = trailer_entry_ptr(sdb);
1326 
1327 		/* Leave loop if no more work to do (block full indicator) */
1328 		if (!te->header.f) {
1329 			done = 1;
1330 			if (!flush_all)
1331 				break;
1332 		}
1333 
1334 		/* Check the sample overflow count */
1335 		if (te->header.overflow)
1336 			/* Account sample overflows and, if a particular limit
1337 			 * is reached, extend the sampling buffer.
1338 			 * For details, see sfb_account_overflows().
1339 			 */
1340 			sampl_overflow += te->header.overflow;
1341 
1342 		/* Timestamps are valid for full sample-data-blocks only */
1343 		debug_sprintf_event(sfdbg, 6, "%s: sdbt %#lx/%#lx "
1344 				    "overflow %llu timestamp %#llx\n",
1345 				    __func__, sdb, (unsigned long)sdbt,
1346 				    te->header.overflow,
1347 				    (te->header.f) ? trailer_timestamp(te) : 0ULL);
1348 
1349 		/* Collect all samples from a single sample-data-block and
1350 		 * flag if an (perf) event overflow happened.  If so, the PMU
1351 		 * is stopped and remaining samples will be discarded.
1352 		 */
1353 		hw_collect_samples(event, (unsigned long *)sdb, &event_overflow);
1354 		num_sdb++;
1355 
1356 		/* Reset trailer (using compare-double-and-swap) */
1357 		/* READ_ONCE() 16 byte header */
1358 		prev.val = __cdsg(&te->header.val, 0, 0);
1359 		do {
1360 			old.val = prev.val;
1361 			new.val = prev.val;
1362 			new.f = 0;
1363 			new.a = 1;
1364 			new.overflow = 0;
1365 			prev.val = __cdsg(&te->header.val, old.val, new.val);
1366 		} while (prev.val != old.val);
1367 
1368 		/* Advance to next sample-data-block */
1369 		sdbt++;
1370 		if (is_link_entry(sdbt))
1371 			sdbt = get_next_sdbt(sdbt);
1372 
1373 		/* Update event hardware registers */
1374 		TEAR_REG(hwc) = (unsigned long) sdbt;
1375 
1376 		/* Stop processing sample-data if all samples of the current
1377 		 * sample-data-block were flushed even if it was not full.
1378 		 */
1379 		if (flush_all && done)
1380 			break;
1381 	}
1382 
1383 	/* Account sample overflows in the event hardware structure */
1384 	if (sampl_overflow)
1385 		OVERFLOW_REG(hwc) = DIV_ROUND_UP(OVERFLOW_REG(hwc) +
1386 						 sampl_overflow, 1 + num_sdb);
1387 
1388 	/* Perf_event_overflow() and perf_event_account_interrupt() limit
1389 	 * the interrupt rate to an upper limit. Roughly 1000 samples per
1390 	 * task tick.
1391 	 * Hitting this limit results in a large number
1392 	 * of throttled REF_REPORT_THROTTLE entries and the samples
1393 	 * are dropped.
1394 	 * Slightly increase the interval to avoid hitting this limit.
1395 	 */
1396 	if (event_overflow) {
1397 		SAMPL_RATE(hwc) += DIV_ROUND_UP(SAMPL_RATE(hwc), 10);
1398 		debug_sprintf_event(sfdbg, 1, "%s: rate adjustment %ld\n",
1399 				    __func__,
1400 				    DIV_ROUND_UP(SAMPL_RATE(hwc), 10));
1401 	}
1402 
1403 	if (sampl_overflow || event_overflow)
1404 		debug_sprintf_event(sfdbg, 4, "%s: "
1405 				    "overflows: sample %llu event %llu"
1406 				    " total %llu num_sdb %llu\n",
1407 				    __func__, sampl_overflow, event_overflow,
1408 				    OVERFLOW_REG(hwc), num_sdb);
1409 }
1410 
1411 #define AUX_SDB_INDEX(aux, i) ((i) % aux->sfb.num_sdb)
1412 #define AUX_SDB_NUM(aux, start, end) (end >= start ? end - start + 1 : 0)
1413 #define AUX_SDB_NUM_ALERT(aux) AUX_SDB_NUM(aux, aux->head, aux->alert_mark)
1414 #define AUX_SDB_NUM_EMPTY(aux) AUX_SDB_NUM(aux, aux->head, aux->empty_mark)
1415 
1416 /*
1417  * Get trailer entry by index of SDB.
1418  */
1419 static struct hws_trailer_entry *aux_sdb_trailer(struct aux_buffer *aux,
1420 						 unsigned long index)
1421 {
1422 	unsigned long sdb;
1423 
1424 	index = AUX_SDB_INDEX(aux, index);
1425 	sdb = aux->sdb_index[index];
1426 	return trailer_entry_ptr(sdb);
1427 }
1428 
1429 /*
1430  * Finish sampling on the cpu. Called by cpumsf_pmu_del() with pmu
1431  * disabled. Collect the full SDBs in AUX buffer which have not reached
1432  * the point of alert indicator. And ignore the SDBs which are not
1433  * full.
1434  *
1435  * 1. Scan SDBs to see how much data is there and consume them.
1436  * 2. Remove alert indicator in the buffer.
1437  */
1438 static void aux_output_end(struct perf_output_handle *handle)
1439 {
1440 	unsigned long i, range_scan, idx;
1441 	struct aux_buffer *aux;
1442 	struct hws_trailer_entry *te;
1443 
1444 	aux = perf_get_aux(handle);
1445 	if (!aux)
1446 		return;
1447 
1448 	range_scan = AUX_SDB_NUM_ALERT(aux);
1449 	for (i = 0, idx = aux->head; i < range_scan; i++, idx++) {
1450 		te = aux_sdb_trailer(aux, idx);
1451 		if (!te->header.f)
1452 			break;
1453 	}
1454 	/* i is num of SDBs which are full */
1455 	perf_aux_output_end(handle, i << PAGE_SHIFT);
1456 
1457 	/* Remove alert indicators in the buffer */
1458 	te = aux_sdb_trailer(aux, aux->alert_mark);
1459 	te->header.a = 0;
1460 
1461 	debug_sprintf_event(sfdbg, 6, "%s: SDBs %ld range %ld head %ld\n",
1462 			    __func__, i, range_scan, aux->head);
1463 }
1464 
1465 /*
1466  * Start sampling on the CPU. Called by cpumsf_pmu_add() when an event
1467  * is first added to the CPU or rescheduled again to the CPU. It is called
1468  * with pmu disabled.
1469  *
1470  * 1. Reset the trailer of SDBs to get ready for new data.
1471  * 2. Tell the hardware where to put the data by reset the SDBs buffer
1472  *    head(tear/dear).
1473  */
1474 static int aux_output_begin(struct perf_output_handle *handle,
1475 			    struct aux_buffer *aux,
1476 			    struct cpu_hw_sf *cpuhw)
1477 {
1478 	unsigned long range;
1479 	unsigned long i, range_scan, idx;
1480 	unsigned long head, base, offset;
1481 	struct hws_trailer_entry *te;
1482 
1483 	if (WARN_ON_ONCE(handle->head & ~PAGE_MASK))
1484 		return -EINVAL;
1485 
1486 	aux->head = handle->head >> PAGE_SHIFT;
1487 	range = (handle->size + 1) >> PAGE_SHIFT;
1488 	if (range <= 1)
1489 		return -ENOMEM;
1490 
1491 	/*
1492 	 * SDBs between aux->head and aux->empty_mark are already ready
1493 	 * for new data. range_scan is num of SDBs not within them.
1494 	 */
1495 	debug_sprintf_event(sfdbg, 6,
1496 			    "%s: range %ld head %ld alert %ld empty %ld\n",
1497 			    __func__, range, aux->head, aux->alert_mark,
1498 			    aux->empty_mark);
1499 	if (range > AUX_SDB_NUM_EMPTY(aux)) {
1500 		range_scan = range - AUX_SDB_NUM_EMPTY(aux);
1501 		idx = aux->empty_mark + 1;
1502 		for (i = 0; i < range_scan; i++, idx++) {
1503 			te = aux_sdb_trailer(aux, idx);
1504 			te->header.f = 0;
1505 			te->header.a = 0;
1506 			te->header.overflow = 0;
1507 		}
1508 		/* Save the position of empty SDBs */
1509 		aux->empty_mark = aux->head + range - 1;
1510 	}
1511 
1512 	/* Set alert indicator */
1513 	aux->alert_mark = aux->head + range/2 - 1;
1514 	te = aux_sdb_trailer(aux, aux->alert_mark);
1515 	te->header.a = 1;
1516 
1517 	/* Reset hardware buffer head */
1518 	head = AUX_SDB_INDEX(aux, aux->head);
1519 	base = aux->sdbt_index[head / CPUM_SF_SDB_PER_TABLE];
1520 	offset = head % CPUM_SF_SDB_PER_TABLE;
1521 	cpuhw->lsctl.tear = base + offset * sizeof(unsigned long);
1522 	cpuhw->lsctl.dear = aux->sdb_index[head];
1523 
1524 	debug_sprintf_event(sfdbg, 6, "%s: head %ld alert %ld empty %ld "
1525 			    "index %ld tear %#lx dear %#lx\n", __func__,
1526 			    aux->head, aux->alert_mark, aux->empty_mark,
1527 			    head / CPUM_SF_SDB_PER_TABLE,
1528 			    cpuhw->lsctl.tear, cpuhw->lsctl.dear);
1529 
1530 	return 0;
1531 }
1532 
1533 /*
1534  * Set alert indicator on SDB at index @alert_index while sampler is running.
1535  *
1536  * Return true if successfully.
1537  * Return false if full indicator is already set by hardware sampler.
1538  */
1539 static bool aux_set_alert(struct aux_buffer *aux, unsigned long alert_index,
1540 			  unsigned long long *overflow)
1541 {
1542 	union hws_trailer_header old, prev, new;
1543 	struct hws_trailer_entry *te;
1544 
1545 	te = aux_sdb_trailer(aux, alert_index);
1546 	/* READ_ONCE() 16 byte header */
1547 	prev.val = __cdsg(&te->header.val, 0, 0);
1548 	do {
1549 		old.val = prev.val;
1550 		new.val = prev.val;
1551 		*overflow = old.overflow;
1552 		if (old.f) {
1553 			/*
1554 			 * SDB is already set by hardware.
1555 			 * Abort and try to set somewhere
1556 			 * behind.
1557 			 */
1558 			return false;
1559 		}
1560 		new.a = 1;
1561 		new.overflow = 0;
1562 		prev.val = __cdsg(&te->header.val, old.val, new.val);
1563 	} while (prev.val != old.val);
1564 	return true;
1565 }
1566 
1567 /*
1568  * aux_reset_buffer() - Scan and setup SDBs for new samples
1569  * @aux:	The AUX buffer to set
1570  * @range:	The range of SDBs to scan started from aux->head
1571  * @overflow:	Set to overflow count
1572  *
1573  * Set alert indicator on the SDB at index of aux->alert_mark. If this SDB is
1574  * marked as empty, check if it is already set full by the hardware sampler.
1575  * If yes, that means new data is already there before we can set an alert
1576  * indicator. Caller should try to set alert indicator to some position behind.
1577  *
1578  * Scan the SDBs in AUX buffer from behind aux->empty_mark. They are used
1579  * previously and have already been consumed by user space. Reset these SDBs
1580  * (clear full indicator and alert indicator) for new data.
1581  * If aux->alert_mark fall in this area, just set it. Overflow count is
1582  * recorded while scanning.
1583  *
1584  * SDBs between aux->head and aux->empty_mark are already reset at last time.
1585  * and ready for new samples. So scanning on this area could be skipped.
1586  *
1587  * Return true if alert indicator is set successfully and false if not.
1588  */
1589 static bool aux_reset_buffer(struct aux_buffer *aux, unsigned long range,
1590 			     unsigned long long *overflow)
1591 {
1592 	unsigned long i, range_scan, idx, idx_old;
1593 	union hws_trailer_header old, prev, new;
1594 	unsigned long long orig_overflow;
1595 	struct hws_trailer_entry *te;
1596 
1597 	debug_sprintf_event(sfdbg, 6, "%s: range %ld head %ld alert %ld "
1598 			    "empty %ld\n", __func__, range, aux->head,
1599 			    aux->alert_mark, aux->empty_mark);
1600 	if (range <= AUX_SDB_NUM_EMPTY(aux))
1601 		/*
1602 		 * No need to scan. All SDBs in range are marked as empty.
1603 		 * Just set alert indicator. Should check race with hardware
1604 		 * sampler.
1605 		 */
1606 		return aux_set_alert(aux, aux->alert_mark, overflow);
1607 
1608 	if (aux->alert_mark <= aux->empty_mark)
1609 		/*
1610 		 * Set alert indicator on empty SDB. Should check race
1611 		 * with hardware sampler.
1612 		 */
1613 		if (!aux_set_alert(aux, aux->alert_mark, overflow))
1614 			return false;
1615 
1616 	/*
1617 	 * Scan the SDBs to clear full and alert indicator used previously.
1618 	 * Start scanning from one SDB behind empty_mark. If the new alert
1619 	 * indicator fall into this range, set it.
1620 	 */
1621 	range_scan = range - AUX_SDB_NUM_EMPTY(aux);
1622 	idx_old = idx = aux->empty_mark + 1;
1623 	for (i = 0; i < range_scan; i++, idx++) {
1624 		te = aux_sdb_trailer(aux, idx);
1625 		/* READ_ONCE() 16 byte header */
1626 		prev.val = __cdsg(&te->header.val, 0, 0);
1627 		do {
1628 			old.val = prev.val;
1629 			new.val = prev.val;
1630 			orig_overflow = old.overflow;
1631 			new.f = 0;
1632 			new.overflow = 0;
1633 			if (idx == aux->alert_mark)
1634 				new.a = 1;
1635 			else
1636 				new.a = 0;
1637 			prev.val = __cdsg(&te->header.val, old.val, new.val);
1638 		} while (prev.val != old.val);
1639 		*overflow += orig_overflow;
1640 	}
1641 
1642 	/* Update empty_mark to new position */
1643 	aux->empty_mark = aux->head + range - 1;
1644 
1645 	debug_sprintf_event(sfdbg, 6, "%s: range_scan %ld idx %ld..%ld "
1646 			    "empty %ld\n", __func__, range_scan, idx_old,
1647 			    idx - 1, aux->empty_mark);
1648 	return true;
1649 }
1650 
1651 /*
1652  * Measurement alert handler for diagnostic mode sampling.
1653  */
1654 static void hw_collect_aux(struct cpu_hw_sf *cpuhw)
1655 {
1656 	struct aux_buffer *aux;
1657 	int done = 0;
1658 	unsigned long range = 0, size;
1659 	unsigned long long overflow = 0;
1660 	struct perf_output_handle *handle = &cpuhw->handle;
1661 	unsigned long num_sdb;
1662 
1663 	aux = perf_get_aux(handle);
1664 	if (WARN_ON_ONCE(!aux))
1665 		return;
1666 
1667 	/* Inform user space new data arrived */
1668 	size = AUX_SDB_NUM_ALERT(aux) << PAGE_SHIFT;
1669 	debug_sprintf_event(sfdbg, 6, "%s: #alert %ld\n", __func__,
1670 			    size >> PAGE_SHIFT);
1671 	perf_aux_output_end(handle, size);
1672 
1673 	num_sdb = aux->sfb.num_sdb;
1674 	while (!done) {
1675 		/* Get an output handle */
1676 		aux = perf_aux_output_begin(handle, cpuhw->event);
1677 		if (handle->size == 0) {
1678 			pr_err("The AUX buffer with %lu pages for the "
1679 			       "diagnostic-sampling mode is full\n",
1680 				num_sdb);
1681 			debug_sprintf_event(sfdbg, 1,
1682 					    "%s: AUX buffer used up\n",
1683 					    __func__);
1684 			break;
1685 		}
1686 		if (WARN_ON_ONCE(!aux))
1687 			return;
1688 
1689 		/* Update head and alert_mark to new position */
1690 		aux->head = handle->head >> PAGE_SHIFT;
1691 		range = (handle->size + 1) >> PAGE_SHIFT;
1692 		if (range == 1)
1693 			aux->alert_mark = aux->head;
1694 		else
1695 			aux->alert_mark = aux->head + range/2 - 1;
1696 
1697 		if (aux_reset_buffer(aux, range, &overflow)) {
1698 			if (!overflow) {
1699 				done = 1;
1700 				break;
1701 			}
1702 			size = range << PAGE_SHIFT;
1703 			perf_aux_output_end(&cpuhw->handle, size);
1704 			pr_err("Sample data caused the AUX buffer with %lu "
1705 			       "pages to overflow\n", aux->sfb.num_sdb);
1706 			debug_sprintf_event(sfdbg, 1, "%s: head %ld range %ld "
1707 					    "overflow %lld\n", __func__,
1708 					    aux->head, range, overflow);
1709 		} else {
1710 			size = AUX_SDB_NUM_ALERT(aux) << PAGE_SHIFT;
1711 			perf_aux_output_end(&cpuhw->handle, size);
1712 			debug_sprintf_event(sfdbg, 6, "%s: head %ld alert %ld "
1713 					    "already full, try another\n",
1714 					    __func__,
1715 					    aux->head, aux->alert_mark);
1716 		}
1717 	}
1718 
1719 	if (done)
1720 		debug_sprintf_event(sfdbg, 6, "%s: head %ld alert %ld "
1721 				    "empty %ld\n", __func__, aux->head,
1722 				    aux->alert_mark, aux->empty_mark);
1723 }
1724 
1725 /*
1726  * Callback when freeing AUX buffers.
1727  */
1728 static void aux_buffer_free(void *data)
1729 {
1730 	struct aux_buffer *aux = data;
1731 	unsigned long i, num_sdbt;
1732 
1733 	if (!aux)
1734 		return;
1735 
1736 	/* Free SDBT. SDB is freed by the caller */
1737 	num_sdbt = aux->sfb.num_sdbt;
1738 	for (i = 0; i < num_sdbt; i++)
1739 		free_page(aux->sdbt_index[i]);
1740 
1741 	kfree(aux->sdbt_index);
1742 	kfree(aux->sdb_index);
1743 	kfree(aux);
1744 
1745 	debug_sprintf_event(sfdbg, 4, "%s: SDBTs %lu\n", __func__, num_sdbt);
1746 }
1747 
1748 static void aux_sdb_init(unsigned long sdb)
1749 {
1750 	struct hws_trailer_entry *te;
1751 
1752 	te = trailer_entry_ptr(sdb);
1753 
1754 	/* Save clock base */
1755 	te->clock_base = 1;
1756 	te->progusage2 = tod_clock_base.tod;
1757 }
1758 
1759 /*
1760  * aux_buffer_setup() - Setup AUX buffer for diagnostic mode sampling
1761  * @event:	Event the buffer is setup for, event->cpu == -1 means current
1762  * @pages:	Array of pointers to buffer pages passed from perf core
1763  * @nr_pages:	Total pages
1764  * @snapshot:	Flag for snapshot mode
1765  *
1766  * This is the callback when setup an event using AUX buffer. Perf tool can
1767  * trigger this by an additional mmap() call on the event. Unlike the buffer
1768  * for basic samples, AUX buffer belongs to the event. It is scheduled with
1769  * the task among online cpus when it is a per-thread event.
1770  *
1771  * Return the private AUX buffer structure if success or NULL if fails.
1772  */
1773 static void *aux_buffer_setup(struct perf_event *event, void **pages,
1774 			      int nr_pages, bool snapshot)
1775 {
1776 	struct sf_buffer *sfb;
1777 	struct aux_buffer *aux;
1778 	unsigned long *new, *tail;
1779 	int i, n_sdbt;
1780 
1781 	if (!nr_pages || !pages)
1782 		return NULL;
1783 
1784 	if (nr_pages > CPUM_SF_MAX_SDB * CPUM_SF_SDB_DIAG_FACTOR) {
1785 		pr_err("AUX buffer size (%i pages) is larger than the "
1786 		       "maximum sampling buffer limit\n",
1787 		       nr_pages);
1788 		return NULL;
1789 	} else if (nr_pages < CPUM_SF_MIN_SDB * CPUM_SF_SDB_DIAG_FACTOR) {
1790 		pr_err("AUX buffer size (%i pages) is less than the "
1791 		       "minimum sampling buffer limit\n",
1792 		       nr_pages);
1793 		return NULL;
1794 	}
1795 
1796 	/* Allocate aux_buffer struct for the event */
1797 	aux = kzalloc(sizeof(struct aux_buffer), GFP_KERNEL);
1798 	if (!aux)
1799 		goto no_aux;
1800 	sfb = &aux->sfb;
1801 
1802 	/* Allocate sdbt_index for fast reference */
1803 	n_sdbt = DIV_ROUND_UP(nr_pages, CPUM_SF_SDB_PER_TABLE);
1804 	aux->sdbt_index = kmalloc_array(n_sdbt, sizeof(void *), GFP_KERNEL);
1805 	if (!aux->sdbt_index)
1806 		goto no_sdbt_index;
1807 
1808 	/* Allocate sdb_index for fast reference */
1809 	aux->sdb_index = kmalloc_array(nr_pages, sizeof(void *), GFP_KERNEL);
1810 	if (!aux->sdb_index)
1811 		goto no_sdb_index;
1812 
1813 	/* Allocate the first SDBT */
1814 	sfb->num_sdbt = 0;
1815 	sfb->sdbt = (unsigned long *) get_zeroed_page(GFP_KERNEL);
1816 	if (!sfb->sdbt)
1817 		goto no_sdbt;
1818 	aux->sdbt_index[sfb->num_sdbt++] = (unsigned long)sfb->sdbt;
1819 	tail = sfb->tail = sfb->sdbt;
1820 
1821 	/*
1822 	 * Link the provided pages of AUX buffer to SDBT.
1823 	 * Allocate SDBT if needed.
1824 	 */
1825 	for (i = 0; i < nr_pages; i++, tail++) {
1826 		if (require_table_link(tail)) {
1827 			new = (unsigned long *) get_zeroed_page(GFP_KERNEL);
1828 			if (!new)
1829 				goto no_sdbt;
1830 			aux->sdbt_index[sfb->num_sdbt++] = (unsigned long)new;
1831 			/* Link current page to tail of chain */
1832 			*tail = (unsigned long)(void *) new + 1;
1833 			tail = new;
1834 		}
1835 		/* Tail is the entry in a SDBT */
1836 		*tail = (unsigned long)pages[i];
1837 		aux->sdb_index[i] = (unsigned long)pages[i];
1838 		aux_sdb_init((unsigned long)pages[i]);
1839 	}
1840 	sfb->num_sdb = nr_pages;
1841 
1842 	/* Link the last entry in the SDBT to the first SDBT */
1843 	*tail = (unsigned long) sfb->sdbt + 1;
1844 	sfb->tail = tail;
1845 
1846 	/*
1847 	 * Initial all SDBs are zeroed. Mark it as empty.
1848 	 * So there is no need to clear the full indicator
1849 	 * when this event is first added.
1850 	 */
1851 	aux->empty_mark = sfb->num_sdb - 1;
1852 
1853 	debug_sprintf_event(sfdbg, 4, "%s: SDBTs %lu SDBs %lu\n", __func__,
1854 			    sfb->num_sdbt, sfb->num_sdb);
1855 
1856 	return aux;
1857 
1858 no_sdbt:
1859 	/* SDBs (AUX buffer pages) are freed by caller */
1860 	for (i = 0; i < sfb->num_sdbt; i++)
1861 		free_page(aux->sdbt_index[i]);
1862 	kfree(aux->sdb_index);
1863 no_sdb_index:
1864 	kfree(aux->sdbt_index);
1865 no_sdbt_index:
1866 	kfree(aux);
1867 no_aux:
1868 	return NULL;
1869 }
1870 
1871 static void cpumsf_pmu_read(struct perf_event *event)
1872 {
1873 	/* Nothing to do ... updates are interrupt-driven */
1874 }
1875 
1876 /* Check if the new sampling period/freqeuncy is appropriate.
1877  *
1878  * Return non-zero on error and zero on passed checks.
1879  */
1880 static int cpumsf_pmu_check_period(struct perf_event *event, u64 value)
1881 {
1882 	struct hws_qsi_info_block si;
1883 	unsigned long rate;
1884 	bool do_freq;
1885 
1886 	memset(&si, 0, sizeof(si));
1887 	if (event->cpu == -1) {
1888 		if (qsi(&si))
1889 			return -ENODEV;
1890 	} else {
1891 		/* Event is pinned to a particular CPU, retrieve the per-CPU
1892 		 * sampling structure for accessing the CPU-specific QSI.
1893 		 */
1894 		struct cpu_hw_sf *cpuhw = &per_cpu(cpu_hw_sf, event->cpu);
1895 
1896 		si = cpuhw->qsi;
1897 	}
1898 
1899 	do_freq = !!SAMPLE_FREQ_MODE(&event->hw);
1900 	rate = getrate(do_freq, value, &si);
1901 	if (!rate)
1902 		return -EINVAL;
1903 
1904 	event->attr.sample_period = rate;
1905 	SAMPL_RATE(&event->hw) = rate;
1906 	hw_init_period(&event->hw, SAMPL_RATE(&event->hw));
1907 	debug_sprintf_event(sfdbg, 4, "%s:"
1908 			    " cpu %d value %#llx period %#llx freq %d\n",
1909 			    __func__, event->cpu, value,
1910 			    event->attr.sample_period, do_freq);
1911 	return 0;
1912 }
1913 
1914 /* Activate sampling control.
1915  * Next call of pmu_enable() starts sampling.
1916  */
1917 static void cpumsf_pmu_start(struct perf_event *event, int flags)
1918 {
1919 	struct cpu_hw_sf *cpuhw = this_cpu_ptr(&cpu_hw_sf);
1920 
1921 	if (WARN_ON_ONCE(!(event->hw.state & PERF_HES_STOPPED)))
1922 		return;
1923 
1924 	if (flags & PERF_EF_RELOAD)
1925 		WARN_ON_ONCE(!(event->hw.state & PERF_HES_UPTODATE));
1926 
1927 	perf_pmu_disable(event->pmu);
1928 	event->hw.state = 0;
1929 	cpuhw->lsctl.cs = 1;
1930 	if (SAMPL_DIAG_MODE(&event->hw))
1931 		cpuhw->lsctl.cd = 1;
1932 	perf_pmu_enable(event->pmu);
1933 }
1934 
1935 /* Deactivate sampling control.
1936  * Next call of pmu_enable() stops sampling.
1937  */
1938 static void cpumsf_pmu_stop(struct perf_event *event, int flags)
1939 {
1940 	struct cpu_hw_sf *cpuhw = this_cpu_ptr(&cpu_hw_sf);
1941 
1942 	if (event->hw.state & PERF_HES_STOPPED)
1943 		return;
1944 
1945 	perf_pmu_disable(event->pmu);
1946 	cpuhw->lsctl.cs = 0;
1947 	cpuhw->lsctl.cd = 0;
1948 	event->hw.state |= PERF_HES_STOPPED;
1949 
1950 	if ((flags & PERF_EF_UPDATE) && !(event->hw.state & PERF_HES_UPTODATE)) {
1951 		hw_perf_event_update(event, 1);
1952 		event->hw.state |= PERF_HES_UPTODATE;
1953 	}
1954 	perf_pmu_enable(event->pmu);
1955 }
1956 
1957 static int cpumsf_pmu_add(struct perf_event *event, int flags)
1958 {
1959 	struct cpu_hw_sf *cpuhw = this_cpu_ptr(&cpu_hw_sf);
1960 	struct aux_buffer *aux;
1961 	int err;
1962 
1963 	if (cpuhw->flags & PMU_F_IN_USE)
1964 		return -EAGAIN;
1965 
1966 	if (!SAMPL_DIAG_MODE(&event->hw) && !cpuhw->sfb.sdbt)
1967 		return -EINVAL;
1968 
1969 	err = 0;
1970 	perf_pmu_disable(event->pmu);
1971 
1972 	event->hw.state = PERF_HES_UPTODATE | PERF_HES_STOPPED;
1973 
1974 	/* Set up sampling controls.  Always program the sampling register
1975 	 * using the SDB-table start.  Reset TEAR_REG event hardware register
1976 	 * that is used by hw_perf_event_update() to store the sampling buffer
1977 	 * position after samples have been flushed.
1978 	 */
1979 	cpuhw->lsctl.s = 0;
1980 	cpuhw->lsctl.h = 1;
1981 	cpuhw->lsctl.interval = SAMPL_RATE(&event->hw);
1982 	if (!SAMPL_DIAG_MODE(&event->hw)) {
1983 		cpuhw->lsctl.tear = virt_to_phys(cpuhw->sfb.sdbt);
1984 		cpuhw->lsctl.dear = *(unsigned long *) cpuhw->sfb.sdbt;
1985 		TEAR_REG(&event->hw) = (unsigned long) cpuhw->sfb.sdbt;
1986 	}
1987 
1988 	/* Ensure sampling functions are in the disabled state.  If disabled,
1989 	 * switch on sampling enable control. */
1990 	if (WARN_ON_ONCE(cpuhw->lsctl.es == 1 || cpuhw->lsctl.ed == 1)) {
1991 		err = -EAGAIN;
1992 		goto out;
1993 	}
1994 	if (SAMPL_DIAG_MODE(&event->hw)) {
1995 		aux = perf_aux_output_begin(&cpuhw->handle, event);
1996 		if (!aux) {
1997 			err = -EINVAL;
1998 			goto out;
1999 		}
2000 		err = aux_output_begin(&cpuhw->handle, aux, cpuhw);
2001 		if (err)
2002 			goto out;
2003 		cpuhw->lsctl.ed = 1;
2004 	}
2005 	cpuhw->lsctl.es = 1;
2006 
2007 	/* Set in_use flag and store event */
2008 	cpuhw->event = event;
2009 	cpuhw->flags |= PMU_F_IN_USE;
2010 
2011 	if (flags & PERF_EF_START)
2012 		cpumsf_pmu_start(event, PERF_EF_RELOAD);
2013 out:
2014 	perf_event_update_userpage(event);
2015 	perf_pmu_enable(event->pmu);
2016 	return err;
2017 }
2018 
2019 static void cpumsf_pmu_del(struct perf_event *event, int flags)
2020 {
2021 	struct cpu_hw_sf *cpuhw = this_cpu_ptr(&cpu_hw_sf);
2022 
2023 	perf_pmu_disable(event->pmu);
2024 	cpumsf_pmu_stop(event, PERF_EF_UPDATE);
2025 
2026 	cpuhw->lsctl.es = 0;
2027 	cpuhw->lsctl.ed = 0;
2028 	cpuhw->flags &= ~PMU_F_IN_USE;
2029 	cpuhw->event = NULL;
2030 
2031 	if (SAMPL_DIAG_MODE(&event->hw))
2032 		aux_output_end(&cpuhw->handle);
2033 	perf_event_update_userpage(event);
2034 	perf_pmu_enable(event->pmu);
2035 }
2036 
2037 CPUMF_EVENT_ATTR(SF, SF_CYCLES_BASIC, PERF_EVENT_CPUM_SF);
2038 CPUMF_EVENT_ATTR(SF, SF_CYCLES_BASIC_DIAG, PERF_EVENT_CPUM_SF_DIAG);
2039 
2040 /* Attribute list for CPU_SF.
2041  *
2042  * The availablitiy depends on the CPU_MF sampling facility authorization
2043  * for basic + diagnositic samples. This is determined at initialization
2044  * time by the sampling facility device driver.
2045  * If the authorization for basic samples is turned off, it should be
2046  * also turned off for diagnostic sampling.
2047  *
2048  * During initialization of the device driver, check the authorization
2049  * level for diagnostic sampling and installs the attribute
2050  * file for diagnostic sampling if necessary.
2051  *
2052  * For now install a placeholder to reference all possible attributes:
2053  * SF_CYCLES_BASIC and SF_CYCLES_BASIC_DIAG.
2054  * Add another entry for the final NULL pointer.
2055  */
2056 enum {
2057 	SF_CYCLES_BASIC_ATTR_IDX = 0,
2058 	SF_CYCLES_BASIC_DIAG_ATTR_IDX,
2059 	SF_CYCLES_ATTR_MAX
2060 };
2061 
2062 static struct attribute *cpumsf_pmu_events_attr[SF_CYCLES_ATTR_MAX + 1] = {
2063 	[SF_CYCLES_BASIC_ATTR_IDX] = CPUMF_EVENT_PTR(SF, SF_CYCLES_BASIC)
2064 };
2065 
2066 PMU_FORMAT_ATTR(event, "config:0-63");
2067 
2068 static struct attribute *cpumsf_pmu_format_attr[] = {
2069 	&format_attr_event.attr,
2070 	NULL,
2071 };
2072 
2073 static struct attribute_group cpumsf_pmu_events_group = {
2074 	.name = "events",
2075 	.attrs = cpumsf_pmu_events_attr,
2076 };
2077 
2078 static struct attribute_group cpumsf_pmu_format_group = {
2079 	.name = "format",
2080 	.attrs = cpumsf_pmu_format_attr,
2081 };
2082 
2083 static const struct attribute_group *cpumsf_pmu_attr_groups[] = {
2084 	&cpumsf_pmu_events_group,
2085 	&cpumsf_pmu_format_group,
2086 	NULL,
2087 };
2088 
2089 static struct pmu cpumf_sampling = {
2090 	.pmu_enable   = cpumsf_pmu_enable,
2091 	.pmu_disable  = cpumsf_pmu_disable,
2092 
2093 	.event_init   = cpumsf_pmu_event_init,
2094 	.add	      = cpumsf_pmu_add,
2095 	.del	      = cpumsf_pmu_del,
2096 
2097 	.start	      = cpumsf_pmu_start,
2098 	.stop	      = cpumsf_pmu_stop,
2099 	.read	      = cpumsf_pmu_read,
2100 
2101 	.attr_groups  = cpumsf_pmu_attr_groups,
2102 
2103 	.setup_aux    = aux_buffer_setup,
2104 	.free_aux     = aux_buffer_free,
2105 
2106 	.check_period = cpumsf_pmu_check_period,
2107 };
2108 
2109 static void cpumf_measurement_alert(struct ext_code ext_code,
2110 				    unsigned int alert, unsigned long unused)
2111 {
2112 	struct cpu_hw_sf *cpuhw;
2113 
2114 	if (!(alert & CPU_MF_INT_SF_MASK))
2115 		return;
2116 	inc_irq_stat(IRQEXT_CMS);
2117 	cpuhw = this_cpu_ptr(&cpu_hw_sf);
2118 
2119 	/* Measurement alerts are shared and might happen when the PMU
2120 	 * is not reserved.  Ignore these alerts in this case. */
2121 	if (!(cpuhw->flags & PMU_F_RESERVED))
2122 		return;
2123 
2124 	/* The processing below must take care of multiple alert events that
2125 	 * might be indicated concurrently. */
2126 
2127 	/* Program alert request */
2128 	if (alert & CPU_MF_INT_SF_PRA) {
2129 		if (cpuhw->flags & PMU_F_IN_USE)
2130 			if (SAMPL_DIAG_MODE(&cpuhw->event->hw))
2131 				hw_collect_aux(cpuhw);
2132 			else
2133 				hw_perf_event_update(cpuhw->event, 0);
2134 		else
2135 			WARN_ON_ONCE(!(cpuhw->flags & PMU_F_IN_USE));
2136 	}
2137 
2138 	/* Report measurement alerts only for non-PRA codes */
2139 	if (alert != CPU_MF_INT_SF_PRA)
2140 		debug_sprintf_event(sfdbg, 6, "%s: alert %#x\n", __func__,
2141 				    alert);
2142 
2143 	/* Sampling authorization change request */
2144 	if (alert & CPU_MF_INT_SF_SACA)
2145 		qsi(&cpuhw->qsi);
2146 
2147 	/* Loss of sample data due to high-priority machine activities */
2148 	if (alert & CPU_MF_INT_SF_LSDA) {
2149 		pr_err("Sample data was lost\n");
2150 		cpuhw->flags |= PMU_F_ERR_LSDA;
2151 		sf_disable();
2152 	}
2153 
2154 	/* Invalid sampling buffer entry */
2155 	if (alert & (CPU_MF_INT_SF_IAE|CPU_MF_INT_SF_ISE)) {
2156 		pr_err("A sampling buffer entry is incorrect (alert=0x%x)\n",
2157 		       alert);
2158 		cpuhw->flags |= PMU_F_ERR_IBE;
2159 		sf_disable();
2160 	}
2161 }
2162 
2163 static int cpusf_pmu_setup(unsigned int cpu, int flags)
2164 {
2165 	/* Ignore the notification if no events are scheduled on the PMU.
2166 	 * This might be racy...
2167 	 */
2168 	if (!atomic_read(&num_events))
2169 		return 0;
2170 
2171 	local_irq_disable();
2172 	setup_pmc_cpu(&flags);
2173 	local_irq_enable();
2174 	return 0;
2175 }
2176 
2177 static int s390_pmu_sf_online_cpu(unsigned int cpu)
2178 {
2179 	return cpusf_pmu_setup(cpu, PMC_INIT);
2180 }
2181 
2182 static int s390_pmu_sf_offline_cpu(unsigned int cpu)
2183 {
2184 	return cpusf_pmu_setup(cpu, PMC_RELEASE);
2185 }
2186 
2187 static int param_get_sfb_size(char *buffer, const struct kernel_param *kp)
2188 {
2189 	if (!cpum_sf_avail())
2190 		return -ENODEV;
2191 	return sprintf(buffer, "%lu,%lu", CPUM_SF_MIN_SDB, CPUM_SF_MAX_SDB);
2192 }
2193 
2194 static int param_set_sfb_size(const char *val, const struct kernel_param *kp)
2195 {
2196 	int rc;
2197 	unsigned long min, max;
2198 
2199 	if (!cpum_sf_avail())
2200 		return -ENODEV;
2201 	if (!val || !strlen(val))
2202 		return -EINVAL;
2203 
2204 	/* Valid parameter values: "min,max" or "max" */
2205 	min = CPUM_SF_MIN_SDB;
2206 	max = CPUM_SF_MAX_SDB;
2207 	if (strchr(val, ','))
2208 		rc = (sscanf(val, "%lu,%lu", &min, &max) == 2) ? 0 : -EINVAL;
2209 	else
2210 		rc = kstrtoul(val, 10, &max);
2211 
2212 	if (min < 2 || min >= max || max > get_num_physpages())
2213 		rc = -EINVAL;
2214 	if (rc)
2215 		return rc;
2216 
2217 	sfb_set_limits(min, max);
2218 	pr_info("The sampling buffer limits have changed to: "
2219 		"min %lu max %lu (diag %lu)\n",
2220 		CPUM_SF_MIN_SDB, CPUM_SF_MAX_SDB, CPUM_SF_SDB_DIAG_FACTOR);
2221 	return 0;
2222 }
2223 
2224 #define param_check_sfb_size(name, p) __param_check(name, p, void)
2225 static const struct kernel_param_ops param_ops_sfb_size = {
2226 	.set = param_set_sfb_size,
2227 	.get = param_get_sfb_size,
2228 };
2229 
2230 #define RS_INIT_FAILURE_QSI	  0x0001
2231 #define RS_INIT_FAILURE_BSDES	  0x0002
2232 #define RS_INIT_FAILURE_ALRT	  0x0003
2233 #define RS_INIT_FAILURE_PERF	  0x0004
2234 static void __init pr_cpumsf_err(unsigned int reason)
2235 {
2236 	pr_err("Sampling facility support for perf is not available: "
2237 	       "reason %#x\n", reason);
2238 }
2239 
2240 static int __init init_cpum_sampling_pmu(void)
2241 {
2242 	struct hws_qsi_info_block si;
2243 	int err;
2244 
2245 	if (!cpum_sf_avail())
2246 		return -ENODEV;
2247 
2248 	memset(&si, 0, sizeof(si));
2249 	if (qsi(&si)) {
2250 		pr_cpumsf_err(RS_INIT_FAILURE_QSI);
2251 		return -ENODEV;
2252 	}
2253 
2254 	if (!si.as && !si.ad)
2255 		return -ENODEV;
2256 
2257 	if (si.bsdes != sizeof(struct hws_basic_entry)) {
2258 		pr_cpumsf_err(RS_INIT_FAILURE_BSDES);
2259 		return -EINVAL;
2260 	}
2261 
2262 	if (si.ad) {
2263 		sfb_set_limits(CPUM_SF_MIN_SDB, CPUM_SF_MAX_SDB);
2264 		/* Sampling of diagnostic data authorized,
2265 		 * install event into attribute list of PMU device.
2266 		 */
2267 		cpumsf_pmu_events_attr[SF_CYCLES_BASIC_DIAG_ATTR_IDX] =
2268 			CPUMF_EVENT_PTR(SF, SF_CYCLES_BASIC_DIAG);
2269 	}
2270 
2271 	sfdbg = debug_register(KMSG_COMPONENT, 2, 1, 80);
2272 	if (!sfdbg) {
2273 		pr_err("Registering for s390dbf failed\n");
2274 		return -ENOMEM;
2275 	}
2276 	debug_register_view(sfdbg, &debug_sprintf_view);
2277 
2278 	err = register_external_irq(EXT_IRQ_MEASURE_ALERT,
2279 				    cpumf_measurement_alert);
2280 	if (err) {
2281 		pr_cpumsf_err(RS_INIT_FAILURE_ALRT);
2282 		debug_unregister(sfdbg);
2283 		goto out;
2284 	}
2285 
2286 	err = perf_pmu_register(&cpumf_sampling, "cpum_sf", PERF_TYPE_RAW);
2287 	if (err) {
2288 		pr_cpumsf_err(RS_INIT_FAILURE_PERF);
2289 		unregister_external_irq(EXT_IRQ_MEASURE_ALERT,
2290 					cpumf_measurement_alert);
2291 		debug_unregister(sfdbg);
2292 		goto out;
2293 	}
2294 
2295 	cpuhp_setup_state(CPUHP_AP_PERF_S390_SF_ONLINE, "perf/s390/sf:online",
2296 			  s390_pmu_sf_online_cpu, s390_pmu_sf_offline_cpu);
2297 out:
2298 	return err;
2299 }
2300 
2301 arch_initcall(init_cpum_sampling_pmu);
2302 core_param(cpum_sfb_size, CPUM_SF_MAX_SDB, sfb_size, 0644);
2303