Linux Audio

Check our new training course

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