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