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