root/arch/s390/kernel/perf_cpum_sf.c

/* [<][>][^][v][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. require_table_link
  2. sf_disable
  3. sf_buffer_available
  4. free_sampling_buffer
  5. alloc_sample_data_block
  6. realloc_sampling_buffer
  7. alloc_sampling_buffer
  8. sfb_set_limits
  9. sfb_max_limit
  10. sfb_pending_allocs
  11. sfb_has_pending_allocs
  12. sfb_account_allocs
  13. sfb_init_allocs
  14. deallocate_buffers
  15. allocate_buffers
  16. min_percent
  17. compute_sfb_extent
  18. sfb_account_overflows
  19. extend_sampling_buffer
  20. setup_pmc_cpu
  21. release_pmc_hardware
  22. reserve_pmc_hardware
  23. hw_perf_event_destroy
  24. hw_init_period
  25. hw_reset_registers
  26. hw_limit_rate
  27. cpumsf_pid_type
  28. cpumsf_output_event_pid
  29. getrate
  30. __hw_perf_event_init_rate
  31. __hw_perf_event_init
  32. cpumsf_pmu_event_init
  33. cpumsf_pmu_enable
  34. cpumsf_pmu_disable
  35. perf_exclude_event
  36. perf_push_sample
  37. perf_event_count_update
  38. debug_sample_entry
  39. hw_collect_samples
  40. hw_perf_event_update
  41. aux_sdb_trailer
  42. aux_output_end
  43. aux_output_begin
  44. aux_set_alert
  45. aux_reset_buffer
  46. hw_collect_aux
  47. aux_buffer_free
  48. aux_sdb_init
  49. aux_buffer_setup
  50. cpumsf_pmu_read
  51. cpumsf_pmu_check_period
  52. cpumsf_pmu_start
  53. cpumsf_pmu_stop
  54. cpumsf_pmu_add
  55. cpumsf_pmu_del
  56. cpumf_measurement_alert
  57. cpusf_pmu_setup
  58. s390_pmu_sf_online_cpu
  59. s390_pmu_sf_offline_cpu
  60. param_get_sfb_size
  61. param_set_sfb_size
  62. pr_cpumsf_err
  63. init_cpum_sampling_pmu

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

/* [<][>][^][v][top][bottom][index][help] */