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