Linux Audio

Check our new training course

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