1 // SPDX-License-Identifier: GPL-2.0 2 /* 3 * Performance events core code: 4 * 5 * Copyright (C) 2008 Thomas Gleixner <[email protected]> 6 * Copyright (C) 2008-2011 Red Hat, Inc., Ingo Molnar 7 * Copyright (C) 2008-2011 Red Hat, Inc., Peter Zijlstra 8 * Copyright © 2009 Paul Mackerras, IBM Corp. <[email protected]> 9 */ 10 11 #include <linux/fs.h> 12 #include <linux/mm.h> 13 #include <linux/cpu.h> 14 #include <linux/smp.h> 15 #include <linux/idr.h> 16 #include <linux/file.h> 17 #include <linux/poll.h> 18 #include <linux/slab.h> 19 #include <linux/hash.h> 20 #include <linux/tick.h> 21 #include <linux/sysfs.h> 22 #include <linux/dcache.h> 23 #include <linux/percpu.h> 24 #include <linux/ptrace.h> 25 #include <linux/reboot.h> 26 #include <linux/vmstat.h> 27 #include <linux/device.h> 28 #include <linux/export.h> 29 #include <linux/vmalloc.h> 30 #include <linux/hardirq.h> 31 #include <linux/hugetlb.h> 32 #include <linux/rculist.h> 33 #include <linux/uaccess.h> 34 #include <linux/syscalls.h> 35 #include <linux/anon_inodes.h> 36 #include <linux/kernel_stat.h> 37 #include <linux/cgroup.h> 38 #include <linux/perf_event.h> 39 #include <linux/trace_events.h> 40 #include <linux/hw_breakpoint.h> 41 #include <linux/mm_types.h> 42 #include <linux/module.h> 43 #include <linux/mman.h> 44 #include <linux/compat.h> 45 #include <linux/bpf.h> 46 #include <linux/filter.h> 47 #include <linux/namei.h> 48 #include <linux/parser.h> 49 #include <linux/sched/clock.h> 50 #include <linux/sched/mm.h> 51 #include <linux/proc_ns.h> 52 #include <linux/mount.h> 53 #include <linux/min_heap.h> 54 #include <linux/highmem.h> 55 #include <linux/pgtable.h> 56 #include <linux/buildid.h> 57 #include <linux/task_work.h> 58 59 #include "internal.h" 60 61 #include <asm/irq_regs.h> 62 63 typedef int (*remote_function_f)(void *); 64 65 struct remote_function_call { 66 struct task_struct *p; 67 remote_function_f func; 68 void *info; 69 int ret; 70 }; 71 72 static void remote_function(void *data) 73 { 74 struct remote_function_call *tfc = data; 75 struct task_struct *p = tfc->p; 76 77 if (p) { 78 /* -EAGAIN */ 79 if (task_cpu(p) != smp_processor_id()) 80 return; 81 82 /* 83 * Now that we're on right CPU with IRQs disabled, we can test 84 * if we hit the right task without races. 85 */ 86 87 tfc->ret = -ESRCH; /* No such (running) process */ 88 if (p != current) 89 return; 90 } 91 92 tfc->ret = tfc->func(tfc->info); 93 } 94 95 /** 96 * task_function_call - call a function on the cpu on which a task runs 97 * @p: the task to evaluate 98 * @func: the function to be called 99 * @info: the function call argument 100 * 101 * Calls the function @func when the task is currently running. This might 102 * be on the current CPU, which just calls the function directly. This will 103 * retry due to any failures in smp_call_function_single(), such as if the 104 * task_cpu() goes offline concurrently. 105 * 106 * returns @func return value or -ESRCH or -ENXIO when the process isn't running 107 */ 108 static int 109 task_function_call(struct task_struct *p, remote_function_f func, void *info) 110 { 111 struct remote_function_call data = { 112 .p = p, 113 .func = func, 114 .info = info, 115 .ret = -EAGAIN, 116 }; 117 int ret; 118 119 for (;;) { 120 ret = smp_call_function_single(task_cpu(p), remote_function, 121 &data, 1); 122 if (!ret) 123 ret = data.ret; 124 125 if (ret != -EAGAIN) 126 break; 127 128 cond_resched(); 129 } 130 131 return ret; 132 } 133 134 /** 135 * cpu_function_call - call a function on the cpu 136 * @cpu: target cpu to queue this function 137 * @func: the function to be called 138 * @info: the function call argument 139 * 140 * Calls the function @func on the remote cpu. 141 * 142 * returns: @func return value or -ENXIO when the cpu is offline 143 */ 144 static int cpu_function_call(int cpu, remote_function_f func, void *info) 145 { 146 struct remote_function_call data = { 147 .p = NULL, 148 .func = func, 149 .info = info, 150 .ret = -ENXIO, /* No such CPU */ 151 }; 152 153 smp_call_function_single(cpu, remote_function, &data, 1); 154 155 return data.ret; 156 } 157 158 enum event_type_t { 159 EVENT_FLEXIBLE = 0x01, 160 EVENT_PINNED = 0x02, 161 EVENT_TIME = 0x04, 162 EVENT_FROZEN = 0x08, 163 /* see ctx_resched() for details */ 164 EVENT_CPU = 0x10, 165 EVENT_CGROUP = 0x20, 166 167 /* compound helpers */ 168 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED, 169 EVENT_TIME_FROZEN = EVENT_TIME | EVENT_FROZEN, 170 }; 171 172 static inline void __perf_ctx_lock(struct perf_event_context *ctx) 173 { 174 raw_spin_lock(&ctx->lock); 175 WARN_ON_ONCE(ctx->is_active & EVENT_FROZEN); 176 } 177 178 static void perf_ctx_lock(struct perf_cpu_context *cpuctx, 179 struct perf_event_context *ctx) 180 { 181 __perf_ctx_lock(&cpuctx->ctx); 182 if (ctx) 183 __perf_ctx_lock(ctx); 184 } 185 186 static inline void __perf_ctx_unlock(struct perf_event_context *ctx) 187 { 188 /* 189 * If ctx_sched_in() didn't again set any ALL flags, clean up 190 * after ctx_sched_out() by clearing is_active. 191 */ 192 if (ctx->is_active & EVENT_FROZEN) { 193 if (!(ctx->is_active & EVENT_ALL)) 194 ctx->is_active = 0; 195 else 196 ctx->is_active &= ~EVENT_FROZEN; 197 } 198 raw_spin_unlock(&ctx->lock); 199 } 200 201 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx, 202 struct perf_event_context *ctx) 203 { 204 if (ctx) 205 __perf_ctx_unlock(ctx); 206 __perf_ctx_unlock(&cpuctx->ctx); 207 } 208 209 #define TASK_TOMBSTONE ((void *)-1L) 210 211 static bool is_kernel_event(struct perf_event *event) 212 { 213 return READ_ONCE(event->owner) == TASK_TOMBSTONE; 214 } 215 216 static DEFINE_PER_CPU(struct perf_cpu_context, perf_cpu_context); 217 218 struct perf_event_context *perf_cpu_task_ctx(void) 219 { 220 lockdep_assert_irqs_disabled(); 221 return this_cpu_ptr(&perf_cpu_context)->task_ctx; 222 } 223 224 /* 225 * On task ctx scheduling... 226 * 227 * When !ctx->nr_events a task context will not be scheduled. This means 228 * we can disable the scheduler hooks (for performance) without leaving 229 * pending task ctx state. 230 * 231 * This however results in two special cases: 232 * 233 * - removing the last event from a task ctx; this is relatively straight 234 * forward and is done in __perf_remove_from_context. 235 * 236 * - adding the first event to a task ctx; this is tricky because we cannot 237 * rely on ctx->is_active and therefore cannot use event_function_call(). 238 * See perf_install_in_context(). 239 * 240 * If ctx->nr_events, then ctx->is_active and cpuctx->task_ctx are set. 241 */ 242 243 typedef void (*event_f)(struct perf_event *, struct perf_cpu_context *, 244 struct perf_event_context *, void *); 245 246 struct event_function_struct { 247 struct perf_event *event; 248 event_f func; 249 void *data; 250 }; 251 252 static int event_function(void *info) 253 { 254 struct event_function_struct *efs = info; 255 struct perf_event *event = efs->event; 256 struct perf_event_context *ctx = event->ctx; 257 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 258 struct perf_event_context *task_ctx = cpuctx->task_ctx; 259 int ret = 0; 260 261 lockdep_assert_irqs_disabled(); 262 263 perf_ctx_lock(cpuctx, task_ctx); 264 /* 265 * Since we do the IPI call without holding ctx->lock things can have 266 * changed, double check we hit the task we set out to hit. 267 */ 268 if (ctx->task) { 269 if (ctx->task != current) { 270 ret = -ESRCH; 271 goto unlock; 272 } 273 274 /* 275 * We only use event_function_call() on established contexts, 276 * and event_function() is only ever called when active (or 277 * rather, we'll have bailed in task_function_call() or the 278 * above ctx->task != current test), therefore we must have 279 * ctx->is_active here. 280 */ 281 WARN_ON_ONCE(!ctx->is_active); 282 /* 283 * And since we have ctx->is_active, cpuctx->task_ctx must 284 * match. 285 */ 286 WARN_ON_ONCE(task_ctx != ctx); 287 } else { 288 WARN_ON_ONCE(&cpuctx->ctx != ctx); 289 } 290 291 efs->func(event, cpuctx, ctx, efs->data); 292 unlock: 293 perf_ctx_unlock(cpuctx, task_ctx); 294 295 return ret; 296 } 297 298 static void event_function_call(struct perf_event *event, event_f func, void *data) 299 { 300 struct perf_event_context *ctx = event->ctx; 301 struct task_struct *task = READ_ONCE(ctx->task); /* verified in event_function */ 302 struct perf_cpu_context *cpuctx; 303 struct event_function_struct efs = { 304 .event = event, 305 .func = func, 306 .data = data, 307 }; 308 309 if (!event->parent) { 310 /* 311 * If this is a !child event, we must hold ctx::mutex to 312 * stabilize the event->ctx relation. See 313 * perf_event_ctx_lock(). 314 */ 315 lockdep_assert_held(&ctx->mutex); 316 } 317 318 if (!task) { 319 cpu_function_call(event->cpu, event_function, &efs); 320 return; 321 } 322 323 if (task == TASK_TOMBSTONE) 324 return; 325 326 again: 327 if (!task_function_call(task, event_function, &efs)) 328 return; 329 330 local_irq_disable(); 331 cpuctx = this_cpu_ptr(&perf_cpu_context); 332 perf_ctx_lock(cpuctx, ctx); 333 /* 334 * Reload the task pointer, it might have been changed by 335 * a concurrent perf_event_context_sched_out(). 336 */ 337 task = ctx->task; 338 if (task == TASK_TOMBSTONE) 339 goto unlock; 340 if (ctx->is_active) { 341 perf_ctx_unlock(cpuctx, ctx); 342 local_irq_enable(); 343 goto again; 344 } 345 func(event, NULL, ctx, data); 346 unlock: 347 perf_ctx_unlock(cpuctx, ctx); 348 local_irq_enable(); 349 } 350 351 /* 352 * Similar to event_function_call() + event_function(), but hard assumes IRQs 353 * are already disabled and we're on the right CPU. 354 */ 355 static void event_function_local(struct perf_event *event, event_f func, void *data) 356 { 357 struct perf_event_context *ctx = event->ctx; 358 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 359 struct task_struct *task = READ_ONCE(ctx->task); 360 struct perf_event_context *task_ctx = NULL; 361 362 lockdep_assert_irqs_disabled(); 363 364 if (task) { 365 if (task == TASK_TOMBSTONE) 366 return; 367 368 task_ctx = ctx; 369 } 370 371 perf_ctx_lock(cpuctx, task_ctx); 372 373 task = ctx->task; 374 if (task == TASK_TOMBSTONE) 375 goto unlock; 376 377 if (task) { 378 /* 379 * We must be either inactive or active and the right task, 380 * otherwise we're screwed, since we cannot IPI to somewhere 381 * else. 382 */ 383 if (ctx->is_active) { 384 if (WARN_ON_ONCE(task != current)) 385 goto unlock; 386 387 if (WARN_ON_ONCE(cpuctx->task_ctx != ctx)) 388 goto unlock; 389 } 390 } else { 391 WARN_ON_ONCE(&cpuctx->ctx != ctx); 392 } 393 394 func(event, cpuctx, ctx, data); 395 unlock: 396 perf_ctx_unlock(cpuctx, task_ctx); 397 } 398 399 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\ 400 PERF_FLAG_FD_OUTPUT |\ 401 PERF_FLAG_PID_CGROUP |\ 402 PERF_FLAG_FD_CLOEXEC) 403 404 /* 405 * branch priv levels that need permission checks 406 */ 407 #define PERF_SAMPLE_BRANCH_PERM_PLM \ 408 (PERF_SAMPLE_BRANCH_KERNEL |\ 409 PERF_SAMPLE_BRANCH_HV) 410 411 /* 412 * perf_sched_events : >0 events exist 413 */ 414 415 static void perf_sched_delayed(struct work_struct *work); 416 DEFINE_STATIC_KEY_FALSE(perf_sched_events); 417 static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed); 418 static DEFINE_MUTEX(perf_sched_mutex); 419 static atomic_t perf_sched_count; 420 421 static DEFINE_PER_CPU(struct pmu_event_list, pmu_sb_events); 422 423 static atomic_t nr_mmap_events __read_mostly; 424 static atomic_t nr_comm_events __read_mostly; 425 static atomic_t nr_namespaces_events __read_mostly; 426 static atomic_t nr_task_events __read_mostly; 427 static atomic_t nr_freq_events __read_mostly; 428 static atomic_t nr_switch_events __read_mostly; 429 static atomic_t nr_ksymbol_events __read_mostly; 430 static atomic_t nr_bpf_events __read_mostly; 431 static atomic_t nr_cgroup_events __read_mostly; 432 static atomic_t nr_text_poke_events __read_mostly; 433 static atomic_t nr_build_id_events __read_mostly; 434 435 static LIST_HEAD(pmus); 436 static DEFINE_MUTEX(pmus_lock); 437 static struct srcu_struct pmus_srcu; 438 static cpumask_var_t perf_online_mask; 439 static cpumask_var_t perf_online_core_mask; 440 static cpumask_var_t perf_online_die_mask; 441 static cpumask_var_t perf_online_cluster_mask; 442 static cpumask_var_t perf_online_pkg_mask; 443 static cpumask_var_t perf_online_sys_mask; 444 static struct kmem_cache *perf_event_cache; 445 446 /* 447 * perf event paranoia level: 448 * -1 - not paranoid at all 449 * 0 - disallow raw tracepoint access for unpriv 450 * 1 - disallow cpu events for unpriv 451 * 2 - disallow kernel profiling for unpriv 452 */ 453 int sysctl_perf_event_paranoid __read_mostly = 2; 454 455 /* Minimum for 512 kiB + 1 user control page. 'free' kiB per user. */ 456 static int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); 457 458 /* 459 * max perf event sample rate 460 */ 461 #define DEFAULT_MAX_SAMPLE_RATE 100000 462 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE) 463 #define DEFAULT_CPU_TIME_MAX_PERCENT 25 464 465 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE; 466 static int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT; 467 468 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ); 469 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS; 470 471 static int perf_sample_allowed_ns __read_mostly = 472 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100; 473 474 static void update_perf_cpu_limits(void) 475 { 476 u64 tmp = perf_sample_period_ns; 477 478 tmp *= sysctl_perf_cpu_time_max_percent; 479 tmp = div_u64(tmp, 100); 480 if (!tmp) 481 tmp = 1; 482 483 WRITE_ONCE(perf_sample_allowed_ns, tmp); 484 } 485 486 static bool perf_rotate_context(struct perf_cpu_pmu_context *cpc); 487 488 static int perf_event_max_sample_rate_handler(const struct ctl_table *table, int write, 489 void *buffer, size_t *lenp, loff_t *ppos) 490 { 491 int ret; 492 int perf_cpu = sysctl_perf_cpu_time_max_percent; 493 /* 494 * If throttling is disabled don't allow the write: 495 */ 496 if (write && (perf_cpu == 100 || perf_cpu == 0)) 497 return -EINVAL; 498 499 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos); 500 if (ret || !write) 501 return ret; 502 503 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ); 504 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate; 505 update_perf_cpu_limits(); 506 507 return 0; 508 } 509 510 static int perf_cpu_time_max_percent_handler(const struct ctl_table *table, int write, 511 void *buffer, size_t *lenp, loff_t *ppos) 512 { 513 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos); 514 515 if (ret || !write) 516 return ret; 517 518 if (sysctl_perf_cpu_time_max_percent == 100 || 519 sysctl_perf_cpu_time_max_percent == 0) { 520 printk(KERN_WARNING 521 "perf: Dynamic interrupt throttling disabled, can hang your system!\n"); 522 WRITE_ONCE(perf_sample_allowed_ns, 0); 523 } else { 524 update_perf_cpu_limits(); 525 } 526 527 return 0; 528 } 529 530 static const struct ctl_table events_core_sysctl_table[] = { 531 /* 532 * User-space relies on this file as a feature check for 533 * perf_events being enabled. It's an ABI, do not remove! 534 */ 535 { 536 .procname = "perf_event_paranoid", 537 .data = &sysctl_perf_event_paranoid, 538 .maxlen = sizeof(sysctl_perf_event_paranoid), 539 .mode = 0644, 540 .proc_handler = proc_dointvec, 541 }, 542 { 543 .procname = "perf_event_mlock_kb", 544 .data = &sysctl_perf_event_mlock, 545 .maxlen = sizeof(sysctl_perf_event_mlock), 546 .mode = 0644, 547 .proc_handler = proc_dointvec, 548 }, 549 { 550 .procname = "perf_event_max_sample_rate", 551 .data = &sysctl_perf_event_sample_rate, 552 .maxlen = sizeof(sysctl_perf_event_sample_rate), 553 .mode = 0644, 554 .proc_handler = perf_event_max_sample_rate_handler, 555 .extra1 = SYSCTL_ONE, 556 }, 557 { 558 .procname = "perf_cpu_time_max_percent", 559 .data = &sysctl_perf_cpu_time_max_percent, 560 .maxlen = sizeof(sysctl_perf_cpu_time_max_percent), 561 .mode = 0644, 562 .proc_handler = perf_cpu_time_max_percent_handler, 563 .extra1 = SYSCTL_ZERO, 564 .extra2 = SYSCTL_ONE_HUNDRED, 565 }, 566 }; 567 568 static int __init init_events_core_sysctls(void) 569 { 570 register_sysctl_init("kernel", events_core_sysctl_table); 571 return 0; 572 } 573 core_initcall(init_events_core_sysctls); 574 575 576 /* 577 * perf samples are done in some very critical code paths (NMIs). 578 * If they take too much CPU time, the system can lock up and not 579 * get any real work done. This will drop the sample rate when 580 * we detect that events are taking too long. 581 */ 582 #define NR_ACCUMULATED_SAMPLES 128 583 static DEFINE_PER_CPU(u64, running_sample_length); 584 585 static u64 __report_avg; 586 static u64 __report_allowed; 587 588 static void perf_duration_warn(struct irq_work *w) 589 { 590 printk_ratelimited(KERN_INFO 591 "perf: interrupt took too long (%lld > %lld), lowering " 592 "kernel.perf_event_max_sample_rate to %d\n", 593 __report_avg, __report_allowed, 594 sysctl_perf_event_sample_rate); 595 } 596 597 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn); 598 599 void perf_sample_event_took(u64 sample_len_ns) 600 { 601 u64 max_len = READ_ONCE(perf_sample_allowed_ns); 602 u64 running_len; 603 u64 avg_len; 604 u32 max; 605 606 if (max_len == 0) 607 return; 608 609 /* Decay the counter by 1 average sample. */ 610 running_len = __this_cpu_read(running_sample_length); 611 running_len -= running_len/NR_ACCUMULATED_SAMPLES; 612 running_len += sample_len_ns; 613 __this_cpu_write(running_sample_length, running_len); 614 615 /* 616 * Note: this will be biased artificially low until we have 617 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us 618 * from having to maintain a count. 619 */ 620 avg_len = running_len/NR_ACCUMULATED_SAMPLES; 621 if (avg_len <= max_len) 622 return; 623 624 __report_avg = avg_len; 625 __report_allowed = max_len; 626 627 /* 628 * Compute a throttle threshold 25% below the current duration. 629 */ 630 avg_len += avg_len / 4; 631 max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent; 632 if (avg_len < max) 633 max /= (u32)avg_len; 634 else 635 max = 1; 636 637 WRITE_ONCE(perf_sample_allowed_ns, avg_len); 638 WRITE_ONCE(max_samples_per_tick, max); 639 640 sysctl_perf_event_sample_rate = max * HZ; 641 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate; 642 643 if (!irq_work_queue(&perf_duration_work)) { 644 early_printk("perf: interrupt took too long (%lld > %lld), lowering " 645 "kernel.perf_event_max_sample_rate to %d\n", 646 __report_avg, __report_allowed, 647 sysctl_perf_event_sample_rate); 648 } 649 } 650 651 static atomic64_t perf_event_id; 652 653 static void update_context_time(struct perf_event_context *ctx); 654 static u64 perf_event_time(struct perf_event *event); 655 656 void __weak perf_event_print_debug(void) { } 657 658 static inline u64 perf_clock(void) 659 { 660 return local_clock(); 661 } 662 663 static inline u64 perf_event_clock(struct perf_event *event) 664 { 665 return event->clock(); 666 } 667 668 /* 669 * State based event timekeeping... 670 * 671 * The basic idea is to use event->state to determine which (if any) time 672 * fields to increment with the current delta. This means we only need to 673 * update timestamps when we change state or when they are explicitly requested 674 * (read). 675 * 676 * Event groups make things a little more complicated, but not terribly so. The 677 * rules for a group are that if the group leader is OFF the entire group is 678 * OFF, irrespective of what the group member states are. This results in 679 * __perf_effective_state(). 680 * 681 * A further ramification is that when a group leader flips between OFF and 682 * !OFF, we need to update all group member times. 683 * 684 * 685 * NOTE: perf_event_time() is based on the (cgroup) context time, and thus we 686 * need to make sure the relevant context time is updated before we try and 687 * update our timestamps. 688 */ 689 690 static __always_inline enum perf_event_state 691 __perf_effective_state(struct perf_event *event) 692 { 693 struct perf_event *leader = event->group_leader; 694 695 if (leader->state <= PERF_EVENT_STATE_OFF) 696 return leader->state; 697 698 return event->state; 699 } 700 701 static __always_inline void 702 __perf_update_times(struct perf_event *event, u64 now, u64 *enabled, u64 *running) 703 { 704 enum perf_event_state state = __perf_effective_state(event); 705 u64 delta = now - event->tstamp; 706 707 *enabled = event->total_time_enabled; 708 if (state >= PERF_EVENT_STATE_INACTIVE) 709 *enabled += delta; 710 711 *running = event->total_time_running; 712 if (state >= PERF_EVENT_STATE_ACTIVE) 713 *running += delta; 714 } 715 716 static void perf_event_update_time(struct perf_event *event) 717 { 718 u64 now = perf_event_time(event); 719 720 __perf_update_times(event, now, &event->total_time_enabled, 721 &event->total_time_running); 722 event->tstamp = now; 723 } 724 725 static void perf_event_update_sibling_time(struct perf_event *leader) 726 { 727 struct perf_event *sibling; 728 729 for_each_sibling_event(sibling, leader) 730 perf_event_update_time(sibling); 731 } 732 733 static void 734 perf_event_set_state(struct perf_event *event, enum perf_event_state state) 735 { 736 if (event->state == state) 737 return; 738 739 perf_event_update_time(event); 740 /* 741 * If a group leader gets enabled/disabled all its siblings 742 * are affected too. 743 */ 744 if ((event->state < 0) ^ (state < 0)) 745 perf_event_update_sibling_time(event); 746 747 WRITE_ONCE(event->state, state); 748 } 749 750 /* 751 * UP store-release, load-acquire 752 */ 753 754 #define __store_release(ptr, val) \ 755 do { \ 756 barrier(); \ 757 WRITE_ONCE(*(ptr), (val)); \ 758 } while (0) 759 760 #define __load_acquire(ptr) \ 761 ({ \ 762 __unqual_scalar_typeof(*(ptr)) ___p = READ_ONCE(*(ptr)); \ 763 barrier(); \ 764 ___p; \ 765 }) 766 767 #define for_each_epc(_epc, _ctx, _pmu, _cgroup) \ 768 list_for_each_entry(_epc, &((_ctx)->pmu_ctx_list), pmu_ctx_entry) \ 769 if (_cgroup && !_epc->nr_cgroups) \ 770 continue; \ 771 else if (_pmu && _epc->pmu != _pmu) \ 772 continue; \ 773 else 774 775 static void perf_ctx_disable(struct perf_event_context *ctx, bool cgroup) 776 { 777 struct perf_event_pmu_context *pmu_ctx; 778 779 for_each_epc(pmu_ctx, ctx, NULL, cgroup) 780 perf_pmu_disable(pmu_ctx->pmu); 781 } 782 783 static void perf_ctx_enable(struct perf_event_context *ctx, bool cgroup) 784 { 785 struct perf_event_pmu_context *pmu_ctx; 786 787 for_each_epc(pmu_ctx, ctx, NULL, cgroup) 788 perf_pmu_enable(pmu_ctx->pmu); 789 } 790 791 static void ctx_sched_out(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type); 792 static void ctx_sched_in(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type); 793 794 #ifdef CONFIG_CGROUP_PERF 795 796 static inline bool 797 perf_cgroup_match(struct perf_event *event) 798 { 799 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 800 801 /* @event doesn't care about cgroup */ 802 if (!event->cgrp) 803 return true; 804 805 /* wants specific cgroup scope but @cpuctx isn't associated with any */ 806 if (!cpuctx->cgrp) 807 return false; 808 809 /* 810 * Cgroup scoping is recursive. An event enabled for a cgroup is 811 * also enabled for all its descendant cgroups. If @cpuctx's 812 * cgroup is a descendant of @event's (the test covers identity 813 * case), it's a match. 814 */ 815 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup, 816 event->cgrp->css.cgroup); 817 } 818 819 static inline void perf_detach_cgroup(struct perf_event *event) 820 { 821 css_put(&event->cgrp->css); 822 event->cgrp = NULL; 823 } 824 825 static inline int is_cgroup_event(struct perf_event *event) 826 { 827 return event->cgrp != NULL; 828 } 829 830 static inline u64 perf_cgroup_event_time(struct perf_event *event) 831 { 832 struct perf_cgroup_info *t; 833 834 t = per_cpu_ptr(event->cgrp->info, event->cpu); 835 return t->time; 836 } 837 838 static inline u64 perf_cgroup_event_time_now(struct perf_event *event, u64 now) 839 { 840 struct perf_cgroup_info *t; 841 842 t = per_cpu_ptr(event->cgrp->info, event->cpu); 843 if (!__load_acquire(&t->active)) 844 return t->time; 845 now += READ_ONCE(t->timeoffset); 846 return now; 847 } 848 849 static inline void __update_cgrp_time(struct perf_cgroup_info *info, u64 now, bool adv) 850 { 851 if (adv) 852 info->time += now - info->timestamp; 853 info->timestamp = now; 854 /* 855 * see update_context_time() 856 */ 857 WRITE_ONCE(info->timeoffset, info->time - info->timestamp); 858 } 859 860 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx, bool final) 861 { 862 struct perf_cgroup *cgrp = cpuctx->cgrp; 863 struct cgroup_subsys_state *css; 864 struct perf_cgroup_info *info; 865 866 if (cgrp) { 867 u64 now = perf_clock(); 868 869 for (css = &cgrp->css; css; css = css->parent) { 870 cgrp = container_of(css, struct perf_cgroup, css); 871 info = this_cpu_ptr(cgrp->info); 872 873 __update_cgrp_time(info, now, true); 874 if (final) 875 __store_release(&info->active, 0); 876 } 877 } 878 } 879 880 static inline void update_cgrp_time_from_event(struct perf_event *event) 881 { 882 struct perf_cgroup_info *info; 883 884 /* 885 * ensure we access cgroup data only when needed and 886 * when we know the cgroup is pinned (css_get) 887 */ 888 if (!is_cgroup_event(event)) 889 return; 890 891 info = this_cpu_ptr(event->cgrp->info); 892 /* 893 * Do not update time when cgroup is not active 894 */ 895 if (info->active) 896 __update_cgrp_time(info, perf_clock(), true); 897 } 898 899 static inline void 900 perf_cgroup_set_timestamp(struct perf_cpu_context *cpuctx) 901 { 902 struct perf_event_context *ctx = &cpuctx->ctx; 903 struct perf_cgroup *cgrp = cpuctx->cgrp; 904 struct perf_cgroup_info *info; 905 struct cgroup_subsys_state *css; 906 907 /* 908 * ctx->lock held by caller 909 * ensure we do not access cgroup data 910 * unless we have the cgroup pinned (css_get) 911 */ 912 if (!cgrp) 913 return; 914 915 WARN_ON_ONCE(!ctx->nr_cgroups); 916 917 for (css = &cgrp->css; css; css = css->parent) { 918 cgrp = container_of(css, struct perf_cgroup, css); 919 info = this_cpu_ptr(cgrp->info); 920 __update_cgrp_time(info, ctx->timestamp, false); 921 __store_release(&info->active, 1); 922 } 923 } 924 925 /* 926 * reschedule events based on the cgroup constraint of task. 927 */ 928 static void perf_cgroup_switch(struct task_struct *task) 929 { 930 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 931 struct perf_cgroup *cgrp; 932 933 /* 934 * cpuctx->cgrp is set when the first cgroup event enabled, 935 * and is cleared when the last cgroup event disabled. 936 */ 937 if (READ_ONCE(cpuctx->cgrp) == NULL) 938 return; 939 940 WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0); 941 942 cgrp = perf_cgroup_from_task(task, NULL); 943 if (READ_ONCE(cpuctx->cgrp) == cgrp) 944 return; 945 946 perf_ctx_lock(cpuctx, cpuctx->task_ctx); 947 perf_ctx_disable(&cpuctx->ctx, true); 948 949 ctx_sched_out(&cpuctx->ctx, NULL, EVENT_ALL|EVENT_CGROUP); 950 /* 951 * must not be done before ctxswout due 952 * to update_cgrp_time_from_cpuctx() in 953 * ctx_sched_out() 954 */ 955 cpuctx->cgrp = cgrp; 956 /* 957 * set cgrp before ctxsw in to allow 958 * perf_cgroup_set_timestamp() in ctx_sched_in() 959 * to not have to pass task around 960 */ 961 ctx_sched_in(&cpuctx->ctx, NULL, EVENT_ALL|EVENT_CGROUP); 962 963 perf_ctx_enable(&cpuctx->ctx, true); 964 perf_ctx_unlock(cpuctx, cpuctx->task_ctx); 965 } 966 967 static int perf_cgroup_ensure_storage(struct perf_event *event, 968 struct cgroup_subsys_state *css) 969 { 970 struct perf_cpu_context *cpuctx; 971 struct perf_event **storage; 972 int cpu, heap_size, ret = 0; 973 974 /* 975 * Allow storage to have sufficient space for an iterator for each 976 * possibly nested cgroup plus an iterator for events with no cgroup. 977 */ 978 for (heap_size = 1; css; css = css->parent) 979 heap_size++; 980 981 for_each_possible_cpu(cpu) { 982 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu); 983 if (heap_size <= cpuctx->heap_size) 984 continue; 985 986 storage = kmalloc_node(heap_size * sizeof(struct perf_event *), 987 GFP_KERNEL, cpu_to_node(cpu)); 988 if (!storage) { 989 ret = -ENOMEM; 990 break; 991 } 992 993 raw_spin_lock_irq(&cpuctx->ctx.lock); 994 if (cpuctx->heap_size < heap_size) { 995 swap(cpuctx->heap, storage); 996 if (storage == cpuctx->heap_default) 997 storage = NULL; 998 cpuctx->heap_size = heap_size; 999 } 1000 raw_spin_unlock_irq(&cpuctx->ctx.lock); 1001 1002 kfree(storage); 1003 } 1004 1005 return ret; 1006 } 1007 1008 static inline int perf_cgroup_connect(int fd, struct perf_event *event, 1009 struct perf_event_attr *attr, 1010 struct perf_event *group_leader) 1011 { 1012 struct perf_cgroup *cgrp; 1013 struct cgroup_subsys_state *css; 1014 CLASS(fd, f)(fd); 1015 int ret = 0; 1016 1017 if (fd_empty(f)) 1018 return -EBADF; 1019 1020 css = css_tryget_online_from_dir(fd_file(f)->f_path.dentry, 1021 &perf_event_cgrp_subsys); 1022 if (IS_ERR(css)) 1023 return PTR_ERR(css); 1024 1025 ret = perf_cgroup_ensure_storage(event, css); 1026 if (ret) 1027 return ret; 1028 1029 cgrp = container_of(css, struct perf_cgroup, css); 1030 event->cgrp = cgrp; 1031 1032 /* 1033 * all events in a group must monitor 1034 * the same cgroup because a task belongs 1035 * to only one perf cgroup at a time 1036 */ 1037 if (group_leader && group_leader->cgrp != cgrp) { 1038 perf_detach_cgroup(event); 1039 ret = -EINVAL; 1040 } 1041 return ret; 1042 } 1043 1044 static inline void 1045 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx) 1046 { 1047 struct perf_cpu_context *cpuctx; 1048 1049 if (!is_cgroup_event(event)) 1050 return; 1051 1052 event->pmu_ctx->nr_cgroups++; 1053 1054 /* 1055 * Because cgroup events are always per-cpu events, 1056 * @ctx == &cpuctx->ctx. 1057 */ 1058 cpuctx = container_of(ctx, struct perf_cpu_context, ctx); 1059 1060 if (ctx->nr_cgroups++) 1061 return; 1062 1063 cpuctx->cgrp = perf_cgroup_from_task(current, ctx); 1064 } 1065 1066 static inline void 1067 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx) 1068 { 1069 struct perf_cpu_context *cpuctx; 1070 1071 if (!is_cgroup_event(event)) 1072 return; 1073 1074 event->pmu_ctx->nr_cgroups--; 1075 1076 /* 1077 * Because cgroup events are always per-cpu events, 1078 * @ctx == &cpuctx->ctx. 1079 */ 1080 cpuctx = container_of(ctx, struct perf_cpu_context, ctx); 1081 1082 if (--ctx->nr_cgroups) 1083 return; 1084 1085 cpuctx->cgrp = NULL; 1086 } 1087 1088 #else /* !CONFIG_CGROUP_PERF */ 1089 1090 static inline bool 1091 perf_cgroup_match(struct perf_event *event) 1092 { 1093 return true; 1094 } 1095 1096 static inline void perf_detach_cgroup(struct perf_event *event) 1097 {} 1098 1099 static inline int is_cgroup_event(struct perf_event *event) 1100 { 1101 return 0; 1102 } 1103 1104 static inline void update_cgrp_time_from_event(struct perf_event *event) 1105 { 1106 } 1107 1108 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx, 1109 bool final) 1110 { 1111 } 1112 1113 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event, 1114 struct perf_event_attr *attr, 1115 struct perf_event *group_leader) 1116 { 1117 return -EINVAL; 1118 } 1119 1120 static inline void 1121 perf_cgroup_set_timestamp(struct perf_cpu_context *cpuctx) 1122 { 1123 } 1124 1125 static inline u64 perf_cgroup_event_time(struct perf_event *event) 1126 { 1127 return 0; 1128 } 1129 1130 static inline u64 perf_cgroup_event_time_now(struct perf_event *event, u64 now) 1131 { 1132 return 0; 1133 } 1134 1135 static inline void 1136 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx) 1137 { 1138 } 1139 1140 static inline void 1141 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx) 1142 { 1143 } 1144 1145 static void perf_cgroup_switch(struct task_struct *task) 1146 { 1147 } 1148 #endif 1149 1150 /* 1151 * set default to be dependent on timer tick just 1152 * like original code 1153 */ 1154 #define PERF_CPU_HRTIMER (1000 / HZ) 1155 /* 1156 * function must be called with interrupts disabled 1157 */ 1158 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr) 1159 { 1160 struct perf_cpu_pmu_context *cpc; 1161 bool rotations; 1162 1163 lockdep_assert_irqs_disabled(); 1164 1165 cpc = container_of(hr, struct perf_cpu_pmu_context, hrtimer); 1166 rotations = perf_rotate_context(cpc); 1167 1168 raw_spin_lock(&cpc->hrtimer_lock); 1169 if (rotations) 1170 hrtimer_forward_now(hr, cpc->hrtimer_interval); 1171 else 1172 cpc->hrtimer_active = 0; 1173 raw_spin_unlock(&cpc->hrtimer_lock); 1174 1175 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART; 1176 } 1177 1178 static void __perf_mux_hrtimer_init(struct perf_cpu_pmu_context *cpc, int cpu) 1179 { 1180 struct hrtimer *timer = &cpc->hrtimer; 1181 struct pmu *pmu = cpc->epc.pmu; 1182 u64 interval; 1183 1184 /* 1185 * check default is sane, if not set then force to 1186 * default interval (1/tick) 1187 */ 1188 interval = pmu->hrtimer_interval_ms; 1189 if (interval < 1) 1190 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER; 1191 1192 cpc->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval); 1193 1194 raw_spin_lock_init(&cpc->hrtimer_lock); 1195 hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED_HARD); 1196 timer->function = perf_mux_hrtimer_handler; 1197 } 1198 1199 static int perf_mux_hrtimer_restart(struct perf_cpu_pmu_context *cpc) 1200 { 1201 struct hrtimer *timer = &cpc->hrtimer; 1202 unsigned long flags; 1203 1204 raw_spin_lock_irqsave(&cpc->hrtimer_lock, flags); 1205 if (!cpc->hrtimer_active) { 1206 cpc->hrtimer_active = 1; 1207 hrtimer_forward_now(timer, cpc->hrtimer_interval); 1208 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED_HARD); 1209 } 1210 raw_spin_unlock_irqrestore(&cpc->hrtimer_lock, flags); 1211 1212 return 0; 1213 } 1214 1215 static int perf_mux_hrtimer_restart_ipi(void *arg) 1216 { 1217 return perf_mux_hrtimer_restart(arg); 1218 } 1219 1220 static __always_inline struct perf_cpu_pmu_context *this_cpc(struct pmu *pmu) 1221 { 1222 return this_cpu_ptr(pmu->cpu_pmu_context); 1223 } 1224 1225 void perf_pmu_disable(struct pmu *pmu) 1226 { 1227 int *count = &this_cpc(pmu)->pmu_disable_count; 1228 if (!(*count)++) 1229 pmu->pmu_disable(pmu); 1230 } 1231 1232 void perf_pmu_enable(struct pmu *pmu) 1233 { 1234 int *count = &this_cpc(pmu)->pmu_disable_count; 1235 if (!--(*count)) 1236 pmu->pmu_enable(pmu); 1237 } 1238 1239 static void perf_assert_pmu_disabled(struct pmu *pmu) 1240 { 1241 int *count = &this_cpc(pmu)->pmu_disable_count; 1242 WARN_ON_ONCE(*count == 0); 1243 } 1244 1245 static inline void perf_pmu_read(struct perf_event *event) 1246 { 1247 if (event->state == PERF_EVENT_STATE_ACTIVE) 1248 event->pmu->read(event); 1249 } 1250 1251 static void get_ctx(struct perf_event_context *ctx) 1252 { 1253 refcount_inc(&ctx->refcount); 1254 } 1255 1256 static void *alloc_task_ctx_data(struct pmu *pmu) 1257 { 1258 if (pmu->task_ctx_cache) 1259 return kmem_cache_zalloc(pmu->task_ctx_cache, GFP_KERNEL); 1260 1261 return NULL; 1262 } 1263 1264 static void free_task_ctx_data(struct pmu *pmu, void *task_ctx_data) 1265 { 1266 if (pmu->task_ctx_cache && task_ctx_data) 1267 kmem_cache_free(pmu->task_ctx_cache, task_ctx_data); 1268 } 1269 1270 static void free_ctx(struct rcu_head *head) 1271 { 1272 struct perf_event_context *ctx; 1273 1274 ctx = container_of(head, struct perf_event_context, rcu_head); 1275 kfree(ctx); 1276 } 1277 1278 static void put_ctx(struct perf_event_context *ctx) 1279 { 1280 if (refcount_dec_and_test(&ctx->refcount)) { 1281 if (ctx->parent_ctx) 1282 put_ctx(ctx->parent_ctx); 1283 if (ctx->task && ctx->task != TASK_TOMBSTONE) 1284 put_task_struct(ctx->task); 1285 call_rcu(&ctx->rcu_head, free_ctx); 1286 } 1287 } 1288 1289 /* 1290 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and 1291 * perf_pmu_migrate_context() we need some magic. 1292 * 1293 * Those places that change perf_event::ctx will hold both 1294 * perf_event_ctx::mutex of the 'old' and 'new' ctx value. 1295 * 1296 * Lock ordering is by mutex address. There are two other sites where 1297 * perf_event_context::mutex nests and those are: 1298 * 1299 * - perf_event_exit_task_context() [ child , 0 ] 1300 * perf_event_exit_event() 1301 * put_event() [ parent, 1 ] 1302 * 1303 * - perf_event_init_context() [ parent, 0 ] 1304 * inherit_task_group() 1305 * inherit_group() 1306 * inherit_event() 1307 * perf_event_alloc() 1308 * perf_init_event() 1309 * perf_try_init_event() [ child , 1 ] 1310 * 1311 * While it appears there is an obvious deadlock here -- the parent and child 1312 * nesting levels are inverted between the two. This is in fact safe because 1313 * life-time rules separate them. That is an exiting task cannot fork, and a 1314 * spawning task cannot (yet) exit. 1315 * 1316 * But remember that these are parent<->child context relations, and 1317 * migration does not affect children, therefore these two orderings should not 1318 * interact. 1319 * 1320 * The change in perf_event::ctx does not affect children (as claimed above) 1321 * because the sys_perf_event_open() case will install a new event and break 1322 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only 1323 * concerned with cpuctx and that doesn't have children. 1324 * 1325 * The places that change perf_event::ctx will issue: 1326 * 1327 * perf_remove_from_context(); 1328 * synchronize_rcu(); 1329 * perf_install_in_context(); 1330 * 1331 * to affect the change. The remove_from_context() + synchronize_rcu() should 1332 * quiesce the event, after which we can install it in the new location. This 1333 * means that only external vectors (perf_fops, prctl) can perturb the event 1334 * while in transit. Therefore all such accessors should also acquire 1335 * perf_event_context::mutex to serialize against this. 1336 * 1337 * However; because event->ctx can change while we're waiting to acquire 1338 * ctx->mutex we must be careful and use the below perf_event_ctx_lock() 1339 * function. 1340 * 1341 * Lock order: 1342 * exec_update_lock 1343 * task_struct::perf_event_mutex 1344 * perf_event_context::mutex 1345 * perf_event::child_mutex; 1346 * perf_event_context::lock 1347 * mmap_lock 1348 * perf_event::mmap_mutex 1349 * perf_buffer::aux_mutex 1350 * perf_addr_filters_head::lock 1351 * 1352 * cpu_hotplug_lock 1353 * pmus_lock 1354 * cpuctx->mutex / perf_event_context::mutex 1355 */ 1356 static struct perf_event_context * 1357 perf_event_ctx_lock_nested(struct perf_event *event, int nesting) 1358 { 1359 struct perf_event_context *ctx; 1360 1361 again: 1362 rcu_read_lock(); 1363 ctx = READ_ONCE(event->ctx); 1364 if (!refcount_inc_not_zero(&ctx->refcount)) { 1365 rcu_read_unlock(); 1366 goto again; 1367 } 1368 rcu_read_unlock(); 1369 1370 mutex_lock_nested(&ctx->mutex, nesting); 1371 if (event->ctx != ctx) { 1372 mutex_unlock(&ctx->mutex); 1373 put_ctx(ctx); 1374 goto again; 1375 } 1376 1377 return ctx; 1378 } 1379 1380 static inline struct perf_event_context * 1381 perf_event_ctx_lock(struct perf_event *event) 1382 { 1383 return perf_event_ctx_lock_nested(event, 0); 1384 } 1385 1386 static void perf_event_ctx_unlock(struct perf_event *event, 1387 struct perf_event_context *ctx) 1388 { 1389 mutex_unlock(&ctx->mutex); 1390 put_ctx(ctx); 1391 } 1392 1393 /* 1394 * This must be done under the ctx->lock, such as to serialize against 1395 * context_equiv(), therefore we cannot call put_ctx() since that might end up 1396 * calling scheduler related locks and ctx->lock nests inside those. 1397 */ 1398 static __must_check struct perf_event_context * 1399 unclone_ctx(struct perf_event_context *ctx) 1400 { 1401 struct perf_event_context *parent_ctx = ctx->parent_ctx; 1402 1403 lockdep_assert_held(&ctx->lock); 1404 1405 if (parent_ctx) 1406 ctx->parent_ctx = NULL; 1407 ctx->generation++; 1408 1409 return parent_ctx; 1410 } 1411 1412 static u32 perf_event_pid_type(struct perf_event *event, struct task_struct *p, 1413 enum pid_type type) 1414 { 1415 u32 nr; 1416 /* 1417 * only top level events have the pid namespace they were created in 1418 */ 1419 if (event->parent) 1420 event = event->parent; 1421 1422 nr = __task_pid_nr_ns(p, type, event->ns); 1423 /* avoid -1 if it is idle thread or runs in another ns */ 1424 if (!nr && !pid_alive(p)) 1425 nr = -1; 1426 return nr; 1427 } 1428 1429 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p) 1430 { 1431 return perf_event_pid_type(event, p, PIDTYPE_TGID); 1432 } 1433 1434 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p) 1435 { 1436 return perf_event_pid_type(event, p, PIDTYPE_PID); 1437 } 1438 1439 /* 1440 * If we inherit events we want to return the parent event id 1441 * to userspace. 1442 */ 1443 static u64 primary_event_id(struct perf_event *event) 1444 { 1445 u64 id = event->id; 1446 1447 if (event->parent) 1448 id = event->parent->id; 1449 1450 return id; 1451 } 1452 1453 /* 1454 * Get the perf_event_context for a task and lock it. 1455 * 1456 * This has to cope with the fact that until it is locked, 1457 * the context could get moved to another task. 1458 */ 1459 static struct perf_event_context * 1460 perf_lock_task_context(struct task_struct *task, unsigned long *flags) 1461 { 1462 struct perf_event_context *ctx; 1463 1464 retry: 1465 /* 1466 * One of the few rules of preemptible RCU is that one cannot do 1467 * rcu_read_unlock() while holding a scheduler (or nested) lock when 1468 * part of the read side critical section was irqs-enabled -- see 1469 * rcu_read_unlock_special(). 1470 * 1471 * Since ctx->lock nests under rq->lock we must ensure the entire read 1472 * side critical section has interrupts disabled. 1473 */ 1474 local_irq_save(*flags); 1475 rcu_read_lock(); 1476 ctx = rcu_dereference(task->perf_event_ctxp); 1477 if (ctx) { 1478 /* 1479 * If this context is a clone of another, it might 1480 * get swapped for another underneath us by 1481 * perf_event_task_sched_out, though the 1482 * rcu_read_lock() protects us from any context 1483 * getting freed. Lock the context and check if it 1484 * got swapped before we could get the lock, and retry 1485 * if so. If we locked the right context, then it 1486 * can't get swapped on us any more. 1487 */ 1488 raw_spin_lock(&ctx->lock); 1489 if (ctx != rcu_dereference(task->perf_event_ctxp)) { 1490 raw_spin_unlock(&ctx->lock); 1491 rcu_read_unlock(); 1492 local_irq_restore(*flags); 1493 goto retry; 1494 } 1495 1496 if (ctx->task == TASK_TOMBSTONE || 1497 !refcount_inc_not_zero(&ctx->refcount)) { 1498 raw_spin_unlock(&ctx->lock); 1499 ctx = NULL; 1500 } else { 1501 WARN_ON_ONCE(ctx->task != task); 1502 } 1503 } 1504 rcu_read_unlock(); 1505 if (!ctx) 1506 local_irq_restore(*flags); 1507 return ctx; 1508 } 1509 1510 /* 1511 * Get the context for a task and increment its pin_count so it 1512 * can't get swapped to another task. This also increments its 1513 * reference count so that the context can't get freed. 1514 */ 1515 static struct perf_event_context * 1516 perf_pin_task_context(struct task_struct *task) 1517 { 1518 struct perf_event_context *ctx; 1519 unsigned long flags; 1520 1521 ctx = perf_lock_task_context(task, &flags); 1522 if (ctx) { 1523 ++ctx->pin_count; 1524 raw_spin_unlock_irqrestore(&ctx->lock, flags); 1525 } 1526 return ctx; 1527 } 1528 1529 static void perf_unpin_context(struct perf_event_context *ctx) 1530 { 1531 unsigned long flags; 1532 1533 raw_spin_lock_irqsave(&ctx->lock, flags); 1534 --ctx->pin_count; 1535 raw_spin_unlock_irqrestore(&ctx->lock, flags); 1536 } 1537 1538 /* 1539 * Update the record of the current time in a context. 1540 */ 1541 static void __update_context_time(struct perf_event_context *ctx, bool adv) 1542 { 1543 u64 now = perf_clock(); 1544 1545 lockdep_assert_held(&ctx->lock); 1546 1547 if (adv) 1548 ctx->time += now - ctx->timestamp; 1549 ctx->timestamp = now; 1550 1551 /* 1552 * The above: time' = time + (now - timestamp), can be re-arranged 1553 * into: time` = now + (time - timestamp), which gives a single value 1554 * offset to compute future time without locks on. 1555 * 1556 * See perf_event_time_now(), which can be used from NMI context where 1557 * it's (obviously) not possible to acquire ctx->lock in order to read 1558 * both the above values in a consistent manner. 1559 */ 1560 WRITE_ONCE(ctx->timeoffset, ctx->time - ctx->timestamp); 1561 } 1562 1563 static void update_context_time(struct perf_event_context *ctx) 1564 { 1565 __update_context_time(ctx, true); 1566 } 1567 1568 static u64 perf_event_time(struct perf_event *event) 1569 { 1570 struct perf_event_context *ctx = event->ctx; 1571 1572 if (unlikely(!ctx)) 1573 return 0; 1574 1575 if (is_cgroup_event(event)) 1576 return perf_cgroup_event_time(event); 1577 1578 return ctx->time; 1579 } 1580 1581 static u64 perf_event_time_now(struct perf_event *event, u64 now) 1582 { 1583 struct perf_event_context *ctx = event->ctx; 1584 1585 if (unlikely(!ctx)) 1586 return 0; 1587 1588 if (is_cgroup_event(event)) 1589 return perf_cgroup_event_time_now(event, now); 1590 1591 if (!(__load_acquire(&ctx->is_active) & EVENT_TIME)) 1592 return ctx->time; 1593 1594 now += READ_ONCE(ctx->timeoffset); 1595 return now; 1596 } 1597 1598 static enum event_type_t get_event_type(struct perf_event *event) 1599 { 1600 struct perf_event_context *ctx = event->ctx; 1601 enum event_type_t event_type; 1602 1603 lockdep_assert_held(&ctx->lock); 1604 1605 /* 1606 * It's 'group type', really, because if our group leader is 1607 * pinned, so are we. 1608 */ 1609 if (event->group_leader != event) 1610 event = event->group_leader; 1611 1612 event_type = event->attr.pinned ? EVENT_PINNED : EVENT_FLEXIBLE; 1613 if (!ctx->task) 1614 event_type |= EVENT_CPU; 1615 1616 return event_type; 1617 } 1618 1619 /* 1620 * Helper function to initialize event group nodes. 1621 */ 1622 static void init_event_group(struct perf_event *event) 1623 { 1624 RB_CLEAR_NODE(&event->group_node); 1625 event->group_index = 0; 1626 } 1627 1628 /* 1629 * Extract pinned or flexible groups from the context 1630 * based on event attrs bits. 1631 */ 1632 static struct perf_event_groups * 1633 get_event_groups(struct perf_event *event, struct perf_event_context *ctx) 1634 { 1635 if (event->attr.pinned) 1636 return &ctx->pinned_groups; 1637 else 1638 return &ctx->flexible_groups; 1639 } 1640 1641 /* 1642 * Helper function to initializes perf_event_group trees. 1643 */ 1644 static void perf_event_groups_init(struct perf_event_groups *groups) 1645 { 1646 groups->tree = RB_ROOT; 1647 groups->index = 0; 1648 } 1649 1650 static inline struct cgroup *event_cgroup(const struct perf_event *event) 1651 { 1652 struct cgroup *cgroup = NULL; 1653 1654 #ifdef CONFIG_CGROUP_PERF 1655 if (event->cgrp) 1656 cgroup = event->cgrp->css.cgroup; 1657 #endif 1658 1659 return cgroup; 1660 } 1661 1662 /* 1663 * Compare function for event groups; 1664 * 1665 * Implements complex key that first sorts by CPU and then by virtual index 1666 * which provides ordering when rotating groups for the same CPU. 1667 */ 1668 static __always_inline int 1669 perf_event_groups_cmp(const int left_cpu, const struct pmu *left_pmu, 1670 const struct cgroup *left_cgroup, const u64 left_group_index, 1671 const struct perf_event *right) 1672 { 1673 if (left_cpu < right->cpu) 1674 return -1; 1675 if (left_cpu > right->cpu) 1676 return 1; 1677 1678 if (left_pmu) { 1679 if (left_pmu < right->pmu_ctx->pmu) 1680 return -1; 1681 if (left_pmu > right->pmu_ctx->pmu) 1682 return 1; 1683 } 1684 1685 #ifdef CONFIG_CGROUP_PERF 1686 { 1687 const struct cgroup *right_cgroup = event_cgroup(right); 1688 1689 if (left_cgroup != right_cgroup) { 1690 if (!left_cgroup) { 1691 /* 1692 * Left has no cgroup but right does, no 1693 * cgroups come first. 1694 */ 1695 return -1; 1696 } 1697 if (!right_cgroup) { 1698 /* 1699 * Right has no cgroup but left does, no 1700 * cgroups come first. 1701 */ 1702 return 1; 1703 } 1704 /* Two dissimilar cgroups, order by id. */ 1705 if (cgroup_id(left_cgroup) < cgroup_id(right_cgroup)) 1706 return -1; 1707 1708 return 1; 1709 } 1710 } 1711 #endif 1712 1713 if (left_group_index < right->group_index) 1714 return -1; 1715 if (left_group_index > right->group_index) 1716 return 1; 1717 1718 return 0; 1719 } 1720 1721 #define __node_2_pe(node) \ 1722 rb_entry((node), struct perf_event, group_node) 1723 1724 static inline bool __group_less(struct rb_node *a, const struct rb_node *b) 1725 { 1726 struct perf_event *e = __node_2_pe(a); 1727 return perf_event_groups_cmp(e->cpu, e->pmu_ctx->pmu, event_cgroup(e), 1728 e->group_index, __node_2_pe(b)) < 0; 1729 } 1730 1731 struct __group_key { 1732 int cpu; 1733 struct pmu *pmu; 1734 struct cgroup *cgroup; 1735 }; 1736 1737 static inline int __group_cmp(const void *key, const struct rb_node *node) 1738 { 1739 const struct __group_key *a = key; 1740 const struct perf_event *b = __node_2_pe(node); 1741 1742 /* partial/subtree match: @cpu, @pmu, @cgroup; ignore: @group_index */ 1743 return perf_event_groups_cmp(a->cpu, a->pmu, a->cgroup, b->group_index, b); 1744 } 1745 1746 static inline int 1747 __group_cmp_ignore_cgroup(const void *key, const struct rb_node *node) 1748 { 1749 const struct __group_key *a = key; 1750 const struct perf_event *b = __node_2_pe(node); 1751 1752 /* partial/subtree match: @cpu, @pmu, ignore: @cgroup, @group_index */ 1753 return perf_event_groups_cmp(a->cpu, a->pmu, event_cgroup(b), 1754 b->group_index, b); 1755 } 1756 1757 /* 1758 * Insert @event into @groups' tree; using 1759 * {@event->cpu, @event->pmu_ctx->pmu, event_cgroup(@event), ++@groups->index} 1760 * as key. This places it last inside the {cpu,pmu,cgroup} subtree. 1761 */ 1762 static void 1763 perf_event_groups_insert(struct perf_event_groups *groups, 1764 struct perf_event *event) 1765 { 1766 event->group_index = ++groups->index; 1767 1768 rb_add(&event->group_node, &groups->tree, __group_less); 1769 } 1770 1771 /* 1772 * Helper function to insert event into the pinned or flexible groups. 1773 */ 1774 static void 1775 add_event_to_groups(struct perf_event *event, struct perf_event_context *ctx) 1776 { 1777 struct perf_event_groups *groups; 1778 1779 groups = get_event_groups(event, ctx); 1780 perf_event_groups_insert(groups, event); 1781 } 1782 1783 /* 1784 * Delete a group from a tree. 1785 */ 1786 static void 1787 perf_event_groups_delete(struct perf_event_groups *groups, 1788 struct perf_event *event) 1789 { 1790 WARN_ON_ONCE(RB_EMPTY_NODE(&event->group_node) || 1791 RB_EMPTY_ROOT(&groups->tree)); 1792 1793 rb_erase(&event->group_node, &groups->tree); 1794 init_event_group(event); 1795 } 1796 1797 /* 1798 * Helper function to delete event from its groups. 1799 */ 1800 static void 1801 del_event_from_groups(struct perf_event *event, struct perf_event_context *ctx) 1802 { 1803 struct perf_event_groups *groups; 1804 1805 groups = get_event_groups(event, ctx); 1806 perf_event_groups_delete(groups, event); 1807 } 1808 1809 /* 1810 * Get the leftmost event in the {cpu,pmu,cgroup} subtree. 1811 */ 1812 static struct perf_event * 1813 perf_event_groups_first(struct perf_event_groups *groups, int cpu, 1814 struct pmu *pmu, struct cgroup *cgrp) 1815 { 1816 struct __group_key key = { 1817 .cpu = cpu, 1818 .pmu = pmu, 1819 .cgroup = cgrp, 1820 }; 1821 struct rb_node *node; 1822 1823 node = rb_find_first(&key, &groups->tree, __group_cmp); 1824 if (node) 1825 return __node_2_pe(node); 1826 1827 return NULL; 1828 } 1829 1830 static struct perf_event * 1831 perf_event_groups_next(struct perf_event *event, struct pmu *pmu) 1832 { 1833 struct __group_key key = { 1834 .cpu = event->cpu, 1835 .pmu = pmu, 1836 .cgroup = event_cgroup(event), 1837 }; 1838 struct rb_node *next; 1839 1840 next = rb_next_match(&key, &event->group_node, __group_cmp); 1841 if (next) 1842 return __node_2_pe(next); 1843 1844 return NULL; 1845 } 1846 1847 #define perf_event_groups_for_cpu_pmu(event, groups, cpu, pmu) \ 1848 for (event = perf_event_groups_first(groups, cpu, pmu, NULL); \ 1849 event; event = perf_event_groups_next(event, pmu)) 1850 1851 /* 1852 * Iterate through the whole groups tree. 1853 */ 1854 #define perf_event_groups_for_each(event, groups) \ 1855 for (event = rb_entry_safe(rb_first(&((groups)->tree)), \ 1856 typeof(*event), group_node); event; \ 1857 event = rb_entry_safe(rb_next(&event->group_node), \ 1858 typeof(*event), group_node)) 1859 1860 /* 1861 * Does the event attribute request inherit with PERF_SAMPLE_READ 1862 */ 1863 static inline bool has_inherit_and_sample_read(struct perf_event_attr *attr) 1864 { 1865 return attr->inherit && (attr->sample_type & PERF_SAMPLE_READ); 1866 } 1867 1868 /* 1869 * Add an event from the lists for its context. 1870 * Must be called with ctx->mutex and ctx->lock held. 1871 */ 1872 static void 1873 list_add_event(struct perf_event *event, struct perf_event_context *ctx) 1874 { 1875 lockdep_assert_held(&ctx->lock); 1876 1877 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT); 1878 event->attach_state |= PERF_ATTACH_CONTEXT; 1879 1880 event->tstamp = perf_event_time(event); 1881 1882 /* 1883 * If we're a stand alone event or group leader, we go to the context 1884 * list, group events are kept attached to the group so that 1885 * perf_group_detach can, at all times, locate all siblings. 1886 */ 1887 if (event->group_leader == event) { 1888 event->group_caps = event->event_caps; 1889 add_event_to_groups(event, ctx); 1890 } 1891 1892 list_add_rcu(&event->event_entry, &ctx->event_list); 1893 ctx->nr_events++; 1894 if (event->hw.flags & PERF_EVENT_FLAG_USER_READ_CNT) 1895 ctx->nr_user++; 1896 if (event->attr.inherit_stat) 1897 ctx->nr_stat++; 1898 if (has_inherit_and_sample_read(&event->attr)) 1899 local_inc(&ctx->nr_no_switch_fast); 1900 1901 if (event->state > PERF_EVENT_STATE_OFF) 1902 perf_cgroup_event_enable(event, ctx); 1903 1904 ctx->generation++; 1905 event->pmu_ctx->nr_events++; 1906 } 1907 1908 /* 1909 * Initialize event state based on the perf_event_attr::disabled. 1910 */ 1911 static inline void perf_event__state_init(struct perf_event *event) 1912 { 1913 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF : 1914 PERF_EVENT_STATE_INACTIVE; 1915 } 1916 1917 static int __perf_event_read_size(u64 read_format, int nr_siblings) 1918 { 1919 int entry = sizeof(u64); /* value */ 1920 int size = 0; 1921 int nr = 1; 1922 1923 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) 1924 size += sizeof(u64); 1925 1926 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) 1927 size += sizeof(u64); 1928 1929 if (read_format & PERF_FORMAT_ID) 1930 entry += sizeof(u64); 1931 1932 if (read_format & PERF_FORMAT_LOST) 1933 entry += sizeof(u64); 1934 1935 if (read_format & PERF_FORMAT_GROUP) { 1936 nr += nr_siblings; 1937 size += sizeof(u64); 1938 } 1939 1940 /* 1941 * Since perf_event_validate_size() limits this to 16k and inhibits 1942 * adding more siblings, this will never overflow. 1943 */ 1944 return size + nr * entry; 1945 } 1946 1947 static void __perf_event_header_size(struct perf_event *event, u64 sample_type) 1948 { 1949 struct perf_sample_data *data; 1950 u16 size = 0; 1951 1952 if (sample_type & PERF_SAMPLE_IP) 1953 size += sizeof(data->ip); 1954 1955 if (sample_type & PERF_SAMPLE_ADDR) 1956 size += sizeof(data->addr); 1957 1958 if (sample_type & PERF_SAMPLE_PERIOD) 1959 size += sizeof(data->period); 1960 1961 if (sample_type & PERF_SAMPLE_WEIGHT_TYPE) 1962 size += sizeof(data->weight.full); 1963 1964 if (sample_type & PERF_SAMPLE_READ) 1965 size += event->read_size; 1966 1967 if (sample_type & PERF_SAMPLE_DATA_SRC) 1968 size += sizeof(data->data_src.val); 1969 1970 if (sample_type & PERF_SAMPLE_TRANSACTION) 1971 size += sizeof(data->txn); 1972 1973 if (sample_type & PERF_SAMPLE_PHYS_ADDR) 1974 size += sizeof(data->phys_addr); 1975 1976 if (sample_type & PERF_SAMPLE_CGROUP) 1977 size += sizeof(data->cgroup); 1978 1979 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE) 1980 size += sizeof(data->data_page_size); 1981 1982 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE) 1983 size += sizeof(data->code_page_size); 1984 1985 event->header_size = size; 1986 } 1987 1988 /* 1989 * Called at perf_event creation and when events are attached/detached from a 1990 * group. 1991 */ 1992 static void perf_event__header_size(struct perf_event *event) 1993 { 1994 event->read_size = 1995 __perf_event_read_size(event->attr.read_format, 1996 event->group_leader->nr_siblings); 1997 __perf_event_header_size(event, event->attr.sample_type); 1998 } 1999 2000 static void perf_event__id_header_size(struct perf_event *event) 2001 { 2002 struct perf_sample_data *data; 2003 u64 sample_type = event->attr.sample_type; 2004 u16 size = 0; 2005 2006 if (sample_type & PERF_SAMPLE_TID) 2007 size += sizeof(data->tid_entry); 2008 2009 if (sample_type & PERF_SAMPLE_TIME) 2010 size += sizeof(data->time); 2011 2012 if (sample_type & PERF_SAMPLE_IDENTIFIER) 2013 size += sizeof(data->id); 2014 2015 if (sample_type & PERF_SAMPLE_ID) 2016 size += sizeof(data->id); 2017 2018 if (sample_type & PERF_SAMPLE_STREAM_ID) 2019 size += sizeof(data->stream_id); 2020 2021 if (sample_type & PERF_SAMPLE_CPU) 2022 size += sizeof(data->cpu_entry); 2023 2024 event->id_header_size = size; 2025 } 2026 2027 /* 2028 * Check that adding an event to the group does not result in anybody 2029 * overflowing the 64k event limit imposed by the output buffer. 2030 * 2031 * Specifically, check that the read_size for the event does not exceed 16k, 2032 * read_size being the one term that grows with groups size. Since read_size 2033 * depends on per-event read_format, also (re)check the existing events. 2034 * 2035 * This leaves 48k for the constant size fields and things like callchains, 2036 * branch stacks and register sets. 2037 */ 2038 static bool perf_event_validate_size(struct perf_event *event) 2039 { 2040 struct perf_event *sibling, *group_leader = event->group_leader; 2041 2042 if (__perf_event_read_size(event->attr.read_format, 2043 group_leader->nr_siblings + 1) > 16*1024) 2044 return false; 2045 2046 if (__perf_event_read_size(group_leader->attr.read_format, 2047 group_leader->nr_siblings + 1) > 16*1024) 2048 return false; 2049 2050 /* 2051 * When creating a new group leader, group_leader->ctx is initialized 2052 * after the size has been validated, but we cannot safely use 2053 * for_each_sibling_event() until group_leader->ctx is set. A new group 2054 * leader cannot have any siblings yet, so we can safely skip checking 2055 * the non-existent siblings. 2056 */ 2057 if (event == group_leader) 2058 return true; 2059 2060 for_each_sibling_event(sibling, group_leader) { 2061 if (__perf_event_read_size(sibling->attr.read_format, 2062 group_leader->nr_siblings + 1) > 16*1024) 2063 return false; 2064 } 2065 2066 return true; 2067 } 2068 2069 static void perf_group_attach(struct perf_event *event) 2070 { 2071 struct perf_event *group_leader = event->group_leader, *pos; 2072 2073 lockdep_assert_held(&event->ctx->lock); 2074 2075 /* 2076 * We can have double attach due to group movement (move_group) in 2077 * perf_event_open(). 2078 */ 2079 if (event->attach_state & PERF_ATTACH_GROUP) 2080 return; 2081 2082 event->attach_state |= PERF_ATTACH_GROUP; 2083 2084 if (group_leader == event) 2085 return; 2086 2087 WARN_ON_ONCE(group_leader->ctx != event->ctx); 2088 2089 group_leader->group_caps &= event->event_caps; 2090 2091 list_add_tail(&event->sibling_list, &group_leader->sibling_list); 2092 group_leader->nr_siblings++; 2093 group_leader->group_generation++; 2094 2095 perf_event__header_size(group_leader); 2096 2097 for_each_sibling_event(pos, group_leader) 2098 perf_event__header_size(pos); 2099 } 2100 2101 /* 2102 * Remove an event from the lists for its context. 2103 * Must be called with ctx->mutex and ctx->lock held. 2104 */ 2105 static void 2106 list_del_event(struct perf_event *event, struct perf_event_context *ctx) 2107 { 2108 WARN_ON_ONCE(event->ctx != ctx); 2109 lockdep_assert_held(&ctx->lock); 2110 2111 /* 2112 * We can have double detach due to exit/hot-unplug + close. 2113 */ 2114 if (!(event->attach_state & PERF_ATTACH_CONTEXT)) 2115 return; 2116 2117 event->attach_state &= ~PERF_ATTACH_CONTEXT; 2118 2119 ctx->nr_events--; 2120 if (event->hw.flags & PERF_EVENT_FLAG_USER_READ_CNT) 2121 ctx->nr_user--; 2122 if (event->attr.inherit_stat) 2123 ctx->nr_stat--; 2124 if (has_inherit_and_sample_read(&event->attr)) 2125 local_dec(&ctx->nr_no_switch_fast); 2126 2127 list_del_rcu(&event->event_entry); 2128 2129 if (event->group_leader == event) 2130 del_event_from_groups(event, ctx); 2131 2132 /* 2133 * If event was in error state, then keep it 2134 * that way, otherwise bogus counts will be 2135 * returned on read(). The only way to get out 2136 * of error state is by explicit re-enabling 2137 * of the event 2138 */ 2139 if (event->state > PERF_EVENT_STATE_OFF) { 2140 perf_cgroup_event_disable(event, ctx); 2141 perf_event_set_state(event, PERF_EVENT_STATE_OFF); 2142 } 2143 2144 ctx->generation++; 2145 event->pmu_ctx->nr_events--; 2146 } 2147 2148 static int 2149 perf_aux_output_match(struct perf_event *event, struct perf_event *aux_event) 2150 { 2151 if (!has_aux(aux_event)) 2152 return 0; 2153 2154 if (!event->pmu->aux_output_match) 2155 return 0; 2156 2157 return event->pmu->aux_output_match(aux_event); 2158 } 2159 2160 static void put_event(struct perf_event *event); 2161 static void event_sched_out(struct perf_event *event, 2162 struct perf_event_context *ctx); 2163 2164 static void perf_put_aux_event(struct perf_event *event) 2165 { 2166 struct perf_event_context *ctx = event->ctx; 2167 struct perf_event *iter; 2168 2169 /* 2170 * If event uses aux_event tear down the link 2171 */ 2172 if (event->aux_event) { 2173 iter = event->aux_event; 2174 event->aux_event = NULL; 2175 put_event(iter); 2176 return; 2177 } 2178 2179 /* 2180 * If the event is an aux_event, tear down all links to 2181 * it from other events. 2182 */ 2183 for_each_sibling_event(iter, event->group_leader) { 2184 if (iter->aux_event != event) 2185 continue; 2186 2187 iter->aux_event = NULL; 2188 put_event(event); 2189 2190 /* 2191 * If it's ACTIVE, schedule it out and put it into ERROR 2192 * state so that we don't try to schedule it again. Note 2193 * that perf_event_enable() will clear the ERROR status. 2194 */ 2195 event_sched_out(iter, ctx); 2196 perf_event_set_state(event, PERF_EVENT_STATE_ERROR); 2197 } 2198 } 2199 2200 static bool perf_need_aux_event(struct perf_event *event) 2201 { 2202 return event->attr.aux_output || has_aux_action(event); 2203 } 2204 2205 static int perf_get_aux_event(struct perf_event *event, 2206 struct perf_event *group_leader) 2207 { 2208 /* 2209 * Our group leader must be an aux event if we want to be 2210 * an aux_output. This way, the aux event will precede its 2211 * aux_output events in the group, and therefore will always 2212 * schedule first. 2213 */ 2214 if (!group_leader) 2215 return 0; 2216 2217 /* 2218 * aux_output and aux_sample_size are mutually exclusive. 2219 */ 2220 if (event->attr.aux_output && event->attr.aux_sample_size) 2221 return 0; 2222 2223 if (event->attr.aux_output && 2224 !perf_aux_output_match(event, group_leader)) 2225 return 0; 2226 2227 if ((event->attr.aux_pause || event->attr.aux_resume) && 2228 !(group_leader->pmu->capabilities & PERF_PMU_CAP_AUX_PAUSE)) 2229 return 0; 2230 2231 if (event->attr.aux_sample_size && !group_leader->pmu->snapshot_aux) 2232 return 0; 2233 2234 if (!atomic_long_inc_not_zero(&group_leader->refcount)) 2235 return 0; 2236 2237 /* 2238 * Link aux_outputs to their aux event; this is undone in 2239 * perf_group_detach() by perf_put_aux_event(). When the 2240 * group in torn down, the aux_output events loose their 2241 * link to the aux_event and can't schedule any more. 2242 */ 2243 event->aux_event = group_leader; 2244 2245 return 1; 2246 } 2247 2248 static inline struct list_head *get_event_list(struct perf_event *event) 2249 { 2250 return event->attr.pinned ? &event->pmu_ctx->pinned_active : 2251 &event->pmu_ctx->flexible_active; 2252 } 2253 2254 /* 2255 * Events that have PERF_EV_CAP_SIBLING require being part of a group and 2256 * cannot exist on their own, schedule them out and move them into the ERROR 2257 * state. Also see _perf_event_enable(), it will not be able to recover 2258 * this ERROR state. 2259 */ 2260 static inline void perf_remove_sibling_event(struct perf_event *event) 2261 { 2262 event_sched_out(event, event->ctx); 2263 perf_event_set_state(event, PERF_EVENT_STATE_ERROR); 2264 } 2265 2266 static void perf_group_detach(struct perf_event *event) 2267 { 2268 struct perf_event *leader = event->group_leader; 2269 struct perf_event *sibling, *tmp; 2270 struct perf_event_context *ctx = event->ctx; 2271 2272 lockdep_assert_held(&ctx->lock); 2273 2274 /* 2275 * We can have double detach due to exit/hot-unplug + close. 2276 */ 2277 if (!(event->attach_state & PERF_ATTACH_GROUP)) 2278 return; 2279 2280 event->attach_state &= ~PERF_ATTACH_GROUP; 2281 2282 perf_put_aux_event(event); 2283 2284 /* 2285 * If this is a sibling, remove it from its group. 2286 */ 2287 if (leader != event) { 2288 list_del_init(&event->sibling_list); 2289 event->group_leader->nr_siblings--; 2290 event->group_leader->group_generation++; 2291 goto out; 2292 } 2293 2294 /* 2295 * If this was a group event with sibling events then 2296 * upgrade the siblings to singleton events by adding them 2297 * to whatever list we are on. 2298 */ 2299 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, sibling_list) { 2300 2301 if (sibling->event_caps & PERF_EV_CAP_SIBLING) 2302 perf_remove_sibling_event(sibling); 2303 2304 sibling->group_leader = sibling; 2305 list_del_init(&sibling->sibling_list); 2306 2307 /* Inherit group flags from the previous leader */ 2308 sibling->group_caps = event->group_caps; 2309 2310 if (sibling->attach_state & PERF_ATTACH_CONTEXT) { 2311 add_event_to_groups(sibling, event->ctx); 2312 2313 if (sibling->state == PERF_EVENT_STATE_ACTIVE) 2314 list_add_tail(&sibling->active_list, get_event_list(sibling)); 2315 } 2316 2317 WARN_ON_ONCE(sibling->ctx != event->ctx); 2318 } 2319 2320 out: 2321 for_each_sibling_event(tmp, leader) 2322 perf_event__header_size(tmp); 2323 2324 perf_event__header_size(leader); 2325 } 2326 2327 static void sync_child_event(struct perf_event *child_event); 2328 2329 static void perf_child_detach(struct perf_event *event) 2330 { 2331 struct perf_event *parent_event = event->parent; 2332 2333 if (!(event->attach_state & PERF_ATTACH_CHILD)) 2334 return; 2335 2336 event->attach_state &= ~PERF_ATTACH_CHILD; 2337 2338 if (WARN_ON_ONCE(!parent_event)) 2339 return; 2340 2341 lockdep_assert_held(&parent_event->child_mutex); 2342 2343 sync_child_event(event); 2344 list_del_init(&event->child_list); 2345 } 2346 2347 static bool is_orphaned_event(struct perf_event *event) 2348 { 2349 return event->state == PERF_EVENT_STATE_DEAD; 2350 } 2351 2352 static inline int 2353 event_filter_match(struct perf_event *event) 2354 { 2355 return (event->cpu == -1 || event->cpu == smp_processor_id()) && 2356 perf_cgroup_match(event); 2357 } 2358 2359 static void 2360 event_sched_out(struct perf_event *event, struct perf_event_context *ctx) 2361 { 2362 struct perf_event_pmu_context *epc = event->pmu_ctx; 2363 struct perf_cpu_pmu_context *cpc = this_cpc(epc->pmu); 2364 enum perf_event_state state = PERF_EVENT_STATE_INACTIVE; 2365 2366 // XXX cpc serialization, probably per-cpu IRQ disabled 2367 2368 WARN_ON_ONCE(event->ctx != ctx); 2369 lockdep_assert_held(&ctx->lock); 2370 2371 if (event->state != PERF_EVENT_STATE_ACTIVE) 2372 return; 2373 2374 /* 2375 * Asymmetry; we only schedule events _IN_ through ctx_sched_in(), but 2376 * we can schedule events _OUT_ individually through things like 2377 * __perf_remove_from_context(). 2378 */ 2379 list_del_init(&event->active_list); 2380 2381 perf_pmu_disable(event->pmu); 2382 2383 event->pmu->del(event, 0); 2384 event->oncpu = -1; 2385 2386 if (event->pending_disable) { 2387 event->pending_disable = 0; 2388 perf_cgroup_event_disable(event, ctx); 2389 state = PERF_EVENT_STATE_OFF; 2390 } 2391 2392 perf_event_set_state(event, state); 2393 2394 if (!is_software_event(event)) 2395 cpc->active_oncpu--; 2396 if (event->attr.freq && event->attr.sample_freq) { 2397 ctx->nr_freq--; 2398 epc->nr_freq--; 2399 } 2400 if (event->attr.exclusive || !cpc->active_oncpu) 2401 cpc->exclusive = 0; 2402 2403 perf_pmu_enable(event->pmu); 2404 } 2405 2406 static void 2407 group_sched_out(struct perf_event *group_event, struct perf_event_context *ctx) 2408 { 2409 struct perf_event *event; 2410 2411 if (group_event->state != PERF_EVENT_STATE_ACTIVE) 2412 return; 2413 2414 perf_assert_pmu_disabled(group_event->pmu_ctx->pmu); 2415 2416 event_sched_out(group_event, ctx); 2417 2418 /* 2419 * Schedule out siblings (if any): 2420 */ 2421 for_each_sibling_event(event, group_event) 2422 event_sched_out(event, ctx); 2423 } 2424 2425 static inline void 2426 __ctx_time_update(struct perf_cpu_context *cpuctx, struct perf_event_context *ctx, bool final) 2427 { 2428 if (ctx->is_active & EVENT_TIME) { 2429 if (ctx->is_active & EVENT_FROZEN) 2430 return; 2431 update_context_time(ctx); 2432 update_cgrp_time_from_cpuctx(cpuctx, final); 2433 } 2434 } 2435 2436 static inline void 2437 ctx_time_update(struct perf_cpu_context *cpuctx, struct perf_event_context *ctx) 2438 { 2439 __ctx_time_update(cpuctx, ctx, false); 2440 } 2441 2442 /* 2443 * To be used inside perf_ctx_lock() / perf_ctx_unlock(). Lasts until perf_ctx_unlock(). 2444 */ 2445 static inline void 2446 ctx_time_freeze(struct perf_cpu_context *cpuctx, struct perf_event_context *ctx) 2447 { 2448 ctx_time_update(cpuctx, ctx); 2449 if (ctx->is_active & EVENT_TIME) 2450 ctx->is_active |= EVENT_FROZEN; 2451 } 2452 2453 static inline void 2454 ctx_time_update_event(struct perf_event_context *ctx, struct perf_event *event) 2455 { 2456 if (ctx->is_active & EVENT_TIME) { 2457 if (ctx->is_active & EVENT_FROZEN) 2458 return; 2459 update_context_time(ctx); 2460 update_cgrp_time_from_event(event); 2461 } 2462 } 2463 2464 #define DETACH_GROUP 0x01UL 2465 #define DETACH_CHILD 0x02UL 2466 #define DETACH_DEAD 0x04UL 2467 2468 /* 2469 * Cross CPU call to remove a performance event 2470 * 2471 * We disable the event on the hardware level first. After that we 2472 * remove it from the context list. 2473 */ 2474 static void 2475 __perf_remove_from_context(struct perf_event *event, 2476 struct perf_cpu_context *cpuctx, 2477 struct perf_event_context *ctx, 2478 void *info) 2479 { 2480 struct perf_event_pmu_context *pmu_ctx = event->pmu_ctx; 2481 unsigned long flags = (unsigned long)info; 2482 2483 ctx_time_update(cpuctx, ctx); 2484 2485 /* 2486 * Ensure event_sched_out() switches to OFF, at the very least 2487 * this avoids raising perf_pending_task() at this time. 2488 */ 2489 if (flags & DETACH_DEAD) 2490 event->pending_disable = 1; 2491 event_sched_out(event, ctx); 2492 if (flags & DETACH_GROUP) 2493 perf_group_detach(event); 2494 if (flags & DETACH_CHILD) 2495 perf_child_detach(event); 2496 list_del_event(event, ctx); 2497 if (flags & DETACH_DEAD) 2498 event->state = PERF_EVENT_STATE_DEAD; 2499 2500 if (!pmu_ctx->nr_events) { 2501 pmu_ctx->rotate_necessary = 0; 2502 2503 if (ctx->task && ctx->is_active) { 2504 struct perf_cpu_pmu_context *cpc = this_cpc(pmu_ctx->pmu); 2505 2506 WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx); 2507 cpc->task_epc = NULL; 2508 } 2509 } 2510 2511 if (!ctx->nr_events && ctx->is_active) { 2512 if (ctx == &cpuctx->ctx) 2513 update_cgrp_time_from_cpuctx(cpuctx, true); 2514 2515 ctx->is_active = 0; 2516 if (ctx->task) { 2517 WARN_ON_ONCE(cpuctx->task_ctx != ctx); 2518 cpuctx->task_ctx = NULL; 2519 } 2520 } 2521 } 2522 2523 /* 2524 * Remove the event from a task's (or a CPU's) list of events. 2525 * 2526 * If event->ctx is a cloned context, callers must make sure that 2527 * every task struct that event->ctx->task could possibly point to 2528 * remains valid. This is OK when called from perf_release since 2529 * that only calls us on the top-level context, which can't be a clone. 2530 * When called from perf_event_exit_task, it's OK because the 2531 * context has been detached from its task. 2532 */ 2533 static void perf_remove_from_context(struct perf_event *event, unsigned long flags) 2534 { 2535 struct perf_event_context *ctx = event->ctx; 2536 2537 lockdep_assert_held(&ctx->mutex); 2538 2539 /* 2540 * Because of perf_event_exit_task(), perf_remove_from_context() ought 2541 * to work in the face of TASK_TOMBSTONE, unlike every other 2542 * event_function_call() user. 2543 */ 2544 raw_spin_lock_irq(&ctx->lock); 2545 if (!ctx->is_active) { 2546 __perf_remove_from_context(event, this_cpu_ptr(&perf_cpu_context), 2547 ctx, (void *)flags); 2548 raw_spin_unlock_irq(&ctx->lock); 2549 return; 2550 } 2551 raw_spin_unlock_irq(&ctx->lock); 2552 2553 event_function_call(event, __perf_remove_from_context, (void *)flags); 2554 } 2555 2556 /* 2557 * Cross CPU call to disable a performance event 2558 */ 2559 static void __perf_event_disable(struct perf_event *event, 2560 struct perf_cpu_context *cpuctx, 2561 struct perf_event_context *ctx, 2562 void *info) 2563 { 2564 if (event->state < PERF_EVENT_STATE_INACTIVE) 2565 return; 2566 2567 perf_pmu_disable(event->pmu_ctx->pmu); 2568 ctx_time_update_event(ctx, event); 2569 2570 if (event == event->group_leader) 2571 group_sched_out(event, ctx); 2572 else 2573 event_sched_out(event, ctx); 2574 2575 perf_event_set_state(event, PERF_EVENT_STATE_OFF); 2576 perf_cgroup_event_disable(event, ctx); 2577 2578 perf_pmu_enable(event->pmu_ctx->pmu); 2579 } 2580 2581 /* 2582 * Disable an event. 2583 * 2584 * If event->ctx is a cloned context, callers must make sure that 2585 * every task struct that event->ctx->task could possibly point to 2586 * remains valid. This condition is satisfied when called through 2587 * perf_event_for_each_child or perf_event_for_each because they 2588 * hold the top-level event's child_mutex, so any descendant that 2589 * goes to exit will block in perf_event_exit_event(). 2590 * 2591 * When called from perf_pending_disable it's OK because event->ctx 2592 * is the current context on this CPU and preemption is disabled, 2593 * hence we can't get into perf_event_task_sched_out for this context. 2594 */ 2595 static void _perf_event_disable(struct perf_event *event) 2596 { 2597 struct perf_event_context *ctx = event->ctx; 2598 2599 raw_spin_lock_irq(&ctx->lock); 2600 if (event->state <= PERF_EVENT_STATE_OFF) { 2601 raw_spin_unlock_irq(&ctx->lock); 2602 return; 2603 } 2604 raw_spin_unlock_irq(&ctx->lock); 2605 2606 event_function_call(event, __perf_event_disable, NULL); 2607 } 2608 2609 void perf_event_disable_local(struct perf_event *event) 2610 { 2611 event_function_local(event, __perf_event_disable, NULL); 2612 } 2613 2614 /* 2615 * Strictly speaking kernel users cannot create groups and therefore this 2616 * interface does not need the perf_event_ctx_lock() magic. 2617 */ 2618 void perf_event_disable(struct perf_event *event) 2619 { 2620 struct perf_event_context *ctx; 2621 2622 ctx = perf_event_ctx_lock(event); 2623 _perf_event_disable(event); 2624 perf_event_ctx_unlock(event, ctx); 2625 } 2626 EXPORT_SYMBOL_GPL(perf_event_disable); 2627 2628 void perf_event_disable_inatomic(struct perf_event *event) 2629 { 2630 event->pending_disable = 1; 2631 irq_work_queue(&event->pending_disable_irq); 2632 } 2633 2634 #define MAX_INTERRUPTS (~0ULL) 2635 2636 static void perf_log_throttle(struct perf_event *event, int enable); 2637 static void perf_log_itrace_start(struct perf_event *event); 2638 2639 static int 2640 event_sched_in(struct perf_event *event, struct perf_event_context *ctx) 2641 { 2642 struct perf_event_pmu_context *epc = event->pmu_ctx; 2643 struct perf_cpu_pmu_context *cpc = this_cpc(epc->pmu); 2644 int ret = 0; 2645 2646 WARN_ON_ONCE(event->ctx != ctx); 2647 2648 lockdep_assert_held(&ctx->lock); 2649 2650 if (event->state <= PERF_EVENT_STATE_OFF) 2651 return 0; 2652 2653 WRITE_ONCE(event->oncpu, smp_processor_id()); 2654 /* 2655 * Order event::oncpu write to happen before the ACTIVE state is 2656 * visible. This allows perf_event_{stop,read}() to observe the correct 2657 * ->oncpu if it sees ACTIVE. 2658 */ 2659 smp_wmb(); 2660 perf_event_set_state(event, PERF_EVENT_STATE_ACTIVE); 2661 2662 /* 2663 * Unthrottle events, since we scheduled we might have missed several 2664 * ticks already, also for a heavily scheduling task there is little 2665 * guarantee it'll get a tick in a timely manner. 2666 */ 2667 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) { 2668 perf_log_throttle(event, 1); 2669 event->hw.interrupts = 0; 2670 } 2671 2672 perf_pmu_disable(event->pmu); 2673 2674 perf_log_itrace_start(event); 2675 2676 if (event->pmu->add(event, PERF_EF_START)) { 2677 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE); 2678 event->oncpu = -1; 2679 ret = -EAGAIN; 2680 goto out; 2681 } 2682 2683 if (!is_software_event(event)) 2684 cpc->active_oncpu++; 2685 if (event->attr.freq && event->attr.sample_freq) { 2686 ctx->nr_freq++; 2687 epc->nr_freq++; 2688 } 2689 if (event->attr.exclusive) 2690 cpc->exclusive = 1; 2691 2692 out: 2693 perf_pmu_enable(event->pmu); 2694 2695 return ret; 2696 } 2697 2698 static int 2699 group_sched_in(struct perf_event *group_event, struct perf_event_context *ctx) 2700 { 2701 struct perf_event *event, *partial_group = NULL; 2702 struct pmu *pmu = group_event->pmu_ctx->pmu; 2703 2704 if (group_event->state == PERF_EVENT_STATE_OFF) 2705 return 0; 2706 2707 pmu->start_txn(pmu, PERF_PMU_TXN_ADD); 2708 2709 if (event_sched_in(group_event, ctx)) 2710 goto error; 2711 2712 /* 2713 * Schedule in siblings as one group (if any): 2714 */ 2715 for_each_sibling_event(event, group_event) { 2716 if (event_sched_in(event, ctx)) { 2717 partial_group = event; 2718 goto group_error; 2719 } 2720 } 2721 2722 if (!pmu->commit_txn(pmu)) 2723 return 0; 2724 2725 group_error: 2726 /* 2727 * Groups can be scheduled in as one unit only, so undo any 2728 * partial group before returning: 2729 * The events up to the failed event are scheduled out normally. 2730 */ 2731 for_each_sibling_event(event, group_event) { 2732 if (event == partial_group) 2733 break; 2734 2735 event_sched_out(event, ctx); 2736 } 2737 event_sched_out(group_event, ctx); 2738 2739 error: 2740 pmu->cancel_txn(pmu); 2741 return -EAGAIN; 2742 } 2743 2744 /* 2745 * Work out whether we can put this event group on the CPU now. 2746 */ 2747 static int group_can_go_on(struct perf_event *event, int can_add_hw) 2748 { 2749 struct perf_event_pmu_context *epc = event->pmu_ctx; 2750 struct perf_cpu_pmu_context *cpc = this_cpc(epc->pmu); 2751 2752 /* 2753 * Groups consisting entirely of software events can always go on. 2754 */ 2755 if (event->group_caps & PERF_EV_CAP_SOFTWARE) 2756 return 1; 2757 /* 2758 * If an exclusive group is already on, no other hardware 2759 * events can go on. 2760 */ 2761 if (cpc->exclusive) 2762 return 0; 2763 /* 2764 * If this group is exclusive and there are already 2765 * events on the CPU, it can't go on. 2766 */ 2767 if (event->attr.exclusive && !list_empty(get_event_list(event))) 2768 return 0; 2769 /* 2770 * Otherwise, try to add it if all previous groups were able 2771 * to go on. 2772 */ 2773 return can_add_hw; 2774 } 2775 2776 static void add_event_to_ctx(struct perf_event *event, 2777 struct perf_event_context *ctx) 2778 { 2779 list_add_event(event, ctx); 2780 perf_group_attach(event); 2781 } 2782 2783 static void task_ctx_sched_out(struct perf_event_context *ctx, 2784 struct pmu *pmu, 2785 enum event_type_t event_type) 2786 { 2787 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 2788 2789 if (!cpuctx->task_ctx) 2790 return; 2791 2792 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx)) 2793 return; 2794 2795 ctx_sched_out(ctx, pmu, event_type); 2796 } 2797 2798 static void perf_event_sched_in(struct perf_cpu_context *cpuctx, 2799 struct perf_event_context *ctx, 2800 struct pmu *pmu) 2801 { 2802 ctx_sched_in(&cpuctx->ctx, pmu, EVENT_PINNED); 2803 if (ctx) 2804 ctx_sched_in(ctx, pmu, EVENT_PINNED); 2805 ctx_sched_in(&cpuctx->ctx, pmu, EVENT_FLEXIBLE); 2806 if (ctx) 2807 ctx_sched_in(ctx, pmu, EVENT_FLEXIBLE); 2808 } 2809 2810 /* 2811 * We want to maintain the following priority of scheduling: 2812 * - CPU pinned (EVENT_CPU | EVENT_PINNED) 2813 * - task pinned (EVENT_PINNED) 2814 * - CPU flexible (EVENT_CPU | EVENT_FLEXIBLE) 2815 * - task flexible (EVENT_FLEXIBLE). 2816 * 2817 * In order to avoid unscheduling and scheduling back in everything every 2818 * time an event is added, only do it for the groups of equal priority and 2819 * below. 2820 * 2821 * This can be called after a batch operation on task events, in which case 2822 * event_type is a bit mask of the types of events involved. For CPU events, 2823 * event_type is only either EVENT_PINNED or EVENT_FLEXIBLE. 2824 */ 2825 static void ctx_resched(struct perf_cpu_context *cpuctx, 2826 struct perf_event_context *task_ctx, 2827 struct pmu *pmu, enum event_type_t event_type) 2828 { 2829 bool cpu_event = !!(event_type & EVENT_CPU); 2830 struct perf_event_pmu_context *epc; 2831 2832 /* 2833 * If pinned groups are involved, flexible groups also need to be 2834 * scheduled out. 2835 */ 2836 if (event_type & EVENT_PINNED) 2837 event_type |= EVENT_FLEXIBLE; 2838 2839 event_type &= EVENT_ALL; 2840 2841 for_each_epc(epc, &cpuctx->ctx, pmu, false) 2842 perf_pmu_disable(epc->pmu); 2843 2844 if (task_ctx) { 2845 for_each_epc(epc, task_ctx, pmu, false) 2846 perf_pmu_disable(epc->pmu); 2847 2848 task_ctx_sched_out(task_ctx, pmu, event_type); 2849 } 2850 2851 /* 2852 * Decide which cpu ctx groups to schedule out based on the types 2853 * of events that caused rescheduling: 2854 * - EVENT_CPU: schedule out corresponding groups; 2855 * - EVENT_PINNED task events: schedule out EVENT_FLEXIBLE groups; 2856 * - otherwise, do nothing more. 2857 */ 2858 if (cpu_event) 2859 ctx_sched_out(&cpuctx->ctx, pmu, event_type); 2860 else if (event_type & EVENT_PINNED) 2861 ctx_sched_out(&cpuctx->ctx, pmu, EVENT_FLEXIBLE); 2862 2863 perf_event_sched_in(cpuctx, task_ctx, pmu); 2864 2865 for_each_epc(epc, &cpuctx->ctx, pmu, false) 2866 perf_pmu_enable(epc->pmu); 2867 2868 if (task_ctx) { 2869 for_each_epc(epc, task_ctx, pmu, false) 2870 perf_pmu_enable(epc->pmu); 2871 } 2872 } 2873 2874 void perf_pmu_resched(struct pmu *pmu) 2875 { 2876 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 2877 struct perf_event_context *task_ctx = cpuctx->task_ctx; 2878 2879 perf_ctx_lock(cpuctx, task_ctx); 2880 ctx_resched(cpuctx, task_ctx, pmu, EVENT_ALL|EVENT_CPU); 2881 perf_ctx_unlock(cpuctx, task_ctx); 2882 } 2883 2884 /* 2885 * Cross CPU call to install and enable a performance event 2886 * 2887 * Very similar to remote_function() + event_function() but cannot assume that 2888 * things like ctx->is_active and cpuctx->task_ctx are set. 2889 */ 2890 static int __perf_install_in_context(void *info) 2891 { 2892 struct perf_event *event = info; 2893 struct perf_event_context *ctx = event->ctx; 2894 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 2895 struct perf_event_context *task_ctx = cpuctx->task_ctx; 2896 bool reprogram = true; 2897 int ret = 0; 2898 2899 raw_spin_lock(&cpuctx->ctx.lock); 2900 if (ctx->task) { 2901 raw_spin_lock(&ctx->lock); 2902 task_ctx = ctx; 2903 2904 reprogram = (ctx->task == current); 2905 2906 /* 2907 * If the task is running, it must be running on this CPU, 2908 * otherwise we cannot reprogram things. 2909 * 2910 * If its not running, we don't care, ctx->lock will 2911 * serialize against it becoming runnable. 2912 */ 2913 if (task_curr(ctx->task) && !reprogram) { 2914 ret = -ESRCH; 2915 goto unlock; 2916 } 2917 2918 WARN_ON_ONCE(reprogram && cpuctx->task_ctx && cpuctx->task_ctx != ctx); 2919 } else if (task_ctx) { 2920 raw_spin_lock(&task_ctx->lock); 2921 } 2922 2923 #ifdef CONFIG_CGROUP_PERF 2924 if (event->state > PERF_EVENT_STATE_OFF && is_cgroup_event(event)) { 2925 /* 2926 * If the current cgroup doesn't match the event's 2927 * cgroup, we should not try to schedule it. 2928 */ 2929 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx); 2930 reprogram = cgroup_is_descendant(cgrp->css.cgroup, 2931 event->cgrp->css.cgroup); 2932 } 2933 #endif 2934 2935 if (reprogram) { 2936 ctx_time_freeze(cpuctx, ctx); 2937 add_event_to_ctx(event, ctx); 2938 ctx_resched(cpuctx, task_ctx, event->pmu_ctx->pmu, 2939 get_event_type(event)); 2940 } else { 2941 add_event_to_ctx(event, ctx); 2942 } 2943 2944 unlock: 2945 perf_ctx_unlock(cpuctx, task_ctx); 2946 2947 return ret; 2948 } 2949 2950 static bool exclusive_event_installable(struct perf_event *event, 2951 struct perf_event_context *ctx); 2952 2953 /* 2954 * Attach a performance event to a context. 2955 * 2956 * Very similar to event_function_call, see comment there. 2957 */ 2958 static void 2959 perf_install_in_context(struct perf_event_context *ctx, 2960 struct perf_event *event, 2961 int cpu) 2962 { 2963 struct task_struct *task = READ_ONCE(ctx->task); 2964 2965 lockdep_assert_held(&ctx->mutex); 2966 2967 WARN_ON_ONCE(!exclusive_event_installable(event, ctx)); 2968 2969 if (event->cpu != -1) 2970 WARN_ON_ONCE(event->cpu != cpu); 2971 2972 /* 2973 * Ensures that if we can observe event->ctx, both the event and ctx 2974 * will be 'complete'. See perf_iterate_sb_cpu(). 2975 */ 2976 smp_store_release(&event->ctx, ctx); 2977 2978 /* 2979 * perf_event_attr::disabled events will not run and can be initialized 2980 * without IPI. Except when this is the first event for the context, in 2981 * that case we need the magic of the IPI to set ctx->is_active. 2982 * 2983 * The IOC_ENABLE that is sure to follow the creation of a disabled 2984 * event will issue the IPI and reprogram the hardware. 2985 */ 2986 if (__perf_effective_state(event) == PERF_EVENT_STATE_OFF && 2987 ctx->nr_events && !is_cgroup_event(event)) { 2988 raw_spin_lock_irq(&ctx->lock); 2989 if (ctx->task == TASK_TOMBSTONE) { 2990 raw_spin_unlock_irq(&ctx->lock); 2991 return; 2992 } 2993 add_event_to_ctx(event, ctx); 2994 raw_spin_unlock_irq(&ctx->lock); 2995 return; 2996 } 2997 2998 if (!task) { 2999 cpu_function_call(cpu, __perf_install_in_context, event); 3000 return; 3001 } 3002 3003 /* 3004 * Should not happen, we validate the ctx is still alive before calling. 3005 */ 3006 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) 3007 return; 3008 3009 /* 3010 * Installing events is tricky because we cannot rely on ctx->is_active 3011 * to be set in case this is the nr_events 0 -> 1 transition. 3012 * 3013 * Instead we use task_curr(), which tells us if the task is running. 3014 * However, since we use task_curr() outside of rq::lock, we can race 3015 * against the actual state. This means the result can be wrong. 3016 * 3017 * If we get a false positive, we retry, this is harmless. 3018 * 3019 * If we get a false negative, things are complicated. If we are after 3020 * perf_event_context_sched_in() ctx::lock will serialize us, and the 3021 * value must be correct. If we're before, it doesn't matter since 3022 * perf_event_context_sched_in() will program the counter. 3023 * 3024 * However, this hinges on the remote context switch having observed 3025 * our task->perf_event_ctxp[] store, such that it will in fact take 3026 * ctx::lock in perf_event_context_sched_in(). 3027 * 3028 * We do this by task_function_call(), if the IPI fails to hit the task 3029 * we know any future context switch of task must see the 3030 * perf_event_ctpx[] store. 3031 */ 3032 3033 /* 3034 * This smp_mb() orders the task->perf_event_ctxp[] store with the 3035 * task_cpu() load, such that if the IPI then does not find the task 3036 * running, a future context switch of that task must observe the 3037 * store. 3038 */ 3039 smp_mb(); 3040 again: 3041 if (!task_function_call(task, __perf_install_in_context, event)) 3042 return; 3043 3044 raw_spin_lock_irq(&ctx->lock); 3045 task = ctx->task; 3046 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) { 3047 /* 3048 * Cannot happen because we already checked above (which also 3049 * cannot happen), and we hold ctx->mutex, which serializes us 3050 * against perf_event_exit_task_context(). 3051 */ 3052 raw_spin_unlock_irq(&ctx->lock); 3053 return; 3054 } 3055 /* 3056 * If the task is not running, ctx->lock will avoid it becoming so, 3057 * thus we can safely install the event. 3058 */ 3059 if (task_curr(task)) { 3060 raw_spin_unlock_irq(&ctx->lock); 3061 goto again; 3062 } 3063 add_event_to_ctx(event, ctx); 3064 raw_spin_unlock_irq(&ctx->lock); 3065 } 3066 3067 /* 3068 * Cross CPU call to enable a performance event 3069 */ 3070 static void __perf_event_enable(struct perf_event *event, 3071 struct perf_cpu_context *cpuctx, 3072 struct perf_event_context *ctx, 3073 void *info) 3074 { 3075 struct perf_event *leader = event->group_leader; 3076 struct perf_event_context *task_ctx; 3077 3078 if (event->state >= PERF_EVENT_STATE_INACTIVE || 3079 event->state <= PERF_EVENT_STATE_ERROR) 3080 return; 3081 3082 ctx_time_freeze(cpuctx, ctx); 3083 3084 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE); 3085 perf_cgroup_event_enable(event, ctx); 3086 3087 if (!ctx->is_active) 3088 return; 3089 3090 if (!event_filter_match(event)) 3091 return; 3092 3093 /* 3094 * If the event is in a group and isn't the group leader, 3095 * then don't put it on unless the group is on. 3096 */ 3097 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE) 3098 return; 3099 3100 task_ctx = cpuctx->task_ctx; 3101 if (ctx->task) 3102 WARN_ON_ONCE(task_ctx != ctx); 3103 3104 ctx_resched(cpuctx, task_ctx, event->pmu_ctx->pmu, get_event_type(event)); 3105 } 3106 3107 /* 3108 * Enable an event. 3109 * 3110 * If event->ctx is a cloned context, callers must make sure that 3111 * every task struct that event->ctx->task could possibly point to 3112 * remains valid. This condition is satisfied when called through 3113 * perf_event_for_each_child or perf_event_for_each as described 3114 * for perf_event_disable. 3115 */ 3116 static void _perf_event_enable(struct perf_event *event) 3117 { 3118 struct perf_event_context *ctx = event->ctx; 3119 3120 raw_spin_lock_irq(&ctx->lock); 3121 if (event->state >= PERF_EVENT_STATE_INACTIVE || 3122 event->state < PERF_EVENT_STATE_ERROR) { 3123 out: 3124 raw_spin_unlock_irq(&ctx->lock); 3125 return; 3126 } 3127 3128 /* 3129 * If the event is in error state, clear that first. 3130 * 3131 * That way, if we see the event in error state below, we know that it 3132 * has gone back into error state, as distinct from the task having 3133 * been scheduled away before the cross-call arrived. 3134 */ 3135 if (event->state == PERF_EVENT_STATE_ERROR) { 3136 /* 3137 * Detached SIBLING events cannot leave ERROR state. 3138 */ 3139 if (event->event_caps & PERF_EV_CAP_SIBLING && 3140 event->group_leader == event) 3141 goto out; 3142 3143 event->state = PERF_EVENT_STATE_OFF; 3144 } 3145 raw_spin_unlock_irq(&ctx->lock); 3146 3147 event_function_call(event, __perf_event_enable, NULL); 3148 } 3149 3150 /* 3151 * See perf_event_disable(); 3152 */ 3153 void perf_event_enable(struct perf_event *event) 3154 { 3155 struct perf_event_context *ctx; 3156 3157 ctx = perf_event_ctx_lock(event); 3158 _perf_event_enable(event); 3159 perf_event_ctx_unlock(event, ctx); 3160 } 3161 EXPORT_SYMBOL_GPL(perf_event_enable); 3162 3163 struct stop_event_data { 3164 struct perf_event *event; 3165 unsigned int restart; 3166 }; 3167 3168 static int __perf_event_stop(void *info) 3169 { 3170 struct stop_event_data *sd = info; 3171 struct perf_event *event = sd->event; 3172 3173 /* if it's already INACTIVE, do nothing */ 3174 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE) 3175 return 0; 3176 3177 /* matches smp_wmb() in event_sched_in() */ 3178 smp_rmb(); 3179 3180 /* 3181 * There is a window with interrupts enabled before we get here, 3182 * so we need to check again lest we try to stop another CPU's event. 3183 */ 3184 if (READ_ONCE(event->oncpu) != smp_processor_id()) 3185 return -EAGAIN; 3186 3187 event->pmu->stop(event, PERF_EF_UPDATE); 3188 3189 /* 3190 * May race with the actual stop (through perf_pmu_output_stop()), 3191 * but it is only used for events with AUX ring buffer, and such 3192 * events will refuse to restart because of rb::aux_mmap_count==0, 3193 * see comments in perf_aux_output_begin(). 3194 * 3195 * Since this is happening on an event-local CPU, no trace is lost 3196 * while restarting. 3197 */ 3198 if (sd->restart) 3199 event->pmu->start(event, 0); 3200 3201 return 0; 3202 } 3203 3204 static int perf_event_stop(struct perf_event *event, int restart) 3205 { 3206 struct stop_event_data sd = { 3207 .event = event, 3208 .restart = restart, 3209 }; 3210 int ret = 0; 3211 3212 do { 3213 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE) 3214 return 0; 3215 3216 /* matches smp_wmb() in event_sched_in() */ 3217 smp_rmb(); 3218 3219 /* 3220 * We only want to restart ACTIVE events, so if the event goes 3221 * inactive here (event->oncpu==-1), there's nothing more to do; 3222 * fall through with ret==-ENXIO. 3223 */ 3224 ret = cpu_function_call(READ_ONCE(event->oncpu), 3225 __perf_event_stop, &sd); 3226 } while (ret == -EAGAIN); 3227 3228 return ret; 3229 } 3230 3231 /* 3232 * In order to contain the amount of racy and tricky in the address filter 3233 * configuration management, it is a two part process: 3234 * 3235 * (p1) when userspace mappings change as a result of (1) or (2) or (3) below, 3236 * we update the addresses of corresponding vmas in 3237 * event::addr_filter_ranges array and bump the event::addr_filters_gen; 3238 * (p2) when an event is scheduled in (pmu::add), it calls 3239 * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync() 3240 * if the generation has changed since the previous call. 3241 * 3242 * If (p1) happens while the event is active, we restart it to force (p2). 3243 * 3244 * (1) perf_addr_filters_apply(): adjusting filters' offsets based on 3245 * pre-existing mappings, called once when new filters arrive via SET_FILTER 3246 * ioctl; 3247 * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly 3248 * registered mapping, called for every new mmap(), with mm::mmap_lock down 3249 * for reading; 3250 * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process 3251 * of exec. 3252 */ 3253 void perf_event_addr_filters_sync(struct perf_event *event) 3254 { 3255 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event); 3256 3257 if (!has_addr_filter(event)) 3258 return; 3259 3260 raw_spin_lock(&ifh->lock); 3261 if (event->addr_filters_gen != event->hw.addr_filters_gen) { 3262 event->pmu->addr_filters_sync(event); 3263 event->hw.addr_filters_gen = event->addr_filters_gen; 3264 } 3265 raw_spin_unlock(&ifh->lock); 3266 } 3267 EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync); 3268 3269 static int _perf_event_refresh(struct perf_event *event, int refresh) 3270 { 3271 /* 3272 * not supported on inherited events 3273 */ 3274 if (event->attr.inherit || !is_sampling_event(event)) 3275 return -EINVAL; 3276 3277 atomic_add(refresh, &event->event_limit); 3278 _perf_event_enable(event); 3279 3280 return 0; 3281 } 3282 3283 /* 3284 * See perf_event_disable() 3285 */ 3286 int perf_event_refresh(struct perf_event *event, int refresh) 3287 { 3288 struct perf_event_context *ctx; 3289 int ret; 3290 3291 ctx = perf_event_ctx_lock(event); 3292 ret = _perf_event_refresh(event, refresh); 3293 perf_event_ctx_unlock(event, ctx); 3294 3295 return ret; 3296 } 3297 EXPORT_SYMBOL_GPL(perf_event_refresh); 3298 3299 static int perf_event_modify_breakpoint(struct perf_event *bp, 3300 struct perf_event_attr *attr) 3301 { 3302 int err; 3303 3304 _perf_event_disable(bp); 3305 3306 err = modify_user_hw_breakpoint_check(bp, attr, true); 3307 3308 if (!bp->attr.disabled) 3309 _perf_event_enable(bp); 3310 3311 return err; 3312 } 3313 3314 /* 3315 * Copy event-type-independent attributes that may be modified. 3316 */ 3317 static void perf_event_modify_copy_attr(struct perf_event_attr *to, 3318 const struct perf_event_attr *from) 3319 { 3320 to->sig_data = from->sig_data; 3321 } 3322 3323 static int perf_event_modify_attr(struct perf_event *event, 3324 struct perf_event_attr *attr) 3325 { 3326 int (*func)(struct perf_event *, struct perf_event_attr *); 3327 struct perf_event *child; 3328 int err; 3329 3330 if (event->attr.type != attr->type) 3331 return -EINVAL; 3332 3333 switch (event->attr.type) { 3334 case PERF_TYPE_BREAKPOINT: 3335 func = perf_event_modify_breakpoint; 3336 break; 3337 default: 3338 /* Place holder for future additions. */ 3339 return -EOPNOTSUPP; 3340 } 3341 3342 WARN_ON_ONCE(event->ctx->parent_ctx); 3343 3344 mutex_lock(&event->child_mutex); 3345 /* 3346 * Event-type-independent attributes must be copied before event-type 3347 * modification, which will validate that final attributes match the 3348 * source attributes after all relevant attributes have been copied. 3349 */ 3350 perf_event_modify_copy_attr(&event->attr, attr); 3351 err = func(event, attr); 3352 if (err) 3353 goto out; 3354 list_for_each_entry(child, &event->child_list, child_list) { 3355 perf_event_modify_copy_attr(&child->attr, attr); 3356 err = func(child, attr); 3357 if (err) 3358 goto out; 3359 } 3360 out: 3361 mutex_unlock(&event->child_mutex); 3362 return err; 3363 } 3364 3365 static void __pmu_ctx_sched_out(struct perf_event_pmu_context *pmu_ctx, 3366 enum event_type_t event_type) 3367 { 3368 struct perf_event_context *ctx = pmu_ctx->ctx; 3369 struct perf_event *event, *tmp; 3370 struct pmu *pmu = pmu_ctx->pmu; 3371 3372 if (ctx->task && !(ctx->is_active & EVENT_ALL)) { 3373 struct perf_cpu_pmu_context *cpc = this_cpc(pmu); 3374 3375 WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx); 3376 cpc->task_epc = NULL; 3377 } 3378 3379 if (!(event_type & EVENT_ALL)) 3380 return; 3381 3382 perf_pmu_disable(pmu); 3383 if (event_type & EVENT_PINNED) { 3384 list_for_each_entry_safe(event, tmp, 3385 &pmu_ctx->pinned_active, 3386 active_list) 3387 group_sched_out(event, ctx); 3388 } 3389 3390 if (event_type & EVENT_FLEXIBLE) { 3391 list_for_each_entry_safe(event, tmp, 3392 &pmu_ctx->flexible_active, 3393 active_list) 3394 group_sched_out(event, ctx); 3395 /* 3396 * Since we cleared EVENT_FLEXIBLE, also clear 3397 * rotate_necessary, is will be reset by 3398 * ctx_flexible_sched_in() when needed. 3399 */ 3400 pmu_ctx->rotate_necessary = 0; 3401 } 3402 perf_pmu_enable(pmu); 3403 } 3404 3405 /* 3406 * Be very careful with the @pmu argument since this will change ctx state. 3407 * The @pmu argument works for ctx_resched(), because that is symmetric in 3408 * ctx_sched_out() / ctx_sched_in() usage and the ctx state ends up invariant. 3409 * 3410 * However, if you were to be asymmetrical, you could end up with messed up 3411 * state, eg. ctx->is_active cleared even though most EPCs would still actually 3412 * be active. 3413 */ 3414 static void 3415 ctx_sched_out(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type) 3416 { 3417 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 3418 struct perf_event_pmu_context *pmu_ctx; 3419 int is_active = ctx->is_active; 3420 bool cgroup = event_type & EVENT_CGROUP; 3421 3422 event_type &= ~EVENT_CGROUP; 3423 3424 lockdep_assert_held(&ctx->lock); 3425 3426 if (likely(!ctx->nr_events)) { 3427 /* 3428 * See __perf_remove_from_context(). 3429 */ 3430 WARN_ON_ONCE(ctx->is_active); 3431 if (ctx->task) 3432 WARN_ON_ONCE(cpuctx->task_ctx); 3433 return; 3434 } 3435 3436 /* 3437 * Always update time if it was set; not only when it changes. 3438 * Otherwise we can 'forget' to update time for any but the last 3439 * context we sched out. For example: 3440 * 3441 * ctx_sched_out(.event_type = EVENT_FLEXIBLE) 3442 * ctx_sched_out(.event_type = EVENT_PINNED) 3443 * 3444 * would only update time for the pinned events. 3445 */ 3446 __ctx_time_update(cpuctx, ctx, ctx == &cpuctx->ctx); 3447 3448 /* 3449 * CPU-release for the below ->is_active store, 3450 * see __load_acquire() in perf_event_time_now() 3451 */ 3452 barrier(); 3453 ctx->is_active &= ~event_type; 3454 3455 if (!(ctx->is_active & EVENT_ALL)) { 3456 /* 3457 * For FROZEN, preserve TIME|FROZEN such that perf_event_time_now() 3458 * does not observe a hole. perf_ctx_unlock() will clean up. 3459 */ 3460 if (ctx->is_active & EVENT_FROZEN) 3461 ctx->is_active &= EVENT_TIME_FROZEN; 3462 else 3463 ctx->is_active = 0; 3464 } 3465 3466 if (ctx->task) { 3467 WARN_ON_ONCE(cpuctx->task_ctx != ctx); 3468 if (!(ctx->is_active & EVENT_ALL)) 3469 cpuctx->task_ctx = NULL; 3470 } 3471 3472 is_active ^= ctx->is_active; /* changed bits */ 3473 3474 for_each_epc(pmu_ctx, ctx, pmu, cgroup) 3475 __pmu_ctx_sched_out(pmu_ctx, is_active); 3476 } 3477 3478 /* 3479 * Test whether two contexts are equivalent, i.e. whether they have both been 3480 * cloned from the same version of the same context. 3481 * 3482 * Equivalence is measured using a generation number in the context that is 3483 * incremented on each modification to it; see unclone_ctx(), list_add_event() 3484 * and list_del_event(). 3485 */ 3486 static int context_equiv(struct perf_event_context *ctx1, 3487 struct perf_event_context *ctx2) 3488 { 3489 lockdep_assert_held(&ctx1->lock); 3490 lockdep_assert_held(&ctx2->lock); 3491 3492 /* Pinning disables the swap optimization */ 3493 if (ctx1->pin_count || ctx2->pin_count) 3494 return 0; 3495 3496 /* If ctx1 is the parent of ctx2 */ 3497 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen) 3498 return 1; 3499 3500 /* If ctx2 is the parent of ctx1 */ 3501 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation) 3502 return 1; 3503 3504 /* 3505 * If ctx1 and ctx2 have the same parent; we flatten the parent 3506 * hierarchy, see perf_event_init_context(). 3507 */ 3508 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx && 3509 ctx1->parent_gen == ctx2->parent_gen) 3510 return 1; 3511 3512 /* Unmatched */ 3513 return 0; 3514 } 3515 3516 static void __perf_event_sync_stat(struct perf_event *event, 3517 struct perf_event *next_event) 3518 { 3519 u64 value; 3520 3521 if (!event->attr.inherit_stat) 3522 return; 3523 3524 /* 3525 * Update the event value, we cannot use perf_event_read() 3526 * because we're in the middle of a context switch and have IRQs 3527 * disabled, which upsets smp_call_function_single(), however 3528 * we know the event must be on the current CPU, therefore we 3529 * don't need to use it. 3530 */ 3531 perf_pmu_read(event); 3532 3533 perf_event_update_time(event); 3534 3535 /* 3536 * In order to keep per-task stats reliable we need to flip the event 3537 * values when we flip the contexts. 3538 */ 3539 value = local64_read(&next_event->count); 3540 value = local64_xchg(&event->count, value); 3541 local64_set(&next_event->count, value); 3542 3543 swap(event->total_time_enabled, next_event->total_time_enabled); 3544 swap(event->total_time_running, next_event->total_time_running); 3545 3546 /* 3547 * Since we swizzled the values, update the user visible data too. 3548 */ 3549 perf_event_update_userpage(event); 3550 perf_event_update_userpage(next_event); 3551 } 3552 3553 static void perf_event_sync_stat(struct perf_event_context *ctx, 3554 struct perf_event_context *next_ctx) 3555 { 3556 struct perf_event *event, *next_event; 3557 3558 if (!ctx->nr_stat) 3559 return; 3560 3561 update_context_time(ctx); 3562 3563 event = list_first_entry(&ctx->event_list, 3564 struct perf_event, event_entry); 3565 3566 next_event = list_first_entry(&next_ctx->event_list, 3567 struct perf_event, event_entry); 3568 3569 while (&event->event_entry != &ctx->event_list && 3570 &next_event->event_entry != &next_ctx->event_list) { 3571 3572 __perf_event_sync_stat(event, next_event); 3573 3574 event = list_next_entry(event, event_entry); 3575 next_event = list_next_entry(next_event, event_entry); 3576 } 3577 } 3578 3579 #define double_list_for_each_entry(pos1, pos2, head1, head2, member) \ 3580 for (pos1 = list_first_entry(head1, typeof(*pos1), member), \ 3581 pos2 = list_first_entry(head2, typeof(*pos2), member); \ 3582 !list_entry_is_head(pos1, head1, member) && \ 3583 !list_entry_is_head(pos2, head2, member); \ 3584 pos1 = list_next_entry(pos1, member), \ 3585 pos2 = list_next_entry(pos2, member)) 3586 3587 static void perf_event_swap_task_ctx_data(struct perf_event_context *prev_ctx, 3588 struct perf_event_context *next_ctx) 3589 { 3590 struct perf_event_pmu_context *prev_epc, *next_epc; 3591 3592 if (!prev_ctx->nr_task_data) 3593 return; 3594 3595 double_list_for_each_entry(prev_epc, next_epc, 3596 &prev_ctx->pmu_ctx_list, &next_ctx->pmu_ctx_list, 3597 pmu_ctx_entry) { 3598 3599 if (WARN_ON_ONCE(prev_epc->pmu != next_epc->pmu)) 3600 continue; 3601 3602 /* 3603 * PMU specific parts of task perf context can require 3604 * additional synchronization. As an example of such 3605 * synchronization see implementation details of Intel 3606 * LBR call stack data profiling; 3607 */ 3608 if (prev_epc->pmu->swap_task_ctx) 3609 prev_epc->pmu->swap_task_ctx(prev_epc, next_epc); 3610 else 3611 swap(prev_epc->task_ctx_data, next_epc->task_ctx_data); 3612 } 3613 } 3614 3615 static void perf_ctx_sched_task_cb(struct perf_event_context *ctx, bool sched_in) 3616 { 3617 struct perf_event_pmu_context *pmu_ctx; 3618 struct perf_cpu_pmu_context *cpc; 3619 3620 list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry) { 3621 cpc = this_cpc(pmu_ctx->pmu); 3622 3623 if (cpc->sched_cb_usage && pmu_ctx->pmu->sched_task) 3624 pmu_ctx->pmu->sched_task(pmu_ctx, sched_in); 3625 } 3626 } 3627 3628 static void 3629 perf_event_context_sched_out(struct task_struct *task, struct task_struct *next) 3630 { 3631 struct perf_event_context *ctx = task->perf_event_ctxp; 3632 struct perf_event_context *next_ctx; 3633 struct perf_event_context *parent, *next_parent; 3634 int do_switch = 1; 3635 3636 if (likely(!ctx)) 3637 return; 3638 3639 rcu_read_lock(); 3640 next_ctx = rcu_dereference(next->perf_event_ctxp); 3641 if (!next_ctx) 3642 goto unlock; 3643 3644 parent = rcu_dereference(ctx->parent_ctx); 3645 next_parent = rcu_dereference(next_ctx->parent_ctx); 3646 3647 /* If neither context have a parent context; they cannot be clones. */ 3648 if (!parent && !next_parent) 3649 goto unlock; 3650 3651 if (next_parent == ctx || next_ctx == parent || next_parent == parent) { 3652 /* 3653 * Looks like the two contexts are clones, so we might be 3654 * able to optimize the context switch. We lock both 3655 * contexts and check that they are clones under the 3656 * lock (including re-checking that neither has been 3657 * uncloned in the meantime). It doesn't matter which 3658 * order we take the locks because no other cpu could 3659 * be trying to lock both of these tasks. 3660 */ 3661 raw_spin_lock(&ctx->lock); 3662 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING); 3663 if (context_equiv(ctx, next_ctx)) { 3664 3665 perf_ctx_disable(ctx, false); 3666 3667 /* PMIs are disabled; ctx->nr_no_switch_fast is stable. */ 3668 if (local_read(&ctx->nr_no_switch_fast) || 3669 local_read(&next_ctx->nr_no_switch_fast)) { 3670 /* 3671 * Must not swap out ctx when there's pending 3672 * events that rely on the ctx->task relation. 3673 * 3674 * Likewise, when a context contains inherit + 3675 * SAMPLE_READ events they should be switched 3676 * out using the slow path so that they are 3677 * treated as if they were distinct contexts. 3678 */ 3679 raw_spin_unlock(&next_ctx->lock); 3680 rcu_read_unlock(); 3681 goto inside_switch; 3682 } 3683 3684 WRITE_ONCE(ctx->task, next); 3685 WRITE_ONCE(next_ctx->task, task); 3686 3687 perf_ctx_sched_task_cb(ctx, false); 3688 perf_event_swap_task_ctx_data(ctx, next_ctx); 3689 3690 perf_ctx_enable(ctx, false); 3691 3692 /* 3693 * RCU_INIT_POINTER here is safe because we've not 3694 * modified the ctx and the above modification of 3695 * ctx->task and ctx->task_ctx_data are immaterial 3696 * since those values are always verified under 3697 * ctx->lock which we're now holding. 3698 */ 3699 RCU_INIT_POINTER(task->perf_event_ctxp, next_ctx); 3700 RCU_INIT_POINTER(next->perf_event_ctxp, ctx); 3701 3702 do_switch = 0; 3703 3704 perf_event_sync_stat(ctx, next_ctx); 3705 } 3706 raw_spin_unlock(&next_ctx->lock); 3707 raw_spin_unlock(&ctx->lock); 3708 } 3709 unlock: 3710 rcu_read_unlock(); 3711 3712 if (do_switch) { 3713 raw_spin_lock(&ctx->lock); 3714 perf_ctx_disable(ctx, false); 3715 3716 inside_switch: 3717 perf_ctx_sched_task_cb(ctx, false); 3718 task_ctx_sched_out(ctx, NULL, EVENT_ALL); 3719 3720 perf_ctx_enable(ctx, false); 3721 raw_spin_unlock(&ctx->lock); 3722 } 3723 } 3724 3725 static DEFINE_PER_CPU(struct list_head, sched_cb_list); 3726 static DEFINE_PER_CPU(int, perf_sched_cb_usages); 3727 3728 void perf_sched_cb_dec(struct pmu *pmu) 3729 { 3730 struct perf_cpu_pmu_context *cpc = this_cpc(pmu); 3731 3732 this_cpu_dec(perf_sched_cb_usages); 3733 barrier(); 3734 3735 if (!--cpc->sched_cb_usage) 3736 list_del(&cpc->sched_cb_entry); 3737 } 3738 3739 3740 void perf_sched_cb_inc(struct pmu *pmu) 3741 { 3742 struct perf_cpu_pmu_context *cpc = this_cpc(pmu); 3743 3744 if (!cpc->sched_cb_usage++) 3745 list_add(&cpc->sched_cb_entry, this_cpu_ptr(&sched_cb_list)); 3746 3747 barrier(); 3748 this_cpu_inc(perf_sched_cb_usages); 3749 } 3750 3751 /* 3752 * This function provides the context switch callback to the lower code 3753 * layer. It is invoked ONLY when the context switch callback is enabled. 3754 * 3755 * This callback is relevant even to per-cpu events; for example multi event 3756 * PEBS requires this to provide PID/TID information. This requires we flush 3757 * all queued PEBS records before we context switch to a new task. 3758 */ 3759 static void __perf_pmu_sched_task(struct perf_cpu_pmu_context *cpc, bool sched_in) 3760 { 3761 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 3762 struct pmu *pmu; 3763 3764 pmu = cpc->epc.pmu; 3765 3766 /* software PMUs will not have sched_task */ 3767 if (WARN_ON_ONCE(!pmu->sched_task)) 3768 return; 3769 3770 perf_ctx_lock(cpuctx, cpuctx->task_ctx); 3771 perf_pmu_disable(pmu); 3772 3773 pmu->sched_task(cpc->task_epc, sched_in); 3774 3775 perf_pmu_enable(pmu); 3776 perf_ctx_unlock(cpuctx, cpuctx->task_ctx); 3777 } 3778 3779 static void perf_pmu_sched_task(struct task_struct *prev, 3780 struct task_struct *next, 3781 bool sched_in) 3782 { 3783 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 3784 struct perf_cpu_pmu_context *cpc; 3785 3786 /* cpuctx->task_ctx will be handled in perf_event_context_sched_in/out */ 3787 if (prev == next || cpuctx->task_ctx) 3788 return; 3789 3790 list_for_each_entry(cpc, this_cpu_ptr(&sched_cb_list), sched_cb_entry) 3791 __perf_pmu_sched_task(cpc, sched_in); 3792 } 3793 3794 static void perf_event_switch(struct task_struct *task, 3795 struct task_struct *next_prev, bool sched_in); 3796 3797 /* 3798 * Called from scheduler to remove the events of the current task, 3799 * with interrupts disabled. 3800 * 3801 * We stop each event and update the event value in event->count. 3802 * 3803 * This does not protect us against NMI, but disable() 3804 * sets the disabled bit in the control field of event _before_ 3805 * accessing the event control register. If a NMI hits, then it will 3806 * not restart the event. 3807 */ 3808 void __perf_event_task_sched_out(struct task_struct *task, 3809 struct task_struct *next) 3810 { 3811 if (__this_cpu_read(perf_sched_cb_usages)) 3812 perf_pmu_sched_task(task, next, false); 3813 3814 if (atomic_read(&nr_switch_events)) 3815 perf_event_switch(task, next, false); 3816 3817 perf_event_context_sched_out(task, next); 3818 3819 /* 3820 * if cgroup events exist on this CPU, then we need 3821 * to check if we have to switch out PMU state. 3822 * cgroup event are system-wide mode only 3823 */ 3824 perf_cgroup_switch(next); 3825 } 3826 3827 static bool perf_less_group_idx(const void *l, const void *r, void __always_unused *args) 3828 { 3829 const struct perf_event *le = *(const struct perf_event **)l; 3830 const struct perf_event *re = *(const struct perf_event **)r; 3831 3832 return le->group_index < re->group_index; 3833 } 3834 3835 DEFINE_MIN_HEAP(struct perf_event *, perf_event_min_heap); 3836 3837 static const struct min_heap_callbacks perf_min_heap = { 3838 .less = perf_less_group_idx, 3839 .swp = NULL, 3840 }; 3841 3842 static void __heap_add(struct perf_event_min_heap *heap, struct perf_event *event) 3843 { 3844 struct perf_event **itrs = heap->data; 3845 3846 if (event) { 3847 itrs[heap->nr] = event; 3848 heap->nr++; 3849 } 3850 } 3851 3852 static void __link_epc(struct perf_event_pmu_context *pmu_ctx) 3853 { 3854 struct perf_cpu_pmu_context *cpc; 3855 3856 if (!pmu_ctx->ctx->task) 3857 return; 3858 3859 cpc = this_cpc(pmu_ctx->pmu); 3860 WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx); 3861 cpc->task_epc = pmu_ctx; 3862 } 3863 3864 static noinline int visit_groups_merge(struct perf_event_context *ctx, 3865 struct perf_event_groups *groups, int cpu, 3866 struct pmu *pmu, 3867 int (*func)(struct perf_event *, void *), 3868 void *data) 3869 { 3870 #ifdef CONFIG_CGROUP_PERF 3871 struct cgroup_subsys_state *css = NULL; 3872 #endif 3873 struct perf_cpu_context *cpuctx = NULL; 3874 /* Space for per CPU and/or any CPU event iterators. */ 3875 struct perf_event *itrs[2]; 3876 struct perf_event_min_heap event_heap; 3877 struct perf_event **evt; 3878 int ret; 3879 3880 if (pmu->filter && pmu->filter(pmu, cpu)) 3881 return 0; 3882 3883 if (!ctx->task) { 3884 cpuctx = this_cpu_ptr(&perf_cpu_context); 3885 event_heap = (struct perf_event_min_heap){ 3886 .data = cpuctx->heap, 3887 .nr = 0, 3888 .size = cpuctx->heap_size, 3889 }; 3890 3891 lockdep_assert_held(&cpuctx->ctx.lock); 3892 3893 #ifdef CONFIG_CGROUP_PERF 3894 if (cpuctx->cgrp) 3895 css = &cpuctx->cgrp->css; 3896 #endif 3897 } else { 3898 event_heap = (struct perf_event_min_heap){ 3899 .data = itrs, 3900 .nr = 0, 3901 .size = ARRAY_SIZE(itrs), 3902 }; 3903 /* Events not within a CPU context may be on any CPU. */ 3904 __heap_add(&event_heap, perf_event_groups_first(groups, -1, pmu, NULL)); 3905 } 3906 evt = event_heap.data; 3907 3908 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, pmu, NULL)); 3909 3910 #ifdef CONFIG_CGROUP_PERF 3911 for (; css; css = css->parent) 3912 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, pmu, css->cgroup)); 3913 #endif 3914 3915 if (event_heap.nr) { 3916 __link_epc((*evt)->pmu_ctx); 3917 perf_assert_pmu_disabled((*evt)->pmu_ctx->pmu); 3918 } 3919 3920 min_heapify_all_inline(&event_heap, &perf_min_heap, NULL); 3921 3922 while (event_heap.nr) { 3923 ret = func(*evt, data); 3924 if (ret) 3925 return ret; 3926 3927 *evt = perf_event_groups_next(*evt, pmu); 3928 if (*evt) 3929 min_heap_sift_down_inline(&event_heap, 0, &perf_min_heap, NULL); 3930 else 3931 min_heap_pop_inline(&event_heap, &perf_min_heap, NULL); 3932 } 3933 3934 return 0; 3935 } 3936 3937 /* 3938 * Because the userpage is strictly per-event (there is no concept of context, 3939 * so there cannot be a context indirection), every userpage must be updated 3940 * when context time starts :-( 3941 * 3942 * IOW, we must not miss EVENT_TIME edges. 3943 */ 3944 static inline bool event_update_userpage(struct perf_event *event) 3945 { 3946 if (likely(!atomic_read(&event->mmap_count))) 3947 return false; 3948 3949 perf_event_update_time(event); 3950 perf_event_update_userpage(event); 3951 3952 return true; 3953 } 3954 3955 static inline void group_update_userpage(struct perf_event *group_event) 3956 { 3957 struct perf_event *event; 3958 3959 if (!event_update_userpage(group_event)) 3960 return; 3961 3962 for_each_sibling_event(event, group_event) 3963 event_update_userpage(event); 3964 } 3965 3966 static int merge_sched_in(struct perf_event *event, void *data) 3967 { 3968 struct perf_event_context *ctx = event->ctx; 3969 int *can_add_hw = data; 3970 3971 if (event->state <= PERF_EVENT_STATE_OFF) 3972 return 0; 3973 3974 if (!event_filter_match(event)) 3975 return 0; 3976 3977 if (group_can_go_on(event, *can_add_hw)) { 3978 if (!group_sched_in(event, ctx)) 3979 list_add_tail(&event->active_list, get_event_list(event)); 3980 } 3981 3982 if (event->state == PERF_EVENT_STATE_INACTIVE) { 3983 *can_add_hw = 0; 3984 if (event->attr.pinned) { 3985 perf_cgroup_event_disable(event, ctx); 3986 perf_event_set_state(event, PERF_EVENT_STATE_ERROR); 3987 } else { 3988 struct perf_cpu_pmu_context *cpc = this_cpc(event->pmu_ctx->pmu); 3989 3990 event->pmu_ctx->rotate_necessary = 1; 3991 perf_mux_hrtimer_restart(cpc); 3992 group_update_userpage(event); 3993 } 3994 } 3995 3996 return 0; 3997 } 3998 3999 static void pmu_groups_sched_in(struct perf_event_context *ctx, 4000 struct perf_event_groups *groups, 4001 struct pmu *pmu) 4002 { 4003 int can_add_hw = 1; 4004 visit_groups_merge(ctx, groups, smp_processor_id(), pmu, 4005 merge_sched_in, &can_add_hw); 4006 } 4007 4008 static void __pmu_ctx_sched_in(struct perf_event_pmu_context *pmu_ctx, 4009 enum event_type_t event_type) 4010 { 4011 struct perf_event_context *ctx = pmu_ctx->ctx; 4012 4013 if (event_type & EVENT_PINNED) 4014 pmu_groups_sched_in(ctx, &ctx->pinned_groups, pmu_ctx->pmu); 4015 if (event_type & EVENT_FLEXIBLE) 4016 pmu_groups_sched_in(ctx, &ctx->flexible_groups, pmu_ctx->pmu); 4017 } 4018 4019 static void 4020 ctx_sched_in(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type) 4021 { 4022 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 4023 struct perf_event_pmu_context *pmu_ctx; 4024 int is_active = ctx->is_active; 4025 bool cgroup = event_type & EVENT_CGROUP; 4026 4027 event_type &= ~EVENT_CGROUP; 4028 4029 lockdep_assert_held(&ctx->lock); 4030 4031 if (likely(!ctx->nr_events)) 4032 return; 4033 4034 if (!(is_active & EVENT_TIME)) { 4035 /* start ctx time */ 4036 __update_context_time(ctx, false); 4037 perf_cgroup_set_timestamp(cpuctx); 4038 /* 4039 * CPU-release for the below ->is_active store, 4040 * see __load_acquire() in perf_event_time_now() 4041 */ 4042 barrier(); 4043 } 4044 4045 ctx->is_active |= (event_type | EVENT_TIME); 4046 if (ctx->task) { 4047 if (!(is_active & EVENT_ALL)) 4048 cpuctx->task_ctx = ctx; 4049 else 4050 WARN_ON_ONCE(cpuctx->task_ctx != ctx); 4051 } 4052 4053 is_active ^= ctx->is_active; /* changed bits */ 4054 4055 /* 4056 * First go through the list and put on any pinned groups 4057 * in order to give them the best chance of going on. 4058 */ 4059 if (is_active & EVENT_PINNED) { 4060 for_each_epc(pmu_ctx, ctx, pmu, cgroup) 4061 __pmu_ctx_sched_in(pmu_ctx, EVENT_PINNED); 4062 } 4063 4064 /* Then walk through the lower prio flexible groups */ 4065 if (is_active & EVENT_FLEXIBLE) { 4066 for_each_epc(pmu_ctx, ctx, pmu, cgroup) 4067 __pmu_ctx_sched_in(pmu_ctx, EVENT_FLEXIBLE); 4068 } 4069 } 4070 4071 static void perf_event_context_sched_in(struct task_struct *task) 4072 { 4073 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 4074 struct perf_event_context *ctx; 4075 4076 rcu_read_lock(); 4077 ctx = rcu_dereference(task->perf_event_ctxp); 4078 if (!ctx) 4079 goto rcu_unlock; 4080 4081 if (cpuctx->task_ctx == ctx) { 4082 perf_ctx_lock(cpuctx, ctx); 4083 perf_ctx_disable(ctx, false); 4084 4085 perf_ctx_sched_task_cb(ctx, true); 4086 4087 perf_ctx_enable(ctx, false); 4088 perf_ctx_unlock(cpuctx, ctx); 4089 goto rcu_unlock; 4090 } 4091 4092 perf_ctx_lock(cpuctx, ctx); 4093 /* 4094 * We must check ctx->nr_events while holding ctx->lock, such 4095 * that we serialize against perf_install_in_context(). 4096 */ 4097 if (!ctx->nr_events) 4098 goto unlock; 4099 4100 perf_ctx_disable(ctx, false); 4101 /* 4102 * We want to keep the following priority order: 4103 * cpu pinned (that don't need to move), task pinned, 4104 * cpu flexible, task flexible. 4105 * 4106 * However, if task's ctx is not carrying any pinned 4107 * events, no need to flip the cpuctx's events around. 4108 */ 4109 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree)) { 4110 perf_ctx_disable(&cpuctx->ctx, false); 4111 ctx_sched_out(&cpuctx->ctx, NULL, EVENT_FLEXIBLE); 4112 } 4113 4114 perf_event_sched_in(cpuctx, ctx, NULL); 4115 4116 perf_ctx_sched_task_cb(cpuctx->task_ctx, true); 4117 4118 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree)) 4119 perf_ctx_enable(&cpuctx->ctx, false); 4120 4121 perf_ctx_enable(ctx, false); 4122 4123 unlock: 4124 perf_ctx_unlock(cpuctx, ctx); 4125 rcu_unlock: 4126 rcu_read_unlock(); 4127 } 4128 4129 /* 4130 * Called from scheduler to add the events of the current task 4131 * with interrupts disabled. 4132 * 4133 * We restore the event value and then enable it. 4134 * 4135 * This does not protect us against NMI, but enable() 4136 * sets the enabled bit in the control field of event _before_ 4137 * accessing the event control register. If a NMI hits, then it will 4138 * keep the event running. 4139 */ 4140 void __perf_event_task_sched_in(struct task_struct *prev, 4141 struct task_struct *task) 4142 { 4143 perf_event_context_sched_in(task); 4144 4145 if (atomic_read(&nr_switch_events)) 4146 perf_event_switch(task, prev, true); 4147 4148 if (__this_cpu_read(perf_sched_cb_usages)) 4149 perf_pmu_sched_task(prev, task, true); 4150 } 4151 4152 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count) 4153 { 4154 u64 frequency = event->attr.sample_freq; 4155 u64 sec = NSEC_PER_SEC; 4156 u64 divisor, dividend; 4157 4158 int count_fls, nsec_fls, frequency_fls, sec_fls; 4159 4160 count_fls = fls64(count); 4161 nsec_fls = fls64(nsec); 4162 frequency_fls = fls64(frequency); 4163 sec_fls = 30; 4164 4165 /* 4166 * We got @count in @nsec, with a target of sample_freq HZ 4167 * the target period becomes: 4168 * 4169 * @count * 10^9 4170 * period = ------------------- 4171 * @nsec * sample_freq 4172 * 4173 */ 4174 4175 /* 4176 * Reduce accuracy by one bit such that @a and @b converge 4177 * to a similar magnitude. 4178 */ 4179 #define REDUCE_FLS(a, b) \ 4180 do { \ 4181 if (a##_fls > b##_fls) { \ 4182 a >>= 1; \ 4183 a##_fls--; \ 4184 } else { \ 4185 b >>= 1; \ 4186 b##_fls--; \ 4187 } \ 4188 } while (0) 4189 4190 /* 4191 * Reduce accuracy until either term fits in a u64, then proceed with 4192 * the other, so that finally we can do a u64/u64 division. 4193 */ 4194 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) { 4195 REDUCE_FLS(nsec, frequency); 4196 REDUCE_FLS(sec, count); 4197 } 4198 4199 if (count_fls + sec_fls > 64) { 4200 divisor = nsec * frequency; 4201 4202 while (count_fls + sec_fls > 64) { 4203 REDUCE_FLS(count, sec); 4204 divisor >>= 1; 4205 } 4206 4207 dividend = count * sec; 4208 } else { 4209 dividend = count * sec; 4210 4211 while (nsec_fls + frequency_fls > 64) { 4212 REDUCE_FLS(nsec, frequency); 4213 dividend >>= 1; 4214 } 4215 4216 divisor = nsec * frequency; 4217 } 4218 4219 if (!divisor) 4220 return dividend; 4221 4222 return div64_u64(dividend, divisor); 4223 } 4224 4225 static DEFINE_PER_CPU(int, perf_throttled_count); 4226 static DEFINE_PER_CPU(u64, perf_throttled_seq); 4227 4228 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable) 4229 { 4230 struct hw_perf_event *hwc = &event->hw; 4231 s64 period, sample_period; 4232 s64 delta; 4233 4234 period = perf_calculate_period(event, nsec, count); 4235 4236 delta = (s64)(period - hwc->sample_period); 4237 if (delta >= 0) 4238 delta += 7; 4239 else 4240 delta -= 7; 4241 delta /= 8; /* low pass filter */ 4242 4243 sample_period = hwc->sample_period + delta; 4244 4245 if (!sample_period) 4246 sample_period = 1; 4247 4248 hwc->sample_period = sample_period; 4249 4250 if (local64_read(&hwc->period_left) > 8*sample_period) { 4251 if (disable) 4252 event->pmu->stop(event, PERF_EF_UPDATE); 4253 4254 local64_set(&hwc->period_left, 0); 4255 4256 if (disable) 4257 event->pmu->start(event, PERF_EF_RELOAD); 4258 } 4259 } 4260 4261 static void perf_adjust_freq_unthr_events(struct list_head *event_list) 4262 { 4263 struct perf_event *event; 4264 struct hw_perf_event *hwc; 4265 u64 now, period = TICK_NSEC; 4266 s64 delta; 4267 4268 list_for_each_entry(event, event_list, active_list) { 4269 if (event->state != PERF_EVENT_STATE_ACTIVE) 4270 continue; 4271 4272 // XXX use visit thingy to avoid the -1,cpu match 4273 if (!event_filter_match(event)) 4274 continue; 4275 4276 hwc = &event->hw; 4277 4278 if (hwc->interrupts == MAX_INTERRUPTS) { 4279 hwc->interrupts = 0; 4280 perf_log_throttle(event, 1); 4281 if (!event->attr.freq || !event->attr.sample_freq) 4282 event->pmu->start(event, 0); 4283 } 4284 4285 if (!event->attr.freq || !event->attr.sample_freq) 4286 continue; 4287 4288 /* 4289 * stop the event and update event->count 4290 */ 4291 event->pmu->stop(event, PERF_EF_UPDATE); 4292 4293 now = local64_read(&event->count); 4294 delta = now - hwc->freq_count_stamp; 4295 hwc->freq_count_stamp = now; 4296 4297 /* 4298 * restart the event 4299 * reload only if value has changed 4300 * we have stopped the event so tell that 4301 * to perf_adjust_period() to avoid stopping it 4302 * twice. 4303 */ 4304 if (delta > 0) 4305 perf_adjust_period(event, period, delta, false); 4306 4307 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0); 4308 } 4309 } 4310 4311 /* 4312 * combine freq adjustment with unthrottling to avoid two passes over the 4313 * events. At the same time, make sure, having freq events does not change 4314 * the rate of unthrottling as that would introduce bias. 4315 */ 4316 static void 4317 perf_adjust_freq_unthr_context(struct perf_event_context *ctx, bool unthrottle) 4318 { 4319 struct perf_event_pmu_context *pmu_ctx; 4320 4321 /* 4322 * only need to iterate over all events iff: 4323 * - context have events in frequency mode (needs freq adjust) 4324 * - there are events to unthrottle on this cpu 4325 */ 4326 if (!(ctx->nr_freq || unthrottle)) 4327 return; 4328 4329 raw_spin_lock(&ctx->lock); 4330 4331 list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry) { 4332 if (!(pmu_ctx->nr_freq || unthrottle)) 4333 continue; 4334 if (!perf_pmu_ctx_is_active(pmu_ctx)) 4335 continue; 4336 if (pmu_ctx->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) 4337 continue; 4338 4339 perf_pmu_disable(pmu_ctx->pmu); 4340 perf_adjust_freq_unthr_events(&pmu_ctx->pinned_active); 4341 perf_adjust_freq_unthr_events(&pmu_ctx->flexible_active); 4342 perf_pmu_enable(pmu_ctx->pmu); 4343 } 4344 4345 raw_spin_unlock(&ctx->lock); 4346 } 4347 4348 /* 4349 * Move @event to the tail of the @ctx's elegible events. 4350 */ 4351 static void rotate_ctx(struct perf_event_context *ctx, struct perf_event *event) 4352 { 4353 /* 4354 * Rotate the first entry last of non-pinned groups. Rotation might be 4355 * disabled by the inheritance code. 4356 */ 4357 if (ctx->rotate_disable) 4358 return; 4359 4360 perf_event_groups_delete(&ctx->flexible_groups, event); 4361 perf_event_groups_insert(&ctx->flexible_groups, event); 4362 } 4363 4364 /* pick an event from the flexible_groups to rotate */ 4365 static inline struct perf_event * 4366 ctx_event_to_rotate(struct perf_event_pmu_context *pmu_ctx) 4367 { 4368 struct perf_event *event; 4369 struct rb_node *node; 4370 struct rb_root *tree; 4371 struct __group_key key = { 4372 .pmu = pmu_ctx->pmu, 4373 }; 4374 4375 /* pick the first active flexible event */ 4376 event = list_first_entry_or_null(&pmu_ctx->flexible_active, 4377 struct perf_event, active_list); 4378 if (event) 4379 goto out; 4380 4381 /* if no active flexible event, pick the first event */ 4382 tree = &pmu_ctx->ctx->flexible_groups.tree; 4383 4384 if (!pmu_ctx->ctx->task) { 4385 key.cpu = smp_processor_id(); 4386 4387 node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup); 4388 if (node) 4389 event = __node_2_pe(node); 4390 goto out; 4391 } 4392 4393 key.cpu = -1; 4394 node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup); 4395 if (node) { 4396 event = __node_2_pe(node); 4397 goto out; 4398 } 4399 4400 key.cpu = smp_processor_id(); 4401 node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup); 4402 if (node) 4403 event = __node_2_pe(node); 4404 4405 out: 4406 /* 4407 * Unconditionally clear rotate_necessary; if ctx_flexible_sched_in() 4408 * finds there are unschedulable events, it will set it again. 4409 */ 4410 pmu_ctx->rotate_necessary = 0; 4411 4412 return event; 4413 } 4414 4415 static bool perf_rotate_context(struct perf_cpu_pmu_context *cpc) 4416 { 4417 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 4418 struct perf_event_pmu_context *cpu_epc, *task_epc = NULL; 4419 struct perf_event *cpu_event = NULL, *task_event = NULL; 4420 int cpu_rotate, task_rotate; 4421 struct pmu *pmu; 4422 4423 /* 4424 * Since we run this from IRQ context, nobody can install new 4425 * events, thus the event count values are stable. 4426 */ 4427 4428 cpu_epc = &cpc->epc; 4429 pmu = cpu_epc->pmu; 4430 task_epc = cpc->task_epc; 4431 4432 cpu_rotate = cpu_epc->rotate_necessary; 4433 task_rotate = task_epc ? task_epc->rotate_necessary : 0; 4434 4435 if (!(cpu_rotate || task_rotate)) 4436 return false; 4437 4438 perf_ctx_lock(cpuctx, cpuctx->task_ctx); 4439 perf_pmu_disable(pmu); 4440 4441 if (task_rotate) 4442 task_event = ctx_event_to_rotate(task_epc); 4443 if (cpu_rotate) 4444 cpu_event = ctx_event_to_rotate(cpu_epc); 4445 4446 /* 4447 * As per the order given at ctx_resched() first 'pop' task flexible 4448 * and then, if needed CPU flexible. 4449 */ 4450 if (task_event || (task_epc && cpu_event)) { 4451 update_context_time(task_epc->ctx); 4452 __pmu_ctx_sched_out(task_epc, EVENT_FLEXIBLE); 4453 } 4454 4455 if (cpu_event) { 4456 update_context_time(&cpuctx->ctx); 4457 __pmu_ctx_sched_out(cpu_epc, EVENT_FLEXIBLE); 4458 rotate_ctx(&cpuctx->ctx, cpu_event); 4459 __pmu_ctx_sched_in(cpu_epc, EVENT_FLEXIBLE); 4460 } 4461 4462 if (task_event) 4463 rotate_ctx(task_epc->ctx, task_event); 4464 4465 if (task_event || (task_epc && cpu_event)) 4466 __pmu_ctx_sched_in(task_epc, EVENT_FLEXIBLE); 4467 4468 perf_pmu_enable(pmu); 4469 perf_ctx_unlock(cpuctx, cpuctx->task_ctx); 4470 4471 return true; 4472 } 4473 4474 void perf_event_task_tick(void) 4475 { 4476 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 4477 struct perf_event_context *ctx; 4478 int throttled; 4479 4480 lockdep_assert_irqs_disabled(); 4481 4482 __this_cpu_inc(perf_throttled_seq); 4483 throttled = __this_cpu_xchg(perf_throttled_count, 0); 4484 tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS); 4485 4486 perf_adjust_freq_unthr_context(&cpuctx->ctx, !!throttled); 4487 4488 rcu_read_lock(); 4489 ctx = rcu_dereference(current->perf_event_ctxp); 4490 if (ctx) 4491 perf_adjust_freq_unthr_context(ctx, !!throttled); 4492 rcu_read_unlock(); 4493 } 4494 4495 static int event_enable_on_exec(struct perf_event *event, 4496 struct perf_event_context *ctx) 4497 { 4498 if (!event->attr.enable_on_exec) 4499 return 0; 4500 4501 event->attr.enable_on_exec = 0; 4502 if (event->state >= PERF_EVENT_STATE_INACTIVE) 4503 return 0; 4504 4505 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE); 4506 4507 return 1; 4508 } 4509 4510 /* 4511 * Enable all of a task's events that have been marked enable-on-exec. 4512 * This expects task == current. 4513 */ 4514 static void perf_event_enable_on_exec(struct perf_event_context *ctx) 4515 { 4516 struct perf_event_context *clone_ctx = NULL; 4517 enum event_type_t event_type = 0; 4518 struct perf_cpu_context *cpuctx; 4519 struct perf_event *event; 4520 unsigned long flags; 4521 int enabled = 0; 4522 4523 local_irq_save(flags); 4524 if (WARN_ON_ONCE(current->perf_event_ctxp != ctx)) 4525 goto out; 4526 4527 if (!ctx->nr_events) 4528 goto out; 4529 4530 cpuctx = this_cpu_ptr(&perf_cpu_context); 4531 perf_ctx_lock(cpuctx, ctx); 4532 ctx_time_freeze(cpuctx, ctx); 4533 4534 list_for_each_entry(event, &ctx->event_list, event_entry) { 4535 enabled |= event_enable_on_exec(event, ctx); 4536 event_type |= get_event_type(event); 4537 } 4538 4539 /* 4540 * Unclone and reschedule this context if we enabled any event. 4541 */ 4542 if (enabled) { 4543 clone_ctx = unclone_ctx(ctx); 4544 ctx_resched(cpuctx, ctx, NULL, event_type); 4545 } 4546 perf_ctx_unlock(cpuctx, ctx); 4547 4548 out: 4549 local_irq_restore(flags); 4550 4551 if (clone_ctx) 4552 put_ctx(clone_ctx); 4553 } 4554 4555 static void perf_remove_from_owner(struct perf_event *event); 4556 static void perf_event_exit_event(struct perf_event *event, 4557 struct perf_event_context *ctx); 4558 4559 /* 4560 * Removes all events from the current task that have been marked 4561 * remove-on-exec, and feeds their values back to parent events. 4562 */ 4563 static void perf_event_remove_on_exec(struct perf_event_context *ctx) 4564 { 4565 struct perf_event_context *clone_ctx = NULL; 4566 struct perf_event *event, *next; 4567 unsigned long flags; 4568 bool modified = false; 4569 4570 mutex_lock(&ctx->mutex); 4571 4572 if (WARN_ON_ONCE(ctx->task != current)) 4573 goto unlock; 4574 4575 list_for_each_entry_safe(event, next, &ctx->event_list, event_entry) { 4576 if (!event->attr.remove_on_exec) 4577 continue; 4578 4579 if (!is_kernel_event(event)) 4580 perf_remove_from_owner(event); 4581 4582 modified = true; 4583 4584 perf_event_exit_event(event, ctx); 4585 } 4586 4587 raw_spin_lock_irqsave(&ctx->lock, flags); 4588 if (modified) 4589 clone_ctx = unclone_ctx(ctx); 4590 raw_spin_unlock_irqrestore(&ctx->lock, flags); 4591 4592 unlock: 4593 mutex_unlock(&ctx->mutex); 4594 4595 if (clone_ctx) 4596 put_ctx(clone_ctx); 4597 } 4598 4599 struct perf_read_data { 4600 struct perf_event *event; 4601 bool group; 4602 int ret; 4603 }; 4604 4605 static inline const struct cpumask *perf_scope_cpu_topology_cpumask(unsigned int scope, int cpu); 4606 4607 static int __perf_event_read_cpu(struct perf_event *event, int event_cpu) 4608 { 4609 int local_cpu = smp_processor_id(); 4610 u16 local_pkg, event_pkg; 4611 4612 if ((unsigned)event_cpu >= nr_cpu_ids) 4613 return event_cpu; 4614 4615 if (event->group_caps & PERF_EV_CAP_READ_SCOPE) { 4616 const struct cpumask *cpumask = perf_scope_cpu_topology_cpumask(event->pmu->scope, event_cpu); 4617 4618 if (cpumask && cpumask_test_cpu(local_cpu, cpumask)) 4619 return local_cpu; 4620 } 4621 4622 if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) { 4623 event_pkg = topology_physical_package_id(event_cpu); 4624 local_pkg = topology_physical_package_id(local_cpu); 4625 4626 if (event_pkg == local_pkg) 4627 return local_cpu; 4628 } 4629 4630 return event_cpu; 4631 } 4632 4633 /* 4634 * Cross CPU call to read the hardware event 4635 */ 4636 static void __perf_event_read(void *info) 4637 { 4638 struct perf_read_data *data = info; 4639 struct perf_event *sub, *event = data->event; 4640 struct perf_event_context *ctx = event->ctx; 4641 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 4642 struct pmu *pmu = event->pmu; 4643 4644 /* 4645 * If this is a task context, we need to check whether it is 4646 * the current task context of this cpu. If not it has been 4647 * scheduled out before the smp call arrived. In that case 4648 * event->count would have been updated to a recent sample 4649 * when the event was scheduled out. 4650 */ 4651 if (ctx->task && cpuctx->task_ctx != ctx) 4652 return; 4653 4654 raw_spin_lock(&ctx->lock); 4655 ctx_time_update_event(ctx, event); 4656 4657 perf_event_update_time(event); 4658 if (data->group) 4659 perf_event_update_sibling_time(event); 4660 4661 if (event->state != PERF_EVENT_STATE_ACTIVE) 4662 goto unlock; 4663 4664 if (!data->group) { 4665 pmu->read(event); 4666 data->ret = 0; 4667 goto unlock; 4668 } 4669 4670 pmu->start_txn(pmu, PERF_PMU_TXN_READ); 4671 4672 pmu->read(event); 4673 4674 for_each_sibling_event(sub, event) 4675 perf_pmu_read(sub); 4676 4677 data->ret = pmu->commit_txn(pmu); 4678 4679 unlock: 4680 raw_spin_unlock(&ctx->lock); 4681 } 4682 4683 static inline u64 perf_event_count(struct perf_event *event, bool self) 4684 { 4685 if (self) 4686 return local64_read(&event->count); 4687 4688 return local64_read(&event->count) + atomic64_read(&event->child_count); 4689 } 4690 4691 static void calc_timer_values(struct perf_event *event, 4692 u64 *now, 4693 u64 *enabled, 4694 u64 *running) 4695 { 4696 u64 ctx_time; 4697 4698 *now = perf_clock(); 4699 ctx_time = perf_event_time_now(event, *now); 4700 __perf_update_times(event, ctx_time, enabled, running); 4701 } 4702 4703 /* 4704 * NMI-safe method to read a local event, that is an event that 4705 * is: 4706 * - either for the current task, or for this CPU 4707 * - does not have inherit set, for inherited task events 4708 * will not be local and we cannot read them atomically 4709 * - must not have a pmu::count method 4710 */ 4711 int perf_event_read_local(struct perf_event *event, u64 *value, 4712 u64 *enabled, u64 *running) 4713 { 4714 unsigned long flags; 4715 int event_oncpu; 4716 int event_cpu; 4717 int ret = 0; 4718 4719 /* 4720 * Disabling interrupts avoids all counter scheduling (context 4721 * switches, timer based rotation and IPIs). 4722 */ 4723 local_irq_save(flags); 4724 4725 /* 4726 * It must not be an event with inherit set, we cannot read 4727 * all child counters from atomic context. 4728 */ 4729 if (event->attr.inherit) { 4730 ret = -EOPNOTSUPP; 4731 goto out; 4732 } 4733 4734 /* If this is a per-task event, it must be for current */ 4735 if ((event->attach_state & PERF_ATTACH_TASK) && 4736 event->hw.target != current) { 4737 ret = -EINVAL; 4738 goto out; 4739 } 4740 4741 /* 4742 * Get the event CPU numbers, and adjust them to local if the event is 4743 * a per-package event that can be read locally 4744 */ 4745 event_oncpu = __perf_event_read_cpu(event, event->oncpu); 4746 event_cpu = __perf_event_read_cpu(event, event->cpu); 4747 4748 /* If this is a per-CPU event, it must be for this CPU */ 4749 if (!(event->attach_state & PERF_ATTACH_TASK) && 4750 event_cpu != smp_processor_id()) { 4751 ret = -EINVAL; 4752 goto out; 4753 } 4754 4755 /* If this is a pinned event it must be running on this CPU */ 4756 if (event->attr.pinned && event_oncpu != smp_processor_id()) { 4757 ret = -EBUSY; 4758 goto out; 4759 } 4760 4761 /* 4762 * If the event is currently on this CPU, its either a per-task event, 4763 * or local to this CPU. Furthermore it means its ACTIVE (otherwise 4764 * oncpu == -1). 4765 */ 4766 if (event_oncpu == smp_processor_id()) 4767 event->pmu->read(event); 4768 4769 *value = local64_read(&event->count); 4770 if (enabled || running) { 4771 u64 __enabled, __running, __now; 4772 4773 calc_timer_values(event, &__now, &__enabled, &__running); 4774 if (enabled) 4775 *enabled = __enabled; 4776 if (running) 4777 *running = __running; 4778 } 4779 out: 4780 local_irq_restore(flags); 4781 4782 return ret; 4783 } 4784 4785 static int perf_event_read(struct perf_event *event, bool group) 4786 { 4787 enum perf_event_state state = READ_ONCE(event->state); 4788 int event_cpu, ret = 0; 4789 4790 /* 4791 * If event is enabled and currently active on a CPU, update the 4792 * value in the event structure: 4793 */ 4794 again: 4795 if (state == PERF_EVENT_STATE_ACTIVE) { 4796 struct perf_read_data data; 4797 4798 /* 4799 * Orders the ->state and ->oncpu loads such that if we see 4800 * ACTIVE we must also see the right ->oncpu. 4801 * 4802 * Matches the smp_wmb() from event_sched_in(). 4803 */ 4804 smp_rmb(); 4805 4806 event_cpu = READ_ONCE(event->oncpu); 4807 if ((unsigned)event_cpu >= nr_cpu_ids) 4808 return 0; 4809 4810 data = (struct perf_read_data){ 4811 .event = event, 4812 .group = group, 4813 .ret = 0, 4814 }; 4815 4816 preempt_disable(); 4817 event_cpu = __perf_event_read_cpu(event, event_cpu); 4818 4819 /* 4820 * Purposely ignore the smp_call_function_single() return 4821 * value. 4822 * 4823 * If event_cpu isn't a valid CPU it means the event got 4824 * scheduled out and that will have updated the event count. 4825 * 4826 * Therefore, either way, we'll have an up-to-date event count 4827 * after this. 4828 */ 4829 (void)smp_call_function_single(event_cpu, __perf_event_read, &data, 1); 4830 preempt_enable(); 4831 ret = data.ret; 4832 4833 } else if (state == PERF_EVENT_STATE_INACTIVE) { 4834 struct perf_event_context *ctx = event->ctx; 4835 unsigned long flags; 4836 4837 raw_spin_lock_irqsave(&ctx->lock, flags); 4838 state = event->state; 4839 if (state != PERF_EVENT_STATE_INACTIVE) { 4840 raw_spin_unlock_irqrestore(&ctx->lock, flags); 4841 goto again; 4842 } 4843 4844 /* 4845 * May read while context is not active (e.g., thread is 4846 * blocked), in that case we cannot update context time 4847 */ 4848 ctx_time_update_event(ctx, event); 4849 4850 perf_event_update_time(event); 4851 if (group) 4852 perf_event_update_sibling_time(event); 4853 raw_spin_unlock_irqrestore(&ctx->lock, flags); 4854 } 4855 4856 return ret; 4857 } 4858 4859 /* 4860 * Initialize the perf_event context in a task_struct: 4861 */ 4862 static void __perf_event_init_context(struct perf_event_context *ctx) 4863 { 4864 raw_spin_lock_init(&ctx->lock); 4865 mutex_init(&ctx->mutex); 4866 INIT_LIST_HEAD(&ctx->pmu_ctx_list); 4867 perf_event_groups_init(&ctx->pinned_groups); 4868 perf_event_groups_init(&ctx->flexible_groups); 4869 INIT_LIST_HEAD(&ctx->event_list); 4870 refcount_set(&ctx->refcount, 1); 4871 } 4872 4873 static void 4874 __perf_init_event_pmu_context(struct perf_event_pmu_context *epc, struct pmu *pmu) 4875 { 4876 epc->pmu = pmu; 4877 INIT_LIST_HEAD(&epc->pmu_ctx_entry); 4878 INIT_LIST_HEAD(&epc->pinned_active); 4879 INIT_LIST_HEAD(&epc->flexible_active); 4880 atomic_set(&epc->refcount, 1); 4881 } 4882 4883 static struct perf_event_context * 4884 alloc_perf_context(struct task_struct *task) 4885 { 4886 struct perf_event_context *ctx; 4887 4888 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL); 4889 if (!ctx) 4890 return NULL; 4891 4892 __perf_event_init_context(ctx); 4893 if (task) 4894 ctx->task = get_task_struct(task); 4895 4896 return ctx; 4897 } 4898 4899 static struct task_struct * 4900 find_lively_task_by_vpid(pid_t vpid) 4901 { 4902 struct task_struct *task; 4903 4904 rcu_read_lock(); 4905 if (!vpid) 4906 task = current; 4907 else 4908 task = find_task_by_vpid(vpid); 4909 if (task) 4910 get_task_struct(task); 4911 rcu_read_unlock(); 4912 4913 if (!task) 4914 return ERR_PTR(-ESRCH); 4915 4916 return task; 4917 } 4918 4919 /* 4920 * Returns a matching context with refcount and pincount. 4921 */ 4922 static struct perf_event_context * 4923 find_get_context(struct task_struct *task, struct perf_event *event) 4924 { 4925 struct perf_event_context *ctx, *clone_ctx = NULL; 4926 struct perf_cpu_context *cpuctx; 4927 unsigned long flags; 4928 int err; 4929 4930 if (!task) { 4931 /* Must be root to operate on a CPU event: */ 4932 err = perf_allow_cpu(&event->attr); 4933 if (err) 4934 return ERR_PTR(err); 4935 4936 cpuctx = per_cpu_ptr(&perf_cpu_context, event->cpu); 4937 ctx = &cpuctx->ctx; 4938 get_ctx(ctx); 4939 raw_spin_lock_irqsave(&ctx->lock, flags); 4940 ++ctx->pin_count; 4941 raw_spin_unlock_irqrestore(&ctx->lock, flags); 4942 4943 return ctx; 4944 } 4945 4946 err = -EINVAL; 4947 retry: 4948 ctx = perf_lock_task_context(task, &flags); 4949 if (ctx) { 4950 clone_ctx = unclone_ctx(ctx); 4951 ++ctx->pin_count; 4952 4953 raw_spin_unlock_irqrestore(&ctx->lock, flags); 4954 4955 if (clone_ctx) 4956 put_ctx(clone_ctx); 4957 } else { 4958 ctx = alloc_perf_context(task); 4959 err = -ENOMEM; 4960 if (!ctx) 4961 goto errout; 4962 4963 err = 0; 4964 mutex_lock(&task->perf_event_mutex); 4965 /* 4966 * If it has already passed perf_event_exit_task(). 4967 * we must see PF_EXITING, it takes this mutex too. 4968 */ 4969 if (task->flags & PF_EXITING) 4970 err = -ESRCH; 4971 else if (task->perf_event_ctxp) 4972 err = -EAGAIN; 4973 else { 4974 get_ctx(ctx); 4975 ++ctx->pin_count; 4976 rcu_assign_pointer(task->perf_event_ctxp, ctx); 4977 } 4978 mutex_unlock(&task->perf_event_mutex); 4979 4980 if (unlikely(err)) { 4981 put_ctx(ctx); 4982 4983 if (err == -EAGAIN) 4984 goto retry; 4985 goto errout; 4986 } 4987 } 4988 4989 return ctx; 4990 4991 errout: 4992 return ERR_PTR(err); 4993 } 4994 4995 static struct perf_event_pmu_context * 4996 find_get_pmu_context(struct pmu *pmu, struct perf_event_context *ctx, 4997 struct perf_event *event) 4998 { 4999 struct perf_event_pmu_context *new = NULL, *pos = NULL, *epc; 5000 void *task_ctx_data = NULL; 5001 5002 if (!ctx->task) { 5003 /* 5004 * perf_pmu_migrate_context() / __perf_pmu_install_event() 5005 * relies on the fact that find_get_pmu_context() cannot fail 5006 * for CPU contexts. 5007 */ 5008 struct perf_cpu_pmu_context *cpc; 5009 5010 cpc = per_cpu_ptr(pmu->cpu_pmu_context, event->cpu); 5011 epc = &cpc->epc; 5012 raw_spin_lock_irq(&ctx->lock); 5013 if (!epc->ctx) { 5014 atomic_set(&epc->refcount, 1); 5015 epc->embedded = 1; 5016 list_add(&epc->pmu_ctx_entry, &ctx->pmu_ctx_list); 5017 epc->ctx = ctx; 5018 } else { 5019 WARN_ON_ONCE(epc->ctx != ctx); 5020 atomic_inc(&epc->refcount); 5021 } 5022 raw_spin_unlock_irq(&ctx->lock); 5023 return epc; 5024 } 5025 5026 new = kzalloc(sizeof(*epc), GFP_KERNEL); 5027 if (!new) 5028 return ERR_PTR(-ENOMEM); 5029 5030 if (event->attach_state & PERF_ATTACH_TASK_DATA) { 5031 task_ctx_data = alloc_task_ctx_data(pmu); 5032 if (!task_ctx_data) { 5033 kfree(new); 5034 return ERR_PTR(-ENOMEM); 5035 } 5036 } 5037 5038 __perf_init_event_pmu_context(new, pmu); 5039 5040 /* 5041 * XXX 5042 * 5043 * lockdep_assert_held(&ctx->mutex); 5044 * 5045 * can't because perf_event_init_task() doesn't actually hold the 5046 * child_ctx->mutex. 5047 */ 5048 5049 raw_spin_lock_irq(&ctx->lock); 5050 list_for_each_entry(epc, &ctx->pmu_ctx_list, pmu_ctx_entry) { 5051 if (epc->pmu == pmu) { 5052 WARN_ON_ONCE(epc->ctx != ctx); 5053 atomic_inc(&epc->refcount); 5054 goto found_epc; 5055 } 5056 /* Make sure the pmu_ctx_list is sorted by PMU type: */ 5057 if (!pos && epc->pmu->type > pmu->type) 5058 pos = epc; 5059 } 5060 5061 epc = new; 5062 new = NULL; 5063 5064 if (!pos) 5065 list_add_tail(&epc->pmu_ctx_entry, &ctx->pmu_ctx_list); 5066 else 5067 list_add(&epc->pmu_ctx_entry, pos->pmu_ctx_entry.prev); 5068 5069 epc->ctx = ctx; 5070 5071 found_epc: 5072 if (task_ctx_data && !epc->task_ctx_data) { 5073 epc->task_ctx_data = task_ctx_data; 5074 task_ctx_data = NULL; 5075 ctx->nr_task_data++; 5076 } 5077 raw_spin_unlock_irq(&ctx->lock); 5078 5079 free_task_ctx_data(pmu, task_ctx_data); 5080 kfree(new); 5081 5082 return epc; 5083 } 5084 5085 static void get_pmu_ctx(struct perf_event_pmu_context *epc) 5086 { 5087 WARN_ON_ONCE(!atomic_inc_not_zero(&epc->refcount)); 5088 } 5089 5090 static void free_epc_rcu(struct rcu_head *head) 5091 { 5092 struct perf_event_pmu_context *epc = container_of(head, typeof(*epc), rcu_head); 5093 5094 kfree(epc->task_ctx_data); 5095 kfree(epc); 5096 } 5097 5098 static void put_pmu_ctx(struct perf_event_pmu_context *epc) 5099 { 5100 struct perf_event_context *ctx = epc->ctx; 5101 unsigned long flags; 5102 5103 /* 5104 * XXX 5105 * 5106 * lockdep_assert_held(&ctx->mutex); 5107 * 5108 * can't because of the call-site in _free_event()/put_event() 5109 * which isn't always called under ctx->mutex. 5110 */ 5111 if (!atomic_dec_and_raw_lock_irqsave(&epc->refcount, &ctx->lock, flags)) 5112 return; 5113 5114 WARN_ON_ONCE(list_empty(&epc->pmu_ctx_entry)); 5115 5116 list_del_init(&epc->pmu_ctx_entry); 5117 epc->ctx = NULL; 5118 5119 WARN_ON_ONCE(!list_empty(&epc->pinned_active)); 5120 WARN_ON_ONCE(!list_empty(&epc->flexible_active)); 5121 5122 raw_spin_unlock_irqrestore(&ctx->lock, flags); 5123 5124 if (epc->embedded) 5125 return; 5126 5127 call_rcu(&epc->rcu_head, free_epc_rcu); 5128 } 5129 5130 static void perf_event_free_filter(struct perf_event *event); 5131 5132 static void free_event_rcu(struct rcu_head *head) 5133 { 5134 struct perf_event *event = container_of(head, typeof(*event), rcu_head); 5135 5136 if (event->ns) 5137 put_pid_ns(event->ns); 5138 perf_event_free_filter(event); 5139 kmem_cache_free(perf_event_cache, event); 5140 } 5141 5142 static void ring_buffer_attach(struct perf_event *event, 5143 struct perf_buffer *rb); 5144 5145 static void detach_sb_event(struct perf_event *event) 5146 { 5147 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu); 5148 5149 raw_spin_lock(&pel->lock); 5150 list_del_rcu(&event->sb_list); 5151 raw_spin_unlock(&pel->lock); 5152 } 5153 5154 static bool is_sb_event(struct perf_event *event) 5155 { 5156 struct perf_event_attr *attr = &event->attr; 5157 5158 if (event->parent) 5159 return false; 5160 5161 if (event->attach_state & PERF_ATTACH_TASK) 5162 return false; 5163 5164 if (attr->mmap || attr->mmap_data || attr->mmap2 || 5165 attr->comm || attr->comm_exec || 5166 attr->task || attr->ksymbol || 5167 attr->context_switch || attr->text_poke || 5168 attr->bpf_event) 5169 return true; 5170 return false; 5171 } 5172 5173 static void unaccount_pmu_sb_event(struct perf_event *event) 5174 { 5175 if (is_sb_event(event)) 5176 detach_sb_event(event); 5177 } 5178 5179 #ifdef CONFIG_NO_HZ_FULL 5180 static DEFINE_SPINLOCK(nr_freq_lock); 5181 #endif 5182 5183 static void unaccount_freq_event_nohz(void) 5184 { 5185 #ifdef CONFIG_NO_HZ_FULL 5186 spin_lock(&nr_freq_lock); 5187 if (atomic_dec_and_test(&nr_freq_events)) 5188 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS); 5189 spin_unlock(&nr_freq_lock); 5190 #endif 5191 } 5192 5193 static void unaccount_freq_event(void) 5194 { 5195 if (tick_nohz_full_enabled()) 5196 unaccount_freq_event_nohz(); 5197 else 5198 atomic_dec(&nr_freq_events); 5199 } 5200 5201 static void unaccount_event(struct perf_event *event) 5202 { 5203 bool dec = false; 5204 5205 if (event->parent) 5206 return; 5207 5208 if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB)) 5209 dec = true; 5210 if (event->attr.mmap || event->attr.mmap_data) 5211 atomic_dec(&nr_mmap_events); 5212 if (event->attr.build_id) 5213 atomic_dec(&nr_build_id_events); 5214 if (event->attr.comm) 5215 atomic_dec(&nr_comm_events); 5216 if (event->attr.namespaces) 5217 atomic_dec(&nr_namespaces_events); 5218 if (event->attr.cgroup) 5219 atomic_dec(&nr_cgroup_events); 5220 if (event->attr.task) 5221 atomic_dec(&nr_task_events); 5222 if (event->attr.freq) 5223 unaccount_freq_event(); 5224 if (event->attr.context_switch) { 5225 dec = true; 5226 atomic_dec(&nr_switch_events); 5227 } 5228 if (is_cgroup_event(event)) 5229 dec = true; 5230 if (has_branch_stack(event)) 5231 dec = true; 5232 if (event->attr.ksymbol) 5233 atomic_dec(&nr_ksymbol_events); 5234 if (event->attr.bpf_event) 5235 atomic_dec(&nr_bpf_events); 5236 if (event->attr.text_poke) 5237 atomic_dec(&nr_text_poke_events); 5238 5239 if (dec) { 5240 if (!atomic_add_unless(&perf_sched_count, -1, 1)) 5241 schedule_delayed_work(&perf_sched_work, HZ); 5242 } 5243 5244 unaccount_pmu_sb_event(event); 5245 } 5246 5247 static void perf_sched_delayed(struct work_struct *work) 5248 { 5249 mutex_lock(&perf_sched_mutex); 5250 if (atomic_dec_and_test(&perf_sched_count)) 5251 static_branch_disable(&perf_sched_events); 5252 mutex_unlock(&perf_sched_mutex); 5253 } 5254 5255 /* 5256 * The following implement mutual exclusion of events on "exclusive" pmus 5257 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled 5258 * at a time, so we disallow creating events that might conflict, namely: 5259 * 5260 * 1) cpu-wide events in the presence of per-task events, 5261 * 2) per-task events in the presence of cpu-wide events, 5262 * 3) two matching events on the same perf_event_context. 5263 * 5264 * The former two cases are handled in the allocation path (perf_event_alloc(), 5265 * _free_event()), the latter -- before the first perf_install_in_context(). 5266 */ 5267 static int exclusive_event_init(struct perf_event *event) 5268 { 5269 struct pmu *pmu = event->pmu; 5270 5271 if (!is_exclusive_pmu(pmu)) 5272 return 0; 5273 5274 /* 5275 * Prevent co-existence of per-task and cpu-wide events on the 5276 * same exclusive pmu. 5277 * 5278 * Negative pmu::exclusive_cnt means there are cpu-wide 5279 * events on this "exclusive" pmu, positive means there are 5280 * per-task events. 5281 * 5282 * Since this is called in perf_event_alloc() path, event::ctx 5283 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK 5284 * to mean "per-task event", because unlike other attach states it 5285 * never gets cleared. 5286 */ 5287 if (event->attach_state & PERF_ATTACH_TASK) { 5288 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt)) 5289 return -EBUSY; 5290 } else { 5291 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt)) 5292 return -EBUSY; 5293 } 5294 5295 event->attach_state |= PERF_ATTACH_EXCLUSIVE; 5296 5297 return 0; 5298 } 5299 5300 static void exclusive_event_destroy(struct perf_event *event) 5301 { 5302 struct pmu *pmu = event->pmu; 5303 5304 /* see comment in exclusive_event_init() */ 5305 if (event->attach_state & PERF_ATTACH_TASK) 5306 atomic_dec(&pmu->exclusive_cnt); 5307 else 5308 atomic_inc(&pmu->exclusive_cnt); 5309 5310 event->attach_state &= ~PERF_ATTACH_EXCLUSIVE; 5311 } 5312 5313 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2) 5314 { 5315 if ((e1->pmu == e2->pmu) && 5316 (e1->cpu == e2->cpu || 5317 e1->cpu == -1 || 5318 e2->cpu == -1)) 5319 return true; 5320 return false; 5321 } 5322 5323 static bool exclusive_event_installable(struct perf_event *event, 5324 struct perf_event_context *ctx) 5325 { 5326 struct perf_event *iter_event; 5327 struct pmu *pmu = event->pmu; 5328 5329 lockdep_assert_held(&ctx->mutex); 5330 5331 if (!is_exclusive_pmu(pmu)) 5332 return true; 5333 5334 list_for_each_entry(iter_event, &ctx->event_list, event_entry) { 5335 if (exclusive_event_match(iter_event, event)) 5336 return false; 5337 } 5338 5339 return true; 5340 } 5341 5342 static void perf_free_addr_filters(struct perf_event *event); 5343 5344 static void perf_pending_task_sync(struct perf_event *event) 5345 { 5346 struct callback_head *head = &event->pending_task; 5347 5348 if (!event->pending_work) 5349 return; 5350 /* 5351 * If the task is queued to the current task's queue, we 5352 * obviously can't wait for it to complete. Simply cancel it. 5353 */ 5354 if (task_work_cancel(current, head)) { 5355 event->pending_work = 0; 5356 local_dec(&event->ctx->nr_no_switch_fast); 5357 return; 5358 } 5359 5360 /* 5361 * All accesses related to the event are within the same RCU section in 5362 * perf_pending_task(). The RCU grace period before the event is freed 5363 * will make sure all those accesses are complete by then. 5364 */ 5365 rcuwait_wait_event(&event->pending_work_wait, !event->pending_work, TASK_UNINTERRUPTIBLE); 5366 } 5367 5368 /* vs perf_event_alloc() error */ 5369 static void __free_event(struct perf_event *event) 5370 { 5371 if (event->attach_state & PERF_ATTACH_CALLCHAIN) 5372 put_callchain_buffers(); 5373 5374 kfree(event->addr_filter_ranges); 5375 5376 if (event->attach_state & PERF_ATTACH_EXCLUSIVE) 5377 exclusive_event_destroy(event); 5378 5379 if (is_cgroup_event(event)) 5380 perf_detach_cgroup(event); 5381 5382 if (event->destroy) 5383 event->destroy(event); 5384 5385 /* 5386 * Must be after ->destroy(), due to uprobe_perf_close() using 5387 * hw.target. 5388 */ 5389 if (event->hw.target) 5390 put_task_struct(event->hw.target); 5391 5392 if (event->pmu_ctx) { 5393 /* 5394 * put_pmu_ctx() needs an event->ctx reference, because of 5395 * epc->ctx. 5396 */ 5397 WARN_ON_ONCE(!event->ctx); 5398 WARN_ON_ONCE(event->pmu_ctx->ctx != event->ctx); 5399 put_pmu_ctx(event->pmu_ctx); 5400 } 5401 5402 /* 5403 * perf_event_free_task() relies on put_ctx() being 'last', in 5404 * particular all task references must be cleaned up. 5405 */ 5406 if (event->ctx) 5407 put_ctx(event->ctx); 5408 5409 if (event->pmu) 5410 module_put(event->pmu->module); 5411 5412 call_rcu(&event->rcu_head, free_event_rcu); 5413 } 5414 5415 DEFINE_FREE(__free_event, struct perf_event *, if (_T) __free_event(_T)) 5416 5417 /* vs perf_event_alloc() success */ 5418 static void _free_event(struct perf_event *event) 5419 { 5420 irq_work_sync(&event->pending_irq); 5421 irq_work_sync(&event->pending_disable_irq); 5422 perf_pending_task_sync(event); 5423 5424 unaccount_event(event); 5425 5426 security_perf_event_free(event); 5427 5428 if (event->rb) { 5429 /* 5430 * Can happen when we close an event with re-directed output. 5431 * 5432 * Since we have a 0 refcount, perf_mmap_close() will skip 5433 * over us; possibly making our ring_buffer_put() the last. 5434 */ 5435 mutex_lock(&event->mmap_mutex); 5436 ring_buffer_attach(event, NULL); 5437 mutex_unlock(&event->mmap_mutex); 5438 } 5439 5440 perf_event_free_bpf_prog(event); 5441 perf_free_addr_filters(event); 5442 5443 __free_event(event); 5444 } 5445 5446 /* 5447 * Used to free events which have a known refcount of 1, such as in error paths 5448 * where the event isn't exposed yet and inherited events. 5449 */ 5450 static void free_event(struct perf_event *event) 5451 { 5452 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1, 5453 "unexpected event refcount: %ld; ptr=%p\n", 5454 atomic_long_read(&event->refcount), event)) { 5455 /* leak to avoid use-after-free */ 5456 return; 5457 } 5458 5459 _free_event(event); 5460 } 5461 5462 /* 5463 * Remove user event from the owner task. 5464 */ 5465 static void perf_remove_from_owner(struct perf_event *event) 5466 { 5467 struct task_struct *owner; 5468 5469 rcu_read_lock(); 5470 /* 5471 * Matches the smp_store_release() in perf_event_exit_task(). If we 5472 * observe !owner it means the list deletion is complete and we can 5473 * indeed free this event, otherwise we need to serialize on 5474 * owner->perf_event_mutex. 5475 */ 5476 owner = READ_ONCE(event->owner); 5477 if (owner) { 5478 /* 5479 * Since delayed_put_task_struct() also drops the last 5480 * task reference we can safely take a new reference 5481 * while holding the rcu_read_lock(). 5482 */ 5483 get_task_struct(owner); 5484 } 5485 rcu_read_unlock(); 5486 5487 if (owner) { 5488 /* 5489 * If we're here through perf_event_exit_task() we're already 5490 * holding ctx->mutex which would be an inversion wrt. the 5491 * normal lock order. 5492 * 5493 * However we can safely take this lock because its the child 5494 * ctx->mutex. 5495 */ 5496 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING); 5497 5498 /* 5499 * We have to re-check the event->owner field, if it is cleared 5500 * we raced with perf_event_exit_task(), acquiring the mutex 5501 * ensured they're done, and we can proceed with freeing the 5502 * event. 5503 */ 5504 if (event->owner) { 5505 list_del_init(&event->owner_entry); 5506 smp_store_release(&event->owner, NULL); 5507 } 5508 mutex_unlock(&owner->perf_event_mutex); 5509 put_task_struct(owner); 5510 } 5511 } 5512 5513 static void put_event(struct perf_event *event) 5514 { 5515 if (!atomic_long_dec_and_test(&event->refcount)) 5516 return; 5517 5518 _free_event(event); 5519 } 5520 5521 /* 5522 * Kill an event dead; while event:refcount will preserve the event 5523 * object, it will not preserve its functionality. Once the last 'user' 5524 * gives up the object, we'll destroy the thing. 5525 */ 5526 int perf_event_release_kernel(struct perf_event *event) 5527 { 5528 struct perf_event_context *ctx = event->ctx; 5529 struct perf_event *child, *tmp; 5530 LIST_HEAD(free_list); 5531 5532 /* 5533 * If we got here through err_alloc: free_event(event); we will not 5534 * have attached to a context yet. 5535 */ 5536 if (!ctx) { 5537 WARN_ON_ONCE(event->attach_state & 5538 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP)); 5539 goto no_ctx; 5540 } 5541 5542 if (!is_kernel_event(event)) 5543 perf_remove_from_owner(event); 5544 5545 ctx = perf_event_ctx_lock(event); 5546 WARN_ON_ONCE(ctx->parent_ctx); 5547 5548 /* 5549 * Mark this event as STATE_DEAD, there is no external reference to it 5550 * anymore. 5551 * 5552 * Anybody acquiring event->child_mutex after the below loop _must_ 5553 * also see this, most importantly inherit_event() which will avoid 5554 * placing more children on the list. 5555 * 5556 * Thus this guarantees that we will in fact observe and kill _ALL_ 5557 * child events. 5558 */ 5559 perf_remove_from_context(event, DETACH_GROUP|DETACH_DEAD); 5560 5561 perf_event_ctx_unlock(event, ctx); 5562 5563 again: 5564 mutex_lock(&event->child_mutex); 5565 list_for_each_entry(child, &event->child_list, child_list) { 5566 void *var = NULL; 5567 5568 /* 5569 * Cannot change, child events are not migrated, see the 5570 * comment with perf_event_ctx_lock_nested(). 5571 */ 5572 ctx = READ_ONCE(child->ctx); 5573 /* 5574 * Since child_mutex nests inside ctx::mutex, we must jump 5575 * through hoops. We start by grabbing a reference on the ctx. 5576 * 5577 * Since the event cannot get freed while we hold the 5578 * child_mutex, the context must also exist and have a !0 5579 * reference count. 5580 */ 5581 get_ctx(ctx); 5582 5583 /* 5584 * Now that we have a ctx ref, we can drop child_mutex, and 5585 * acquire ctx::mutex without fear of it going away. Then we 5586 * can re-acquire child_mutex. 5587 */ 5588 mutex_unlock(&event->child_mutex); 5589 mutex_lock(&ctx->mutex); 5590 mutex_lock(&event->child_mutex); 5591 5592 /* 5593 * Now that we hold ctx::mutex and child_mutex, revalidate our 5594 * state, if child is still the first entry, it didn't get freed 5595 * and we can continue doing so. 5596 */ 5597 tmp = list_first_entry_or_null(&event->child_list, 5598 struct perf_event, child_list); 5599 if (tmp == child) { 5600 perf_remove_from_context(child, DETACH_GROUP); 5601 list_move(&child->child_list, &free_list); 5602 /* 5603 * This matches the refcount bump in inherit_event(); 5604 * this can't be the last reference. 5605 */ 5606 put_event(event); 5607 } else { 5608 var = &ctx->refcount; 5609 } 5610 5611 mutex_unlock(&event->child_mutex); 5612 mutex_unlock(&ctx->mutex); 5613 put_ctx(ctx); 5614 5615 if (var) { 5616 /* 5617 * If perf_event_free_task() has deleted all events from the 5618 * ctx while the child_mutex got released above, make sure to 5619 * notify about the preceding put_ctx(). 5620 */ 5621 smp_mb(); /* pairs with wait_var_event() */ 5622 wake_up_var(var); 5623 } 5624 goto again; 5625 } 5626 mutex_unlock(&event->child_mutex); 5627 5628 list_for_each_entry_safe(child, tmp, &free_list, child_list) { 5629 void *var = &child->ctx->refcount; 5630 5631 list_del(&child->child_list); 5632 free_event(child); 5633 5634 /* 5635 * Wake any perf_event_free_task() waiting for this event to be 5636 * freed. 5637 */ 5638 smp_mb(); /* pairs with wait_var_event() */ 5639 wake_up_var(var); 5640 } 5641 5642 no_ctx: 5643 put_event(event); /* Must be the 'last' reference */ 5644 return 0; 5645 } 5646 EXPORT_SYMBOL_GPL(perf_event_release_kernel); 5647 5648 /* 5649 * Called when the last reference to the file is gone. 5650 */ 5651 static int perf_release(struct inode *inode, struct file *file) 5652 { 5653 perf_event_release_kernel(file->private_data); 5654 return 0; 5655 } 5656 5657 static u64 __perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running) 5658 { 5659 struct perf_event *child; 5660 u64 total = 0; 5661 5662 *enabled = 0; 5663 *running = 0; 5664 5665 mutex_lock(&event->child_mutex); 5666 5667 (void)perf_event_read(event, false); 5668 total += perf_event_count(event, false); 5669 5670 *enabled += event->total_time_enabled + 5671 atomic64_read(&event->child_total_time_enabled); 5672 *running += event->total_time_running + 5673 atomic64_read(&event->child_total_time_running); 5674 5675 list_for_each_entry(child, &event->child_list, child_list) { 5676 (void)perf_event_read(child, false); 5677 total += perf_event_count(child, false); 5678 *enabled += child->total_time_enabled; 5679 *running += child->total_time_running; 5680 } 5681 mutex_unlock(&event->child_mutex); 5682 5683 return total; 5684 } 5685 5686 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running) 5687 { 5688 struct perf_event_context *ctx; 5689 u64 count; 5690 5691 ctx = perf_event_ctx_lock(event); 5692 count = __perf_event_read_value(event, enabled, running); 5693 perf_event_ctx_unlock(event, ctx); 5694 5695 return count; 5696 } 5697 EXPORT_SYMBOL_GPL(perf_event_read_value); 5698 5699 static int __perf_read_group_add(struct perf_event *leader, 5700 u64 read_format, u64 *values) 5701 { 5702 struct perf_event_context *ctx = leader->ctx; 5703 struct perf_event *sub, *parent; 5704 unsigned long flags; 5705 int n = 1; /* skip @nr */ 5706 int ret; 5707 5708 ret = perf_event_read(leader, true); 5709 if (ret) 5710 return ret; 5711 5712 raw_spin_lock_irqsave(&ctx->lock, flags); 5713 /* 5714 * Verify the grouping between the parent and child (inherited) 5715 * events is still in tact. 5716 * 5717 * Specifically: 5718 * - leader->ctx->lock pins leader->sibling_list 5719 * - parent->child_mutex pins parent->child_list 5720 * - parent->ctx->mutex pins parent->sibling_list 5721 * 5722 * Because parent->ctx != leader->ctx (and child_list nests inside 5723 * ctx->mutex), group destruction is not atomic between children, also 5724 * see perf_event_release_kernel(). Additionally, parent can grow the 5725 * group. 5726 * 5727 * Therefore it is possible to have parent and child groups in a 5728 * different configuration and summing over such a beast makes no sense 5729 * what so ever. 5730 * 5731 * Reject this. 5732 */ 5733 parent = leader->parent; 5734 if (parent && 5735 (parent->group_generation != leader->group_generation || 5736 parent->nr_siblings != leader->nr_siblings)) { 5737 ret = -ECHILD; 5738 goto unlock; 5739 } 5740 5741 /* 5742 * Since we co-schedule groups, {enabled,running} times of siblings 5743 * will be identical to those of the leader, so we only publish one 5744 * set. 5745 */ 5746 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) { 5747 values[n++] += leader->total_time_enabled + 5748 atomic64_read(&leader->child_total_time_enabled); 5749 } 5750 5751 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) { 5752 values[n++] += leader->total_time_running + 5753 atomic64_read(&leader->child_total_time_running); 5754 } 5755 5756 /* 5757 * Write {count,id} tuples for every sibling. 5758 */ 5759 values[n++] += perf_event_count(leader, false); 5760 if (read_format & PERF_FORMAT_ID) 5761 values[n++] = primary_event_id(leader); 5762 if (read_format & PERF_FORMAT_LOST) 5763 values[n++] = atomic64_read(&leader->lost_samples); 5764 5765 for_each_sibling_event(sub, leader) { 5766 values[n++] += perf_event_count(sub, false); 5767 if (read_format & PERF_FORMAT_ID) 5768 values[n++] = primary_event_id(sub); 5769 if (read_format & PERF_FORMAT_LOST) 5770 values[n++] = atomic64_read(&sub->lost_samples); 5771 } 5772 5773 unlock: 5774 raw_spin_unlock_irqrestore(&ctx->lock, flags); 5775 return ret; 5776 } 5777 5778 static int perf_read_group(struct perf_event *event, 5779 u64 read_format, char __user *buf) 5780 { 5781 struct perf_event *leader = event->group_leader, *child; 5782 struct perf_event_context *ctx = leader->ctx; 5783 int ret; 5784 u64 *values; 5785 5786 lockdep_assert_held(&ctx->mutex); 5787 5788 values = kzalloc(event->read_size, GFP_KERNEL); 5789 if (!values) 5790 return -ENOMEM; 5791 5792 values[0] = 1 + leader->nr_siblings; 5793 5794 mutex_lock(&leader->child_mutex); 5795 5796 ret = __perf_read_group_add(leader, read_format, values); 5797 if (ret) 5798 goto unlock; 5799 5800 list_for_each_entry(child, &leader->child_list, child_list) { 5801 ret = __perf_read_group_add(child, read_format, values); 5802 if (ret) 5803 goto unlock; 5804 } 5805 5806 mutex_unlock(&leader->child_mutex); 5807 5808 ret = event->read_size; 5809 if (copy_to_user(buf, values, event->read_size)) 5810 ret = -EFAULT; 5811 goto out; 5812 5813 unlock: 5814 mutex_unlock(&leader->child_mutex); 5815 out: 5816 kfree(values); 5817 return ret; 5818 } 5819 5820 static int perf_read_one(struct perf_event *event, 5821 u64 read_format, char __user *buf) 5822 { 5823 u64 enabled, running; 5824 u64 values[5]; 5825 int n = 0; 5826 5827 values[n++] = __perf_event_read_value(event, &enabled, &running); 5828 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) 5829 values[n++] = enabled; 5830 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) 5831 values[n++] = running; 5832 if (read_format & PERF_FORMAT_ID) 5833 values[n++] = primary_event_id(event); 5834 if (read_format & PERF_FORMAT_LOST) 5835 values[n++] = atomic64_read(&event->lost_samples); 5836 5837 if (copy_to_user(buf, values, n * sizeof(u64))) 5838 return -EFAULT; 5839 5840 return n * sizeof(u64); 5841 } 5842 5843 static bool is_event_hup(struct perf_event *event) 5844 { 5845 bool no_children; 5846 5847 if (event->state > PERF_EVENT_STATE_EXIT) 5848 return false; 5849 5850 mutex_lock(&event->child_mutex); 5851 no_children = list_empty(&event->child_list); 5852 mutex_unlock(&event->child_mutex); 5853 return no_children; 5854 } 5855 5856 /* 5857 * Read the performance event - simple non blocking version for now 5858 */ 5859 static ssize_t 5860 __perf_read(struct perf_event *event, char __user *buf, size_t count) 5861 { 5862 u64 read_format = event->attr.read_format; 5863 int ret; 5864 5865 /* 5866 * Return end-of-file for a read on an event that is in 5867 * error state (i.e. because it was pinned but it couldn't be 5868 * scheduled on to the CPU at some point). 5869 */ 5870 if (event->state == PERF_EVENT_STATE_ERROR) 5871 return 0; 5872 5873 if (count < event->read_size) 5874 return -ENOSPC; 5875 5876 WARN_ON_ONCE(event->ctx->parent_ctx); 5877 if (read_format & PERF_FORMAT_GROUP) 5878 ret = perf_read_group(event, read_format, buf); 5879 else 5880 ret = perf_read_one(event, read_format, buf); 5881 5882 return ret; 5883 } 5884 5885 static ssize_t 5886 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) 5887 { 5888 struct perf_event *event = file->private_data; 5889 struct perf_event_context *ctx; 5890 int ret; 5891 5892 ret = security_perf_event_read(event); 5893 if (ret) 5894 return ret; 5895 5896 ctx = perf_event_ctx_lock(event); 5897 ret = __perf_read(event, buf, count); 5898 perf_event_ctx_unlock(event, ctx); 5899 5900 return ret; 5901 } 5902 5903 static __poll_t perf_poll(struct file *file, poll_table *wait) 5904 { 5905 struct perf_event *event = file->private_data; 5906 struct perf_buffer *rb; 5907 __poll_t events = EPOLLHUP; 5908 5909 poll_wait(file, &event->waitq, wait); 5910 5911 if (is_event_hup(event)) 5912 return events; 5913 5914 /* 5915 * Pin the event->rb by taking event->mmap_mutex; otherwise 5916 * perf_event_set_output() can swizzle our rb and make us miss wakeups. 5917 */ 5918 mutex_lock(&event->mmap_mutex); 5919 rb = event->rb; 5920 if (rb) 5921 events = atomic_xchg(&rb->poll, 0); 5922 mutex_unlock(&event->mmap_mutex); 5923 return events; 5924 } 5925 5926 static void _perf_event_reset(struct perf_event *event) 5927 { 5928 (void)perf_event_read(event, false); 5929 local64_set(&event->count, 0); 5930 perf_event_update_userpage(event); 5931 } 5932 5933 /* Assume it's not an event with inherit set. */ 5934 u64 perf_event_pause(struct perf_event *event, bool reset) 5935 { 5936 struct perf_event_context *ctx; 5937 u64 count; 5938 5939 ctx = perf_event_ctx_lock(event); 5940 WARN_ON_ONCE(event->attr.inherit); 5941 _perf_event_disable(event); 5942 count = local64_read(&event->count); 5943 if (reset) 5944 local64_set(&event->count, 0); 5945 perf_event_ctx_unlock(event, ctx); 5946 5947 return count; 5948 } 5949 EXPORT_SYMBOL_GPL(perf_event_pause); 5950 5951 /* 5952 * Holding the top-level event's child_mutex means that any 5953 * descendant process that has inherited this event will block 5954 * in perf_event_exit_event() if it goes to exit, thus satisfying the 5955 * task existence requirements of perf_event_enable/disable. 5956 */ 5957 static void perf_event_for_each_child(struct perf_event *event, 5958 void (*func)(struct perf_event *)) 5959 { 5960 struct perf_event *child; 5961 5962 WARN_ON_ONCE(event->ctx->parent_ctx); 5963 5964 mutex_lock(&event->child_mutex); 5965 func(event); 5966 list_for_each_entry(child, &event->child_list, child_list) 5967 func(child); 5968 mutex_unlock(&event->child_mutex); 5969 } 5970 5971 static void perf_event_for_each(struct perf_event *event, 5972 void (*func)(struct perf_event *)) 5973 { 5974 struct perf_event_context *ctx = event->ctx; 5975 struct perf_event *sibling; 5976 5977 lockdep_assert_held(&ctx->mutex); 5978 5979 event = event->group_leader; 5980 5981 perf_event_for_each_child(event, func); 5982 for_each_sibling_event(sibling, event) 5983 perf_event_for_each_child(sibling, func); 5984 } 5985 5986 static void __perf_event_period(struct perf_event *event, 5987 struct perf_cpu_context *cpuctx, 5988 struct perf_event_context *ctx, 5989 void *info) 5990 { 5991 u64 value = *((u64 *)info); 5992 bool active; 5993 5994 if (event->attr.freq) { 5995 event->attr.sample_freq = value; 5996 } else { 5997 event->attr.sample_period = value; 5998 event->hw.sample_period = value; 5999 } 6000 6001 active = (event->state == PERF_EVENT_STATE_ACTIVE); 6002 if (active) { 6003 perf_pmu_disable(event->pmu); 6004 /* 6005 * We could be throttled; unthrottle now to avoid the tick 6006 * trying to unthrottle while we already re-started the event. 6007 */ 6008 if (event->hw.interrupts == MAX_INTERRUPTS) { 6009 event->hw.interrupts = 0; 6010 perf_log_throttle(event, 1); 6011 } 6012 event->pmu->stop(event, PERF_EF_UPDATE); 6013 } 6014 6015 local64_set(&event->hw.period_left, 0); 6016 6017 if (active) { 6018 event->pmu->start(event, PERF_EF_RELOAD); 6019 perf_pmu_enable(event->pmu); 6020 } 6021 } 6022 6023 static int perf_event_check_period(struct perf_event *event, u64 value) 6024 { 6025 return event->pmu->check_period(event, value); 6026 } 6027 6028 static int _perf_event_period(struct perf_event *event, u64 value) 6029 { 6030 if (!is_sampling_event(event)) 6031 return -EINVAL; 6032 6033 if (!value) 6034 return -EINVAL; 6035 6036 if (event->attr.freq) { 6037 if (value > sysctl_perf_event_sample_rate) 6038 return -EINVAL; 6039 } else { 6040 if (perf_event_check_period(event, value)) 6041 return -EINVAL; 6042 if (value & (1ULL << 63)) 6043 return -EINVAL; 6044 } 6045 6046 event_function_call(event, __perf_event_period, &value); 6047 6048 return 0; 6049 } 6050 6051 int perf_event_period(struct perf_event *event, u64 value) 6052 { 6053 struct perf_event_context *ctx; 6054 int ret; 6055 6056 ctx = perf_event_ctx_lock(event); 6057 ret = _perf_event_period(event, value); 6058 perf_event_ctx_unlock(event, ctx); 6059 6060 return ret; 6061 } 6062 EXPORT_SYMBOL_GPL(perf_event_period); 6063 6064 static const struct file_operations perf_fops; 6065 6066 static inline bool is_perf_file(struct fd f) 6067 { 6068 return !fd_empty(f) && fd_file(f)->f_op == &perf_fops; 6069 } 6070 6071 static int perf_event_set_output(struct perf_event *event, 6072 struct perf_event *output_event); 6073 static int perf_event_set_filter(struct perf_event *event, void __user *arg); 6074 static int perf_copy_attr(struct perf_event_attr __user *uattr, 6075 struct perf_event_attr *attr); 6076 6077 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg) 6078 { 6079 void (*func)(struct perf_event *); 6080 u32 flags = arg; 6081 6082 switch (cmd) { 6083 case PERF_EVENT_IOC_ENABLE: 6084 func = _perf_event_enable; 6085 break; 6086 case PERF_EVENT_IOC_DISABLE: 6087 func = _perf_event_disable; 6088 break; 6089 case PERF_EVENT_IOC_RESET: 6090 func = _perf_event_reset; 6091 break; 6092 6093 case PERF_EVENT_IOC_REFRESH: 6094 return _perf_event_refresh(event, arg); 6095 6096 case PERF_EVENT_IOC_PERIOD: 6097 { 6098 u64 value; 6099 6100 if (copy_from_user(&value, (u64 __user *)arg, sizeof(value))) 6101 return -EFAULT; 6102 6103 return _perf_event_period(event, value); 6104 } 6105 case PERF_EVENT_IOC_ID: 6106 { 6107 u64 id = primary_event_id(event); 6108 6109 if (copy_to_user((void __user *)arg, &id, sizeof(id))) 6110 return -EFAULT; 6111 return 0; 6112 } 6113 6114 case PERF_EVENT_IOC_SET_OUTPUT: 6115 { 6116 CLASS(fd, output)(arg); // arg == -1 => empty 6117 struct perf_event *output_event = NULL; 6118 if (arg != -1) { 6119 if (!is_perf_file(output)) 6120 return -EBADF; 6121 output_event = fd_file(output)->private_data; 6122 } 6123 return perf_event_set_output(event, output_event); 6124 } 6125 6126 case PERF_EVENT_IOC_SET_FILTER: 6127 return perf_event_set_filter(event, (void __user *)arg); 6128 6129 case PERF_EVENT_IOC_SET_BPF: 6130 { 6131 struct bpf_prog *prog; 6132 int err; 6133 6134 prog = bpf_prog_get(arg); 6135 if (IS_ERR(prog)) 6136 return PTR_ERR(prog); 6137 6138 err = perf_event_set_bpf_prog(event, prog, 0); 6139 if (err) { 6140 bpf_prog_put(prog); 6141 return err; 6142 } 6143 6144 return 0; 6145 } 6146 6147 case PERF_EVENT_IOC_PAUSE_OUTPUT: { 6148 struct perf_buffer *rb; 6149 6150 rcu_read_lock(); 6151 rb = rcu_dereference(event->rb); 6152 if (!rb || !rb->nr_pages) { 6153 rcu_read_unlock(); 6154 return -EINVAL; 6155 } 6156 rb_toggle_paused(rb, !!arg); 6157 rcu_read_unlock(); 6158 return 0; 6159 } 6160 6161 case PERF_EVENT_IOC_QUERY_BPF: 6162 return perf_event_query_prog_array(event, (void __user *)arg); 6163 6164 case PERF_EVENT_IOC_MODIFY_ATTRIBUTES: { 6165 struct perf_event_attr new_attr; 6166 int err = perf_copy_attr((struct perf_event_attr __user *)arg, 6167 &new_attr); 6168 6169 if (err) 6170 return err; 6171 6172 return perf_event_modify_attr(event, &new_attr); 6173 } 6174 default: 6175 return -ENOTTY; 6176 } 6177 6178 if (flags & PERF_IOC_FLAG_GROUP) 6179 perf_event_for_each(event, func); 6180 else 6181 perf_event_for_each_child(event, func); 6182 6183 return 0; 6184 } 6185 6186 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg) 6187 { 6188 struct perf_event *event = file->private_data; 6189 struct perf_event_context *ctx; 6190 long ret; 6191 6192 /* Treat ioctl like writes as it is likely a mutating operation. */ 6193 ret = security_perf_event_write(event); 6194 if (ret) 6195 return ret; 6196 6197 ctx = perf_event_ctx_lock(event); 6198 ret = _perf_ioctl(event, cmd, arg); 6199 perf_event_ctx_unlock(event, ctx); 6200 6201 return ret; 6202 } 6203 6204 #ifdef CONFIG_COMPAT 6205 static long perf_compat_ioctl(struct file *file, unsigned int cmd, 6206 unsigned long arg) 6207 { 6208 switch (_IOC_NR(cmd)) { 6209 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER): 6210 case _IOC_NR(PERF_EVENT_IOC_ID): 6211 case _IOC_NR(PERF_EVENT_IOC_QUERY_BPF): 6212 case _IOC_NR(PERF_EVENT_IOC_MODIFY_ATTRIBUTES): 6213 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */ 6214 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) { 6215 cmd &= ~IOCSIZE_MASK; 6216 cmd |= sizeof(void *) << IOCSIZE_SHIFT; 6217 } 6218 break; 6219 } 6220 return perf_ioctl(file, cmd, arg); 6221 } 6222 #else 6223 # define perf_compat_ioctl NULL 6224 #endif 6225 6226 int perf_event_task_enable(void) 6227 { 6228 struct perf_event_context *ctx; 6229 struct perf_event *event; 6230 6231 mutex_lock(¤t->perf_event_mutex); 6232 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) { 6233 ctx = perf_event_ctx_lock(event); 6234 perf_event_for_each_child(event, _perf_event_enable); 6235 perf_event_ctx_unlock(event, ctx); 6236 } 6237 mutex_unlock(¤t->perf_event_mutex); 6238 6239 return 0; 6240 } 6241 6242 int perf_event_task_disable(void) 6243 { 6244 struct perf_event_context *ctx; 6245 struct perf_event *event; 6246 6247 mutex_lock(¤t->perf_event_mutex); 6248 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) { 6249 ctx = perf_event_ctx_lock(event); 6250 perf_event_for_each_child(event, _perf_event_disable); 6251 perf_event_ctx_unlock(event, ctx); 6252 } 6253 mutex_unlock(¤t->perf_event_mutex); 6254 6255 return 0; 6256 } 6257 6258 static int perf_event_index(struct perf_event *event) 6259 { 6260 if (event->hw.state & PERF_HES_STOPPED) 6261 return 0; 6262 6263 if (event->state != PERF_EVENT_STATE_ACTIVE) 6264 return 0; 6265 6266 return event->pmu->event_idx(event); 6267 } 6268 6269 static void perf_event_init_userpage(struct perf_event *event) 6270 { 6271 struct perf_event_mmap_page *userpg; 6272 struct perf_buffer *rb; 6273 6274 rcu_read_lock(); 6275 rb = rcu_dereference(event->rb); 6276 if (!rb) 6277 goto unlock; 6278 6279 userpg = rb->user_page; 6280 6281 /* Allow new userspace to detect that bit 0 is deprecated */ 6282 userpg->cap_bit0_is_deprecated = 1; 6283 userpg->size = offsetof(struct perf_event_mmap_page, __reserved); 6284 userpg->data_offset = PAGE_SIZE; 6285 userpg->data_size = perf_data_size(rb); 6286 6287 unlock: 6288 rcu_read_unlock(); 6289 } 6290 6291 void __weak arch_perf_update_userpage( 6292 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now) 6293 { 6294 } 6295 6296 /* 6297 * Callers need to ensure there can be no nesting of this function, otherwise 6298 * the seqlock logic goes bad. We can not serialize this because the arch 6299 * code calls this from NMI context. 6300 */ 6301 void perf_event_update_userpage(struct perf_event *event) 6302 { 6303 struct perf_event_mmap_page *userpg; 6304 struct perf_buffer *rb; 6305 u64 enabled, running, now; 6306 6307 rcu_read_lock(); 6308 rb = rcu_dereference(event->rb); 6309 if (!rb) 6310 goto unlock; 6311 6312 /* 6313 * compute total_time_enabled, total_time_running 6314 * based on snapshot values taken when the event 6315 * was last scheduled in. 6316 * 6317 * we cannot simply called update_context_time() 6318 * because of locking issue as we can be called in 6319 * NMI context 6320 */ 6321 calc_timer_values(event, &now, &enabled, &running); 6322 6323 userpg = rb->user_page; 6324 /* 6325 * Disable preemption to guarantee consistent time stamps are stored to 6326 * the user page. 6327 */ 6328 preempt_disable(); 6329 ++userpg->lock; 6330 barrier(); 6331 userpg->index = perf_event_index(event); 6332 userpg->offset = perf_event_count(event, false); 6333 if (userpg->index) 6334 userpg->offset -= local64_read(&event->hw.prev_count); 6335 6336 userpg->time_enabled = enabled + 6337 atomic64_read(&event->child_total_time_enabled); 6338 6339 userpg->time_running = running + 6340 atomic64_read(&event->child_total_time_running); 6341 6342 arch_perf_update_userpage(event, userpg, now); 6343 6344 barrier(); 6345 ++userpg->lock; 6346 preempt_enable(); 6347 unlock: 6348 rcu_read_unlock(); 6349 } 6350 EXPORT_SYMBOL_GPL(perf_event_update_userpage); 6351 6352 static void ring_buffer_attach(struct perf_event *event, 6353 struct perf_buffer *rb) 6354 { 6355 struct perf_buffer *old_rb = NULL; 6356 unsigned long flags; 6357 6358 WARN_ON_ONCE(event->parent); 6359 6360 if (event->rb) { 6361 /* 6362 * Should be impossible, we set this when removing 6363 * event->rb_entry and wait/clear when adding event->rb_entry. 6364 */ 6365 WARN_ON_ONCE(event->rcu_pending); 6366 6367 old_rb = event->rb; 6368 spin_lock_irqsave(&old_rb->event_lock, flags); 6369 list_del_rcu(&event->rb_entry); 6370 spin_unlock_irqrestore(&old_rb->event_lock, flags); 6371 6372 event->rcu_batches = get_state_synchronize_rcu(); 6373 event->rcu_pending = 1; 6374 } 6375 6376 if (rb) { 6377 if (event->rcu_pending) { 6378 cond_synchronize_rcu(event->rcu_batches); 6379 event->rcu_pending = 0; 6380 } 6381 6382 spin_lock_irqsave(&rb->event_lock, flags); 6383 list_add_rcu(&event->rb_entry, &rb->event_list); 6384 spin_unlock_irqrestore(&rb->event_lock, flags); 6385 } 6386 6387 /* 6388 * Avoid racing with perf_mmap_close(AUX): stop the event 6389 * before swizzling the event::rb pointer; if it's getting 6390 * unmapped, its aux_mmap_count will be 0 and it won't 6391 * restart. See the comment in __perf_pmu_output_stop(). 6392 * 6393 * Data will inevitably be lost when set_output is done in 6394 * mid-air, but then again, whoever does it like this is 6395 * not in for the data anyway. 6396 */ 6397 if (has_aux(event)) 6398 perf_event_stop(event, 0); 6399 6400 rcu_assign_pointer(event->rb, rb); 6401 6402 if (old_rb) { 6403 ring_buffer_put(old_rb); 6404 /* 6405 * Since we detached before setting the new rb, so that we 6406 * could attach the new rb, we could have missed a wakeup. 6407 * Provide it now. 6408 */ 6409 wake_up_all(&event->waitq); 6410 } 6411 } 6412 6413 static void ring_buffer_wakeup(struct perf_event *event) 6414 { 6415 struct perf_buffer *rb; 6416 6417 if (event->parent) 6418 event = event->parent; 6419 6420 rcu_read_lock(); 6421 rb = rcu_dereference(event->rb); 6422 if (rb) { 6423 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) 6424 wake_up_all(&event->waitq); 6425 } 6426 rcu_read_unlock(); 6427 } 6428 6429 struct perf_buffer *ring_buffer_get(struct perf_event *event) 6430 { 6431 struct perf_buffer *rb; 6432 6433 if (event->parent) 6434 event = event->parent; 6435 6436 rcu_read_lock(); 6437 rb = rcu_dereference(event->rb); 6438 if (rb) { 6439 if (!refcount_inc_not_zero(&rb->refcount)) 6440 rb = NULL; 6441 } 6442 rcu_read_unlock(); 6443 6444 return rb; 6445 } 6446 6447 void ring_buffer_put(struct perf_buffer *rb) 6448 { 6449 if (!refcount_dec_and_test(&rb->refcount)) 6450 return; 6451 6452 WARN_ON_ONCE(!list_empty(&rb->event_list)); 6453 6454 call_rcu(&rb->rcu_head, rb_free_rcu); 6455 } 6456 6457 static void perf_mmap_open(struct vm_area_struct *vma) 6458 { 6459 struct perf_event *event = vma->vm_file->private_data; 6460 6461 atomic_inc(&event->mmap_count); 6462 atomic_inc(&event->rb->mmap_count); 6463 6464 if (vma->vm_pgoff) 6465 atomic_inc(&event->rb->aux_mmap_count); 6466 6467 if (event->pmu->event_mapped) 6468 event->pmu->event_mapped(event, vma->vm_mm); 6469 } 6470 6471 static void perf_pmu_output_stop(struct perf_event *event); 6472 6473 /* 6474 * A buffer can be mmap()ed multiple times; either directly through the same 6475 * event, or through other events by use of perf_event_set_output(). 6476 * 6477 * In order to undo the VM accounting done by perf_mmap() we need to destroy 6478 * the buffer here, where we still have a VM context. This means we need 6479 * to detach all events redirecting to us. 6480 */ 6481 static void perf_mmap_close(struct vm_area_struct *vma) 6482 { 6483 struct perf_event *event = vma->vm_file->private_data; 6484 struct perf_buffer *rb = ring_buffer_get(event); 6485 struct user_struct *mmap_user = rb->mmap_user; 6486 int mmap_locked = rb->mmap_locked; 6487 unsigned long size = perf_data_size(rb); 6488 bool detach_rest = false; 6489 6490 if (event->pmu->event_unmapped) 6491 event->pmu->event_unmapped(event, vma->vm_mm); 6492 6493 /* 6494 * The AUX buffer is strictly a sub-buffer, serialize using aux_mutex 6495 * to avoid complications. 6496 */ 6497 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff && 6498 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &rb->aux_mutex)) { 6499 /* 6500 * Stop all AUX events that are writing to this buffer, 6501 * so that we can free its AUX pages and corresponding PMU 6502 * data. Note that after rb::aux_mmap_count dropped to zero, 6503 * they won't start any more (see perf_aux_output_begin()). 6504 */ 6505 perf_pmu_output_stop(event); 6506 6507 /* now it's safe to free the pages */ 6508 atomic_long_sub(rb->aux_nr_pages - rb->aux_mmap_locked, &mmap_user->locked_vm); 6509 atomic64_sub(rb->aux_mmap_locked, &vma->vm_mm->pinned_vm); 6510 6511 /* this has to be the last one */ 6512 rb_free_aux(rb); 6513 WARN_ON_ONCE(refcount_read(&rb->aux_refcount)); 6514 6515 mutex_unlock(&rb->aux_mutex); 6516 } 6517 6518 if (atomic_dec_and_test(&rb->mmap_count)) 6519 detach_rest = true; 6520 6521 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex)) 6522 goto out_put; 6523 6524 ring_buffer_attach(event, NULL); 6525 mutex_unlock(&event->mmap_mutex); 6526 6527 /* If there's still other mmap()s of this buffer, we're done. */ 6528 if (!detach_rest) 6529 goto out_put; 6530 6531 /* 6532 * No other mmap()s, detach from all other events that might redirect 6533 * into the now unreachable buffer. Somewhat complicated by the 6534 * fact that rb::event_lock otherwise nests inside mmap_mutex. 6535 */ 6536 again: 6537 rcu_read_lock(); 6538 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) { 6539 if (!atomic_long_inc_not_zero(&event->refcount)) { 6540 /* 6541 * This event is en-route to free_event() which will 6542 * detach it and remove it from the list. 6543 */ 6544 continue; 6545 } 6546 rcu_read_unlock(); 6547 6548 mutex_lock(&event->mmap_mutex); 6549 /* 6550 * Check we didn't race with perf_event_set_output() which can 6551 * swizzle the rb from under us while we were waiting to 6552 * acquire mmap_mutex. 6553 * 6554 * If we find a different rb; ignore this event, a next 6555 * iteration will no longer find it on the list. We have to 6556 * still restart the iteration to make sure we're not now 6557 * iterating the wrong list. 6558 */ 6559 if (event->rb == rb) 6560 ring_buffer_attach(event, NULL); 6561 6562 mutex_unlock(&event->mmap_mutex); 6563 put_event(event); 6564 6565 /* 6566 * Restart the iteration; either we're on the wrong list or 6567 * destroyed its integrity by doing a deletion. 6568 */ 6569 goto again; 6570 } 6571 rcu_read_unlock(); 6572 6573 /* 6574 * It could be there's still a few 0-ref events on the list; they'll 6575 * get cleaned up by free_event() -- they'll also still have their 6576 * ref on the rb and will free it whenever they are done with it. 6577 * 6578 * Aside from that, this buffer is 'fully' detached and unmapped, 6579 * undo the VM accounting. 6580 */ 6581 6582 atomic_long_sub((size >> PAGE_SHIFT) + 1 - mmap_locked, 6583 &mmap_user->locked_vm); 6584 atomic64_sub(mmap_locked, &vma->vm_mm->pinned_vm); 6585 free_uid(mmap_user); 6586 6587 out_put: 6588 ring_buffer_put(rb); /* could be last */ 6589 } 6590 6591 static vm_fault_t perf_mmap_pfn_mkwrite(struct vm_fault *vmf) 6592 { 6593 /* The first page is the user control page, others are read-only. */ 6594 return vmf->pgoff == 0 ? 0 : VM_FAULT_SIGBUS; 6595 } 6596 6597 static const struct vm_operations_struct perf_mmap_vmops = { 6598 .open = perf_mmap_open, 6599 .close = perf_mmap_close, /* non mergeable */ 6600 .pfn_mkwrite = perf_mmap_pfn_mkwrite, 6601 }; 6602 6603 static int map_range(struct perf_buffer *rb, struct vm_area_struct *vma) 6604 { 6605 unsigned long nr_pages = vma_pages(vma); 6606 int err = 0; 6607 unsigned long pagenum; 6608 6609 /* 6610 * We map this as a VM_PFNMAP VMA. 6611 * 6612 * This is not ideal as this is designed broadly for mappings of PFNs 6613 * referencing memory-mapped I/O ranges or non-system RAM i.e. for which 6614 * !pfn_valid(pfn). 6615 * 6616 * We are mapping kernel-allocated memory (memory we manage ourselves) 6617 * which would more ideally be mapped using vm_insert_page() or a 6618 * similar mechanism, that is as a VM_MIXEDMAP mapping. 6619 * 6620 * However this won't work here, because: 6621 * 6622 * 1. It uses vma->vm_page_prot, but this field has not been completely 6623 * setup at the point of the f_op->mmp() hook, so we are unable to 6624 * indicate that this should be mapped CoW in order that the 6625 * mkwrite() hook can be invoked to make the first page R/W and the 6626 * rest R/O as desired. 6627 * 6628 * 2. Anything other than a VM_PFNMAP of valid PFNs will result in 6629 * vm_normal_page() returning a struct page * pointer, which means 6630 * vm_ops->page_mkwrite() will be invoked rather than 6631 * vm_ops->pfn_mkwrite(), and this means we have to set page->mapping 6632 * to work around retry logic in the fault handler, however this 6633 * field is no longer allowed to be used within struct page. 6634 * 6635 * 3. Having a struct page * made available in the fault logic also 6636 * means that the page gets put on the rmap and becomes 6637 * inappropriately accessible and subject to map and ref counting. 6638 * 6639 * Ideally we would have a mechanism that could explicitly express our 6640 * desires, but this is not currently the case, so we instead use 6641 * VM_PFNMAP. 6642 * 6643 * We manage the lifetime of these mappings with internal refcounts (see 6644 * perf_mmap_open() and perf_mmap_close()) so we ensure the lifetime of 6645 * this mapping is maintained correctly. 6646 */ 6647 for (pagenum = 0; pagenum < nr_pages; pagenum++) { 6648 unsigned long va = vma->vm_start + PAGE_SIZE * pagenum; 6649 struct page *page = perf_mmap_to_page(rb, vma->vm_pgoff + pagenum); 6650 6651 if (page == NULL) { 6652 err = -EINVAL; 6653 break; 6654 } 6655 6656 /* Map readonly, perf_mmap_pfn_mkwrite() called on write fault. */ 6657 err = remap_pfn_range(vma, va, page_to_pfn(page), PAGE_SIZE, 6658 vm_get_page_prot(vma->vm_flags & ~VM_SHARED)); 6659 if (err) 6660 break; 6661 } 6662 6663 #ifdef CONFIG_MMU 6664 /* Clear any partial mappings on error. */ 6665 if (err) 6666 zap_page_range_single(vma, vma->vm_start, nr_pages * PAGE_SIZE, NULL); 6667 #endif 6668 6669 return err; 6670 } 6671 6672 static int perf_mmap(struct file *file, struct vm_area_struct *vma) 6673 { 6674 struct perf_event *event = file->private_data; 6675 unsigned long user_locked, user_lock_limit; 6676 struct user_struct *user = current_user(); 6677 struct mutex *aux_mutex = NULL; 6678 struct perf_buffer *rb = NULL; 6679 unsigned long locked, lock_limit; 6680 unsigned long vma_size; 6681 unsigned long nr_pages; 6682 long user_extra = 0, extra = 0; 6683 int ret = 0, flags = 0; 6684 6685 /* 6686 * Don't allow mmap() of inherited per-task counters. This would 6687 * create a performance issue due to all children writing to the 6688 * same rb. 6689 */ 6690 if (event->cpu == -1 && event->attr.inherit) 6691 return -EINVAL; 6692 6693 if (!(vma->vm_flags & VM_SHARED)) 6694 return -EINVAL; 6695 6696 ret = security_perf_event_read(event); 6697 if (ret) 6698 return ret; 6699 6700 vma_size = vma->vm_end - vma->vm_start; 6701 nr_pages = vma_size / PAGE_SIZE; 6702 6703 if (nr_pages > INT_MAX) 6704 return -ENOMEM; 6705 6706 if (vma_size != PAGE_SIZE * nr_pages) 6707 return -EINVAL; 6708 6709 user_extra = nr_pages; 6710 6711 if (vma->vm_pgoff == 0) { 6712 nr_pages -= 1; 6713 6714 /* 6715 * If we have rb pages ensure they're a power-of-two number, so we 6716 * can do bitmasks instead of modulo. 6717 */ 6718 if (nr_pages != 0 && !is_power_of_2(nr_pages)) 6719 return -EINVAL; 6720 6721 WARN_ON_ONCE(event->ctx->parent_ctx); 6722 mutex_lock(&event->mmap_mutex); 6723 6724 if (event->rb) { 6725 if (data_page_nr(event->rb) != nr_pages) { 6726 ret = -EINVAL; 6727 goto unlock; 6728 } 6729 6730 if (atomic_inc_not_zero(&event->rb->mmap_count)) { 6731 /* 6732 * Success -- managed to mmap() the same buffer 6733 * multiple times. 6734 */ 6735 ret = 0; 6736 /* We need the rb to map pages. */ 6737 rb = event->rb; 6738 goto unlock; 6739 } 6740 6741 /* 6742 * Raced against perf_mmap_close()'s 6743 * atomic_dec_and_mutex_lock() remove the 6744 * event and continue as if !event->rb 6745 */ 6746 ring_buffer_attach(event, NULL); 6747 } 6748 6749 } else { 6750 /* 6751 * AUX area mapping: if rb->aux_nr_pages != 0, it's already 6752 * mapped, all subsequent mappings should have the same size 6753 * and offset. Must be above the normal perf buffer. 6754 */ 6755 u64 aux_offset, aux_size; 6756 6757 if (!event->rb) 6758 return -EINVAL; 6759 6760 mutex_lock(&event->mmap_mutex); 6761 ret = -EINVAL; 6762 6763 rb = event->rb; 6764 if (!rb) 6765 goto aux_unlock; 6766 6767 aux_mutex = &rb->aux_mutex; 6768 mutex_lock(aux_mutex); 6769 6770 aux_offset = READ_ONCE(rb->user_page->aux_offset); 6771 aux_size = READ_ONCE(rb->user_page->aux_size); 6772 6773 if (aux_offset < perf_data_size(rb) + PAGE_SIZE) 6774 goto aux_unlock; 6775 6776 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT) 6777 goto aux_unlock; 6778 6779 /* already mapped with a different offset */ 6780 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff) 6781 goto aux_unlock; 6782 6783 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE) 6784 goto aux_unlock; 6785 6786 /* already mapped with a different size */ 6787 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages) 6788 goto aux_unlock; 6789 6790 if (!is_power_of_2(nr_pages)) 6791 goto aux_unlock; 6792 6793 if (!atomic_inc_not_zero(&rb->mmap_count)) 6794 goto aux_unlock; 6795 6796 if (rb_has_aux(rb)) { 6797 atomic_inc(&rb->aux_mmap_count); 6798 ret = 0; 6799 goto unlock; 6800 } 6801 6802 atomic_set(&rb->aux_mmap_count, 1); 6803 } 6804 6805 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10); 6806 6807 /* 6808 * Increase the limit linearly with more CPUs: 6809 */ 6810 user_lock_limit *= num_online_cpus(); 6811 6812 user_locked = atomic_long_read(&user->locked_vm); 6813 6814 /* 6815 * sysctl_perf_event_mlock may have changed, so that 6816 * user->locked_vm > user_lock_limit 6817 */ 6818 if (user_locked > user_lock_limit) 6819 user_locked = user_lock_limit; 6820 user_locked += user_extra; 6821 6822 if (user_locked > user_lock_limit) { 6823 /* 6824 * charge locked_vm until it hits user_lock_limit; 6825 * charge the rest from pinned_vm 6826 */ 6827 extra = user_locked - user_lock_limit; 6828 user_extra -= extra; 6829 } 6830 6831 lock_limit = rlimit(RLIMIT_MEMLOCK); 6832 lock_limit >>= PAGE_SHIFT; 6833 locked = atomic64_read(&vma->vm_mm->pinned_vm) + extra; 6834 6835 if ((locked > lock_limit) && perf_is_paranoid() && 6836 !capable(CAP_IPC_LOCK)) { 6837 ret = -EPERM; 6838 goto unlock; 6839 } 6840 6841 WARN_ON(!rb && event->rb); 6842 6843 if (vma->vm_flags & VM_WRITE) 6844 flags |= RING_BUFFER_WRITABLE; 6845 6846 if (!rb) { 6847 rb = rb_alloc(nr_pages, 6848 event->attr.watermark ? event->attr.wakeup_watermark : 0, 6849 event->cpu, flags); 6850 6851 if (!rb) { 6852 ret = -ENOMEM; 6853 goto unlock; 6854 } 6855 6856 atomic_set(&rb->mmap_count, 1); 6857 rb->mmap_user = get_current_user(); 6858 rb->mmap_locked = extra; 6859 6860 ring_buffer_attach(event, rb); 6861 6862 perf_event_update_time(event); 6863 perf_event_init_userpage(event); 6864 perf_event_update_userpage(event); 6865 } else { 6866 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages, 6867 event->attr.aux_watermark, flags); 6868 if (!ret) 6869 rb->aux_mmap_locked = extra; 6870 } 6871 6872 unlock: 6873 if (!ret) { 6874 atomic_long_add(user_extra, &user->locked_vm); 6875 atomic64_add(extra, &vma->vm_mm->pinned_vm); 6876 6877 atomic_inc(&event->mmap_count); 6878 } else if (rb) { 6879 atomic_dec(&rb->mmap_count); 6880 } 6881 aux_unlock: 6882 if (aux_mutex) 6883 mutex_unlock(aux_mutex); 6884 mutex_unlock(&event->mmap_mutex); 6885 6886 /* 6887 * Since pinned accounting is per vm we cannot allow fork() to copy our 6888 * vma. 6889 */ 6890 vm_flags_set(vma, VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP); 6891 vma->vm_ops = &perf_mmap_vmops; 6892 6893 if (!ret) 6894 ret = map_range(rb, vma); 6895 6896 if (event->pmu->event_mapped) 6897 event->pmu->event_mapped(event, vma->vm_mm); 6898 6899 return ret; 6900 } 6901 6902 static int perf_fasync(int fd, struct file *filp, int on) 6903 { 6904 struct inode *inode = file_inode(filp); 6905 struct perf_event *event = filp->private_data; 6906 int retval; 6907 6908 inode_lock(inode); 6909 retval = fasync_helper(fd, filp, on, &event->fasync); 6910 inode_unlock(inode); 6911 6912 if (retval < 0) 6913 return retval; 6914 6915 return 0; 6916 } 6917 6918 static const struct file_operations perf_fops = { 6919 .release = perf_release, 6920 .read = perf_read, 6921 .poll = perf_poll, 6922 .unlocked_ioctl = perf_ioctl, 6923 .compat_ioctl = perf_compat_ioctl, 6924 .mmap = perf_mmap, 6925 .fasync = perf_fasync, 6926 }; 6927 6928 /* 6929 * Perf event wakeup 6930 * 6931 * If there's data, ensure we set the poll() state and publish everything 6932 * to user-space before waking everybody up. 6933 */ 6934 6935 void perf_event_wakeup(struct perf_event *event) 6936 { 6937 ring_buffer_wakeup(event); 6938 6939 if (event->pending_kill) { 6940 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill); 6941 event->pending_kill = 0; 6942 } 6943 } 6944 6945 static void perf_sigtrap(struct perf_event *event) 6946 { 6947 /* 6948 * We'd expect this to only occur if the irq_work is delayed and either 6949 * ctx->task or current has changed in the meantime. This can be the 6950 * case on architectures that do not implement arch_irq_work_raise(). 6951 */ 6952 if (WARN_ON_ONCE(event->ctx->task != current)) 6953 return; 6954 6955 /* 6956 * Both perf_pending_task() and perf_pending_irq() can race with the 6957 * task exiting. 6958 */ 6959 if (current->flags & PF_EXITING) 6960 return; 6961 6962 send_sig_perf((void __user *)event->pending_addr, 6963 event->orig_type, event->attr.sig_data); 6964 } 6965 6966 /* 6967 * Deliver the pending work in-event-context or follow the context. 6968 */ 6969 static void __perf_pending_disable(struct perf_event *event) 6970 { 6971 int cpu = READ_ONCE(event->oncpu); 6972 6973 /* 6974 * If the event isn't running; we done. event_sched_out() will have 6975 * taken care of things. 6976 */ 6977 if (cpu < 0) 6978 return; 6979 6980 /* 6981 * Yay, we hit home and are in the context of the event. 6982 */ 6983 if (cpu == smp_processor_id()) { 6984 if (event->pending_disable) { 6985 event->pending_disable = 0; 6986 perf_event_disable_local(event); 6987 } 6988 return; 6989 } 6990 6991 /* 6992 * CPU-A CPU-B 6993 * 6994 * perf_event_disable_inatomic() 6995 * @pending_disable = CPU-A; 6996 * irq_work_queue(); 6997 * 6998 * sched-out 6999 * @pending_disable = -1; 7000 * 7001 * sched-in 7002 * perf_event_disable_inatomic() 7003 * @pending_disable = CPU-B; 7004 * irq_work_queue(); // FAILS 7005 * 7006 * irq_work_run() 7007 * perf_pending_disable() 7008 * 7009 * But the event runs on CPU-B and wants disabling there. 7010 */ 7011 irq_work_queue_on(&event->pending_disable_irq, cpu); 7012 } 7013 7014 static void perf_pending_disable(struct irq_work *entry) 7015 { 7016 struct perf_event *event = container_of(entry, struct perf_event, pending_disable_irq); 7017 int rctx; 7018 7019 /* 7020 * If we 'fail' here, that's OK, it means recursion is already disabled 7021 * and we won't recurse 'further'. 7022 */ 7023 rctx = perf_swevent_get_recursion_context(); 7024 __perf_pending_disable(event); 7025 if (rctx >= 0) 7026 perf_swevent_put_recursion_context(rctx); 7027 } 7028 7029 static void perf_pending_irq(struct irq_work *entry) 7030 { 7031 struct perf_event *event = container_of(entry, struct perf_event, pending_irq); 7032 int rctx; 7033 7034 /* 7035 * If we 'fail' here, that's OK, it means recursion is already disabled 7036 * and we won't recurse 'further'. 7037 */ 7038 rctx = perf_swevent_get_recursion_context(); 7039 7040 /* 7041 * The wakeup isn't bound to the context of the event -- it can happen 7042 * irrespective of where the event is. 7043 */ 7044 if (event->pending_wakeup) { 7045 event->pending_wakeup = 0; 7046 perf_event_wakeup(event); 7047 } 7048 7049 if (rctx >= 0) 7050 perf_swevent_put_recursion_context(rctx); 7051 } 7052 7053 static void perf_pending_task(struct callback_head *head) 7054 { 7055 struct perf_event *event = container_of(head, struct perf_event, pending_task); 7056 int rctx; 7057 7058 /* 7059 * All accesses to the event must belong to the same implicit RCU read-side 7060 * critical section as the ->pending_work reset. See comment in 7061 * perf_pending_task_sync(). 7062 */ 7063 rcu_read_lock(); 7064 /* 7065 * If we 'fail' here, that's OK, it means recursion is already disabled 7066 * and we won't recurse 'further'. 7067 */ 7068 rctx = perf_swevent_get_recursion_context(); 7069 7070 if (event->pending_work) { 7071 event->pending_work = 0; 7072 perf_sigtrap(event); 7073 local_dec(&event->ctx->nr_no_switch_fast); 7074 rcuwait_wake_up(&event->pending_work_wait); 7075 } 7076 rcu_read_unlock(); 7077 7078 if (rctx >= 0) 7079 perf_swevent_put_recursion_context(rctx); 7080 } 7081 7082 #ifdef CONFIG_GUEST_PERF_EVENTS 7083 struct perf_guest_info_callbacks __rcu *perf_guest_cbs; 7084 7085 DEFINE_STATIC_CALL_RET0(__perf_guest_state, *perf_guest_cbs->state); 7086 DEFINE_STATIC_CALL_RET0(__perf_guest_get_ip, *perf_guest_cbs->get_ip); 7087 DEFINE_STATIC_CALL_RET0(__perf_guest_handle_intel_pt_intr, *perf_guest_cbs->handle_intel_pt_intr); 7088 7089 void perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs) 7090 { 7091 if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs))) 7092 return; 7093 7094 rcu_assign_pointer(perf_guest_cbs, cbs); 7095 static_call_update(__perf_guest_state, cbs->state); 7096 static_call_update(__perf_guest_get_ip, cbs->get_ip); 7097 7098 /* Implementing ->handle_intel_pt_intr is optional. */ 7099 if (cbs->handle_intel_pt_intr) 7100 static_call_update(__perf_guest_handle_intel_pt_intr, 7101 cbs->handle_intel_pt_intr); 7102 } 7103 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks); 7104 7105 void perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs) 7106 { 7107 if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs) != cbs)) 7108 return; 7109 7110 rcu_assign_pointer(perf_guest_cbs, NULL); 7111 static_call_update(__perf_guest_state, (void *)&__static_call_return0); 7112 static_call_update(__perf_guest_get_ip, (void *)&__static_call_return0); 7113 static_call_update(__perf_guest_handle_intel_pt_intr, 7114 (void *)&__static_call_return0); 7115 synchronize_rcu(); 7116 } 7117 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks); 7118 #endif 7119 7120 static bool should_sample_guest(struct perf_event *event) 7121 { 7122 return !event->attr.exclude_guest && perf_guest_state(); 7123 } 7124 7125 unsigned long perf_misc_flags(struct perf_event *event, 7126 struct pt_regs *regs) 7127 { 7128 if (should_sample_guest(event)) 7129 return perf_arch_guest_misc_flags(regs); 7130 7131 return perf_arch_misc_flags(regs); 7132 } 7133 7134 unsigned long perf_instruction_pointer(struct perf_event *event, 7135 struct pt_regs *regs) 7136 { 7137 if (should_sample_guest(event)) 7138 return perf_guest_get_ip(); 7139 7140 return perf_arch_instruction_pointer(regs); 7141 } 7142 7143 static void 7144 perf_output_sample_regs(struct perf_output_handle *handle, 7145 struct pt_regs *regs, u64 mask) 7146 { 7147 int bit; 7148 DECLARE_BITMAP(_mask, 64); 7149 7150 bitmap_from_u64(_mask, mask); 7151 for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) { 7152 u64 val; 7153 7154 val = perf_reg_value(regs, bit); 7155 perf_output_put(handle, val); 7156 } 7157 } 7158 7159 static void perf_sample_regs_user(struct perf_regs *regs_user, 7160 struct pt_regs *regs) 7161 { 7162 if (user_mode(regs)) { 7163 regs_user->abi = perf_reg_abi(current); 7164 regs_user->regs = regs; 7165 } else if (!(current->flags & PF_KTHREAD)) { 7166 perf_get_regs_user(regs_user, regs); 7167 } else { 7168 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE; 7169 regs_user->regs = NULL; 7170 } 7171 } 7172 7173 static void perf_sample_regs_intr(struct perf_regs *regs_intr, 7174 struct pt_regs *regs) 7175 { 7176 regs_intr->regs = regs; 7177 regs_intr->abi = perf_reg_abi(current); 7178 } 7179 7180 7181 /* 7182 * Get remaining task size from user stack pointer. 7183 * 7184 * It'd be better to take stack vma map and limit this more 7185 * precisely, but there's no way to get it safely under interrupt, 7186 * so using TASK_SIZE as limit. 7187 */ 7188 static u64 perf_ustack_task_size(struct pt_regs *regs) 7189 { 7190 unsigned long addr = perf_user_stack_pointer(regs); 7191 7192 if (!addr || addr >= TASK_SIZE) 7193 return 0; 7194 7195 return TASK_SIZE - addr; 7196 } 7197 7198 static u16 7199 perf_sample_ustack_size(u16 stack_size, u16 header_size, 7200 struct pt_regs *regs) 7201 { 7202 u64 task_size; 7203 7204 /* No regs, no stack pointer, no dump. */ 7205 if (!regs) 7206 return 0; 7207 7208 /* 7209 * Check if we fit in with the requested stack size into the: 7210 * - TASK_SIZE 7211 * If we don't, we limit the size to the TASK_SIZE. 7212 * 7213 * - remaining sample size 7214 * If we don't, we customize the stack size to 7215 * fit in to the remaining sample size. 7216 */ 7217 7218 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs)); 7219 stack_size = min(stack_size, (u16) task_size); 7220 7221 /* Current header size plus static size and dynamic size. */ 7222 header_size += 2 * sizeof(u64); 7223 7224 /* Do we fit in with the current stack dump size? */ 7225 if ((u16) (header_size + stack_size) < header_size) { 7226 /* 7227 * If we overflow the maximum size for the sample, 7228 * we customize the stack dump size to fit in. 7229 */ 7230 stack_size = USHRT_MAX - header_size - sizeof(u64); 7231 stack_size = round_up(stack_size, sizeof(u64)); 7232 } 7233 7234 return stack_size; 7235 } 7236 7237 static void 7238 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size, 7239 struct pt_regs *regs) 7240 { 7241 /* Case of a kernel thread, nothing to dump */ 7242 if (!regs) { 7243 u64 size = 0; 7244 perf_output_put(handle, size); 7245 } else { 7246 unsigned long sp; 7247 unsigned int rem; 7248 u64 dyn_size; 7249 7250 /* 7251 * We dump: 7252 * static size 7253 * - the size requested by user or the best one we can fit 7254 * in to the sample max size 7255 * data 7256 * - user stack dump data 7257 * dynamic size 7258 * - the actual dumped size 7259 */ 7260 7261 /* Static size. */ 7262 perf_output_put(handle, dump_size); 7263 7264 /* Data. */ 7265 sp = perf_user_stack_pointer(regs); 7266 rem = __output_copy_user(handle, (void *) sp, dump_size); 7267 dyn_size = dump_size - rem; 7268 7269 perf_output_skip(handle, rem); 7270 7271 /* Dynamic size. */ 7272 perf_output_put(handle, dyn_size); 7273 } 7274 } 7275 7276 static unsigned long perf_prepare_sample_aux(struct perf_event *event, 7277 struct perf_sample_data *data, 7278 size_t size) 7279 { 7280 struct perf_event *sampler = event->aux_event; 7281 struct perf_buffer *rb; 7282 7283 data->aux_size = 0; 7284 7285 if (!sampler) 7286 goto out; 7287 7288 if (WARN_ON_ONCE(READ_ONCE(sampler->state) != PERF_EVENT_STATE_ACTIVE)) 7289 goto out; 7290 7291 if (WARN_ON_ONCE(READ_ONCE(sampler->oncpu) != smp_processor_id())) 7292 goto out; 7293 7294 rb = ring_buffer_get(sampler); 7295 if (!rb) 7296 goto out; 7297 7298 /* 7299 * If this is an NMI hit inside sampling code, don't take 7300 * the sample. See also perf_aux_sample_output(). 7301 */ 7302 if (READ_ONCE(rb->aux_in_sampling)) { 7303 data->aux_size = 0; 7304 } else { 7305 size = min_t(size_t, size, perf_aux_size(rb)); 7306 data->aux_size = ALIGN(size, sizeof(u64)); 7307 } 7308 ring_buffer_put(rb); 7309 7310 out: 7311 return data->aux_size; 7312 } 7313 7314 static long perf_pmu_snapshot_aux(struct perf_buffer *rb, 7315 struct perf_event *event, 7316 struct perf_output_handle *handle, 7317 unsigned long size) 7318 { 7319 unsigned long flags; 7320 long ret; 7321 7322 /* 7323 * Normal ->start()/->stop() callbacks run in IRQ mode in scheduler 7324 * paths. If we start calling them in NMI context, they may race with 7325 * the IRQ ones, that is, for example, re-starting an event that's just 7326 * been stopped, which is why we're using a separate callback that 7327 * doesn't change the event state. 7328 * 7329 * IRQs need to be disabled to prevent IPIs from racing with us. 7330 */ 7331 local_irq_save(flags); 7332 /* 7333 * Guard against NMI hits inside the critical section; 7334 * see also perf_prepare_sample_aux(). 7335 */ 7336 WRITE_ONCE(rb->aux_in_sampling, 1); 7337 barrier(); 7338 7339 ret = event->pmu->snapshot_aux(event, handle, size); 7340 7341 barrier(); 7342 WRITE_ONCE(rb->aux_in_sampling, 0); 7343 local_irq_restore(flags); 7344 7345 return ret; 7346 } 7347 7348 static void perf_aux_sample_output(struct perf_event *event, 7349 struct perf_output_handle *handle, 7350 struct perf_sample_data *data) 7351 { 7352 struct perf_event *sampler = event->aux_event; 7353 struct perf_buffer *rb; 7354 unsigned long pad; 7355 long size; 7356 7357 if (WARN_ON_ONCE(!sampler || !data->aux_size)) 7358 return; 7359 7360 rb = ring_buffer_get(sampler); 7361 if (!rb) 7362 return; 7363 7364 size = perf_pmu_snapshot_aux(rb, sampler, handle, data->aux_size); 7365 7366 /* 7367 * An error here means that perf_output_copy() failed (returned a 7368 * non-zero surplus that it didn't copy), which in its current 7369 * enlightened implementation is not possible. If that changes, we'd 7370 * like to know. 7371 */ 7372 if (WARN_ON_ONCE(size < 0)) 7373 goto out_put; 7374 7375 /* 7376 * The pad comes from ALIGN()ing data->aux_size up to u64 in 7377 * perf_prepare_sample_aux(), so should not be more than that. 7378 */ 7379 pad = data->aux_size - size; 7380 if (WARN_ON_ONCE(pad >= sizeof(u64))) 7381 pad = 8; 7382 7383 if (pad) { 7384 u64 zero = 0; 7385 perf_output_copy(handle, &zero, pad); 7386 } 7387 7388 out_put: 7389 ring_buffer_put(rb); 7390 } 7391 7392 /* 7393 * A set of common sample data types saved even for non-sample records 7394 * when event->attr.sample_id_all is set. 7395 */ 7396 #define PERF_SAMPLE_ID_ALL (PERF_SAMPLE_TID | PERF_SAMPLE_TIME | \ 7397 PERF_SAMPLE_ID | PERF_SAMPLE_STREAM_ID | \ 7398 PERF_SAMPLE_CPU | PERF_SAMPLE_IDENTIFIER) 7399 7400 static void __perf_event_header__init_id(struct perf_sample_data *data, 7401 struct perf_event *event, 7402 u64 sample_type) 7403 { 7404 data->type = event->attr.sample_type; 7405 data->sample_flags |= data->type & PERF_SAMPLE_ID_ALL; 7406 7407 if (sample_type & PERF_SAMPLE_TID) { 7408 /* namespace issues */ 7409 data->tid_entry.pid = perf_event_pid(event, current); 7410 data->tid_entry.tid = perf_event_tid(event, current); 7411 } 7412 7413 if (sample_type & PERF_SAMPLE_TIME) 7414 data->time = perf_event_clock(event); 7415 7416 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER)) 7417 data->id = primary_event_id(event); 7418 7419 if (sample_type & PERF_SAMPLE_STREAM_ID) 7420 data->stream_id = event->id; 7421 7422 if (sample_type & PERF_SAMPLE_CPU) { 7423 data->cpu_entry.cpu = raw_smp_processor_id(); 7424 data->cpu_entry.reserved = 0; 7425 } 7426 } 7427 7428 void perf_event_header__init_id(struct perf_event_header *header, 7429 struct perf_sample_data *data, 7430 struct perf_event *event) 7431 { 7432 if (event->attr.sample_id_all) { 7433 header->size += event->id_header_size; 7434 __perf_event_header__init_id(data, event, event->attr.sample_type); 7435 } 7436 } 7437 7438 static void __perf_event__output_id_sample(struct perf_output_handle *handle, 7439 struct perf_sample_data *data) 7440 { 7441 u64 sample_type = data->type; 7442 7443 if (sample_type & PERF_SAMPLE_TID) 7444 perf_output_put(handle, data->tid_entry); 7445 7446 if (sample_type & PERF_SAMPLE_TIME) 7447 perf_output_put(handle, data->time); 7448 7449 if (sample_type & PERF_SAMPLE_ID) 7450 perf_output_put(handle, data->id); 7451 7452 if (sample_type & PERF_SAMPLE_STREAM_ID) 7453 perf_output_put(handle, data->stream_id); 7454 7455 if (sample_type & PERF_SAMPLE_CPU) 7456 perf_output_put(handle, data->cpu_entry); 7457 7458 if (sample_type & PERF_SAMPLE_IDENTIFIER) 7459 perf_output_put(handle, data->id); 7460 } 7461 7462 void perf_event__output_id_sample(struct perf_event *event, 7463 struct perf_output_handle *handle, 7464 struct perf_sample_data *sample) 7465 { 7466 if (event->attr.sample_id_all) 7467 __perf_event__output_id_sample(handle, sample); 7468 } 7469 7470 static void perf_output_read_one(struct perf_output_handle *handle, 7471 struct perf_event *event, 7472 u64 enabled, u64 running) 7473 { 7474 u64 read_format = event->attr.read_format; 7475 u64 values[5]; 7476 int n = 0; 7477 7478 values[n++] = perf_event_count(event, has_inherit_and_sample_read(&event->attr)); 7479 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) { 7480 values[n++] = enabled + 7481 atomic64_read(&event->child_total_time_enabled); 7482 } 7483 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) { 7484 values[n++] = running + 7485 atomic64_read(&event->child_total_time_running); 7486 } 7487 if (read_format & PERF_FORMAT_ID) 7488 values[n++] = primary_event_id(event); 7489 if (read_format & PERF_FORMAT_LOST) 7490 values[n++] = atomic64_read(&event->lost_samples); 7491 7492 __output_copy(handle, values, n * sizeof(u64)); 7493 } 7494 7495 static void perf_output_read_group(struct perf_output_handle *handle, 7496 struct perf_event *event, 7497 u64 enabled, u64 running) 7498 { 7499 struct perf_event *leader = event->group_leader, *sub; 7500 u64 read_format = event->attr.read_format; 7501 unsigned long flags; 7502 u64 values[6]; 7503 int n = 0; 7504 bool self = has_inherit_and_sample_read(&event->attr); 7505 7506 /* 7507 * Disabling interrupts avoids all counter scheduling 7508 * (context switches, timer based rotation and IPIs). 7509 */ 7510 local_irq_save(flags); 7511 7512 values[n++] = 1 + leader->nr_siblings; 7513 7514 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) 7515 values[n++] = enabled; 7516 7517 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) 7518 values[n++] = running; 7519 7520 if ((leader != event) && !handle->skip_read) 7521 perf_pmu_read(leader); 7522 7523 values[n++] = perf_event_count(leader, self); 7524 if (read_format & PERF_FORMAT_ID) 7525 values[n++] = primary_event_id(leader); 7526 if (read_format & PERF_FORMAT_LOST) 7527 values[n++] = atomic64_read(&leader->lost_samples); 7528 7529 __output_copy(handle, values, n * sizeof(u64)); 7530 7531 for_each_sibling_event(sub, leader) { 7532 n = 0; 7533 7534 if ((sub != event) && !handle->skip_read) 7535 perf_pmu_read(sub); 7536 7537 values[n++] = perf_event_count(sub, self); 7538 if (read_format & PERF_FORMAT_ID) 7539 values[n++] = primary_event_id(sub); 7540 if (read_format & PERF_FORMAT_LOST) 7541 values[n++] = atomic64_read(&sub->lost_samples); 7542 7543 __output_copy(handle, values, n * sizeof(u64)); 7544 } 7545 7546 local_irq_restore(flags); 7547 } 7548 7549 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\ 7550 PERF_FORMAT_TOTAL_TIME_RUNNING) 7551 7552 /* 7553 * XXX PERF_SAMPLE_READ vs inherited events seems difficult. 7554 * 7555 * The problem is that its both hard and excessively expensive to iterate the 7556 * child list, not to mention that its impossible to IPI the children running 7557 * on another CPU, from interrupt/NMI context. 7558 * 7559 * Instead the combination of PERF_SAMPLE_READ and inherit will track per-thread 7560 * counts rather than attempting to accumulate some value across all children on 7561 * all cores. 7562 */ 7563 static void perf_output_read(struct perf_output_handle *handle, 7564 struct perf_event *event) 7565 { 7566 u64 enabled = 0, running = 0, now; 7567 u64 read_format = event->attr.read_format; 7568 7569 /* 7570 * compute total_time_enabled, total_time_running 7571 * based on snapshot values taken when the event 7572 * was last scheduled in. 7573 * 7574 * we cannot simply called update_context_time() 7575 * because of locking issue as we are called in 7576 * NMI context 7577 */ 7578 if (read_format & PERF_FORMAT_TOTAL_TIMES) 7579 calc_timer_values(event, &now, &enabled, &running); 7580 7581 if (event->attr.read_format & PERF_FORMAT_GROUP) 7582 perf_output_read_group(handle, event, enabled, running); 7583 else 7584 perf_output_read_one(handle, event, enabled, running); 7585 } 7586 7587 void perf_output_sample(struct perf_output_handle *handle, 7588 struct perf_event_header *header, 7589 struct perf_sample_data *data, 7590 struct perf_event *event) 7591 { 7592 u64 sample_type = data->type; 7593 7594 if (data->sample_flags & PERF_SAMPLE_READ) 7595 handle->skip_read = 1; 7596 7597 perf_output_put(handle, *header); 7598 7599 if (sample_type & PERF_SAMPLE_IDENTIFIER) 7600 perf_output_put(handle, data->id); 7601 7602 if (sample_type & PERF_SAMPLE_IP) 7603 perf_output_put(handle, data->ip); 7604 7605 if (sample_type & PERF_SAMPLE_TID) 7606 perf_output_put(handle, data->tid_entry); 7607 7608 if (sample_type & PERF_SAMPLE_TIME) 7609 perf_output_put(handle, data->time); 7610 7611 if (sample_type & PERF_SAMPLE_ADDR) 7612 perf_output_put(handle, data->addr); 7613 7614 if (sample_type & PERF_SAMPLE_ID) 7615 perf_output_put(handle, data->id); 7616 7617 if (sample_type & PERF_SAMPLE_STREAM_ID) 7618 perf_output_put(handle, data->stream_id); 7619 7620 if (sample_type & PERF_SAMPLE_CPU) 7621 perf_output_put(handle, data->cpu_entry); 7622 7623 if (sample_type & PERF_SAMPLE_PERIOD) 7624 perf_output_put(handle, data->period); 7625 7626 if (sample_type & PERF_SAMPLE_READ) 7627 perf_output_read(handle, event); 7628 7629 if (sample_type & PERF_SAMPLE_CALLCHAIN) { 7630 int size = 1; 7631 7632 size += data->callchain->nr; 7633 size *= sizeof(u64); 7634 __output_copy(handle, data->callchain, size); 7635 } 7636 7637 if (sample_type & PERF_SAMPLE_RAW) { 7638 struct perf_raw_record *raw = data->raw; 7639 7640 if (raw) { 7641 struct perf_raw_frag *frag = &raw->frag; 7642 7643 perf_output_put(handle, raw->size); 7644 do { 7645 if (frag->copy) { 7646 __output_custom(handle, frag->copy, 7647 frag->data, frag->size); 7648 } else { 7649 __output_copy(handle, frag->data, 7650 frag->size); 7651 } 7652 if (perf_raw_frag_last(frag)) 7653 break; 7654 frag = frag->next; 7655 } while (1); 7656 if (frag->pad) 7657 __output_skip(handle, NULL, frag->pad); 7658 } else { 7659 struct { 7660 u32 size; 7661 u32 data; 7662 } raw = { 7663 .size = sizeof(u32), 7664 .data = 0, 7665 }; 7666 perf_output_put(handle, raw); 7667 } 7668 } 7669 7670 if (sample_type & PERF_SAMPLE_BRANCH_STACK) { 7671 if (data->br_stack) { 7672 size_t size; 7673 7674 size = data->br_stack->nr 7675 * sizeof(struct perf_branch_entry); 7676 7677 perf_output_put(handle, data->br_stack->nr); 7678 if (branch_sample_hw_index(event)) 7679 perf_output_put(handle, data->br_stack->hw_idx); 7680 perf_output_copy(handle, data->br_stack->entries, size); 7681 /* 7682 * Add the extension space which is appended 7683 * right after the struct perf_branch_stack. 7684 */ 7685 if (data->br_stack_cntr) { 7686 size = data->br_stack->nr * sizeof(u64); 7687 perf_output_copy(handle, data->br_stack_cntr, size); 7688 } 7689 } else { 7690 /* 7691 * we always store at least the value of nr 7692 */ 7693 u64 nr = 0; 7694 perf_output_put(handle, nr); 7695 } 7696 } 7697 7698 if (sample_type & PERF_SAMPLE_REGS_USER) { 7699 u64 abi = data->regs_user.abi; 7700 7701 /* 7702 * If there are no regs to dump, notice it through 7703 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE). 7704 */ 7705 perf_output_put(handle, abi); 7706 7707 if (abi) { 7708 u64 mask = event->attr.sample_regs_user; 7709 perf_output_sample_regs(handle, 7710 data->regs_user.regs, 7711 mask); 7712 } 7713 } 7714 7715 if (sample_type & PERF_SAMPLE_STACK_USER) { 7716 perf_output_sample_ustack(handle, 7717 data->stack_user_size, 7718 data->regs_user.regs); 7719 } 7720 7721 if (sample_type & PERF_SAMPLE_WEIGHT_TYPE) 7722 perf_output_put(handle, data->weight.full); 7723 7724 if (sample_type & PERF_SAMPLE_DATA_SRC) 7725 perf_output_put(handle, data->data_src.val); 7726 7727 if (sample_type & PERF_SAMPLE_TRANSACTION) 7728 perf_output_put(handle, data->txn); 7729 7730 if (sample_type & PERF_SAMPLE_REGS_INTR) { 7731 u64 abi = data->regs_intr.abi; 7732 /* 7733 * If there are no regs to dump, notice it through 7734 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE). 7735 */ 7736 perf_output_put(handle, abi); 7737 7738 if (abi) { 7739 u64 mask = event->attr.sample_regs_intr; 7740 7741 perf_output_sample_regs(handle, 7742 data->regs_intr.regs, 7743 mask); 7744 } 7745 } 7746 7747 if (sample_type & PERF_SAMPLE_PHYS_ADDR) 7748 perf_output_put(handle, data->phys_addr); 7749 7750 if (sample_type & PERF_SAMPLE_CGROUP) 7751 perf_output_put(handle, data->cgroup); 7752 7753 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE) 7754 perf_output_put(handle, data->data_page_size); 7755 7756 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE) 7757 perf_output_put(handle, data->code_page_size); 7758 7759 if (sample_type & PERF_SAMPLE_AUX) { 7760 perf_output_put(handle, data->aux_size); 7761 7762 if (data->aux_size) 7763 perf_aux_sample_output(event, handle, data); 7764 } 7765 7766 if (!event->attr.watermark) { 7767 int wakeup_events = event->attr.wakeup_events; 7768 7769 if (wakeup_events) { 7770 struct perf_buffer *rb = handle->rb; 7771 int events = local_inc_return(&rb->events); 7772 7773 if (events >= wakeup_events) { 7774 local_sub(wakeup_events, &rb->events); 7775 local_inc(&rb->wakeup); 7776 } 7777 } 7778 } 7779 } 7780 7781 static u64 perf_virt_to_phys(u64 virt) 7782 { 7783 u64 phys_addr = 0; 7784 7785 if (!virt) 7786 return 0; 7787 7788 if (virt >= TASK_SIZE) { 7789 /* If it's vmalloc()d memory, leave phys_addr as 0 */ 7790 if (virt_addr_valid((void *)(uintptr_t)virt) && 7791 !(virt >= VMALLOC_START && virt < VMALLOC_END)) 7792 phys_addr = (u64)virt_to_phys((void *)(uintptr_t)virt); 7793 } else { 7794 /* 7795 * Walking the pages tables for user address. 7796 * Interrupts are disabled, so it prevents any tear down 7797 * of the page tables. 7798 * Try IRQ-safe get_user_page_fast_only first. 7799 * If failed, leave phys_addr as 0. 7800 */ 7801 if (current->mm != NULL) { 7802 struct page *p; 7803 7804 pagefault_disable(); 7805 if (get_user_page_fast_only(virt, 0, &p)) { 7806 phys_addr = page_to_phys(p) + virt % PAGE_SIZE; 7807 put_page(p); 7808 } 7809 pagefault_enable(); 7810 } 7811 } 7812 7813 return phys_addr; 7814 } 7815 7816 /* 7817 * Return the pagetable size of a given virtual address. 7818 */ 7819 static u64 perf_get_pgtable_size(struct mm_struct *mm, unsigned long addr) 7820 { 7821 u64 size = 0; 7822 7823 #ifdef CONFIG_HAVE_GUP_FAST 7824 pgd_t *pgdp, pgd; 7825 p4d_t *p4dp, p4d; 7826 pud_t *pudp, pud; 7827 pmd_t *pmdp, pmd; 7828 pte_t *ptep, pte; 7829 7830 pgdp = pgd_offset(mm, addr); 7831 pgd = READ_ONCE(*pgdp); 7832 if (pgd_none(pgd)) 7833 return 0; 7834 7835 if (pgd_leaf(pgd)) 7836 return pgd_leaf_size(pgd); 7837 7838 p4dp = p4d_offset_lockless(pgdp, pgd, addr); 7839 p4d = READ_ONCE(*p4dp); 7840 if (!p4d_present(p4d)) 7841 return 0; 7842 7843 if (p4d_leaf(p4d)) 7844 return p4d_leaf_size(p4d); 7845 7846 pudp = pud_offset_lockless(p4dp, p4d, addr); 7847 pud = READ_ONCE(*pudp); 7848 if (!pud_present(pud)) 7849 return 0; 7850 7851 if (pud_leaf(pud)) 7852 return pud_leaf_size(pud); 7853 7854 pmdp = pmd_offset_lockless(pudp, pud, addr); 7855 again: 7856 pmd = pmdp_get_lockless(pmdp); 7857 if (!pmd_present(pmd)) 7858 return 0; 7859 7860 if (pmd_leaf(pmd)) 7861 return pmd_leaf_size(pmd); 7862 7863 ptep = pte_offset_map(&pmd, addr); 7864 if (!ptep) 7865 goto again; 7866 7867 pte = ptep_get_lockless(ptep); 7868 if (pte_present(pte)) 7869 size = __pte_leaf_size(pmd, pte); 7870 pte_unmap(ptep); 7871 #endif /* CONFIG_HAVE_GUP_FAST */ 7872 7873 return size; 7874 } 7875 7876 static u64 perf_get_page_size(unsigned long addr) 7877 { 7878 struct mm_struct *mm; 7879 unsigned long flags; 7880 u64 size; 7881 7882 if (!addr) 7883 return 0; 7884 7885 /* 7886 * Software page-table walkers must disable IRQs, 7887 * which prevents any tear down of the page tables. 7888 */ 7889 local_irq_save(flags); 7890 7891 mm = current->mm; 7892 if (!mm) { 7893 /* 7894 * For kernel threads and the like, use init_mm so that 7895 * we can find kernel memory. 7896 */ 7897 mm = &init_mm; 7898 } 7899 7900 size = perf_get_pgtable_size(mm, addr); 7901 7902 local_irq_restore(flags); 7903 7904 return size; 7905 } 7906 7907 static struct perf_callchain_entry __empty_callchain = { .nr = 0, }; 7908 7909 struct perf_callchain_entry * 7910 perf_callchain(struct perf_event *event, struct pt_regs *regs) 7911 { 7912 bool kernel = !event->attr.exclude_callchain_kernel; 7913 bool user = !event->attr.exclude_callchain_user; 7914 /* Disallow cross-task user callchains. */ 7915 bool crosstask = event->ctx->task && event->ctx->task != current; 7916 const u32 max_stack = event->attr.sample_max_stack; 7917 struct perf_callchain_entry *callchain; 7918 7919 if (!kernel && !user) 7920 return &__empty_callchain; 7921 7922 callchain = get_perf_callchain(regs, 0, kernel, user, 7923 max_stack, crosstask, true); 7924 return callchain ?: &__empty_callchain; 7925 } 7926 7927 static __always_inline u64 __cond_set(u64 flags, u64 s, u64 d) 7928 { 7929 return d * !!(flags & s); 7930 } 7931 7932 void perf_prepare_sample(struct perf_sample_data *data, 7933 struct perf_event *event, 7934 struct pt_regs *regs) 7935 { 7936 u64 sample_type = event->attr.sample_type; 7937 u64 filtered_sample_type; 7938 7939 /* 7940 * Add the sample flags that are dependent to others. And clear the 7941 * sample flags that have already been done by the PMU driver. 7942 */ 7943 filtered_sample_type = sample_type; 7944 filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_CODE_PAGE_SIZE, 7945 PERF_SAMPLE_IP); 7946 filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_DATA_PAGE_SIZE | 7947 PERF_SAMPLE_PHYS_ADDR, PERF_SAMPLE_ADDR); 7948 filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_STACK_USER, 7949 PERF_SAMPLE_REGS_USER); 7950 filtered_sample_type &= ~data->sample_flags; 7951 7952 if (filtered_sample_type == 0) { 7953 /* Make sure it has the correct data->type for output */ 7954 data->type = event->attr.sample_type; 7955 return; 7956 } 7957 7958 __perf_event_header__init_id(data, event, filtered_sample_type); 7959 7960 if (filtered_sample_type & PERF_SAMPLE_IP) { 7961 data->ip = perf_instruction_pointer(event, regs); 7962 data->sample_flags |= PERF_SAMPLE_IP; 7963 } 7964 7965 if (filtered_sample_type & PERF_SAMPLE_CALLCHAIN) 7966 perf_sample_save_callchain(data, event, regs); 7967 7968 if (filtered_sample_type & PERF_SAMPLE_RAW) { 7969 data->raw = NULL; 7970 data->dyn_size += sizeof(u64); 7971 data->sample_flags |= PERF_SAMPLE_RAW; 7972 } 7973 7974 if (filtered_sample_type & PERF_SAMPLE_BRANCH_STACK) { 7975 data->br_stack = NULL; 7976 data->dyn_size += sizeof(u64); 7977 data->sample_flags |= PERF_SAMPLE_BRANCH_STACK; 7978 } 7979 7980 if (filtered_sample_type & PERF_SAMPLE_REGS_USER) 7981 perf_sample_regs_user(&data->regs_user, regs); 7982 7983 /* 7984 * It cannot use the filtered_sample_type here as REGS_USER can be set 7985 * by STACK_USER (using __cond_set() above) and we don't want to update 7986 * the dyn_size if it's not requested by users. 7987 */ 7988 if ((sample_type & ~data->sample_flags) & PERF_SAMPLE_REGS_USER) { 7989 /* regs dump ABI info */ 7990 int size = sizeof(u64); 7991 7992 if (data->regs_user.regs) { 7993 u64 mask = event->attr.sample_regs_user; 7994 size += hweight64(mask) * sizeof(u64); 7995 } 7996 7997 data->dyn_size += size; 7998 data->sample_flags |= PERF_SAMPLE_REGS_USER; 7999 } 8000 8001 if (filtered_sample_type & PERF_SAMPLE_STACK_USER) { 8002 /* 8003 * Either we need PERF_SAMPLE_STACK_USER bit to be always 8004 * processed as the last one or have additional check added 8005 * in case new sample type is added, because we could eat 8006 * up the rest of the sample size. 8007 */ 8008 u16 stack_size = event->attr.sample_stack_user; 8009 u16 header_size = perf_sample_data_size(data, event); 8010 u16 size = sizeof(u64); 8011 8012 stack_size = perf_sample_ustack_size(stack_size, header_size, 8013 data->regs_user.regs); 8014 8015 /* 8016 * If there is something to dump, add space for the dump 8017 * itself and for the field that tells the dynamic size, 8018 * which is how many have been actually dumped. 8019 */ 8020 if (stack_size) 8021 size += sizeof(u64) + stack_size; 8022 8023 data->stack_user_size = stack_size; 8024 data->dyn_size += size; 8025 data->sample_flags |= PERF_SAMPLE_STACK_USER; 8026 } 8027 8028 if (filtered_sample_type & PERF_SAMPLE_WEIGHT_TYPE) { 8029 data->weight.full = 0; 8030 data->sample_flags |= PERF_SAMPLE_WEIGHT_TYPE; 8031 } 8032 8033 if (filtered_sample_type & PERF_SAMPLE_DATA_SRC) { 8034 data->data_src.val = PERF_MEM_NA; 8035 data->sample_flags |= PERF_SAMPLE_DATA_SRC; 8036 } 8037 8038 if (filtered_sample_type & PERF_SAMPLE_TRANSACTION) { 8039 data->txn = 0; 8040 data->sample_flags |= PERF_SAMPLE_TRANSACTION; 8041 } 8042 8043 if (filtered_sample_type & PERF_SAMPLE_ADDR) { 8044 data->addr = 0; 8045 data->sample_flags |= PERF_SAMPLE_ADDR; 8046 } 8047 8048 if (filtered_sample_type & PERF_SAMPLE_REGS_INTR) { 8049 /* regs dump ABI info */ 8050 int size = sizeof(u64); 8051 8052 perf_sample_regs_intr(&data->regs_intr, regs); 8053 8054 if (data->regs_intr.regs) { 8055 u64 mask = event->attr.sample_regs_intr; 8056 8057 size += hweight64(mask) * sizeof(u64); 8058 } 8059 8060 data->dyn_size += size; 8061 data->sample_flags |= PERF_SAMPLE_REGS_INTR; 8062 } 8063 8064 if (filtered_sample_type & PERF_SAMPLE_PHYS_ADDR) { 8065 data->phys_addr = perf_virt_to_phys(data->addr); 8066 data->sample_flags |= PERF_SAMPLE_PHYS_ADDR; 8067 } 8068 8069 #ifdef CONFIG_CGROUP_PERF 8070 if (filtered_sample_type & PERF_SAMPLE_CGROUP) { 8071 struct cgroup *cgrp; 8072 8073 /* protected by RCU */ 8074 cgrp = task_css_check(current, perf_event_cgrp_id, 1)->cgroup; 8075 data->cgroup = cgroup_id(cgrp); 8076 data->sample_flags |= PERF_SAMPLE_CGROUP; 8077 } 8078 #endif 8079 8080 /* 8081 * PERF_DATA_PAGE_SIZE requires PERF_SAMPLE_ADDR. If the user doesn't 8082 * require PERF_SAMPLE_ADDR, kernel implicitly retrieve the data->addr, 8083 * but the value will not dump to the userspace. 8084 */ 8085 if (filtered_sample_type & PERF_SAMPLE_DATA_PAGE_SIZE) { 8086 data->data_page_size = perf_get_page_size(data->addr); 8087 data->sample_flags |= PERF_SAMPLE_DATA_PAGE_SIZE; 8088 } 8089 8090 if (filtered_sample_type & PERF_SAMPLE_CODE_PAGE_SIZE) { 8091 data->code_page_size = perf_get_page_size(data->ip); 8092 data->sample_flags |= PERF_SAMPLE_CODE_PAGE_SIZE; 8093 } 8094 8095 if (filtered_sample_type & PERF_SAMPLE_AUX) { 8096 u64 size; 8097 u16 header_size = perf_sample_data_size(data, event); 8098 8099 header_size += sizeof(u64); /* size */ 8100 8101 /* 8102 * Given the 16bit nature of header::size, an AUX sample can 8103 * easily overflow it, what with all the preceding sample bits. 8104 * Make sure this doesn't happen by using up to U16_MAX bytes 8105 * per sample in total (rounded down to 8 byte boundary). 8106 */ 8107 size = min_t(size_t, U16_MAX - header_size, 8108 event->attr.aux_sample_size); 8109 size = rounddown(size, 8); 8110 size = perf_prepare_sample_aux(event, data, size); 8111 8112 WARN_ON_ONCE(size + header_size > U16_MAX); 8113 data->dyn_size += size + sizeof(u64); /* size above */ 8114 data->sample_flags |= PERF_SAMPLE_AUX; 8115 } 8116 } 8117 8118 void perf_prepare_header(struct perf_event_header *header, 8119 struct perf_sample_data *data, 8120 struct perf_event *event, 8121 struct pt_regs *regs) 8122 { 8123 header->type = PERF_RECORD_SAMPLE; 8124 header->size = perf_sample_data_size(data, event); 8125 header->misc = perf_misc_flags(event, regs); 8126 8127 /* 8128 * If you're adding more sample types here, you likely need to do 8129 * something about the overflowing header::size, like repurpose the 8130 * lowest 3 bits of size, which should be always zero at the moment. 8131 * This raises a more important question, do we really need 512k sized 8132 * samples and why, so good argumentation is in order for whatever you 8133 * do here next. 8134 */ 8135 WARN_ON_ONCE(header->size & 7); 8136 } 8137 8138 static void __perf_event_aux_pause(struct perf_event *event, bool pause) 8139 { 8140 if (pause) { 8141 if (!event->hw.aux_paused) { 8142 event->hw.aux_paused = 1; 8143 event->pmu->stop(event, PERF_EF_PAUSE); 8144 } 8145 } else { 8146 if (event->hw.aux_paused) { 8147 event->hw.aux_paused = 0; 8148 event->pmu->start(event, PERF_EF_RESUME); 8149 } 8150 } 8151 } 8152 8153 static void perf_event_aux_pause(struct perf_event *event, bool pause) 8154 { 8155 struct perf_buffer *rb; 8156 8157 if (WARN_ON_ONCE(!event)) 8158 return; 8159 8160 rb = ring_buffer_get(event); 8161 if (!rb) 8162 return; 8163 8164 scoped_guard (irqsave) { 8165 /* 8166 * Guard against self-recursion here. Another event could trip 8167 * this same from NMI context. 8168 */ 8169 if (READ_ONCE(rb->aux_in_pause_resume)) 8170 break; 8171 8172 WRITE_ONCE(rb->aux_in_pause_resume, 1); 8173 barrier(); 8174 __perf_event_aux_pause(event, pause); 8175 barrier(); 8176 WRITE_ONCE(rb->aux_in_pause_resume, 0); 8177 } 8178 ring_buffer_put(rb); 8179 } 8180 8181 static __always_inline int 8182 __perf_event_output(struct perf_event *event, 8183 struct perf_sample_data *data, 8184 struct pt_regs *regs, 8185 int (*output_begin)(struct perf_output_handle *, 8186 struct perf_sample_data *, 8187 struct perf_event *, 8188 unsigned int)) 8189 { 8190 struct perf_output_handle handle; 8191 struct perf_event_header header; 8192 int err; 8193 8194 /* protect the callchain buffers */ 8195 rcu_read_lock(); 8196 8197 perf_prepare_sample(data, event, regs); 8198 perf_prepare_header(&header, data, event, regs); 8199 8200 err = output_begin(&handle, data, event, header.size); 8201 if (err) 8202 goto exit; 8203 8204 perf_output_sample(&handle, &header, data, event); 8205 8206 perf_output_end(&handle); 8207 8208 exit: 8209 rcu_read_unlock(); 8210 return err; 8211 } 8212 8213 void 8214 perf_event_output_forward(struct perf_event *event, 8215 struct perf_sample_data *data, 8216 struct pt_regs *regs) 8217 { 8218 __perf_event_output(event, data, regs, perf_output_begin_forward); 8219 } 8220 8221 void 8222 perf_event_output_backward(struct perf_event *event, 8223 struct perf_sample_data *data, 8224 struct pt_regs *regs) 8225 { 8226 __perf_event_output(event, data, regs, perf_output_begin_backward); 8227 } 8228 8229 int 8230 perf_event_output(struct perf_event *event, 8231 struct perf_sample_data *data, 8232 struct pt_regs *regs) 8233 { 8234 return __perf_event_output(event, data, regs, perf_output_begin); 8235 } 8236 8237 /* 8238 * read event_id 8239 */ 8240 8241 struct perf_read_event { 8242 struct perf_event_header header; 8243 8244 u32 pid; 8245 u32 tid; 8246 }; 8247 8248 static void 8249 perf_event_read_event(struct perf_event *event, 8250 struct task_struct *task) 8251 { 8252 struct perf_output_handle handle; 8253 struct perf_sample_data sample; 8254 struct perf_read_event read_event = { 8255 .header = { 8256 .type = PERF_RECORD_READ, 8257 .misc = 0, 8258 .size = sizeof(read_event) + event->read_size, 8259 }, 8260 .pid = perf_event_pid(event, task), 8261 .tid = perf_event_tid(event, task), 8262 }; 8263 int ret; 8264 8265 perf_event_header__init_id(&read_event.header, &sample, event); 8266 ret = perf_output_begin(&handle, &sample, event, read_event.header.size); 8267 if (ret) 8268 return; 8269 8270 perf_output_put(&handle, read_event); 8271 perf_output_read(&handle, event); 8272 perf_event__output_id_sample(event, &handle, &sample); 8273 8274 perf_output_end(&handle); 8275 } 8276 8277 typedef void (perf_iterate_f)(struct perf_event *event, void *data); 8278 8279 static void 8280 perf_iterate_ctx(struct perf_event_context *ctx, 8281 perf_iterate_f output, 8282 void *data, bool all) 8283 { 8284 struct perf_event *event; 8285 8286 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) { 8287 if (!all) { 8288 if (event->state < PERF_EVENT_STATE_INACTIVE) 8289 continue; 8290 if (!event_filter_match(event)) 8291 continue; 8292 } 8293 8294 output(event, data); 8295 } 8296 } 8297 8298 static void perf_iterate_sb_cpu(perf_iterate_f output, void *data) 8299 { 8300 struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events); 8301 struct perf_event *event; 8302 8303 list_for_each_entry_rcu(event, &pel->list, sb_list) { 8304 /* 8305 * Skip events that are not fully formed yet; ensure that 8306 * if we observe event->ctx, both event and ctx will be 8307 * complete enough. See perf_install_in_context(). 8308 */ 8309 if (!smp_load_acquire(&event->ctx)) 8310 continue; 8311 8312 if (event->state < PERF_EVENT_STATE_INACTIVE) 8313 continue; 8314 if (!event_filter_match(event)) 8315 continue; 8316 output(event, data); 8317 } 8318 } 8319 8320 /* 8321 * Iterate all events that need to receive side-band events. 8322 * 8323 * For new callers; ensure that account_pmu_sb_event() includes 8324 * your event, otherwise it might not get delivered. 8325 */ 8326 static void 8327 perf_iterate_sb(perf_iterate_f output, void *data, 8328 struct perf_event_context *task_ctx) 8329 { 8330 struct perf_event_context *ctx; 8331 8332 rcu_read_lock(); 8333 preempt_disable(); 8334 8335 /* 8336 * If we have task_ctx != NULL we only notify the task context itself. 8337 * The task_ctx is set only for EXIT events before releasing task 8338 * context. 8339 */ 8340 if (task_ctx) { 8341 perf_iterate_ctx(task_ctx, output, data, false); 8342 goto done; 8343 } 8344 8345 perf_iterate_sb_cpu(output, data); 8346 8347 ctx = rcu_dereference(current->perf_event_ctxp); 8348 if (ctx) 8349 perf_iterate_ctx(ctx, output, data, false); 8350 done: 8351 preempt_enable(); 8352 rcu_read_unlock(); 8353 } 8354 8355 /* 8356 * Clear all file-based filters at exec, they'll have to be 8357 * re-instated when/if these objects are mmapped again. 8358 */ 8359 static void perf_event_addr_filters_exec(struct perf_event *event, void *data) 8360 { 8361 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event); 8362 struct perf_addr_filter *filter; 8363 unsigned int restart = 0, count = 0; 8364 unsigned long flags; 8365 8366 if (!has_addr_filter(event)) 8367 return; 8368 8369 raw_spin_lock_irqsave(&ifh->lock, flags); 8370 list_for_each_entry(filter, &ifh->list, entry) { 8371 if (filter->path.dentry) { 8372 event->addr_filter_ranges[count].start = 0; 8373 event->addr_filter_ranges[count].size = 0; 8374 restart++; 8375 } 8376 8377 count++; 8378 } 8379 8380 if (restart) 8381 event->addr_filters_gen++; 8382 raw_spin_unlock_irqrestore(&ifh->lock, flags); 8383 8384 if (restart) 8385 perf_event_stop(event, 1); 8386 } 8387 8388 void perf_event_exec(void) 8389 { 8390 struct perf_event_context *ctx; 8391 8392 ctx = perf_pin_task_context(current); 8393 if (!ctx) 8394 return; 8395 8396 perf_event_enable_on_exec(ctx); 8397 perf_event_remove_on_exec(ctx); 8398 scoped_guard(rcu) 8399 perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL, true); 8400 8401 perf_unpin_context(ctx); 8402 put_ctx(ctx); 8403 } 8404 8405 struct remote_output { 8406 struct perf_buffer *rb; 8407 int err; 8408 }; 8409 8410 static void __perf_event_output_stop(struct perf_event *event, void *data) 8411 { 8412 struct perf_event *parent = event->parent; 8413 struct remote_output *ro = data; 8414 struct perf_buffer *rb = ro->rb; 8415 struct stop_event_data sd = { 8416 .event = event, 8417 }; 8418 8419 if (!has_aux(event)) 8420 return; 8421 8422 if (!parent) 8423 parent = event; 8424 8425 /* 8426 * In case of inheritance, it will be the parent that links to the 8427 * ring-buffer, but it will be the child that's actually using it. 8428 * 8429 * We are using event::rb to determine if the event should be stopped, 8430 * however this may race with ring_buffer_attach() (through set_output), 8431 * which will make us skip the event that actually needs to be stopped. 8432 * So ring_buffer_attach() has to stop an aux event before re-assigning 8433 * its rb pointer. 8434 */ 8435 if (rcu_dereference(parent->rb) == rb) 8436 ro->err = __perf_event_stop(&sd); 8437 } 8438 8439 static int __perf_pmu_output_stop(void *info) 8440 { 8441 struct perf_event *event = info; 8442 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 8443 struct remote_output ro = { 8444 .rb = event->rb, 8445 }; 8446 8447 rcu_read_lock(); 8448 perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false); 8449 if (cpuctx->task_ctx) 8450 perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop, 8451 &ro, false); 8452 rcu_read_unlock(); 8453 8454 return ro.err; 8455 } 8456 8457 static void perf_pmu_output_stop(struct perf_event *event) 8458 { 8459 struct perf_event *iter; 8460 int err, cpu; 8461 8462 restart: 8463 rcu_read_lock(); 8464 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) { 8465 /* 8466 * For per-CPU events, we need to make sure that neither they 8467 * nor their children are running; for cpu==-1 events it's 8468 * sufficient to stop the event itself if it's active, since 8469 * it can't have children. 8470 */ 8471 cpu = iter->cpu; 8472 if (cpu == -1) 8473 cpu = READ_ONCE(iter->oncpu); 8474 8475 if (cpu == -1) 8476 continue; 8477 8478 err = cpu_function_call(cpu, __perf_pmu_output_stop, event); 8479 if (err == -EAGAIN) { 8480 rcu_read_unlock(); 8481 goto restart; 8482 } 8483 } 8484 rcu_read_unlock(); 8485 } 8486 8487 /* 8488 * task tracking -- fork/exit 8489 * 8490 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task 8491 */ 8492 8493 struct perf_task_event { 8494 struct task_struct *task; 8495 struct perf_event_context *task_ctx; 8496 8497 struct { 8498 struct perf_event_header header; 8499 8500 u32 pid; 8501 u32 ppid; 8502 u32 tid; 8503 u32 ptid; 8504 u64 time; 8505 } event_id; 8506 }; 8507 8508 static int perf_event_task_match(struct perf_event *event) 8509 { 8510 return event->attr.comm || event->attr.mmap || 8511 event->attr.mmap2 || event->attr.mmap_data || 8512 event->attr.task; 8513 } 8514 8515 static void perf_event_task_output(struct perf_event *event, 8516 void *data) 8517 { 8518 struct perf_task_event *task_event = data; 8519 struct perf_output_handle handle; 8520 struct perf_sample_data sample; 8521 struct task_struct *task = task_event->task; 8522 int ret, size = task_event->event_id.header.size; 8523 8524 if (!perf_event_task_match(event)) 8525 return; 8526 8527 perf_event_header__init_id(&task_event->event_id.header, &sample, event); 8528 8529 ret = perf_output_begin(&handle, &sample, event, 8530 task_event->event_id.header.size); 8531 if (ret) 8532 goto out; 8533 8534 task_event->event_id.pid = perf_event_pid(event, task); 8535 task_event->event_id.tid = perf_event_tid(event, task); 8536 8537 if (task_event->event_id.header.type == PERF_RECORD_EXIT) { 8538 task_event->event_id.ppid = perf_event_pid(event, 8539 task->real_parent); 8540 task_event->event_id.ptid = perf_event_pid(event, 8541 task->real_parent); 8542 } else { /* PERF_RECORD_FORK */ 8543 task_event->event_id.ppid = perf_event_pid(event, current); 8544 task_event->event_id.ptid = perf_event_tid(event, current); 8545 } 8546 8547 task_event->event_id.time = perf_event_clock(event); 8548 8549 perf_output_put(&handle, task_event->event_id); 8550 8551 perf_event__output_id_sample(event, &handle, &sample); 8552 8553 perf_output_end(&handle); 8554 out: 8555 task_event->event_id.header.size = size; 8556 } 8557 8558 static void perf_event_task(struct task_struct *task, 8559 struct perf_event_context *task_ctx, 8560 int new) 8561 { 8562 struct perf_task_event task_event; 8563 8564 if (!atomic_read(&nr_comm_events) && 8565 !atomic_read(&nr_mmap_events) && 8566 !atomic_read(&nr_task_events)) 8567 return; 8568 8569 task_event = (struct perf_task_event){ 8570 .task = task, 8571 .task_ctx = task_ctx, 8572 .event_id = { 8573 .header = { 8574 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT, 8575 .misc = 0, 8576 .size = sizeof(task_event.event_id), 8577 }, 8578 /* .pid */ 8579 /* .ppid */ 8580 /* .tid */ 8581 /* .ptid */ 8582 /* .time */ 8583 }, 8584 }; 8585 8586 perf_iterate_sb(perf_event_task_output, 8587 &task_event, 8588 task_ctx); 8589 } 8590 8591 void perf_event_fork(struct task_struct *task) 8592 { 8593 perf_event_task(task, NULL, 1); 8594 perf_event_namespaces(task); 8595 } 8596 8597 /* 8598 * comm tracking 8599 */ 8600 8601 struct perf_comm_event { 8602 struct task_struct *task; 8603 char *comm; 8604 int comm_size; 8605 8606 struct { 8607 struct perf_event_header header; 8608 8609 u32 pid; 8610 u32 tid; 8611 } event_id; 8612 }; 8613 8614 static int perf_event_comm_match(struct perf_event *event) 8615 { 8616 return event->attr.comm; 8617 } 8618 8619 static void perf_event_comm_output(struct perf_event *event, 8620 void *data) 8621 { 8622 struct perf_comm_event *comm_event = data; 8623 struct perf_output_handle handle; 8624 struct perf_sample_data sample; 8625 int size = comm_event->event_id.header.size; 8626 int ret; 8627 8628 if (!perf_event_comm_match(event)) 8629 return; 8630 8631 perf_event_header__init_id(&comm_event->event_id.header, &sample, event); 8632 ret = perf_output_begin(&handle, &sample, event, 8633 comm_event->event_id.header.size); 8634 8635 if (ret) 8636 goto out; 8637 8638 comm_event->event_id.pid = perf_event_pid(event, comm_event->task); 8639 comm_event->event_id.tid = perf_event_tid(event, comm_event->task); 8640 8641 perf_output_put(&handle, comm_event->event_id); 8642 __output_copy(&handle, comm_event->comm, 8643 comm_event->comm_size); 8644 8645 perf_event__output_id_sample(event, &handle, &sample); 8646 8647 perf_output_end(&handle); 8648 out: 8649 comm_event->event_id.header.size = size; 8650 } 8651 8652 static void perf_event_comm_event(struct perf_comm_event *comm_event) 8653 { 8654 char comm[TASK_COMM_LEN]; 8655 unsigned int size; 8656 8657 memset(comm, 0, sizeof(comm)); 8658 strscpy(comm, comm_event->task->comm, sizeof(comm)); 8659 size = ALIGN(strlen(comm)+1, sizeof(u64)); 8660 8661 comm_event->comm = comm; 8662 comm_event->comm_size = size; 8663 8664 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size; 8665 8666 perf_iterate_sb(perf_event_comm_output, 8667 comm_event, 8668 NULL); 8669 } 8670 8671 void perf_event_comm(struct task_struct *task, bool exec) 8672 { 8673 struct perf_comm_event comm_event; 8674 8675 if (!atomic_read(&nr_comm_events)) 8676 return; 8677 8678 comm_event = (struct perf_comm_event){ 8679 .task = task, 8680 /* .comm */ 8681 /* .comm_size */ 8682 .event_id = { 8683 .header = { 8684 .type = PERF_RECORD_COMM, 8685 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0, 8686 /* .size */ 8687 }, 8688 /* .pid */ 8689 /* .tid */ 8690 }, 8691 }; 8692 8693 perf_event_comm_event(&comm_event); 8694 } 8695 8696 /* 8697 * namespaces tracking 8698 */ 8699 8700 struct perf_namespaces_event { 8701 struct task_struct *task; 8702 8703 struct { 8704 struct perf_event_header header; 8705 8706 u32 pid; 8707 u32 tid; 8708 u64 nr_namespaces; 8709 struct perf_ns_link_info link_info[NR_NAMESPACES]; 8710 } event_id; 8711 }; 8712 8713 static int perf_event_namespaces_match(struct perf_event *event) 8714 { 8715 return event->attr.namespaces; 8716 } 8717 8718 static void perf_event_namespaces_output(struct perf_event *event, 8719 void *data) 8720 { 8721 struct perf_namespaces_event *namespaces_event = data; 8722 struct perf_output_handle handle; 8723 struct perf_sample_data sample; 8724 u16 header_size = namespaces_event->event_id.header.size; 8725 int ret; 8726 8727 if (!perf_event_namespaces_match(event)) 8728 return; 8729 8730 perf_event_header__init_id(&namespaces_event->event_id.header, 8731 &sample, event); 8732 ret = perf_output_begin(&handle, &sample, event, 8733 namespaces_event->event_id.header.size); 8734 if (ret) 8735 goto out; 8736 8737 namespaces_event->event_id.pid = perf_event_pid(event, 8738 namespaces_event->task); 8739 namespaces_event->event_id.tid = perf_event_tid(event, 8740 namespaces_event->task); 8741 8742 perf_output_put(&handle, namespaces_event->event_id); 8743 8744 perf_event__output_id_sample(event, &handle, &sample); 8745 8746 perf_output_end(&handle); 8747 out: 8748 namespaces_event->event_id.header.size = header_size; 8749 } 8750 8751 static void perf_fill_ns_link_info(struct perf_ns_link_info *ns_link_info, 8752 struct task_struct *task, 8753 const struct proc_ns_operations *ns_ops) 8754 { 8755 struct path ns_path; 8756 struct inode *ns_inode; 8757 int error; 8758 8759 error = ns_get_path(&ns_path, task, ns_ops); 8760 if (!error) { 8761 ns_inode = ns_path.dentry->d_inode; 8762 ns_link_info->dev = new_encode_dev(ns_inode->i_sb->s_dev); 8763 ns_link_info->ino = ns_inode->i_ino; 8764 path_put(&ns_path); 8765 } 8766 } 8767 8768 void perf_event_namespaces(struct task_struct *task) 8769 { 8770 struct perf_namespaces_event namespaces_event; 8771 struct perf_ns_link_info *ns_link_info; 8772 8773 if (!atomic_read(&nr_namespaces_events)) 8774 return; 8775 8776 namespaces_event = (struct perf_namespaces_event){ 8777 .task = task, 8778 .event_id = { 8779 .header = { 8780 .type = PERF_RECORD_NAMESPACES, 8781 .misc = 0, 8782 .size = sizeof(namespaces_event.event_id), 8783 }, 8784 /* .pid */ 8785 /* .tid */ 8786 .nr_namespaces = NR_NAMESPACES, 8787 /* .link_info[NR_NAMESPACES] */ 8788 }, 8789 }; 8790 8791 ns_link_info = namespaces_event.event_id.link_info; 8792 8793 perf_fill_ns_link_info(&ns_link_info[MNT_NS_INDEX], 8794 task, &mntns_operations); 8795 8796 #ifdef CONFIG_USER_NS 8797 perf_fill_ns_link_info(&ns_link_info[USER_NS_INDEX], 8798 task, &userns_operations); 8799 #endif 8800 #ifdef CONFIG_NET_NS 8801 perf_fill_ns_link_info(&ns_link_info[NET_NS_INDEX], 8802 task, &netns_operations); 8803 #endif 8804 #ifdef CONFIG_UTS_NS 8805 perf_fill_ns_link_info(&ns_link_info[UTS_NS_INDEX], 8806 task, &utsns_operations); 8807 #endif 8808 #ifdef CONFIG_IPC_NS 8809 perf_fill_ns_link_info(&ns_link_info[IPC_NS_INDEX], 8810 task, &ipcns_operations); 8811 #endif 8812 #ifdef CONFIG_PID_NS 8813 perf_fill_ns_link_info(&ns_link_info[PID_NS_INDEX], 8814 task, &pidns_operations); 8815 #endif 8816 #ifdef CONFIG_CGROUPS 8817 perf_fill_ns_link_info(&ns_link_info[CGROUP_NS_INDEX], 8818 task, &cgroupns_operations); 8819 #endif 8820 8821 perf_iterate_sb(perf_event_namespaces_output, 8822 &namespaces_event, 8823 NULL); 8824 } 8825 8826 /* 8827 * cgroup tracking 8828 */ 8829 #ifdef CONFIG_CGROUP_PERF 8830 8831 struct perf_cgroup_event { 8832 char *path; 8833 int path_size; 8834 struct { 8835 struct perf_event_header header; 8836 u64 id; 8837 char path[]; 8838 } event_id; 8839 }; 8840 8841 static int perf_event_cgroup_match(struct perf_event *event) 8842 { 8843 return event->attr.cgroup; 8844 } 8845 8846 static void perf_event_cgroup_output(struct perf_event *event, void *data) 8847 { 8848 struct perf_cgroup_event *cgroup_event = data; 8849 struct perf_output_handle handle; 8850 struct perf_sample_data sample; 8851 u16 header_size = cgroup_event->event_id.header.size; 8852 int ret; 8853 8854 if (!perf_event_cgroup_match(event)) 8855 return; 8856 8857 perf_event_header__init_id(&cgroup_event->event_id.header, 8858 &sample, event); 8859 ret = perf_output_begin(&handle, &sample, event, 8860 cgroup_event->event_id.header.size); 8861 if (ret) 8862 goto out; 8863 8864 perf_output_put(&handle, cgroup_event->event_id); 8865 __output_copy(&handle, cgroup_event->path, cgroup_event->path_size); 8866 8867 perf_event__output_id_sample(event, &handle, &sample); 8868 8869 perf_output_end(&handle); 8870 out: 8871 cgroup_event->event_id.header.size = header_size; 8872 } 8873 8874 static void perf_event_cgroup(struct cgroup *cgrp) 8875 { 8876 struct perf_cgroup_event cgroup_event; 8877 char path_enomem[16] = "//enomem"; 8878 char *pathname; 8879 size_t size; 8880 8881 if (!atomic_read(&nr_cgroup_events)) 8882 return; 8883 8884 cgroup_event = (struct perf_cgroup_event){ 8885 .event_id = { 8886 .header = { 8887 .type = PERF_RECORD_CGROUP, 8888 .misc = 0, 8889 .size = sizeof(cgroup_event.event_id), 8890 }, 8891 .id = cgroup_id(cgrp), 8892 }, 8893 }; 8894 8895 pathname = kmalloc(PATH_MAX, GFP_KERNEL); 8896 if (pathname == NULL) { 8897 cgroup_event.path = path_enomem; 8898 } else { 8899 /* just to be sure to have enough space for alignment */ 8900 cgroup_path(cgrp, pathname, PATH_MAX - sizeof(u64)); 8901 cgroup_event.path = pathname; 8902 } 8903 8904 /* 8905 * Since our buffer works in 8 byte units we need to align our string 8906 * size to a multiple of 8. However, we must guarantee the tail end is 8907 * zero'd out to avoid leaking random bits to userspace. 8908 */ 8909 size = strlen(cgroup_event.path) + 1; 8910 while (!IS_ALIGNED(size, sizeof(u64))) 8911 cgroup_event.path[size++] = '\0'; 8912 8913 cgroup_event.event_id.header.size += size; 8914 cgroup_event.path_size = size; 8915 8916 perf_iterate_sb(perf_event_cgroup_output, 8917 &cgroup_event, 8918 NULL); 8919 8920 kfree(pathname); 8921 } 8922 8923 #endif 8924 8925 /* 8926 * mmap tracking 8927 */ 8928 8929 struct perf_mmap_event { 8930 struct vm_area_struct *vma; 8931 8932 const char *file_name; 8933 int file_size; 8934 int maj, min; 8935 u64 ino; 8936 u64 ino_generation; 8937 u32 prot, flags; 8938 u8 build_id[BUILD_ID_SIZE_MAX]; 8939 u32 build_id_size; 8940 8941 struct { 8942 struct perf_event_header header; 8943 8944 u32 pid; 8945 u32 tid; 8946 u64 start; 8947 u64 len; 8948 u64 pgoff; 8949 } event_id; 8950 }; 8951 8952 static int perf_event_mmap_match(struct perf_event *event, 8953 void *data) 8954 { 8955 struct perf_mmap_event *mmap_event = data; 8956 struct vm_area_struct *vma = mmap_event->vma; 8957 int executable = vma->vm_flags & VM_EXEC; 8958 8959 return (!executable && event->attr.mmap_data) || 8960 (executable && (event->attr.mmap || event->attr.mmap2)); 8961 } 8962 8963 static void perf_event_mmap_output(struct perf_event *event, 8964 void *data) 8965 { 8966 struct perf_mmap_event *mmap_event = data; 8967 struct perf_output_handle handle; 8968 struct perf_sample_data sample; 8969 int size = mmap_event->event_id.header.size; 8970 u32 type = mmap_event->event_id.header.type; 8971 bool use_build_id; 8972 int ret; 8973 8974 if (!perf_event_mmap_match(event, data)) 8975 return; 8976 8977 if (event->attr.mmap2) { 8978 mmap_event->event_id.header.type = PERF_RECORD_MMAP2; 8979 mmap_event->event_id.header.size += sizeof(mmap_event->maj); 8980 mmap_event->event_id.header.size += sizeof(mmap_event->min); 8981 mmap_event->event_id.header.size += sizeof(mmap_event->ino); 8982 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation); 8983 mmap_event->event_id.header.size += sizeof(mmap_event->prot); 8984 mmap_event->event_id.header.size += sizeof(mmap_event->flags); 8985 } 8986 8987 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event); 8988 ret = perf_output_begin(&handle, &sample, event, 8989 mmap_event->event_id.header.size); 8990 if (ret) 8991 goto out; 8992 8993 mmap_event->event_id.pid = perf_event_pid(event, current); 8994 mmap_event->event_id.tid = perf_event_tid(event, current); 8995 8996 use_build_id = event->attr.build_id && mmap_event->build_id_size; 8997 8998 if (event->attr.mmap2 && use_build_id) 8999 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_BUILD_ID; 9000 9001 perf_output_put(&handle, mmap_event->event_id); 9002 9003 if (event->attr.mmap2) { 9004 if (use_build_id) { 9005 u8 size[4] = { (u8) mmap_event->build_id_size, 0, 0, 0 }; 9006 9007 __output_copy(&handle, size, 4); 9008 __output_copy(&handle, mmap_event->build_id, BUILD_ID_SIZE_MAX); 9009 } else { 9010 perf_output_put(&handle, mmap_event->maj); 9011 perf_output_put(&handle, mmap_event->min); 9012 perf_output_put(&handle, mmap_event->ino); 9013 perf_output_put(&handle, mmap_event->ino_generation); 9014 } 9015 perf_output_put(&handle, mmap_event->prot); 9016 perf_output_put(&handle, mmap_event->flags); 9017 } 9018 9019 __output_copy(&handle, mmap_event->file_name, 9020 mmap_event->file_size); 9021 9022 perf_event__output_id_sample(event, &handle, &sample); 9023 9024 perf_output_end(&handle); 9025 out: 9026 mmap_event->event_id.header.size = size; 9027 mmap_event->event_id.header.type = type; 9028 } 9029 9030 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event) 9031 { 9032 struct vm_area_struct *vma = mmap_event->vma; 9033 struct file *file = vma->vm_file; 9034 int maj = 0, min = 0; 9035 u64 ino = 0, gen = 0; 9036 u32 prot = 0, flags = 0; 9037 unsigned int size; 9038 char tmp[16]; 9039 char *buf = NULL; 9040 char *name = NULL; 9041 9042 if (vma->vm_flags & VM_READ) 9043 prot |= PROT_READ; 9044 if (vma->vm_flags & VM_WRITE) 9045 prot |= PROT_WRITE; 9046 if (vma->vm_flags & VM_EXEC) 9047 prot |= PROT_EXEC; 9048 9049 if (vma->vm_flags & VM_MAYSHARE) 9050 flags = MAP_SHARED; 9051 else 9052 flags = MAP_PRIVATE; 9053 9054 if (vma->vm_flags & VM_LOCKED) 9055 flags |= MAP_LOCKED; 9056 if (is_vm_hugetlb_page(vma)) 9057 flags |= MAP_HUGETLB; 9058 9059 if (file) { 9060 struct inode *inode; 9061 dev_t dev; 9062 9063 buf = kmalloc(PATH_MAX, GFP_KERNEL); 9064 if (!buf) { 9065 name = "//enomem"; 9066 goto cpy_name; 9067 } 9068 /* 9069 * d_path() works from the end of the rb backwards, so we 9070 * need to add enough zero bytes after the string to handle 9071 * the 64bit alignment we do later. 9072 */ 9073 name = file_path(file, buf, PATH_MAX - sizeof(u64)); 9074 if (IS_ERR(name)) { 9075 name = "//toolong"; 9076 goto cpy_name; 9077 } 9078 inode = file_inode(vma->vm_file); 9079 dev = inode->i_sb->s_dev; 9080 ino = inode->i_ino; 9081 gen = inode->i_generation; 9082 maj = MAJOR(dev); 9083 min = MINOR(dev); 9084 9085 goto got_name; 9086 } else { 9087 if (vma->vm_ops && vma->vm_ops->name) 9088 name = (char *) vma->vm_ops->name(vma); 9089 if (!name) 9090 name = (char *)arch_vma_name(vma); 9091 if (!name) { 9092 if (vma_is_initial_heap(vma)) 9093 name = "[heap]"; 9094 else if (vma_is_initial_stack(vma)) 9095 name = "[stack]"; 9096 else 9097 name = "//anon"; 9098 } 9099 } 9100 9101 cpy_name: 9102 strscpy(tmp, name, sizeof(tmp)); 9103 name = tmp; 9104 got_name: 9105 /* 9106 * Since our buffer works in 8 byte units we need to align our string 9107 * size to a multiple of 8. However, we must guarantee the tail end is 9108 * zero'd out to avoid leaking random bits to userspace. 9109 */ 9110 size = strlen(name)+1; 9111 while (!IS_ALIGNED(size, sizeof(u64))) 9112 name[size++] = '\0'; 9113 9114 mmap_event->file_name = name; 9115 mmap_event->file_size = size; 9116 mmap_event->maj = maj; 9117 mmap_event->min = min; 9118 mmap_event->ino = ino; 9119 mmap_event->ino_generation = gen; 9120 mmap_event->prot = prot; 9121 mmap_event->flags = flags; 9122 9123 if (!(vma->vm_flags & VM_EXEC)) 9124 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA; 9125 9126 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size; 9127 9128 if (atomic_read(&nr_build_id_events)) 9129 build_id_parse_nofault(vma, mmap_event->build_id, &mmap_event->build_id_size); 9130 9131 perf_iterate_sb(perf_event_mmap_output, 9132 mmap_event, 9133 NULL); 9134 9135 kfree(buf); 9136 } 9137 9138 /* 9139 * Check whether inode and address range match filter criteria. 9140 */ 9141 static bool perf_addr_filter_match(struct perf_addr_filter *filter, 9142 struct file *file, unsigned long offset, 9143 unsigned long size) 9144 { 9145 /* d_inode(NULL) won't be equal to any mapped user-space file */ 9146 if (!filter->path.dentry) 9147 return false; 9148 9149 if (d_inode(filter->path.dentry) != file_inode(file)) 9150 return false; 9151 9152 if (filter->offset > offset + size) 9153 return false; 9154 9155 if (filter->offset + filter->size < offset) 9156 return false; 9157 9158 return true; 9159 } 9160 9161 static bool perf_addr_filter_vma_adjust(struct perf_addr_filter *filter, 9162 struct vm_area_struct *vma, 9163 struct perf_addr_filter_range *fr) 9164 { 9165 unsigned long vma_size = vma->vm_end - vma->vm_start; 9166 unsigned long off = vma->vm_pgoff << PAGE_SHIFT; 9167 struct file *file = vma->vm_file; 9168 9169 if (!perf_addr_filter_match(filter, file, off, vma_size)) 9170 return false; 9171 9172 if (filter->offset < off) { 9173 fr->start = vma->vm_start; 9174 fr->size = min(vma_size, filter->size - (off - filter->offset)); 9175 } else { 9176 fr->start = vma->vm_start + filter->offset - off; 9177 fr->size = min(vma->vm_end - fr->start, filter->size); 9178 } 9179 9180 return true; 9181 } 9182 9183 static void __perf_addr_filters_adjust(struct perf_event *event, void *data) 9184 { 9185 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event); 9186 struct vm_area_struct *vma = data; 9187 struct perf_addr_filter *filter; 9188 unsigned int restart = 0, count = 0; 9189 unsigned long flags; 9190 9191 if (!has_addr_filter(event)) 9192 return; 9193 9194 if (!vma->vm_file) 9195 return; 9196 9197 raw_spin_lock_irqsave(&ifh->lock, flags); 9198 list_for_each_entry(filter, &ifh->list, entry) { 9199 if (perf_addr_filter_vma_adjust(filter, vma, 9200 &event->addr_filter_ranges[count])) 9201 restart++; 9202 9203 count++; 9204 } 9205 9206 if (restart) 9207 event->addr_filters_gen++; 9208 raw_spin_unlock_irqrestore(&ifh->lock, flags); 9209 9210 if (restart) 9211 perf_event_stop(event, 1); 9212 } 9213 9214 /* 9215 * Adjust all task's events' filters to the new vma 9216 */ 9217 static void perf_addr_filters_adjust(struct vm_area_struct *vma) 9218 { 9219 struct perf_event_context *ctx; 9220 9221 /* 9222 * Data tracing isn't supported yet and as such there is no need 9223 * to keep track of anything that isn't related to executable code: 9224 */ 9225 if (!(vma->vm_flags & VM_EXEC)) 9226 return; 9227 9228 rcu_read_lock(); 9229 ctx = rcu_dereference(current->perf_event_ctxp); 9230 if (ctx) 9231 perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true); 9232 rcu_read_unlock(); 9233 } 9234 9235 void perf_event_mmap(struct vm_area_struct *vma) 9236 { 9237 struct perf_mmap_event mmap_event; 9238 9239 if (!atomic_read(&nr_mmap_events)) 9240 return; 9241 9242 mmap_event = (struct perf_mmap_event){ 9243 .vma = vma, 9244 /* .file_name */ 9245 /* .file_size */ 9246 .event_id = { 9247 .header = { 9248 .type = PERF_RECORD_MMAP, 9249 .misc = PERF_RECORD_MISC_USER, 9250 /* .size */ 9251 }, 9252 /* .pid */ 9253 /* .tid */ 9254 .start = vma->vm_start, 9255 .len = vma->vm_end - vma->vm_start, 9256 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT, 9257 }, 9258 /* .maj (attr_mmap2 only) */ 9259 /* .min (attr_mmap2 only) */ 9260 /* .ino (attr_mmap2 only) */ 9261 /* .ino_generation (attr_mmap2 only) */ 9262 /* .prot (attr_mmap2 only) */ 9263 /* .flags (attr_mmap2 only) */ 9264 }; 9265 9266 perf_addr_filters_adjust(vma); 9267 perf_event_mmap_event(&mmap_event); 9268 } 9269 9270 void perf_event_aux_event(struct perf_event *event, unsigned long head, 9271 unsigned long size, u64 flags) 9272 { 9273 struct perf_output_handle handle; 9274 struct perf_sample_data sample; 9275 struct perf_aux_event { 9276 struct perf_event_header header; 9277 u64 offset; 9278 u64 size; 9279 u64 flags; 9280 } rec = { 9281 .header = { 9282 .type = PERF_RECORD_AUX, 9283 .misc = 0, 9284 .size = sizeof(rec), 9285 }, 9286 .offset = head, 9287 .size = size, 9288 .flags = flags, 9289 }; 9290 int ret; 9291 9292 perf_event_header__init_id(&rec.header, &sample, event); 9293 ret = perf_output_begin(&handle, &sample, event, rec.header.size); 9294 9295 if (ret) 9296 return; 9297 9298 perf_output_put(&handle, rec); 9299 perf_event__output_id_sample(event, &handle, &sample); 9300 9301 perf_output_end(&handle); 9302 } 9303 9304 /* 9305 * Lost/dropped samples logging 9306 */ 9307 void perf_log_lost_samples(struct perf_event *event, u64 lost) 9308 { 9309 struct perf_output_handle handle; 9310 struct perf_sample_data sample; 9311 int ret; 9312 9313 struct { 9314 struct perf_event_header header; 9315 u64 lost; 9316 } lost_samples_event = { 9317 .header = { 9318 .type = PERF_RECORD_LOST_SAMPLES, 9319 .misc = 0, 9320 .size = sizeof(lost_samples_event), 9321 }, 9322 .lost = lost, 9323 }; 9324 9325 perf_event_header__init_id(&lost_samples_event.header, &sample, event); 9326 9327 ret = perf_output_begin(&handle, &sample, event, 9328 lost_samples_event.header.size); 9329 if (ret) 9330 return; 9331 9332 perf_output_put(&handle, lost_samples_event); 9333 perf_event__output_id_sample(event, &handle, &sample); 9334 perf_output_end(&handle); 9335 } 9336 9337 /* 9338 * context_switch tracking 9339 */ 9340 9341 struct perf_switch_event { 9342 struct task_struct *task; 9343 struct task_struct *next_prev; 9344 9345 struct { 9346 struct perf_event_header header; 9347 u32 next_prev_pid; 9348 u32 next_prev_tid; 9349 } event_id; 9350 }; 9351 9352 static int perf_event_switch_match(struct perf_event *event) 9353 { 9354 return event->attr.context_switch; 9355 } 9356 9357 static void perf_event_switch_output(struct perf_event *event, void *data) 9358 { 9359 struct perf_switch_event *se = data; 9360 struct perf_output_handle handle; 9361 struct perf_sample_data sample; 9362 int ret; 9363 9364 if (!perf_event_switch_match(event)) 9365 return; 9366 9367 /* Only CPU-wide events are allowed to see next/prev pid/tid */ 9368 if (event->ctx->task) { 9369 se->event_id.header.type = PERF_RECORD_SWITCH; 9370 se->event_id.header.size = sizeof(se->event_id.header); 9371 } else { 9372 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE; 9373 se->event_id.header.size = sizeof(se->event_id); 9374 se->event_id.next_prev_pid = 9375 perf_event_pid(event, se->next_prev); 9376 se->event_id.next_prev_tid = 9377 perf_event_tid(event, se->next_prev); 9378 } 9379 9380 perf_event_header__init_id(&se->event_id.header, &sample, event); 9381 9382 ret = perf_output_begin(&handle, &sample, event, se->event_id.header.size); 9383 if (ret) 9384 return; 9385 9386 if (event->ctx->task) 9387 perf_output_put(&handle, se->event_id.header); 9388 else 9389 perf_output_put(&handle, se->event_id); 9390 9391 perf_event__output_id_sample(event, &handle, &sample); 9392 9393 perf_output_end(&handle); 9394 } 9395 9396 static void perf_event_switch(struct task_struct *task, 9397 struct task_struct *next_prev, bool sched_in) 9398 { 9399 struct perf_switch_event switch_event; 9400 9401 /* N.B. caller checks nr_switch_events != 0 */ 9402 9403 switch_event = (struct perf_switch_event){ 9404 .task = task, 9405 .next_prev = next_prev, 9406 .event_id = { 9407 .header = { 9408 /* .type */ 9409 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT, 9410 /* .size */ 9411 }, 9412 /* .next_prev_pid */ 9413 /* .next_prev_tid */ 9414 }, 9415 }; 9416 9417 if (!sched_in && task_is_runnable(task)) { 9418 switch_event.event_id.header.misc |= 9419 PERF_RECORD_MISC_SWITCH_OUT_PREEMPT; 9420 } 9421 9422 perf_iterate_sb(perf_event_switch_output, &switch_event, NULL); 9423 } 9424 9425 /* 9426 * IRQ throttle logging 9427 */ 9428 9429 static void perf_log_throttle(struct perf_event *event, int enable) 9430 { 9431 struct perf_output_handle handle; 9432 struct perf_sample_data sample; 9433 int ret; 9434 9435 struct { 9436 struct perf_event_header header; 9437 u64 time; 9438 u64 id; 9439 u64 stream_id; 9440 } throttle_event = { 9441 .header = { 9442 .type = PERF_RECORD_THROTTLE, 9443 .misc = 0, 9444 .size = sizeof(throttle_event), 9445 }, 9446 .time = perf_event_clock(event), 9447 .id = primary_event_id(event), 9448 .stream_id = event->id, 9449 }; 9450 9451 if (enable) 9452 throttle_event.header.type = PERF_RECORD_UNTHROTTLE; 9453 9454 perf_event_header__init_id(&throttle_event.header, &sample, event); 9455 9456 ret = perf_output_begin(&handle, &sample, event, 9457 throttle_event.header.size); 9458 if (ret) 9459 return; 9460 9461 perf_output_put(&handle, throttle_event); 9462 perf_event__output_id_sample(event, &handle, &sample); 9463 perf_output_end(&handle); 9464 } 9465 9466 /* 9467 * ksymbol register/unregister tracking 9468 */ 9469 9470 struct perf_ksymbol_event { 9471 const char *name; 9472 int name_len; 9473 struct { 9474 struct perf_event_header header; 9475 u64 addr; 9476 u32 len; 9477 u16 ksym_type; 9478 u16 flags; 9479 } event_id; 9480 }; 9481 9482 static int perf_event_ksymbol_match(struct perf_event *event) 9483 { 9484 return event->attr.ksymbol; 9485 } 9486 9487 static void perf_event_ksymbol_output(struct perf_event *event, void *data) 9488 { 9489 struct perf_ksymbol_event *ksymbol_event = data; 9490 struct perf_output_handle handle; 9491 struct perf_sample_data sample; 9492 int ret; 9493 9494 if (!perf_event_ksymbol_match(event)) 9495 return; 9496 9497 perf_event_header__init_id(&ksymbol_event->event_id.header, 9498 &sample, event); 9499 ret = perf_output_begin(&handle, &sample, event, 9500 ksymbol_event->event_id.header.size); 9501 if (ret) 9502 return; 9503 9504 perf_output_put(&handle, ksymbol_event->event_id); 9505 __output_copy(&handle, ksymbol_event->name, ksymbol_event->name_len); 9506 perf_event__output_id_sample(event, &handle, &sample); 9507 9508 perf_output_end(&handle); 9509 } 9510 9511 void perf_event_ksymbol(u16 ksym_type, u64 addr, u32 len, bool unregister, 9512 const char *sym) 9513 { 9514 struct perf_ksymbol_event ksymbol_event; 9515 char name[KSYM_NAME_LEN]; 9516 u16 flags = 0; 9517 int name_len; 9518 9519 if (!atomic_read(&nr_ksymbol_events)) 9520 return; 9521 9522 if (ksym_type >= PERF_RECORD_KSYMBOL_TYPE_MAX || 9523 ksym_type == PERF_RECORD_KSYMBOL_TYPE_UNKNOWN) 9524 goto err; 9525 9526 strscpy(name, sym, KSYM_NAME_LEN); 9527 name_len = strlen(name) + 1; 9528 while (!IS_ALIGNED(name_len, sizeof(u64))) 9529 name[name_len++] = '\0'; 9530 BUILD_BUG_ON(KSYM_NAME_LEN % sizeof(u64)); 9531 9532 if (unregister) 9533 flags |= PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER; 9534 9535 ksymbol_event = (struct perf_ksymbol_event){ 9536 .name = name, 9537 .name_len = name_len, 9538 .event_id = { 9539 .header = { 9540 .type = PERF_RECORD_KSYMBOL, 9541 .size = sizeof(ksymbol_event.event_id) + 9542 name_len, 9543 }, 9544 .addr = addr, 9545 .len = len, 9546 .ksym_type = ksym_type, 9547 .flags = flags, 9548 }, 9549 }; 9550 9551 perf_iterate_sb(perf_event_ksymbol_output, &ksymbol_event, NULL); 9552 return; 9553 err: 9554 WARN_ONCE(1, "%s: Invalid KSYMBOL type 0x%x\n", __func__, ksym_type); 9555 } 9556 9557 /* 9558 * bpf program load/unload tracking 9559 */ 9560 9561 struct perf_bpf_event { 9562 struct bpf_prog *prog; 9563 struct { 9564 struct perf_event_header header; 9565 u16 type; 9566 u16 flags; 9567 u32 id; 9568 u8 tag[BPF_TAG_SIZE]; 9569 } event_id; 9570 }; 9571 9572 static int perf_event_bpf_match(struct perf_event *event) 9573 { 9574 return event->attr.bpf_event; 9575 } 9576 9577 static void perf_event_bpf_output(struct perf_event *event, void *data) 9578 { 9579 struct perf_bpf_event *bpf_event = data; 9580 struct perf_output_handle handle; 9581 struct perf_sample_data sample; 9582 int ret; 9583 9584 if (!perf_event_bpf_match(event)) 9585 return; 9586 9587 perf_event_header__init_id(&bpf_event->event_id.header, 9588 &sample, event); 9589 ret = perf_output_begin(&handle, &sample, event, 9590 bpf_event->event_id.header.size); 9591 if (ret) 9592 return; 9593 9594 perf_output_put(&handle, bpf_event->event_id); 9595 perf_event__output_id_sample(event, &handle, &sample); 9596 9597 perf_output_end(&handle); 9598 } 9599 9600 static void perf_event_bpf_emit_ksymbols(struct bpf_prog *prog, 9601 enum perf_bpf_event_type type) 9602 { 9603 bool unregister = type == PERF_BPF_EVENT_PROG_UNLOAD; 9604 int i; 9605 9606 perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF, 9607 (u64)(unsigned long)prog->bpf_func, 9608 prog->jited_len, unregister, 9609 prog->aux->ksym.name); 9610 9611 for (i = 1; i < prog->aux->func_cnt; i++) { 9612 struct bpf_prog *subprog = prog->aux->func[i]; 9613 9614 perf_event_ksymbol( 9615 PERF_RECORD_KSYMBOL_TYPE_BPF, 9616 (u64)(unsigned long)subprog->bpf_func, 9617 subprog->jited_len, unregister, 9618 subprog->aux->ksym.name); 9619 } 9620 } 9621 9622 void perf_event_bpf_event(struct bpf_prog *prog, 9623 enum perf_bpf_event_type type, 9624 u16 flags) 9625 { 9626 struct perf_bpf_event bpf_event; 9627 9628 switch (type) { 9629 case PERF_BPF_EVENT_PROG_LOAD: 9630 case PERF_BPF_EVENT_PROG_UNLOAD: 9631 if (atomic_read(&nr_ksymbol_events)) 9632 perf_event_bpf_emit_ksymbols(prog, type); 9633 break; 9634 default: 9635 return; 9636 } 9637 9638 if (!atomic_read(&nr_bpf_events)) 9639 return; 9640 9641 bpf_event = (struct perf_bpf_event){ 9642 .prog = prog, 9643 .event_id = { 9644 .header = { 9645 .type = PERF_RECORD_BPF_EVENT, 9646 .size = sizeof(bpf_event.event_id), 9647 }, 9648 .type = type, 9649 .flags = flags, 9650 .id = prog->aux->id, 9651 }, 9652 }; 9653 9654 BUILD_BUG_ON(BPF_TAG_SIZE % sizeof(u64)); 9655 9656 memcpy(bpf_event.event_id.tag, prog->tag, BPF_TAG_SIZE); 9657 perf_iterate_sb(perf_event_bpf_output, &bpf_event, NULL); 9658 } 9659 9660 struct perf_text_poke_event { 9661 const void *old_bytes; 9662 const void *new_bytes; 9663 size_t pad; 9664 u16 old_len; 9665 u16 new_len; 9666 9667 struct { 9668 struct perf_event_header header; 9669 9670 u64 addr; 9671 } event_id; 9672 }; 9673 9674 static int perf_event_text_poke_match(struct perf_event *event) 9675 { 9676 return event->attr.text_poke; 9677 } 9678 9679 static void perf_event_text_poke_output(struct perf_event *event, void *data) 9680 { 9681 struct perf_text_poke_event *text_poke_event = data; 9682 struct perf_output_handle handle; 9683 struct perf_sample_data sample; 9684 u64 padding = 0; 9685 int ret; 9686 9687 if (!perf_event_text_poke_match(event)) 9688 return; 9689 9690 perf_event_header__init_id(&text_poke_event->event_id.header, &sample, event); 9691 9692 ret = perf_output_begin(&handle, &sample, event, 9693 text_poke_event->event_id.header.size); 9694 if (ret) 9695 return; 9696 9697 perf_output_put(&handle, text_poke_event->event_id); 9698 perf_output_put(&handle, text_poke_event->old_len); 9699 perf_output_put(&handle, text_poke_event->new_len); 9700 9701 __output_copy(&handle, text_poke_event->old_bytes, text_poke_event->old_len); 9702 __output_copy(&handle, text_poke_event->new_bytes, text_poke_event->new_len); 9703 9704 if (text_poke_event->pad) 9705 __output_copy(&handle, &padding, text_poke_event->pad); 9706 9707 perf_event__output_id_sample(event, &handle, &sample); 9708 9709 perf_output_end(&handle); 9710 } 9711 9712 void perf_event_text_poke(const void *addr, const void *old_bytes, 9713 size_t old_len, const void *new_bytes, size_t new_len) 9714 { 9715 struct perf_text_poke_event text_poke_event; 9716 size_t tot, pad; 9717 9718 if (!atomic_read(&nr_text_poke_events)) 9719 return; 9720 9721 tot = sizeof(text_poke_event.old_len) + old_len; 9722 tot += sizeof(text_poke_event.new_len) + new_len; 9723 pad = ALIGN(tot, sizeof(u64)) - tot; 9724 9725 text_poke_event = (struct perf_text_poke_event){ 9726 .old_bytes = old_bytes, 9727 .new_bytes = new_bytes, 9728 .pad = pad, 9729 .old_len = old_len, 9730 .new_len = new_len, 9731 .event_id = { 9732 .header = { 9733 .type = PERF_RECORD_TEXT_POKE, 9734 .misc = PERF_RECORD_MISC_KERNEL, 9735 .size = sizeof(text_poke_event.event_id) + tot + pad, 9736 }, 9737 .addr = (unsigned long)addr, 9738 }, 9739 }; 9740 9741 perf_iterate_sb(perf_event_text_poke_output, &text_poke_event, NULL); 9742 } 9743 9744 void perf_event_itrace_started(struct perf_event *event) 9745 { 9746 event->attach_state |= PERF_ATTACH_ITRACE; 9747 } 9748 9749 static void perf_log_itrace_start(struct perf_event *event) 9750 { 9751 struct perf_output_handle handle; 9752 struct perf_sample_data sample; 9753 struct perf_aux_event { 9754 struct perf_event_header header; 9755 u32 pid; 9756 u32 tid; 9757 } rec; 9758 int ret; 9759 9760 if (event->parent) 9761 event = event->parent; 9762 9763 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) || 9764 event->attach_state & PERF_ATTACH_ITRACE) 9765 return; 9766 9767 rec.header.type = PERF_RECORD_ITRACE_START; 9768 rec.header.misc = 0; 9769 rec.header.size = sizeof(rec); 9770 rec.pid = perf_event_pid(event, current); 9771 rec.tid = perf_event_tid(event, current); 9772 9773 perf_event_header__init_id(&rec.header, &sample, event); 9774 ret = perf_output_begin(&handle, &sample, event, rec.header.size); 9775 9776 if (ret) 9777 return; 9778 9779 perf_output_put(&handle, rec); 9780 perf_event__output_id_sample(event, &handle, &sample); 9781 9782 perf_output_end(&handle); 9783 } 9784 9785 void perf_report_aux_output_id(struct perf_event *event, u64 hw_id) 9786 { 9787 struct perf_output_handle handle; 9788 struct perf_sample_data sample; 9789 struct perf_aux_event { 9790 struct perf_event_header header; 9791 u64 hw_id; 9792 } rec; 9793 int ret; 9794 9795 if (event->parent) 9796 event = event->parent; 9797 9798 rec.header.type = PERF_RECORD_AUX_OUTPUT_HW_ID; 9799 rec.header.misc = 0; 9800 rec.header.size = sizeof(rec); 9801 rec.hw_id = hw_id; 9802 9803 perf_event_header__init_id(&rec.header, &sample, event); 9804 ret = perf_output_begin(&handle, &sample, event, rec.header.size); 9805 9806 if (ret) 9807 return; 9808 9809 perf_output_put(&handle, rec); 9810 perf_event__output_id_sample(event, &handle, &sample); 9811 9812 perf_output_end(&handle); 9813 } 9814 EXPORT_SYMBOL_GPL(perf_report_aux_output_id); 9815 9816 static int 9817 __perf_event_account_interrupt(struct perf_event *event, int throttle) 9818 { 9819 struct hw_perf_event *hwc = &event->hw; 9820 int ret = 0; 9821 u64 seq; 9822 9823 seq = __this_cpu_read(perf_throttled_seq); 9824 if (seq != hwc->interrupts_seq) { 9825 hwc->interrupts_seq = seq; 9826 hwc->interrupts = 1; 9827 } else { 9828 hwc->interrupts++; 9829 if (unlikely(throttle && 9830 hwc->interrupts > max_samples_per_tick)) { 9831 __this_cpu_inc(perf_throttled_count); 9832 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS); 9833 hwc->interrupts = MAX_INTERRUPTS; 9834 perf_log_throttle(event, 0); 9835 ret = 1; 9836 } 9837 } 9838 9839 if (event->attr.freq) { 9840 u64 now = perf_clock(); 9841 s64 delta = now - hwc->freq_time_stamp; 9842 9843 hwc->freq_time_stamp = now; 9844 9845 if (delta > 0 && delta < 2*TICK_NSEC) 9846 perf_adjust_period(event, delta, hwc->last_period, true); 9847 } 9848 9849 return ret; 9850 } 9851 9852 int perf_event_account_interrupt(struct perf_event *event) 9853 { 9854 return __perf_event_account_interrupt(event, 1); 9855 } 9856 9857 static inline bool sample_is_allowed(struct perf_event *event, struct pt_regs *regs) 9858 { 9859 /* 9860 * Due to interrupt latency (AKA "skid"), we may enter the 9861 * kernel before taking an overflow, even if the PMU is only 9862 * counting user events. 9863 */ 9864 if (event->attr.exclude_kernel && !user_mode(regs)) 9865 return false; 9866 9867 return true; 9868 } 9869 9870 #ifdef CONFIG_BPF_SYSCALL 9871 static int bpf_overflow_handler(struct perf_event *event, 9872 struct perf_sample_data *data, 9873 struct pt_regs *regs) 9874 { 9875 struct bpf_perf_event_data_kern ctx = { 9876 .data = data, 9877 .event = event, 9878 }; 9879 struct bpf_prog *prog; 9880 int ret = 0; 9881 9882 ctx.regs = perf_arch_bpf_user_pt_regs(regs); 9883 if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1)) 9884 goto out; 9885 rcu_read_lock(); 9886 prog = READ_ONCE(event->prog); 9887 if (prog) { 9888 perf_prepare_sample(data, event, regs); 9889 ret = bpf_prog_run(prog, &ctx); 9890 } 9891 rcu_read_unlock(); 9892 out: 9893 __this_cpu_dec(bpf_prog_active); 9894 9895 return ret; 9896 } 9897 9898 static inline int perf_event_set_bpf_handler(struct perf_event *event, 9899 struct bpf_prog *prog, 9900 u64 bpf_cookie) 9901 { 9902 if (event->overflow_handler_context) 9903 /* hw breakpoint or kernel counter */ 9904 return -EINVAL; 9905 9906 if (event->prog) 9907 return -EEXIST; 9908 9909 if (prog->type != BPF_PROG_TYPE_PERF_EVENT) 9910 return -EINVAL; 9911 9912 if (event->attr.precise_ip && 9913 prog->call_get_stack && 9914 (!(event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) || 9915 event->attr.exclude_callchain_kernel || 9916 event->attr.exclude_callchain_user)) { 9917 /* 9918 * On perf_event with precise_ip, calling bpf_get_stack() 9919 * may trigger unwinder warnings and occasional crashes. 9920 * bpf_get_[stack|stackid] works around this issue by using 9921 * callchain attached to perf_sample_data. If the 9922 * perf_event does not full (kernel and user) callchain 9923 * attached to perf_sample_data, do not allow attaching BPF 9924 * program that calls bpf_get_[stack|stackid]. 9925 */ 9926 return -EPROTO; 9927 } 9928 9929 event->prog = prog; 9930 event->bpf_cookie = bpf_cookie; 9931 return 0; 9932 } 9933 9934 static inline void perf_event_free_bpf_handler(struct perf_event *event) 9935 { 9936 struct bpf_prog *prog = event->prog; 9937 9938 if (!prog) 9939 return; 9940 9941 event->prog = NULL; 9942 bpf_prog_put(prog); 9943 } 9944 #else 9945 static inline int bpf_overflow_handler(struct perf_event *event, 9946 struct perf_sample_data *data, 9947 struct pt_regs *regs) 9948 { 9949 return 1; 9950 } 9951 9952 static inline int perf_event_set_bpf_handler(struct perf_event *event, 9953 struct bpf_prog *prog, 9954 u64 bpf_cookie) 9955 { 9956 return -EOPNOTSUPP; 9957 } 9958 9959 static inline void perf_event_free_bpf_handler(struct perf_event *event) 9960 { 9961 } 9962 #endif 9963 9964 /* 9965 * Generic event overflow handling, sampling. 9966 */ 9967 9968 static int __perf_event_overflow(struct perf_event *event, 9969 int throttle, struct perf_sample_data *data, 9970 struct pt_regs *regs) 9971 { 9972 int events = atomic_read(&event->event_limit); 9973 int ret = 0; 9974 9975 /* 9976 * Non-sampling counters might still use the PMI to fold short 9977 * hardware counters, ignore those. 9978 */ 9979 if (unlikely(!is_sampling_event(event))) 9980 return 0; 9981 9982 ret = __perf_event_account_interrupt(event, throttle); 9983 9984 if (event->attr.aux_pause) 9985 perf_event_aux_pause(event->aux_event, true); 9986 9987 if (event->prog && event->prog->type == BPF_PROG_TYPE_PERF_EVENT && 9988 !bpf_overflow_handler(event, data, regs)) 9989 goto out; 9990 9991 /* 9992 * XXX event_limit might not quite work as expected on inherited 9993 * events 9994 */ 9995 9996 event->pending_kill = POLL_IN; 9997 if (events && atomic_dec_and_test(&event->event_limit)) { 9998 ret = 1; 9999 event->pending_kill = POLL_HUP; 10000 perf_event_disable_inatomic(event); 10001 } 10002 10003 if (event->attr.sigtrap) { 10004 /* 10005 * The desired behaviour of sigtrap vs invalid samples is a bit 10006 * tricky; on the one hand, one should not loose the SIGTRAP if 10007 * it is the first event, on the other hand, we should also not 10008 * trigger the WARN or override the data address. 10009 */ 10010 bool valid_sample = sample_is_allowed(event, regs); 10011 unsigned int pending_id = 1; 10012 enum task_work_notify_mode notify_mode; 10013 10014 if (regs) 10015 pending_id = hash32_ptr((void *)instruction_pointer(regs)) ?: 1; 10016 10017 notify_mode = in_nmi() ? TWA_NMI_CURRENT : TWA_RESUME; 10018 10019 if (!event->pending_work && 10020 !task_work_add(current, &event->pending_task, notify_mode)) { 10021 event->pending_work = pending_id; 10022 local_inc(&event->ctx->nr_no_switch_fast); 10023 10024 event->pending_addr = 0; 10025 if (valid_sample && (data->sample_flags & PERF_SAMPLE_ADDR)) 10026 event->pending_addr = data->addr; 10027 10028 } else if (event->attr.exclude_kernel && valid_sample) { 10029 /* 10030 * Should not be able to return to user space without 10031 * consuming pending_work; with exceptions: 10032 * 10033 * 1. Where !exclude_kernel, events can overflow again 10034 * in the kernel without returning to user space. 10035 * 10036 * 2. Events that can overflow again before the IRQ- 10037 * work without user space progress (e.g. hrtimer). 10038 * To approximate progress (with false negatives), 10039 * check 32-bit hash of the current IP. 10040 */ 10041 WARN_ON_ONCE(event->pending_work != pending_id); 10042 } 10043 } 10044 10045 READ_ONCE(event->overflow_handler)(event, data, regs); 10046 10047 if (*perf_event_fasync(event) && event->pending_kill) { 10048 event->pending_wakeup = 1; 10049 irq_work_queue(&event->pending_irq); 10050 } 10051 out: 10052 if (event->attr.aux_resume) 10053 perf_event_aux_pause(event->aux_event, false); 10054 10055 return ret; 10056 } 10057 10058 int perf_event_overflow(struct perf_event *event, 10059 struct perf_sample_data *data, 10060 struct pt_regs *regs) 10061 { 10062 return __perf_event_overflow(event, 1, data, regs); 10063 } 10064 10065 /* 10066 * Generic software event infrastructure 10067 */ 10068 10069 struct swevent_htable { 10070 struct swevent_hlist *swevent_hlist; 10071 struct mutex hlist_mutex; 10072 int hlist_refcount; 10073 }; 10074 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable); 10075 10076 /* 10077 * We directly increment event->count and keep a second value in 10078 * event->hw.period_left to count intervals. This period event 10079 * is kept in the range [-sample_period, 0] so that we can use the 10080 * sign as trigger. 10081 */ 10082 10083 u64 perf_swevent_set_period(struct perf_event *event) 10084 { 10085 struct hw_perf_event *hwc = &event->hw; 10086 u64 period = hwc->last_period; 10087 u64 nr, offset; 10088 s64 old, val; 10089 10090 hwc->last_period = hwc->sample_period; 10091 10092 old = local64_read(&hwc->period_left); 10093 do { 10094 val = old; 10095 if (val < 0) 10096 return 0; 10097 10098 nr = div64_u64(period + val, period); 10099 offset = nr * period; 10100 val -= offset; 10101 } while (!local64_try_cmpxchg(&hwc->period_left, &old, val)); 10102 10103 return nr; 10104 } 10105 10106 static void perf_swevent_overflow(struct perf_event *event, u64 overflow, 10107 struct perf_sample_data *data, 10108 struct pt_regs *regs) 10109 { 10110 struct hw_perf_event *hwc = &event->hw; 10111 int throttle = 0; 10112 10113 if (!overflow) 10114 overflow = perf_swevent_set_period(event); 10115 10116 if (hwc->interrupts == MAX_INTERRUPTS) 10117 return; 10118 10119 for (; overflow; overflow--) { 10120 if (__perf_event_overflow(event, throttle, 10121 data, regs)) { 10122 /* 10123 * We inhibit the overflow from happening when 10124 * hwc->interrupts == MAX_INTERRUPTS. 10125 */ 10126 break; 10127 } 10128 throttle = 1; 10129 } 10130 } 10131 10132 static void perf_swevent_event(struct perf_event *event, u64 nr, 10133 struct perf_sample_data *data, 10134 struct pt_regs *regs) 10135 { 10136 struct hw_perf_event *hwc = &event->hw; 10137 10138 local64_add(nr, &event->count); 10139 10140 if (!regs) 10141 return; 10142 10143 if (!is_sampling_event(event)) 10144 return; 10145 10146 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) { 10147 data->period = nr; 10148 return perf_swevent_overflow(event, 1, data, regs); 10149 } else 10150 data->period = event->hw.last_period; 10151 10152 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq) 10153 return perf_swevent_overflow(event, 1, data, regs); 10154 10155 if (local64_add_negative(nr, &hwc->period_left)) 10156 return; 10157 10158 perf_swevent_overflow(event, 0, data, regs); 10159 } 10160 10161 int perf_exclude_event(struct perf_event *event, struct pt_regs *regs) 10162 { 10163 if (event->hw.state & PERF_HES_STOPPED) 10164 return 1; 10165 10166 if (regs) { 10167 if (event->attr.exclude_user && user_mode(regs)) 10168 return 1; 10169 10170 if (event->attr.exclude_kernel && !user_mode(regs)) 10171 return 1; 10172 } 10173 10174 return 0; 10175 } 10176 10177 static int perf_swevent_match(struct perf_event *event, 10178 enum perf_type_id type, 10179 u32 event_id, 10180 struct perf_sample_data *data, 10181 struct pt_regs *regs) 10182 { 10183 if (event->attr.type != type) 10184 return 0; 10185 10186 if (event->attr.config != event_id) 10187 return 0; 10188 10189 if (perf_exclude_event(event, regs)) 10190 return 0; 10191 10192 return 1; 10193 } 10194 10195 static inline u64 swevent_hash(u64 type, u32 event_id) 10196 { 10197 u64 val = event_id | (type << 32); 10198 10199 return hash_64(val, SWEVENT_HLIST_BITS); 10200 } 10201 10202 static inline struct hlist_head * 10203 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id) 10204 { 10205 u64 hash = swevent_hash(type, event_id); 10206 10207 return &hlist->heads[hash]; 10208 } 10209 10210 /* For the read side: events when they trigger */ 10211 static inline struct hlist_head * 10212 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id) 10213 { 10214 struct swevent_hlist *hlist; 10215 10216 hlist = rcu_dereference(swhash->swevent_hlist); 10217 if (!hlist) 10218 return NULL; 10219 10220 return __find_swevent_head(hlist, type, event_id); 10221 } 10222 10223 /* For the event head insertion and removal in the hlist */ 10224 static inline struct hlist_head * 10225 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event) 10226 { 10227 struct swevent_hlist *hlist; 10228 u32 event_id = event->attr.config; 10229 u64 type = event->attr.type; 10230 10231 /* 10232 * Event scheduling is always serialized against hlist allocation 10233 * and release. Which makes the protected version suitable here. 10234 * The context lock guarantees that. 10235 */ 10236 hlist = rcu_dereference_protected(swhash->swevent_hlist, 10237 lockdep_is_held(&event->ctx->lock)); 10238 if (!hlist) 10239 return NULL; 10240 10241 return __find_swevent_head(hlist, type, event_id); 10242 } 10243 10244 static void do_perf_sw_event(enum perf_type_id type, u32 event_id, 10245 u64 nr, 10246 struct perf_sample_data *data, 10247 struct pt_regs *regs) 10248 { 10249 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable); 10250 struct perf_event *event; 10251 struct hlist_head *head; 10252 10253 rcu_read_lock(); 10254 head = find_swevent_head_rcu(swhash, type, event_id); 10255 if (!head) 10256 goto end; 10257 10258 hlist_for_each_entry_rcu(event, head, hlist_entry) { 10259 if (perf_swevent_match(event, type, event_id, data, regs)) 10260 perf_swevent_event(event, nr, data, regs); 10261 } 10262 end: 10263 rcu_read_unlock(); 10264 } 10265 10266 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]); 10267 10268 int perf_swevent_get_recursion_context(void) 10269 { 10270 return get_recursion_context(current->perf_recursion); 10271 } 10272 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context); 10273 10274 void perf_swevent_put_recursion_context(int rctx) 10275 { 10276 put_recursion_context(current->perf_recursion, rctx); 10277 } 10278 10279 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr) 10280 { 10281 struct perf_sample_data data; 10282 10283 if (WARN_ON_ONCE(!regs)) 10284 return; 10285 10286 perf_sample_data_init(&data, addr, 0); 10287 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs); 10288 } 10289 10290 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr) 10291 { 10292 int rctx; 10293 10294 preempt_disable_notrace(); 10295 rctx = perf_swevent_get_recursion_context(); 10296 if (unlikely(rctx < 0)) 10297 goto fail; 10298 10299 ___perf_sw_event(event_id, nr, regs, addr); 10300 10301 perf_swevent_put_recursion_context(rctx); 10302 fail: 10303 preempt_enable_notrace(); 10304 } 10305 10306 static void perf_swevent_read(struct perf_event *event) 10307 { 10308 } 10309 10310 static int perf_swevent_add(struct perf_event *event, int flags) 10311 { 10312 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable); 10313 struct hw_perf_event *hwc = &event->hw; 10314 struct hlist_head *head; 10315 10316 if (is_sampling_event(event)) { 10317 hwc->last_period = hwc->sample_period; 10318 perf_swevent_set_period(event); 10319 } 10320 10321 hwc->state = !(flags & PERF_EF_START); 10322 10323 head = find_swevent_head(swhash, event); 10324 if (WARN_ON_ONCE(!head)) 10325 return -EINVAL; 10326 10327 hlist_add_head_rcu(&event->hlist_entry, head); 10328 perf_event_update_userpage(event); 10329 10330 return 0; 10331 } 10332 10333 static void perf_swevent_del(struct perf_event *event, int flags) 10334 { 10335 hlist_del_rcu(&event->hlist_entry); 10336 } 10337 10338 static void perf_swevent_start(struct perf_event *event, int flags) 10339 { 10340 event->hw.state = 0; 10341 } 10342 10343 static void perf_swevent_stop(struct perf_event *event, int flags) 10344 { 10345 event->hw.state = PERF_HES_STOPPED; 10346 } 10347 10348 /* Deref the hlist from the update side */ 10349 static inline struct swevent_hlist * 10350 swevent_hlist_deref(struct swevent_htable *swhash) 10351 { 10352 return rcu_dereference_protected(swhash->swevent_hlist, 10353 lockdep_is_held(&swhash->hlist_mutex)); 10354 } 10355 10356 static void swevent_hlist_release(struct swevent_htable *swhash) 10357 { 10358 struct swevent_hlist *hlist = swevent_hlist_deref(swhash); 10359 10360 if (!hlist) 10361 return; 10362 10363 RCU_INIT_POINTER(swhash->swevent_hlist, NULL); 10364 kfree_rcu(hlist, rcu_head); 10365 } 10366 10367 static void swevent_hlist_put_cpu(int cpu) 10368 { 10369 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu); 10370 10371 mutex_lock(&swhash->hlist_mutex); 10372 10373 if (!--swhash->hlist_refcount) 10374 swevent_hlist_release(swhash); 10375 10376 mutex_unlock(&swhash->hlist_mutex); 10377 } 10378 10379 static void swevent_hlist_put(void) 10380 { 10381 int cpu; 10382 10383 for_each_possible_cpu(cpu) 10384 swevent_hlist_put_cpu(cpu); 10385 } 10386 10387 static int swevent_hlist_get_cpu(int cpu) 10388 { 10389 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu); 10390 int err = 0; 10391 10392 mutex_lock(&swhash->hlist_mutex); 10393 if (!swevent_hlist_deref(swhash) && 10394 cpumask_test_cpu(cpu, perf_online_mask)) { 10395 struct swevent_hlist *hlist; 10396 10397 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL); 10398 if (!hlist) { 10399 err = -ENOMEM; 10400 goto exit; 10401 } 10402 rcu_assign_pointer(swhash->swevent_hlist, hlist); 10403 } 10404 swhash->hlist_refcount++; 10405 exit: 10406 mutex_unlock(&swhash->hlist_mutex); 10407 10408 return err; 10409 } 10410 10411 static int swevent_hlist_get(void) 10412 { 10413 int err, cpu, failed_cpu; 10414 10415 mutex_lock(&pmus_lock); 10416 for_each_possible_cpu(cpu) { 10417 err = swevent_hlist_get_cpu(cpu); 10418 if (err) { 10419 failed_cpu = cpu; 10420 goto fail; 10421 } 10422 } 10423 mutex_unlock(&pmus_lock); 10424 return 0; 10425 fail: 10426 for_each_possible_cpu(cpu) { 10427 if (cpu == failed_cpu) 10428 break; 10429 swevent_hlist_put_cpu(cpu); 10430 } 10431 mutex_unlock(&pmus_lock); 10432 return err; 10433 } 10434 10435 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX]; 10436 10437 static void sw_perf_event_destroy(struct perf_event *event) 10438 { 10439 u64 event_id = event->attr.config; 10440 10441 WARN_ON(event->parent); 10442 10443 static_key_slow_dec(&perf_swevent_enabled[event_id]); 10444 swevent_hlist_put(); 10445 } 10446 10447 static struct pmu perf_cpu_clock; /* fwd declaration */ 10448 static struct pmu perf_task_clock; 10449 10450 static int perf_swevent_init(struct perf_event *event) 10451 { 10452 u64 event_id = event->attr.config; 10453 10454 if (event->attr.type != PERF_TYPE_SOFTWARE) 10455 return -ENOENT; 10456 10457 /* 10458 * no branch sampling for software events 10459 */ 10460 if (has_branch_stack(event)) 10461 return -EOPNOTSUPP; 10462 10463 switch (event_id) { 10464 case PERF_COUNT_SW_CPU_CLOCK: 10465 event->attr.type = perf_cpu_clock.type; 10466 return -ENOENT; 10467 case PERF_COUNT_SW_TASK_CLOCK: 10468 event->attr.type = perf_task_clock.type; 10469 return -ENOENT; 10470 10471 default: 10472 break; 10473 } 10474 10475 if (event_id >= PERF_COUNT_SW_MAX) 10476 return -ENOENT; 10477 10478 if (!event->parent) { 10479 int err; 10480 10481 err = swevent_hlist_get(); 10482 if (err) 10483 return err; 10484 10485 static_key_slow_inc(&perf_swevent_enabled[event_id]); 10486 event->destroy = sw_perf_event_destroy; 10487 } 10488 10489 return 0; 10490 } 10491 10492 static struct pmu perf_swevent = { 10493 .task_ctx_nr = perf_sw_context, 10494 10495 .capabilities = PERF_PMU_CAP_NO_NMI, 10496 10497 .event_init = perf_swevent_init, 10498 .add = perf_swevent_add, 10499 .del = perf_swevent_del, 10500 .start = perf_swevent_start, 10501 .stop = perf_swevent_stop, 10502 .read = perf_swevent_read, 10503 }; 10504 10505 #ifdef CONFIG_EVENT_TRACING 10506 10507 static void tp_perf_event_destroy(struct perf_event *event) 10508 { 10509 perf_trace_destroy(event); 10510 } 10511 10512 static int perf_tp_event_init(struct perf_event *event) 10513 { 10514 int err; 10515 10516 if (event->attr.type != PERF_TYPE_TRACEPOINT) 10517 return -ENOENT; 10518 10519 /* 10520 * no branch sampling for tracepoint events 10521 */ 10522 if (has_branch_stack(event)) 10523 return -EOPNOTSUPP; 10524 10525 err = perf_trace_init(event); 10526 if (err) 10527 return err; 10528 10529 event->destroy = tp_perf_event_destroy; 10530 10531 return 0; 10532 } 10533 10534 static struct pmu perf_tracepoint = { 10535 .task_ctx_nr = perf_sw_context, 10536 10537 .event_init = perf_tp_event_init, 10538 .add = perf_trace_add, 10539 .del = perf_trace_del, 10540 .start = perf_swevent_start, 10541 .stop = perf_swevent_stop, 10542 .read = perf_swevent_read, 10543 }; 10544 10545 static int perf_tp_filter_match(struct perf_event *event, 10546 struct perf_raw_record *raw) 10547 { 10548 void *record = raw->frag.data; 10549 10550 /* only top level events have filters set */ 10551 if (event->parent) 10552 event = event->parent; 10553 10554 if (likely(!event->filter) || filter_match_preds(event->filter, record)) 10555 return 1; 10556 return 0; 10557 } 10558 10559 static int perf_tp_event_match(struct perf_event *event, 10560 struct perf_raw_record *raw, 10561 struct pt_regs *regs) 10562 { 10563 if (event->hw.state & PERF_HES_STOPPED) 10564 return 0; 10565 /* 10566 * If exclude_kernel, only trace user-space tracepoints (uprobes) 10567 */ 10568 if (event->attr.exclude_kernel && !user_mode(regs)) 10569 return 0; 10570 10571 if (!perf_tp_filter_match(event, raw)) 10572 return 0; 10573 10574 return 1; 10575 } 10576 10577 void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx, 10578 struct trace_event_call *call, u64 count, 10579 struct pt_regs *regs, struct hlist_head *head, 10580 struct task_struct *task) 10581 { 10582 if (bpf_prog_array_valid(call)) { 10583 *(struct pt_regs **)raw_data = regs; 10584 if (!trace_call_bpf(call, raw_data) || hlist_empty(head)) { 10585 perf_swevent_put_recursion_context(rctx); 10586 return; 10587 } 10588 } 10589 perf_tp_event(call->event.type, count, raw_data, size, regs, head, 10590 rctx, task); 10591 } 10592 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit); 10593 10594 static void __perf_tp_event_target_task(u64 count, void *record, 10595 struct pt_regs *regs, 10596 struct perf_sample_data *data, 10597 struct perf_raw_record *raw, 10598 struct perf_event *event) 10599 { 10600 struct trace_entry *entry = record; 10601 10602 if (event->attr.config != entry->type) 10603 return; 10604 /* Cannot deliver synchronous signal to other task. */ 10605 if (event->attr.sigtrap) 10606 return; 10607 if (perf_tp_event_match(event, raw, regs)) { 10608 perf_sample_data_init(data, 0, 0); 10609 perf_sample_save_raw_data(data, event, raw); 10610 perf_swevent_event(event, count, data, regs); 10611 } 10612 } 10613 10614 static void perf_tp_event_target_task(u64 count, void *record, 10615 struct pt_regs *regs, 10616 struct perf_sample_data *data, 10617 struct perf_raw_record *raw, 10618 struct perf_event_context *ctx) 10619 { 10620 unsigned int cpu = smp_processor_id(); 10621 struct pmu *pmu = &perf_tracepoint; 10622 struct perf_event *event, *sibling; 10623 10624 perf_event_groups_for_cpu_pmu(event, &ctx->pinned_groups, cpu, pmu) { 10625 __perf_tp_event_target_task(count, record, regs, data, raw, event); 10626 for_each_sibling_event(sibling, event) 10627 __perf_tp_event_target_task(count, record, regs, data, raw, sibling); 10628 } 10629 10630 perf_event_groups_for_cpu_pmu(event, &ctx->flexible_groups, cpu, pmu) { 10631 __perf_tp_event_target_task(count, record, regs, data, raw, event); 10632 for_each_sibling_event(sibling, event) 10633 __perf_tp_event_target_task(count, record, regs, data, raw, sibling); 10634 } 10635 } 10636 10637 void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size, 10638 struct pt_regs *regs, struct hlist_head *head, int rctx, 10639 struct task_struct *task) 10640 { 10641 struct perf_sample_data data; 10642 struct perf_event *event; 10643 10644 struct perf_raw_record raw = { 10645 .frag = { 10646 .size = entry_size, 10647 .data = record, 10648 }, 10649 }; 10650 10651 perf_trace_buf_update(record, event_type); 10652 10653 hlist_for_each_entry_rcu(event, head, hlist_entry) { 10654 if (perf_tp_event_match(event, &raw, regs)) { 10655 /* 10656 * Here use the same on-stack perf_sample_data, 10657 * some members in data are event-specific and 10658 * need to be re-computed for different sweveents. 10659 * Re-initialize data->sample_flags safely to avoid 10660 * the problem that next event skips preparing data 10661 * because data->sample_flags is set. 10662 */ 10663 perf_sample_data_init(&data, 0, 0); 10664 perf_sample_save_raw_data(&data, event, &raw); 10665 perf_swevent_event(event, count, &data, regs); 10666 } 10667 } 10668 10669 /* 10670 * If we got specified a target task, also iterate its context and 10671 * deliver this event there too. 10672 */ 10673 if (task && task != current) { 10674 struct perf_event_context *ctx; 10675 10676 rcu_read_lock(); 10677 ctx = rcu_dereference(task->perf_event_ctxp); 10678 if (!ctx) 10679 goto unlock; 10680 10681 raw_spin_lock(&ctx->lock); 10682 perf_tp_event_target_task(count, record, regs, &data, &raw, ctx); 10683 raw_spin_unlock(&ctx->lock); 10684 unlock: 10685 rcu_read_unlock(); 10686 } 10687 10688 perf_swevent_put_recursion_context(rctx); 10689 } 10690 EXPORT_SYMBOL_GPL(perf_tp_event); 10691 10692 #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS) 10693 /* 10694 * Flags in config, used by dynamic PMU kprobe and uprobe 10695 * The flags should match following PMU_FORMAT_ATTR(). 10696 * 10697 * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe 10698 * if not set, create kprobe/uprobe 10699 * 10700 * The following values specify a reference counter (or semaphore in the 10701 * terminology of tools like dtrace, systemtap, etc.) Userspace Statically 10702 * Defined Tracepoints (USDT). Currently, we use 40 bit for the offset. 10703 * 10704 * PERF_UPROBE_REF_CTR_OFFSET_BITS # of bits in config as th offset 10705 * PERF_UPROBE_REF_CTR_OFFSET_SHIFT # of bits to shift left 10706 */ 10707 enum perf_probe_config { 10708 PERF_PROBE_CONFIG_IS_RETPROBE = 1U << 0, /* [k,u]retprobe */ 10709 PERF_UPROBE_REF_CTR_OFFSET_BITS = 32, 10710 PERF_UPROBE_REF_CTR_OFFSET_SHIFT = 64 - PERF_UPROBE_REF_CTR_OFFSET_BITS, 10711 }; 10712 10713 PMU_FORMAT_ATTR(retprobe, "config:0"); 10714 #endif 10715 10716 #ifdef CONFIG_KPROBE_EVENTS 10717 static struct attribute *kprobe_attrs[] = { 10718 &format_attr_retprobe.attr, 10719 NULL, 10720 }; 10721 10722 static struct attribute_group kprobe_format_group = { 10723 .name = "format", 10724 .attrs = kprobe_attrs, 10725 }; 10726 10727 static const struct attribute_group *kprobe_attr_groups[] = { 10728 &kprobe_format_group, 10729 NULL, 10730 }; 10731 10732 static int perf_kprobe_event_init(struct perf_event *event); 10733 static struct pmu perf_kprobe = { 10734 .task_ctx_nr = perf_sw_context, 10735 .event_init = perf_kprobe_event_init, 10736 .add = perf_trace_add, 10737 .del = perf_trace_del, 10738 .start = perf_swevent_start, 10739 .stop = perf_swevent_stop, 10740 .read = perf_swevent_read, 10741 .attr_groups = kprobe_attr_groups, 10742 }; 10743 10744 static int perf_kprobe_event_init(struct perf_event *event) 10745 { 10746 int err; 10747 bool is_retprobe; 10748 10749 if (event->attr.type != perf_kprobe.type) 10750 return -ENOENT; 10751 10752 if (!perfmon_capable()) 10753 return -EACCES; 10754 10755 /* 10756 * no branch sampling for probe events 10757 */ 10758 if (has_branch_stack(event)) 10759 return -EOPNOTSUPP; 10760 10761 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE; 10762 err = perf_kprobe_init(event, is_retprobe); 10763 if (err) 10764 return err; 10765 10766 event->destroy = perf_kprobe_destroy; 10767 10768 return 0; 10769 } 10770 #endif /* CONFIG_KPROBE_EVENTS */ 10771 10772 #ifdef CONFIG_UPROBE_EVENTS 10773 PMU_FORMAT_ATTR(ref_ctr_offset, "config:32-63"); 10774 10775 static struct attribute *uprobe_attrs[] = { 10776 &format_attr_retprobe.attr, 10777 &format_attr_ref_ctr_offset.attr, 10778 NULL, 10779 }; 10780 10781 static struct attribute_group uprobe_format_group = { 10782 .name = "format", 10783 .attrs = uprobe_attrs, 10784 }; 10785 10786 static const struct attribute_group *uprobe_attr_groups[] = { 10787 &uprobe_format_group, 10788 NULL, 10789 }; 10790 10791 static int perf_uprobe_event_init(struct perf_event *event); 10792 static struct pmu perf_uprobe = { 10793 .task_ctx_nr = perf_sw_context, 10794 .event_init = perf_uprobe_event_init, 10795 .add = perf_trace_add, 10796 .del = perf_trace_del, 10797 .start = perf_swevent_start, 10798 .stop = perf_swevent_stop, 10799 .read = perf_swevent_read, 10800 .attr_groups = uprobe_attr_groups, 10801 }; 10802 10803 static int perf_uprobe_event_init(struct perf_event *event) 10804 { 10805 int err; 10806 unsigned long ref_ctr_offset; 10807 bool is_retprobe; 10808 10809 if (event->attr.type != perf_uprobe.type) 10810 return -ENOENT; 10811 10812 if (!perfmon_capable()) 10813 return -EACCES; 10814 10815 /* 10816 * no branch sampling for probe events 10817 */ 10818 if (has_branch_stack(event)) 10819 return -EOPNOTSUPP; 10820 10821 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE; 10822 ref_ctr_offset = event->attr.config >> PERF_UPROBE_REF_CTR_OFFSET_SHIFT; 10823 err = perf_uprobe_init(event, ref_ctr_offset, is_retprobe); 10824 if (err) 10825 return err; 10826 10827 event->destroy = perf_uprobe_destroy; 10828 10829 return 0; 10830 } 10831 #endif /* CONFIG_UPROBE_EVENTS */ 10832 10833 static inline void perf_tp_register(void) 10834 { 10835 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT); 10836 #ifdef CONFIG_KPROBE_EVENTS 10837 perf_pmu_register(&perf_kprobe, "kprobe", -1); 10838 #endif 10839 #ifdef CONFIG_UPROBE_EVENTS 10840 perf_pmu_register(&perf_uprobe, "uprobe", -1); 10841 #endif 10842 } 10843 10844 static void perf_event_free_filter(struct perf_event *event) 10845 { 10846 ftrace_profile_free_filter(event); 10847 } 10848 10849 /* 10850 * returns true if the event is a tracepoint, or a kprobe/upprobe created 10851 * with perf_event_open() 10852 */ 10853 static inline bool perf_event_is_tracing(struct perf_event *event) 10854 { 10855 if (event->pmu == &perf_tracepoint) 10856 return true; 10857 #ifdef CONFIG_KPROBE_EVENTS 10858 if (event->pmu == &perf_kprobe) 10859 return true; 10860 #endif 10861 #ifdef CONFIG_UPROBE_EVENTS 10862 if (event->pmu == &perf_uprobe) 10863 return true; 10864 #endif 10865 return false; 10866 } 10867 10868 int perf_event_set_bpf_prog(struct perf_event *event, struct bpf_prog *prog, 10869 u64 bpf_cookie) 10870 { 10871 bool is_kprobe, is_uprobe, is_tracepoint, is_syscall_tp; 10872 10873 if (!perf_event_is_tracing(event)) 10874 return perf_event_set_bpf_handler(event, prog, bpf_cookie); 10875 10876 is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_KPROBE; 10877 is_uprobe = event->tp_event->flags & TRACE_EVENT_FL_UPROBE; 10878 is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT; 10879 is_syscall_tp = is_syscall_trace_event(event->tp_event); 10880 if (!is_kprobe && !is_uprobe && !is_tracepoint && !is_syscall_tp) 10881 /* bpf programs can only be attached to u/kprobe or tracepoint */ 10882 return -EINVAL; 10883 10884 if (((is_kprobe || is_uprobe) && prog->type != BPF_PROG_TYPE_KPROBE) || 10885 (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT) || 10886 (is_syscall_tp && prog->type != BPF_PROG_TYPE_TRACEPOINT)) 10887 return -EINVAL; 10888 10889 if (prog->type == BPF_PROG_TYPE_KPROBE && prog->sleepable && !is_uprobe) 10890 /* only uprobe programs are allowed to be sleepable */ 10891 return -EINVAL; 10892 10893 /* Kprobe override only works for kprobes, not uprobes. */ 10894 if (prog->kprobe_override && !is_kprobe) 10895 return -EINVAL; 10896 10897 if (is_tracepoint || is_syscall_tp) { 10898 int off = trace_event_get_offsets(event->tp_event); 10899 10900 if (prog->aux->max_ctx_offset > off) 10901 return -EACCES; 10902 } 10903 10904 return perf_event_attach_bpf_prog(event, prog, bpf_cookie); 10905 } 10906 10907 void perf_event_free_bpf_prog(struct perf_event *event) 10908 { 10909 if (!event->prog) 10910 return; 10911 10912 if (!perf_event_is_tracing(event)) { 10913 perf_event_free_bpf_handler(event); 10914 return; 10915 } 10916 perf_event_detach_bpf_prog(event); 10917 } 10918 10919 #else 10920 10921 static inline void perf_tp_register(void) 10922 { 10923 } 10924 10925 static void perf_event_free_filter(struct perf_event *event) 10926 { 10927 } 10928 10929 int perf_event_set_bpf_prog(struct perf_event *event, struct bpf_prog *prog, 10930 u64 bpf_cookie) 10931 { 10932 return -ENOENT; 10933 } 10934 10935 void perf_event_free_bpf_prog(struct perf_event *event) 10936 { 10937 } 10938 #endif /* CONFIG_EVENT_TRACING */ 10939 10940 #ifdef CONFIG_HAVE_HW_BREAKPOINT 10941 void perf_bp_event(struct perf_event *bp, void *data) 10942 { 10943 struct perf_sample_data sample; 10944 struct pt_regs *regs = data; 10945 10946 perf_sample_data_init(&sample, bp->attr.bp_addr, 0); 10947 10948 if (!bp->hw.state && !perf_exclude_event(bp, regs)) 10949 perf_swevent_event(bp, 1, &sample, regs); 10950 } 10951 #endif 10952 10953 /* 10954 * Allocate a new address filter 10955 */ 10956 static struct perf_addr_filter * 10957 perf_addr_filter_new(struct perf_event *event, struct list_head *filters) 10958 { 10959 int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu); 10960 struct perf_addr_filter *filter; 10961 10962 filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node); 10963 if (!filter) 10964 return NULL; 10965 10966 INIT_LIST_HEAD(&filter->entry); 10967 list_add_tail(&filter->entry, filters); 10968 10969 return filter; 10970 } 10971 10972 static void free_filters_list(struct list_head *filters) 10973 { 10974 struct perf_addr_filter *filter, *iter; 10975 10976 list_for_each_entry_safe(filter, iter, filters, entry) { 10977 path_put(&filter->path); 10978 list_del(&filter->entry); 10979 kfree(filter); 10980 } 10981 } 10982 10983 /* 10984 * Free existing address filters and optionally install new ones 10985 */ 10986 static void perf_addr_filters_splice(struct perf_event *event, 10987 struct list_head *head) 10988 { 10989 unsigned long flags; 10990 LIST_HEAD(list); 10991 10992 if (!has_addr_filter(event)) 10993 return; 10994 10995 /* don't bother with children, they don't have their own filters */ 10996 if (event->parent) 10997 return; 10998 10999 raw_spin_lock_irqsave(&event->addr_filters.lock, flags); 11000 11001 list_splice_init(&event->addr_filters.list, &list); 11002 if (head) 11003 list_splice(head, &event->addr_filters.list); 11004 11005 raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags); 11006 11007 free_filters_list(&list); 11008 } 11009 11010 static void perf_free_addr_filters(struct perf_event *event) 11011 { 11012 /* 11013 * Used during free paths, there is no concurrency. 11014 */ 11015 if (list_empty(&event->addr_filters.list)) 11016 return; 11017 11018 perf_addr_filters_splice(event, NULL); 11019 } 11020 11021 /* 11022 * Scan through mm's vmas and see if one of them matches the 11023 * @filter; if so, adjust filter's address range. 11024 * Called with mm::mmap_lock down for reading. 11025 */ 11026 static void perf_addr_filter_apply(struct perf_addr_filter *filter, 11027 struct mm_struct *mm, 11028 struct perf_addr_filter_range *fr) 11029 { 11030 struct vm_area_struct *vma; 11031 VMA_ITERATOR(vmi, mm, 0); 11032 11033 for_each_vma(vmi, vma) { 11034 if (!vma->vm_file) 11035 continue; 11036 11037 if (perf_addr_filter_vma_adjust(filter, vma, fr)) 11038 return; 11039 } 11040 } 11041 11042 /* 11043 * Update event's address range filters based on the 11044 * task's existing mappings, if any. 11045 */ 11046 static void perf_event_addr_filters_apply(struct perf_event *event) 11047 { 11048 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event); 11049 struct task_struct *task = READ_ONCE(event->ctx->task); 11050 struct perf_addr_filter *filter; 11051 struct mm_struct *mm = NULL; 11052 unsigned int count = 0; 11053 unsigned long flags; 11054 11055 /* 11056 * We may observe TASK_TOMBSTONE, which means that the event tear-down 11057 * will stop on the parent's child_mutex that our caller is also holding 11058 */ 11059 if (task == TASK_TOMBSTONE) 11060 return; 11061 11062 if (ifh->nr_file_filters) { 11063 mm = get_task_mm(task); 11064 if (!mm) 11065 goto restart; 11066 11067 mmap_read_lock(mm); 11068 } 11069 11070 raw_spin_lock_irqsave(&ifh->lock, flags); 11071 list_for_each_entry(filter, &ifh->list, entry) { 11072 if (filter->path.dentry) { 11073 /* 11074 * Adjust base offset if the filter is associated to a 11075 * binary that needs to be mapped: 11076 */ 11077 event->addr_filter_ranges[count].start = 0; 11078 event->addr_filter_ranges[count].size = 0; 11079 11080 perf_addr_filter_apply(filter, mm, &event->addr_filter_ranges[count]); 11081 } else { 11082 event->addr_filter_ranges[count].start = filter->offset; 11083 event->addr_filter_ranges[count].size = filter->size; 11084 } 11085 11086 count++; 11087 } 11088 11089 event->addr_filters_gen++; 11090 raw_spin_unlock_irqrestore(&ifh->lock, flags); 11091 11092 if (ifh->nr_file_filters) { 11093 mmap_read_unlock(mm); 11094 11095 mmput(mm); 11096 } 11097 11098 restart: 11099 perf_event_stop(event, 1); 11100 } 11101 11102 /* 11103 * Address range filtering: limiting the data to certain 11104 * instruction address ranges. Filters are ioctl()ed to us from 11105 * userspace as ascii strings. 11106 * 11107 * Filter string format: 11108 * 11109 * ACTION RANGE_SPEC 11110 * where ACTION is one of the 11111 * * "filter": limit the trace to this region 11112 * * "start": start tracing from this address 11113 * * "stop": stop tracing at this address/region; 11114 * RANGE_SPEC is 11115 * * for kernel addresses: <start address>[/<size>] 11116 * * for object files: <start address>[/<size>]@</path/to/object/file> 11117 * 11118 * if <size> is not specified or is zero, the range is treated as a single 11119 * address; not valid for ACTION=="filter". 11120 */ 11121 enum { 11122 IF_ACT_NONE = -1, 11123 IF_ACT_FILTER, 11124 IF_ACT_START, 11125 IF_ACT_STOP, 11126 IF_SRC_FILE, 11127 IF_SRC_KERNEL, 11128 IF_SRC_FILEADDR, 11129 IF_SRC_KERNELADDR, 11130 }; 11131 11132 enum { 11133 IF_STATE_ACTION = 0, 11134 IF_STATE_SOURCE, 11135 IF_STATE_END, 11136 }; 11137 11138 static const match_table_t if_tokens = { 11139 { IF_ACT_FILTER, "filter" }, 11140 { IF_ACT_START, "start" }, 11141 { IF_ACT_STOP, "stop" }, 11142 { IF_SRC_FILE, "%u/%u@%s" }, 11143 { IF_SRC_KERNEL, "%u/%u" }, 11144 { IF_SRC_FILEADDR, "%u@%s" }, 11145 { IF_SRC_KERNELADDR, "%u" }, 11146 { IF_ACT_NONE, NULL }, 11147 }; 11148 11149 /* 11150 * Address filter string parser 11151 */ 11152 static int 11153 perf_event_parse_addr_filter(struct perf_event *event, char *fstr, 11154 struct list_head *filters) 11155 { 11156 struct perf_addr_filter *filter = NULL; 11157 char *start, *orig, *filename = NULL; 11158 substring_t args[MAX_OPT_ARGS]; 11159 int state = IF_STATE_ACTION, token; 11160 unsigned int kernel = 0; 11161 int ret = -EINVAL; 11162 11163 orig = fstr = kstrdup(fstr, GFP_KERNEL); 11164 if (!fstr) 11165 return -ENOMEM; 11166 11167 while ((start = strsep(&fstr, " ,\n")) != NULL) { 11168 static const enum perf_addr_filter_action_t actions[] = { 11169 [IF_ACT_FILTER] = PERF_ADDR_FILTER_ACTION_FILTER, 11170 [IF_ACT_START] = PERF_ADDR_FILTER_ACTION_START, 11171 [IF_ACT_STOP] = PERF_ADDR_FILTER_ACTION_STOP, 11172 }; 11173 ret = -EINVAL; 11174 11175 if (!*start) 11176 continue; 11177 11178 /* filter definition begins */ 11179 if (state == IF_STATE_ACTION) { 11180 filter = perf_addr_filter_new(event, filters); 11181 if (!filter) 11182 goto fail; 11183 } 11184 11185 token = match_token(start, if_tokens, args); 11186 switch (token) { 11187 case IF_ACT_FILTER: 11188 case IF_ACT_START: 11189 case IF_ACT_STOP: 11190 if (state != IF_STATE_ACTION) 11191 goto fail; 11192 11193 filter->action = actions[token]; 11194 state = IF_STATE_SOURCE; 11195 break; 11196 11197 case IF_SRC_KERNELADDR: 11198 case IF_SRC_KERNEL: 11199 kernel = 1; 11200 fallthrough; 11201 11202 case IF_SRC_FILEADDR: 11203 case IF_SRC_FILE: 11204 if (state != IF_STATE_SOURCE) 11205 goto fail; 11206 11207 *args[0].to = 0; 11208 ret = kstrtoul(args[0].from, 0, &filter->offset); 11209 if (ret) 11210 goto fail; 11211 11212 if (token == IF_SRC_KERNEL || token == IF_SRC_FILE) { 11213 *args[1].to = 0; 11214 ret = kstrtoul(args[1].from, 0, &filter->size); 11215 if (ret) 11216 goto fail; 11217 } 11218 11219 if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) { 11220 int fpos = token == IF_SRC_FILE ? 2 : 1; 11221 11222 kfree(filename); 11223 filename = match_strdup(&args[fpos]); 11224 if (!filename) { 11225 ret = -ENOMEM; 11226 goto fail; 11227 } 11228 } 11229 11230 state = IF_STATE_END; 11231 break; 11232 11233 default: 11234 goto fail; 11235 } 11236 11237 /* 11238 * Filter definition is fully parsed, validate and install it. 11239 * Make sure that it doesn't contradict itself or the event's 11240 * attribute. 11241 */ 11242 if (state == IF_STATE_END) { 11243 ret = -EINVAL; 11244 11245 /* 11246 * ACTION "filter" must have a non-zero length region 11247 * specified. 11248 */ 11249 if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER && 11250 !filter->size) 11251 goto fail; 11252 11253 if (!kernel) { 11254 if (!filename) 11255 goto fail; 11256 11257 /* 11258 * For now, we only support file-based filters 11259 * in per-task events; doing so for CPU-wide 11260 * events requires additional context switching 11261 * trickery, since same object code will be 11262 * mapped at different virtual addresses in 11263 * different processes. 11264 */ 11265 ret = -EOPNOTSUPP; 11266 if (!event->ctx->task) 11267 goto fail; 11268 11269 /* look up the path and grab its inode */ 11270 ret = kern_path(filename, LOOKUP_FOLLOW, 11271 &filter->path); 11272 if (ret) 11273 goto fail; 11274 11275 ret = -EINVAL; 11276 if (!filter->path.dentry || 11277 !S_ISREG(d_inode(filter->path.dentry) 11278 ->i_mode)) 11279 goto fail; 11280 11281 event->addr_filters.nr_file_filters++; 11282 } 11283 11284 /* ready to consume more filters */ 11285 kfree(filename); 11286 filename = NULL; 11287 state = IF_STATE_ACTION; 11288 filter = NULL; 11289 kernel = 0; 11290 } 11291 } 11292 11293 if (state != IF_STATE_ACTION) 11294 goto fail; 11295 11296 kfree(filename); 11297 kfree(orig); 11298 11299 return 0; 11300 11301 fail: 11302 kfree(filename); 11303 free_filters_list(filters); 11304 kfree(orig); 11305 11306 return ret; 11307 } 11308 11309 static int 11310 perf_event_set_addr_filter(struct perf_event *event, char *filter_str) 11311 { 11312 LIST_HEAD(filters); 11313 int ret; 11314 11315 /* 11316 * Since this is called in perf_ioctl() path, we're already holding 11317 * ctx::mutex. 11318 */ 11319 lockdep_assert_held(&event->ctx->mutex); 11320 11321 if (WARN_ON_ONCE(event->parent)) 11322 return -EINVAL; 11323 11324 ret = perf_event_parse_addr_filter(event, filter_str, &filters); 11325 if (ret) 11326 goto fail_clear_files; 11327 11328 ret = event->pmu->addr_filters_validate(&filters); 11329 if (ret) 11330 goto fail_free_filters; 11331 11332 /* remove existing filters, if any */ 11333 perf_addr_filters_splice(event, &filters); 11334 11335 /* install new filters */ 11336 perf_event_for_each_child(event, perf_event_addr_filters_apply); 11337 11338 return ret; 11339 11340 fail_free_filters: 11341 free_filters_list(&filters); 11342 11343 fail_clear_files: 11344 event->addr_filters.nr_file_filters = 0; 11345 11346 return ret; 11347 } 11348 11349 static int perf_event_set_filter(struct perf_event *event, void __user *arg) 11350 { 11351 int ret = -EINVAL; 11352 char *filter_str; 11353 11354 filter_str = strndup_user(arg, PAGE_SIZE); 11355 if (IS_ERR(filter_str)) 11356 return PTR_ERR(filter_str); 11357 11358 #ifdef CONFIG_EVENT_TRACING 11359 if (perf_event_is_tracing(event)) { 11360 struct perf_event_context *ctx = event->ctx; 11361 11362 /* 11363 * Beware, here be dragons!! 11364 * 11365 * the tracepoint muck will deadlock against ctx->mutex, but 11366 * the tracepoint stuff does not actually need it. So 11367 * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we 11368 * already have a reference on ctx. 11369 * 11370 * This can result in event getting moved to a different ctx, 11371 * but that does not affect the tracepoint state. 11372 */ 11373 mutex_unlock(&ctx->mutex); 11374 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str); 11375 mutex_lock(&ctx->mutex); 11376 } else 11377 #endif 11378 if (has_addr_filter(event)) 11379 ret = perf_event_set_addr_filter(event, filter_str); 11380 11381 kfree(filter_str); 11382 return ret; 11383 } 11384 11385 /* 11386 * hrtimer based swevent callback 11387 */ 11388 11389 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer) 11390 { 11391 enum hrtimer_restart ret = HRTIMER_RESTART; 11392 struct perf_sample_data data; 11393 struct pt_regs *regs; 11394 struct perf_event *event; 11395 u64 period; 11396 11397 event = container_of(hrtimer, struct perf_event, hw.hrtimer); 11398 11399 if (event->state != PERF_EVENT_STATE_ACTIVE) 11400 return HRTIMER_NORESTART; 11401 11402 event->pmu->read(event); 11403 11404 perf_sample_data_init(&data, 0, event->hw.last_period); 11405 regs = get_irq_regs(); 11406 11407 if (regs && !perf_exclude_event(event, regs)) { 11408 if (!(event->attr.exclude_idle && is_idle_task(current))) 11409 if (__perf_event_overflow(event, 1, &data, regs)) 11410 ret = HRTIMER_NORESTART; 11411 } 11412 11413 period = max_t(u64, 10000, event->hw.sample_period); 11414 hrtimer_forward_now(hrtimer, ns_to_ktime(period)); 11415 11416 return ret; 11417 } 11418 11419 static void perf_swevent_start_hrtimer(struct perf_event *event) 11420 { 11421 struct hw_perf_event *hwc = &event->hw; 11422 s64 period; 11423 11424 if (!is_sampling_event(event)) 11425 return; 11426 11427 period = local64_read(&hwc->period_left); 11428 if (period) { 11429 if (period < 0) 11430 period = 10000; 11431 11432 local64_set(&hwc->period_left, 0); 11433 } else { 11434 period = max_t(u64, 10000, hwc->sample_period); 11435 } 11436 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period), 11437 HRTIMER_MODE_REL_PINNED_HARD); 11438 } 11439 11440 static void perf_swevent_cancel_hrtimer(struct perf_event *event) 11441 { 11442 struct hw_perf_event *hwc = &event->hw; 11443 11444 if (is_sampling_event(event)) { 11445 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer); 11446 local64_set(&hwc->period_left, ktime_to_ns(remaining)); 11447 11448 hrtimer_cancel(&hwc->hrtimer); 11449 } 11450 } 11451 11452 static void perf_swevent_init_hrtimer(struct perf_event *event) 11453 { 11454 struct hw_perf_event *hwc = &event->hw; 11455 11456 if (!is_sampling_event(event)) 11457 return; 11458 11459 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD); 11460 hwc->hrtimer.function = perf_swevent_hrtimer; 11461 11462 /* 11463 * Since hrtimers have a fixed rate, we can do a static freq->period 11464 * mapping and avoid the whole period adjust feedback stuff. 11465 */ 11466 if (event->attr.freq) { 11467 long freq = event->attr.sample_freq; 11468 11469 event->attr.sample_period = NSEC_PER_SEC / freq; 11470 hwc->sample_period = event->attr.sample_period; 11471 local64_set(&hwc->period_left, hwc->sample_period); 11472 hwc->last_period = hwc->sample_period; 11473 event->attr.freq = 0; 11474 } 11475 } 11476 11477 /* 11478 * Software event: cpu wall time clock 11479 */ 11480 11481 static void cpu_clock_event_update(struct perf_event *event) 11482 { 11483 s64 prev; 11484 u64 now; 11485 11486 now = local_clock(); 11487 prev = local64_xchg(&event->hw.prev_count, now); 11488 local64_add(now - prev, &event->count); 11489 } 11490 11491 static void cpu_clock_event_start(struct perf_event *event, int flags) 11492 { 11493 local64_set(&event->hw.prev_count, local_clock()); 11494 perf_swevent_start_hrtimer(event); 11495 } 11496 11497 static void cpu_clock_event_stop(struct perf_event *event, int flags) 11498 { 11499 perf_swevent_cancel_hrtimer(event); 11500 cpu_clock_event_update(event); 11501 } 11502 11503 static int cpu_clock_event_add(struct perf_event *event, int flags) 11504 { 11505 if (flags & PERF_EF_START) 11506 cpu_clock_event_start(event, flags); 11507 perf_event_update_userpage(event); 11508 11509 return 0; 11510 } 11511 11512 static void cpu_clock_event_del(struct perf_event *event, int flags) 11513 { 11514 cpu_clock_event_stop(event, flags); 11515 } 11516 11517 static void cpu_clock_event_read(struct perf_event *event) 11518 { 11519 cpu_clock_event_update(event); 11520 } 11521 11522 static int cpu_clock_event_init(struct perf_event *event) 11523 { 11524 if (event->attr.type != perf_cpu_clock.type) 11525 return -ENOENT; 11526 11527 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK) 11528 return -ENOENT; 11529 11530 /* 11531 * no branch sampling for software events 11532 */ 11533 if (has_branch_stack(event)) 11534 return -EOPNOTSUPP; 11535 11536 perf_swevent_init_hrtimer(event); 11537 11538 return 0; 11539 } 11540 11541 static struct pmu perf_cpu_clock = { 11542 .task_ctx_nr = perf_sw_context, 11543 11544 .capabilities = PERF_PMU_CAP_NO_NMI, 11545 .dev = PMU_NULL_DEV, 11546 11547 .event_init = cpu_clock_event_init, 11548 .add = cpu_clock_event_add, 11549 .del = cpu_clock_event_del, 11550 .start = cpu_clock_event_start, 11551 .stop = cpu_clock_event_stop, 11552 .read = cpu_clock_event_read, 11553 }; 11554 11555 /* 11556 * Software event: task time clock 11557 */ 11558 11559 static void task_clock_event_update(struct perf_event *event, u64 now) 11560 { 11561 u64 prev; 11562 s64 delta; 11563 11564 prev = local64_xchg(&event->hw.prev_count, now); 11565 delta = now - prev; 11566 local64_add(delta, &event->count); 11567 } 11568 11569 static void task_clock_event_start(struct perf_event *event, int flags) 11570 { 11571 local64_set(&event->hw.prev_count, event->ctx->time); 11572 perf_swevent_start_hrtimer(event); 11573 } 11574 11575 static void task_clock_event_stop(struct perf_event *event, int flags) 11576 { 11577 perf_swevent_cancel_hrtimer(event); 11578 task_clock_event_update(event, event->ctx->time); 11579 } 11580 11581 static int task_clock_event_add(struct perf_event *event, int flags) 11582 { 11583 if (flags & PERF_EF_START) 11584 task_clock_event_start(event, flags); 11585 perf_event_update_userpage(event); 11586 11587 return 0; 11588 } 11589 11590 static void task_clock_event_del(struct perf_event *event, int flags) 11591 { 11592 task_clock_event_stop(event, PERF_EF_UPDATE); 11593 } 11594 11595 static void task_clock_event_read(struct perf_event *event) 11596 { 11597 u64 now = perf_clock(); 11598 u64 delta = now - event->ctx->timestamp; 11599 u64 time = event->ctx->time + delta; 11600 11601 task_clock_event_update(event, time); 11602 } 11603 11604 static int task_clock_event_init(struct perf_event *event) 11605 { 11606 if (event->attr.type != perf_task_clock.type) 11607 return -ENOENT; 11608 11609 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK) 11610 return -ENOENT; 11611 11612 /* 11613 * no branch sampling for software events 11614 */ 11615 if (has_branch_stack(event)) 11616 return -EOPNOTSUPP; 11617 11618 perf_swevent_init_hrtimer(event); 11619 11620 return 0; 11621 } 11622 11623 static struct pmu perf_task_clock = { 11624 .task_ctx_nr = perf_sw_context, 11625 11626 .capabilities = PERF_PMU_CAP_NO_NMI, 11627 .dev = PMU_NULL_DEV, 11628 11629 .event_init = task_clock_event_init, 11630 .add = task_clock_event_add, 11631 .del = task_clock_event_del, 11632 .start = task_clock_event_start, 11633 .stop = task_clock_event_stop, 11634 .read = task_clock_event_read, 11635 }; 11636 11637 static void perf_pmu_nop_void(struct pmu *pmu) 11638 { 11639 } 11640 11641 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags) 11642 { 11643 } 11644 11645 static int perf_pmu_nop_int(struct pmu *pmu) 11646 { 11647 return 0; 11648 } 11649 11650 static int perf_event_nop_int(struct perf_event *event, u64 value) 11651 { 11652 return 0; 11653 } 11654 11655 static DEFINE_PER_CPU(unsigned int, nop_txn_flags); 11656 11657 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags) 11658 { 11659 __this_cpu_write(nop_txn_flags, flags); 11660 11661 if (flags & ~PERF_PMU_TXN_ADD) 11662 return; 11663 11664 perf_pmu_disable(pmu); 11665 } 11666 11667 static int perf_pmu_commit_txn(struct pmu *pmu) 11668 { 11669 unsigned int flags = __this_cpu_read(nop_txn_flags); 11670 11671 __this_cpu_write(nop_txn_flags, 0); 11672 11673 if (flags & ~PERF_PMU_TXN_ADD) 11674 return 0; 11675 11676 perf_pmu_enable(pmu); 11677 return 0; 11678 } 11679 11680 static void perf_pmu_cancel_txn(struct pmu *pmu) 11681 { 11682 unsigned int flags = __this_cpu_read(nop_txn_flags); 11683 11684 __this_cpu_write(nop_txn_flags, 0); 11685 11686 if (flags & ~PERF_PMU_TXN_ADD) 11687 return; 11688 11689 perf_pmu_enable(pmu); 11690 } 11691 11692 static int perf_event_idx_default(struct perf_event *event) 11693 { 11694 return 0; 11695 } 11696 11697 /* 11698 * Let userspace know that this PMU supports address range filtering: 11699 */ 11700 static ssize_t nr_addr_filters_show(struct device *dev, 11701 struct device_attribute *attr, 11702 char *page) 11703 { 11704 struct pmu *pmu = dev_get_drvdata(dev); 11705 11706 return scnprintf(page, PAGE_SIZE - 1, "%d\n", pmu->nr_addr_filters); 11707 } 11708 DEVICE_ATTR_RO(nr_addr_filters); 11709 11710 static struct idr pmu_idr; 11711 11712 static ssize_t 11713 type_show(struct device *dev, struct device_attribute *attr, char *page) 11714 { 11715 struct pmu *pmu = dev_get_drvdata(dev); 11716 11717 return scnprintf(page, PAGE_SIZE - 1, "%d\n", pmu->type); 11718 } 11719 static DEVICE_ATTR_RO(type); 11720 11721 static ssize_t 11722 perf_event_mux_interval_ms_show(struct device *dev, 11723 struct device_attribute *attr, 11724 char *page) 11725 { 11726 struct pmu *pmu = dev_get_drvdata(dev); 11727 11728 return scnprintf(page, PAGE_SIZE - 1, "%d\n", pmu->hrtimer_interval_ms); 11729 } 11730 11731 static DEFINE_MUTEX(mux_interval_mutex); 11732 11733 static ssize_t 11734 perf_event_mux_interval_ms_store(struct device *dev, 11735 struct device_attribute *attr, 11736 const char *buf, size_t count) 11737 { 11738 struct pmu *pmu = dev_get_drvdata(dev); 11739 int timer, cpu, ret; 11740 11741 ret = kstrtoint(buf, 0, &timer); 11742 if (ret) 11743 return ret; 11744 11745 if (timer < 1) 11746 return -EINVAL; 11747 11748 /* same value, noting to do */ 11749 if (timer == pmu->hrtimer_interval_ms) 11750 return count; 11751 11752 mutex_lock(&mux_interval_mutex); 11753 pmu->hrtimer_interval_ms = timer; 11754 11755 /* update all cpuctx for this PMU */ 11756 cpus_read_lock(); 11757 for_each_online_cpu(cpu) { 11758 struct perf_cpu_pmu_context *cpc; 11759 cpc = per_cpu_ptr(pmu->cpu_pmu_context, cpu); 11760 cpc->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer); 11761 11762 cpu_function_call(cpu, perf_mux_hrtimer_restart_ipi, cpc); 11763 } 11764 cpus_read_unlock(); 11765 mutex_unlock(&mux_interval_mutex); 11766 11767 return count; 11768 } 11769 static DEVICE_ATTR_RW(perf_event_mux_interval_ms); 11770 11771 static inline const struct cpumask *perf_scope_cpu_topology_cpumask(unsigned int scope, int cpu) 11772 { 11773 switch (scope) { 11774 case PERF_PMU_SCOPE_CORE: 11775 return topology_sibling_cpumask(cpu); 11776 case PERF_PMU_SCOPE_DIE: 11777 return topology_die_cpumask(cpu); 11778 case PERF_PMU_SCOPE_CLUSTER: 11779 return topology_cluster_cpumask(cpu); 11780 case PERF_PMU_SCOPE_PKG: 11781 return topology_core_cpumask(cpu); 11782 case PERF_PMU_SCOPE_SYS_WIDE: 11783 return cpu_online_mask; 11784 } 11785 11786 return NULL; 11787 } 11788 11789 static inline struct cpumask *perf_scope_cpumask(unsigned int scope) 11790 { 11791 switch (scope) { 11792 case PERF_PMU_SCOPE_CORE: 11793 return perf_online_core_mask; 11794 case PERF_PMU_SCOPE_DIE: 11795 return perf_online_die_mask; 11796 case PERF_PMU_SCOPE_CLUSTER: 11797 return perf_online_cluster_mask; 11798 case PERF_PMU_SCOPE_PKG: 11799 return perf_online_pkg_mask; 11800 case PERF_PMU_SCOPE_SYS_WIDE: 11801 return perf_online_sys_mask; 11802 } 11803 11804 return NULL; 11805 } 11806 11807 static ssize_t cpumask_show(struct device *dev, struct device_attribute *attr, 11808 char *buf) 11809 { 11810 struct pmu *pmu = dev_get_drvdata(dev); 11811 struct cpumask *mask = perf_scope_cpumask(pmu->scope); 11812 11813 if (mask) 11814 return cpumap_print_to_pagebuf(true, buf, mask); 11815 return 0; 11816 } 11817 11818 static DEVICE_ATTR_RO(cpumask); 11819 11820 static struct attribute *pmu_dev_attrs[] = { 11821 &dev_attr_type.attr, 11822 &dev_attr_perf_event_mux_interval_ms.attr, 11823 &dev_attr_nr_addr_filters.attr, 11824 &dev_attr_cpumask.attr, 11825 NULL, 11826 }; 11827 11828 static umode_t pmu_dev_is_visible(struct kobject *kobj, struct attribute *a, int n) 11829 { 11830 struct device *dev = kobj_to_dev(kobj); 11831 struct pmu *pmu = dev_get_drvdata(dev); 11832 11833 if (n == 2 && !pmu->nr_addr_filters) 11834 return 0; 11835 11836 /* cpumask */ 11837 if (n == 3 && pmu->scope == PERF_PMU_SCOPE_NONE) 11838 return 0; 11839 11840 return a->mode; 11841 } 11842 11843 static struct attribute_group pmu_dev_attr_group = { 11844 .is_visible = pmu_dev_is_visible, 11845 .attrs = pmu_dev_attrs, 11846 }; 11847 11848 static const struct attribute_group *pmu_dev_groups[] = { 11849 &pmu_dev_attr_group, 11850 NULL, 11851 }; 11852 11853 static int pmu_bus_running; 11854 static struct bus_type pmu_bus = { 11855 .name = "event_source", 11856 .dev_groups = pmu_dev_groups, 11857 }; 11858 11859 static void pmu_dev_release(struct device *dev) 11860 { 11861 kfree(dev); 11862 } 11863 11864 static int pmu_dev_alloc(struct pmu *pmu) 11865 { 11866 int ret = -ENOMEM; 11867 11868 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL); 11869 if (!pmu->dev) 11870 goto out; 11871 11872 pmu->dev->groups = pmu->attr_groups; 11873 device_initialize(pmu->dev); 11874 11875 dev_set_drvdata(pmu->dev, pmu); 11876 pmu->dev->bus = &pmu_bus; 11877 pmu->dev->parent = pmu->parent; 11878 pmu->dev->release = pmu_dev_release; 11879 11880 ret = dev_set_name(pmu->dev, "%s", pmu->name); 11881 if (ret) 11882 goto free_dev; 11883 11884 ret = device_add(pmu->dev); 11885 if (ret) 11886 goto free_dev; 11887 11888 if (pmu->attr_update) { 11889 ret = sysfs_update_groups(&pmu->dev->kobj, pmu->attr_update); 11890 if (ret) 11891 goto del_dev; 11892 } 11893 11894 out: 11895 return ret; 11896 11897 del_dev: 11898 device_del(pmu->dev); 11899 11900 free_dev: 11901 put_device(pmu->dev); 11902 pmu->dev = NULL; 11903 goto out; 11904 } 11905 11906 static struct lock_class_key cpuctx_mutex; 11907 static struct lock_class_key cpuctx_lock; 11908 11909 static bool idr_cmpxchg(struct idr *idr, unsigned long id, void *old, void *new) 11910 { 11911 void *tmp, *val = idr_find(idr, id); 11912 11913 if (val != old) 11914 return false; 11915 11916 tmp = idr_replace(idr, new, id); 11917 if (IS_ERR(tmp)) 11918 return false; 11919 11920 WARN_ON_ONCE(tmp != val); 11921 return true; 11922 } 11923 11924 static void perf_pmu_free(struct pmu *pmu) 11925 { 11926 if (pmu_bus_running && pmu->dev && pmu->dev != PMU_NULL_DEV) { 11927 if (pmu->nr_addr_filters) 11928 device_remove_file(pmu->dev, &dev_attr_nr_addr_filters); 11929 device_del(pmu->dev); 11930 put_device(pmu->dev); 11931 } 11932 free_percpu(pmu->cpu_pmu_context); 11933 } 11934 11935 DEFINE_FREE(pmu_unregister, struct pmu *, if (_T) perf_pmu_free(_T)) 11936 11937 int perf_pmu_register(struct pmu *_pmu, const char *name, int type) 11938 { 11939 int cpu, max = PERF_TYPE_MAX; 11940 11941 struct pmu *pmu __free(pmu_unregister) = _pmu; 11942 guard(mutex)(&pmus_lock); 11943 11944 if (WARN_ONCE(!name, "Can not register anonymous pmu.\n")) 11945 return -EINVAL; 11946 11947 if (WARN_ONCE(pmu->scope >= PERF_PMU_MAX_SCOPE, 11948 "Can not register a pmu with an invalid scope.\n")) 11949 return -EINVAL; 11950 11951 pmu->name = name; 11952 11953 if (type >= 0) 11954 max = type; 11955 11956 CLASS(idr_alloc, pmu_type)(&pmu_idr, NULL, max, 0, GFP_KERNEL); 11957 if (pmu_type.id < 0) 11958 return pmu_type.id; 11959 11960 WARN_ON(type >= 0 && pmu_type.id != type); 11961 11962 pmu->type = pmu_type.id; 11963 atomic_set(&pmu->exclusive_cnt, 0); 11964 11965 if (pmu_bus_running && !pmu->dev) { 11966 int ret = pmu_dev_alloc(pmu); 11967 if (ret) 11968 return ret; 11969 } 11970 11971 pmu->cpu_pmu_context = alloc_percpu(struct perf_cpu_pmu_context); 11972 if (!pmu->cpu_pmu_context) 11973 return -ENOMEM; 11974 11975 for_each_possible_cpu(cpu) { 11976 struct perf_cpu_pmu_context *cpc; 11977 11978 cpc = per_cpu_ptr(pmu->cpu_pmu_context, cpu); 11979 __perf_init_event_pmu_context(&cpc->epc, pmu); 11980 __perf_mux_hrtimer_init(cpc, cpu); 11981 } 11982 11983 if (!pmu->start_txn) { 11984 if (pmu->pmu_enable) { 11985 /* 11986 * If we have pmu_enable/pmu_disable calls, install 11987 * transaction stubs that use that to try and batch 11988 * hardware accesses. 11989 */ 11990 pmu->start_txn = perf_pmu_start_txn; 11991 pmu->commit_txn = perf_pmu_commit_txn; 11992 pmu->cancel_txn = perf_pmu_cancel_txn; 11993 } else { 11994 pmu->start_txn = perf_pmu_nop_txn; 11995 pmu->commit_txn = perf_pmu_nop_int; 11996 pmu->cancel_txn = perf_pmu_nop_void; 11997 } 11998 } 11999 12000 if (!pmu->pmu_enable) { 12001 pmu->pmu_enable = perf_pmu_nop_void; 12002 pmu->pmu_disable = perf_pmu_nop_void; 12003 } 12004 12005 if (!pmu->check_period) 12006 pmu->check_period = perf_event_nop_int; 12007 12008 if (!pmu->event_idx) 12009 pmu->event_idx = perf_event_idx_default; 12010 12011 /* 12012 * Now that the PMU is complete, make it visible to perf_try_init_event(). 12013 */ 12014 if (!idr_cmpxchg(&pmu_idr, pmu->type, NULL, pmu)) 12015 return -EINVAL; 12016 list_add_rcu(&pmu->entry, &pmus); 12017 12018 take_idr_id(pmu_type); 12019 _pmu = no_free_ptr(pmu); // let it rip 12020 return 0; 12021 } 12022 EXPORT_SYMBOL_GPL(perf_pmu_register); 12023 12024 void perf_pmu_unregister(struct pmu *pmu) 12025 { 12026 scoped_guard (mutex, &pmus_lock) { 12027 list_del_rcu(&pmu->entry); 12028 idr_remove(&pmu_idr, pmu->type); 12029 } 12030 12031 /* 12032 * We dereference the pmu list under both SRCU and regular RCU, so 12033 * synchronize against both of those. 12034 */ 12035 synchronize_srcu(&pmus_srcu); 12036 synchronize_rcu(); 12037 12038 perf_pmu_free(pmu); 12039 } 12040 EXPORT_SYMBOL_GPL(perf_pmu_unregister); 12041 12042 static inline bool has_extended_regs(struct perf_event *event) 12043 { 12044 return (event->attr.sample_regs_user & PERF_REG_EXTENDED_MASK) || 12045 (event->attr.sample_regs_intr & PERF_REG_EXTENDED_MASK); 12046 } 12047 12048 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event) 12049 { 12050 struct perf_event_context *ctx = NULL; 12051 int ret; 12052 12053 if (!try_module_get(pmu->module)) 12054 return -ENODEV; 12055 12056 /* 12057 * A number of pmu->event_init() methods iterate the sibling_list to, 12058 * for example, validate if the group fits on the PMU. Therefore, 12059 * if this is a sibling event, acquire the ctx->mutex to protect 12060 * the sibling_list. 12061 */ 12062 if (event->group_leader != event && pmu->task_ctx_nr != perf_sw_context) { 12063 /* 12064 * This ctx->mutex can nest when we're called through 12065 * inheritance. See the perf_event_ctx_lock_nested() comment. 12066 */ 12067 ctx = perf_event_ctx_lock_nested(event->group_leader, 12068 SINGLE_DEPTH_NESTING); 12069 BUG_ON(!ctx); 12070 } 12071 12072 event->pmu = pmu; 12073 ret = pmu->event_init(event); 12074 12075 if (ctx) 12076 perf_event_ctx_unlock(event->group_leader, ctx); 12077 12078 if (!ret) { 12079 if (!(pmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS) && 12080 has_extended_regs(event)) 12081 ret = -EOPNOTSUPP; 12082 12083 if (pmu->capabilities & PERF_PMU_CAP_NO_EXCLUDE && 12084 event_has_any_exclude_flag(event)) 12085 ret = -EINVAL; 12086 12087 if (pmu->scope != PERF_PMU_SCOPE_NONE && event->cpu >= 0) { 12088 const struct cpumask *cpumask = perf_scope_cpu_topology_cpumask(pmu->scope, event->cpu); 12089 struct cpumask *pmu_cpumask = perf_scope_cpumask(pmu->scope); 12090 int cpu; 12091 12092 if (pmu_cpumask && cpumask) { 12093 cpu = cpumask_any_and(pmu_cpumask, cpumask); 12094 if (cpu >= nr_cpu_ids) 12095 ret = -ENODEV; 12096 else 12097 event->event_caps |= PERF_EV_CAP_READ_SCOPE; 12098 } else { 12099 ret = -ENODEV; 12100 } 12101 } 12102 12103 if (ret && event->destroy) 12104 event->destroy(event); 12105 } 12106 12107 if (ret) { 12108 event->pmu = NULL; 12109 module_put(pmu->module); 12110 } 12111 12112 return ret; 12113 } 12114 12115 static struct pmu *perf_init_event(struct perf_event *event) 12116 { 12117 bool extended_type = false; 12118 struct pmu *pmu; 12119 int type, ret; 12120 12121 guard(srcu)(&pmus_srcu); 12122 12123 /* 12124 * Save original type before calling pmu->event_init() since certain 12125 * pmus overwrites event->attr.type to forward event to another pmu. 12126 */ 12127 event->orig_type = event->attr.type; 12128 12129 /* Try parent's PMU first: */ 12130 if (event->parent && event->parent->pmu) { 12131 pmu = event->parent->pmu; 12132 ret = perf_try_init_event(pmu, event); 12133 if (!ret) 12134 return pmu; 12135 } 12136 12137 /* 12138 * PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE 12139 * are often aliases for PERF_TYPE_RAW. 12140 */ 12141 type = event->attr.type; 12142 if (type == PERF_TYPE_HARDWARE || type == PERF_TYPE_HW_CACHE) { 12143 type = event->attr.config >> PERF_PMU_TYPE_SHIFT; 12144 if (!type) { 12145 type = PERF_TYPE_RAW; 12146 } else { 12147 extended_type = true; 12148 event->attr.config &= PERF_HW_EVENT_MASK; 12149 } 12150 } 12151 12152 again: 12153 scoped_guard (rcu) 12154 pmu = idr_find(&pmu_idr, type); 12155 if (pmu) { 12156 if (event->attr.type != type && type != PERF_TYPE_RAW && 12157 !(pmu->capabilities & PERF_PMU_CAP_EXTENDED_HW_TYPE)) 12158 return ERR_PTR(-ENOENT); 12159 12160 ret = perf_try_init_event(pmu, event); 12161 if (ret == -ENOENT && event->attr.type != type && !extended_type) { 12162 type = event->attr.type; 12163 goto again; 12164 } 12165 12166 if (ret) 12167 return ERR_PTR(ret); 12168 12169 return pmu; 12170 } 12171 12172 list_for_each_entry_rcu(pmu, &pmus, entry, lockdep_is_held(&pmus_srcu)) { 12173 ret = perf_try_init_event(pmu, event); 12174 if (!ret) 12175 return pmu; 12176 12177 if (ret != -ENOENT) 12178 return ERR_PTR(ret); 12179 } 12180 12181 return ERR_PTR(-ENOENT); 12182 } 12183 12184 static void attach_sb_event(struct perf_event *event) 12185 { 12186 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu); 12187 12188 raw_spin_lock(&pel->lock); 12189 list_add_rcu(&event->sb_list, &pel->list); 12190 raw_spin_unlock(&pel->lock); 12191 } 12192 12193 /* 12194 * We keep a list of all !task (and therefore per-cpu) events 12195 * that need to receive side-band records. 12196 * 12197 * This avoids having to scan all the various PMU per-cpu contexts 12198 * looking for them. 12199 */ 12200 static void account_pmu_sb_event(struct perf_event *event) 12201 { 12202 if (is_sb_event(event)) 12203 attach_sb_event(event); 12204 } 12205 12206 /* Freq events need the tick to stay alive (see perf_event_task_tick). */ 12207 static void account_freq_event_nohz(void) 12208 { 12209 #ifdef CONFIG_NO_HZ_FULL 12210 /* Lock so we don't race with concurrent unaccount */ 12211 spin_lock(&nr_freq_lock); 12212 if (atomic_inc_return(&nr_freq_events) == 1) 12213 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS); 12214 spin_unlock(&nr_freq_lock); 12215 #endif 12216 } 12217 12218 static void account_freq_event(void) 12219 { 12220 if (tick_nohz_full_enabled()) 12221 account_freq_event_nohz(); 12222 else 12223 atomic_inc(&nr_freq_events); 12224 } 12225 12226 12227 static void account_event(struct perf_event *event) 12228 { 12229 bool inc = false; 12230 12231 if (event->parent) 12232 return; 12233 12234 if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB)) 12235 inc = true; 12236 if (event->attr.mmap || event->attr.mmap_data) 12237 atomic_inc(&nr_mmap_events); 12238 if (event->attr.build_id) 12239 atomic_inc(&nr_build_id_events); 12240 if (event->attr.comm) 12241 atomic_inc(&nr_comm_events); 12242 if (event->attr.namespaces) 12243 atomic_inc(&nr_namespaces_events); 12244 if (event->attr.cgroup) 12245 atomic_inc(&nr_cgroup_events); 12246 if (event->attr.task) 12247 atomic_inc(&nr_task_events); 12248 if (event->attr.freq) 12249 account_freq_event(); 12250 if (event->attr.context_switch) { 12251 atomic_inc(&nr_switch_events); 12252 inc = true; 12253 } 12254 if (has_branch_stack(event)) 12255 inc = true; 12256 if (is_cgroup_event(event)) 12257 inc = true; 12258 if (event->attr.ksymbol) 12259 atomic_inc(&nr_ksymbol_events); 12260 if (event->attr.bpf_event) 12261 atomic_inc(&nr_bpf_events); 12262 if (event->attr.text_poke) 12263 atomic_inc(&nr_text_poke_events); 12264 12265 if (inc) { 12266 /* 12267 * We need the mutex here because static_branch_enable() 12268 * must complete *before* the perf_sched_count increment 12269 * becomes visible. 12270 */ 12271 if (atomic_inc_not_zero(&perf_sched_count)) 12272 goto enabled; 12273 12274 mutex_lock(&perf_sched_mutex); 12275 if (!atomic_read(&perf_sched_count)) { 12276 static_branch_enable(&perf_sched_events); 12277 /* 12278 * Guarantee that all CPUs observe they key change and 12279 * call the perf scheduling hooks before proceeding to 12280 * install events that need them. 12281 */ 12282 synchronize_rcu(); 12283 } 12284 /* 12285 * Now that we have waited for the sync_sched(), allow further 12286 * increments to by-pass the mutex. 12287 */ 12288 atomic_inc(&perf_sched_count); 12289 mutex_unlock(&perf_sched_mutex); 12290 } 12291 enabled: 12292 12293 account_pmu_sb_event(event); 12294 } 12295 12296 /* 12297 * Allocate and initialize an event structure 12298 */ 12299 static struct perf_event * 12300 perf_event_alloc(struct perf_event_attr *attr, int cpu, 12301 struct task_struct *task, 12302 struct perf_event *group_leader, 12303 struct perf_event *parent_event, 12304 perf_overflow_handler_t overflow_handler, 12305 void *context, int cgroup_fd) 12306 { 12307 struct pmu *pmu; 12308 struct hw_perf_event *hwc; 12309 long err = -EINVAL; 12310 int node; 12311 12312 if ((unsigned)cpu >= nr_cpu_ids) { 12313 if (!task || cpu != -1) 12314 return ERR_PTR(-EINVAL); 12315 } 12316 if (attr->sigtrap && !task) { 12317 /* Requires a task: avoid signalling random tasks. */ 12318 return ERR_PTR(-EINVAL); 12319 } 12320 12321 node = (cpu >= 0) ? cpu_to_node(cpu) : -1; 12322 struct perf_event *event __free(__free_event) = 12323 kmem_cache_alloc_node(perf_event_cache, GFP_KERNEL | __GFP_ZERO, node); 12324 if (!event) 12325 return ERR_PTR(-ENOMEM); 12326 12327 /* 12328 * Single events are their own group leaders, with an 12329 * empty sibling list: 12330 */ 12331 if (!group_leader) 12332 group_leader = event; 12333 12334 mutex_init(&event->child_mutex); 12335 INIT_LIST_HEAD(&event->child_list); 12336 12337 INIT_LIST_HEAD(&event->event_entry); 12338 INIT_LIST_HEAD(&event->sibling_list); 12339 INIT_LIST_HEAD(&event->active_list); 12340 init_event_group(event); 12341 INIT_LIST_HEAD(&event->rb_entry); 12342 INIT_LIST_HEAD(&event->active_entry); 12343 INIT_LIST_HEAD(&event->addr_filters.list); 12344 INIT_HLIST_NODE(&event->hlist_entry); 12345 12346 12347 init_waitqueue_head(&event->waitq); 12348 init_irq_work(&event->pending_irq, perf_pending_irq); 12349 event->pending_disable_irq = IRQ_WORK_INIT_HARD(perf_pending_disable); 12350 init_task_work(&event->pending_task, perf_pending_task); 12351 rcuwait_init(&event->pending_work_wait); 12352 12353 mutex_init(&event->mmap_mutex); 12354 raw_spin_lock_init(&event->addr_filters.lock); 12355 12356 atomic_long_set(&event->refcount, 1); 12357 event->cpu = cpu; 12358 event->attr = *attr; 12359 event->group_leader = group_leader; 12360 event->pmu = NULL; 12361 event->oncpu = -1; 12362 12363 event->parent = parent_event; 12364 12365 event->ns = get_pid_ns(task_active_pid_ns(current)); 12366 event->id = atomic64_inc_return(&perf_event_id); 12367 12368 event->state = PERF_EVENT_STATE_INACTIVE; 12369 12370 if (parent_event) 12371 event->event_caps = parent_event->event_caps; 12372 12373 if (task) { 12374 event->attach_state = PERF_ATTACH_TASK; 12375 /* 12376 * XXX pmu::event_init needs to know what task to account to 12377 * and we cannot use the ctx information because we need the 12378 * pmu before we get a ctx. 12379 */ 12380 event->hw.target = get_task_struct(task); 12381 } 12382 12383 event->clock = &local_clock; 12384 if (parent_event) 12385 event->clock = parent_event->clock; 12386 12387 if (!overflow_handler && parent_event) { 12388 overflow_handler = parent_event->overflow_handler; 12389 context = parent_event->overflow_handler_context; 12390 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING) 12391 if (parent_event->prog) { 12392 struct bpf_prog *prog = parent_event->prog; 12393 12394 bpf_prog_inc(prog); 12395 event->prog = prog; 12396 } 12397 #endif 12398 } 12399 12400 if (overflow_handler) { 12401 event->overflow_handler = overflow_handler; 12402 event->overflow_handler_context = context; 12403 } else if (is_write_backward(event)){ 12404 event->overflow_handler = perf_event_output_backward; 12405 event->overflow_handler_context = NULL; 12406 } else { 12407 event->overflow_handler = perf_event_output_forward; 12408 event->overflow_handler_context = NULL; 12409 } 12410 12411 perf_event__state_init(event); 12412 12413 pmu = NULL; 12414 12415 hwc = &event->hw; 12416 hwc->sample_period = attr->sample_period; 12417 if (attr->freq && attr->sample_freq) 12418 hwc->sample_period = 1; 12419 hwc->last_period = hwc->sample_period; 12420 12421 local64_set(&hwc->period_left, hwc->sample_period); 12422 12423 /* 12424 * We do not support PERF_SAMPLE_READ on inherited events unless 12425 * PERF_SAMPLE_TID is also selected, which allows inherited events to 12426 * collect per-thread samples. 12427 * See perf_output_read(). 12428 */ 12429 if (has_inherit_and_sample_read(attr) && !(attr->sample_type & PERF_SAMPLE_TID)) 12430 return ERR_PTR(-EINVAL); 12431 12432 if (!has_branch_stack(event)) 12433 event->attr.branch_sample_type = 0; 12434 12435 pmu = perf_init_event(event); 12436 if (IS_ERR(pmu)) 12437 return (void*)pmu; 12438 12439 /* 12440 * Disallow uncore-task events. Similarly, disallow uncore-cgroup 12441 * events (they don't make sense as the cgroup will be different 12442 * on other CPUs in the uncore mask). 12443 */ 12444 if (pmu->task_ctx_nr == perf_invalid_context && (task || cgroup_fd != -1)) 12445 return ERR_PTR(-EINVAL); 12446 12447 if (event->attr.aux_output && 12448 (!(pmu->capabilities & PERF_PMU_CAP_AUX_OUTPUT) || 12449 event->attr.aux_pause || event->attr.aux_resume)) 12450 return ERR_PTR(-EOPNOTSUPP); 12451 12452 if (event->attr.aux_pause && event->attr.aux_resume) 12453 return ERR_PTR(-EINVAL); 12454 12455 if (event->attr.aux_start_paused) { 12456 if (!(pmu->capabilities & PERF_PMU_CAP_AUX_PAUSE)) 12457 return ERR_PTR(-EOPNOTSUPP); 12458 event->hw.aux_paused = 1; 12459 } 12460 12461 if (cgroup_fd != -1) { 12462 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader); 12463 if (err) 12464 return ERR_PTR(err); 12465 } 12466 12467 err = exclusive_event_init(event); 12468 if (err) 12469 return ERR_PTR(err); 12470 12471 if (has_addr_filter(event)) { 12472 event->addr_filter_ranges = kcalloc(pmu->nr_addr_filters, 12473 sizeof(struct perf_addr_filter_range), 12474 GFP_KERNEL); 12475 if (!event->addr_filter_ranges) 12476 return ERR_PTR(-ENOMEM); 12477 12478 /* 12479 * Clone the parent's vma offsets: they are valid until exec() 12480 * even if the mm is not shared with the parent. 12481 */ 12482 if (event->parent) { 12483 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event); 12484 12485 raw_spin_lock_irq(&ifh->lock); 12486 memcpy(event->addr_filter_ranges, 12487 event->parent->addr_filter_ranges, 12488 pmu->nr_addr_filters * sizeof(struct perf_addr_filter_range)); 12489 raw_spin_unlock_irq(&ifh->lock); 12490 } 12491 12492 /* force hw sync on the address filters */ 12493 event->addr_filters_gen = 1; 12494 } 12495 12496 if (!event->parent) { 12497 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) { 12498 err = get_callchain_buffers(attr->sample_max_stack); 12499 if (err) 12500 return ERR_PTR(err); 12501 event->attach_state |= PERF_ATTACH_CALLCHAIN; 12502 } 12503 } 12504 12505 err = security_perf_event_alloc(event); 12506 if (err) 12507 return ERR_PTR(err); 12508 12509 /* symmetric to unaccount_event() in _free_event() */ 12510 account_event(event); 12511 12512 return_ptr(event); 12513 } 12514 12515 static int perf_copy_attr(struct perf_event_attr __user *uattr, 12516 struct perf_event_attr *attr) 12517 { 12518 u32 size; 12519 int ret; 12520 12521 /* Zero the full structure, so that a short copy will be nice. */ 12522 memset(attr, 0, sizeof(*attr)); 12523 12524 ret = get_user(size, &uattr->size); 12525 if (ret) 12526 return ret; 12527 12528 /* ABI compatibility quirk: */ 12529 if (!size) 12530 size = PERF_ATTR_SIZE_VER0; 12531 if (size < PERF_ATTR_SIZE_VER0 || size > PAGE_SIZE) 12532 goto err_size; 12533 12534 ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size); 12535 if (ret) { 12536 if (ret == -E2BIG) 12537 goto err_size; 12538 return ret; 12539 } 12540 12541 attr->size = size; 12542 12543 if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3) 12544 return -EINVAL; 12545 12546 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1)) 12547 return -EINVAL; 12548 12549 if (attr->read_format & ~(PERF_FORMAT_MAX-1)) 12550 return -EINVAL; 12551 12552 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) { 12553 u64 mask = attr->branch_sample_type; 12554 12555 /* only using defined bits */ 12556 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1)) 12557 return -EINVAL; 12558 12559 /* at least one branch bit must be set */ 12560 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL)) 12561 return -EINVAL; 12562 12563 /* propagate priv level, when not set for branch */ 12564 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) { 12565 12566 /* exclude_kernel checked on syscall entry */ 12567 if (!attr->exclude_kernel) 12568 mask |= PERF_SAMPLE_BRANCH_KERNEL; 12569 12570 if (!attr->exclude_user) 12571 mask |= PERF_SAMPLE_BRANCH_USER; 12572 12573 if (!attr->exclude_hv) 12574 mask |= PERF_SAMPLE_BRANCH_HV; 12575 /* 12576 * adjust user setting (for HW filter setup) 12577 */ 12578 attr->branch_sample_type = mask; 12579 } 12580 /* privileged levels capture (kernel, hv): check permissions */ 12581 if (mask & PERF_SAMPLE_BRANCH_PERM_PLM) { 12582 ret = perf_allow_kernel(attr); 12583 if (ret) 12584 return ret; 12585 } 12586 } 12587 12588 if (attr->sample_type & PERF_SAMPLE_REGS_USER) { 12589 ret = perf_reg_validate(attr->sample_regs_user); 12590 if (ret) 12591 return ret; 12592 } 12593 12594 if (attr->sample_type & PERF_SAMPLE_STACK_USER) { 12595 if (!arch_perf_have_user_stack_dump()) 12596 return -ENOSYS; 12597 12598 /* 12599 * We have __u32 type for the size, but so far 12600 * we can only use __u16 as maximum due to the 12601 * __u16 sample size limit. 12602 */ 12603 if (attr->sample_stack_user >= USHRT_MAX) 12604 return -EINVAL; 12605 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64))) 12606 return -EINVAL; 12607 } 12608 12609 if (!attr->sample_max_stack) 12610 attr->sample_max_stack = sysctl_perf_event_max_stack; 12611 12612 if (attr->sample_type & PERF_SAMPLE_REGS_INTR) 12613 ret = perf_reg_validate(attr->sample_regs_intr); 12614 12615 #ifndef CONFIG_CGROUP_PERF 12616 if (attr->sample_type & PERF_SAMPLE_CGROUP) 12617 return -EINVAL; 12618 #endif 12619 if ((attr->sample_type & PERF_SAMPLE_WEIGHT) && 12620 (attr->sample_type & PERF_SAMPLE_WEIGHT_STRUCT)) 12621 return -EINVAL; 12622 12623 if (!attr->inherit && attr->inherit_thread) 12624 return -EINVAL; 12625 12626 if (attr->remove_on_exec && attr->enable_on_exec) 12627 return -EINVAL; 12628 12629 if (attr->sigtrap && !attr->remove_on_exec) 12630 return -EINVAL; 12631 12632 out: 12633 return ret; 12634 12635 err_size: 12636 put_user(sizeof(*attr), &uattr->size); 12637 ret = -E2BIG; 12638 goto out; 12639 } 12640 12641 static void mutex_lock_double(struct mutex *a, struct mutex *b) 12642 { 12643 if (b < a) 12644 swap(a, b); 12645 12646 mutex_lock(a); 12647 mutex_lock_nested(b, SINGLE_DEPTH_NESTING); 12648 } 12649 12650 static int 12651 perf_event_set_output(struct perf_event *event, struct perf_event *output_event) 12652 { 12653 struct perf_buffer *rb = NULL; 12654 int ret = -EINVAL; 12655 12656 if (!output_event) { 12657 mutex_lock(&event->mmap_mutex); 12658 goto set; 12659 } 12660 12661 /* don't allow circular references */ 12662 if (event == output_event) 12663 goto out; 12664 12665 /* 12666 * Don't allow cross-cpu buffers 12667 */ 12668 if (output_event->cpu != event->cpu) 12669 goto out; 12670 12671 /* 12672 * If its not a per-cpu rb, it must be the same task. 12673 */ 12674 if (output_event->cpu == -1 && output_event->hw.target != event->hw.target) 12675 goto out; 12676 12677 /* 12678 * Mixing clocks in the same buffer is trouble you don't need. 12679 */ 12680 if (output_event->clock != event->clock) 12681 goto out; 12682 12683 /* 12684 * Either writing ring buffer from beginning or from end. 12685 * Mixing is not allowed. 12686 */ 12687 if (is_write_backward(output_event) != is_write_backward(event)) 12688 goto out; 12689 12690 /* 12691 * If both events generate aux data, they must be on the same PMU 12692 */ 12693 if (has_aux(event) && has_aux(output_event) && 12694 event->pmu != output_event->pmu) 12695 goto out; 12696 12697 /* 12698 * Hold both mmap_mutex to serialize against perf_mmap_close(). Since 12699 * output_event is already on rb->event_list, and the list iteration 12700 * restarts after every removal, it is guaranteed this new event is 12701 * observed *OR* if output_event is already removed, it's guaranteed we 12702 * observe !rb->mmap_count. 12703 */ 12704 mutex_lock_double(&event->mmap_mutex, &output_event->mmap_mutex); 12705 set: 12706 /* Can't redirect output if we've got an active mmap() */ 12707 if (atomic_read(&event->mmap_count)) 12708 goto unlock; 12709 12710 if (output_event) { 12711 /* get the rb we want to redirect to */ 12712 rb = ring_buffer_get(output_event); 12713 if (!rb) 12714 goto unlock; 12715 12716 /* did we race against perf_mmap_close() */ 12717 if (!atomic_read(&rb->mmap_count)) { 12718 ring_buffer_put(rb); 12719 goto unlock; 12720 } 12721 } 12722 12723 ring_buffer_attach(event, rb); 12724 12725 ret = 0; 12726 unlock: 12727 mutex_unlock(&event->mmap_mutex); 12728 if (output_event) 12729 mutex_unlock(&output_event->mmap_mutex); 12730 12731 out: 12732 return ret; 12733 } 12734 12735 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id) 12736 { 12737 bool nmi_safe = false; 12738 12739 switch (clk_id) { 12740 case CLOCK_MONOTONIC: 12741 event->clock = &ktime_get_mono_fast_ns; 12742 nmi_safe = true; 12743 break; 12744 12745 case CLOCK_MONOTONIC_RAW: 12746 event->clock = &ktime_get_raw_fast_ns; 12747 nmi_safe = true; 12748 break; 12749 12750 case CLOCK_REALTIME: 12751 event->clock = &ktime_get_real_ns; 12752 break; 12753 12754 case CLOCK_BOOTTIME: 12755 event->clock = &ktime_get_boottime_ns; 12756 break; 12757 12758 case CLOCK_TAI: 12759 event->clock = &ktime_get_clocktai_ns; 12760 break; 12761 12762 default: 12763 return -EINVAL; 12764 } 12765 12766 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI)) 12767 return -EINVAL; 12768 12769 return 0; 12770 } 12771 12772 static bool 12773 perf_check_permission(struct perf_event_attr *attr, struct task_struct *task) 12774 { 12775 unsigned int ptrace_mode = PTRACE_MODE_READ_REALCREDS; 12776 bool is_capable = perfmon_capable(); 12777 12778 if (attr->sigtrap) { 12779 /* 12780 * perf_event_attr::sigtrap sends signals to the other task. 12781 * Require the current task to also have CAP_KILL. 12782 */ 12783 rcu_read_lock(); 12784 is_capable &= ns_capable(__task_cred(task)->user_ns, CAP_KILL); 12785 rcu_read_unlock(); 12786 12787 /* 12788 * If the required capabilities aren't available, checks for 12789 * ptrace permissions: upgrade to ATTACH, since sending signals 12790 * can effectively change the target task. 12791 */ 12792 ptrace_mode = PTRACE_MODE_ATTACH_REALCREDS; 12793 } 12794 12795 /* 12796 * Preserve ptrace permission check for backwards compatibility. The 12797 * ptrace check also includes checks that the current task and other 12798 * task have matching uids, and is therefore not done here explicitly. 12799 */ 12800 return is_capable || ptrace_may_access(task, ptrace_mode); 12801 } 12802 12803 /** 12804 * sys_perf_event_open - open a performance event, associate it to a task/cpu 12805 * 12806 * @attr_uptr: event_id type attributes for monitoring/sampling 12807 * @pid: target pid 12808 * @cpu: target cpu 12809 * @group_fd: group leader event fd 12810 * @flags: perf event open flags 12811 */ 12812 SYSCALL_DEFINE5(perf_event_open, 12813 struct perf_event_attr __user *, attr_uptr, 12814 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags) 12815 { 12816 struct perf_event *group_leader = NULL, *output_event = NULL; 12817 struct perf_event_pmu_context *pmu_ctx; 12818 struct perf_event *event, *sibling; 12819 struct perf_event_attr attr; 12820 struct perf_event_context *ctx; 12821 struct file *event_file = NULL; 12822 struct task_struct *task = NULL; 12823 struct pmu *pmu; 12824 int event_fd; 12825 int move_group = 0; 12826 int err; 12827 int f_flags = O_RDWR; 12828 int cgroup_fd = -1; 12829 12830 /* for future expandability... */ 12831 if (flags & ~PERF_FLAG_ALL) 12832 return -EINVAL; 12833 12834 err = perf_copy_attr(attr_uptr, &attr); 12835 if (err) 12836 return err; 12837 12838 /* Do we allow access to perf_event_open(2) ? */ 12839 err = security_perf_event_open(&attr, PERF_SECURITY_OPEN); 12840 if (err) 12841 return err; 12842 12843 if (!attr.exclude_kernel) { 12844 err = perf_allow_kernel(&attr); 12845 if (err) 12846 return err; 12847 } 12848 12849 if (attr.namespaces) { 12850 if (!perfmon_capable()) 12851 return -EACCES; 12852 } 12853 12854 if (attr.freq) { 12855 if (attr.sample_freq > sysctl_perf_event_sample_rate) 12856 return -EINVAL; 12857 } else { 12858 if (attr.sample_period & (1ULL << 63)) 12859 return -EINVAL; 12860 } 12861 12862 /* Only privileged users can get physical addresses */ 12863 if ((attr.sample_type & PERF_SAMPLE_PHYS_ADDR)) { 12864 err = perf_allow_kernel(&attr); 12865 if (err) 12866 return err; 12867 } 12868 12869 /* REGS_INTR can leak data, lockdown must prevent this */ 12870 if (attr.sample_type & PERF_SAMPLE_REGS_INTR) { 12871 err = security_locked_down(LOCKDOWN_PERF); 12872 if (err) 12873 return err; 12874 } 12875 12876 /* 12877 * In cgroup mode, the pid argument is used to pass the fd 12878 * opened to the cgroup directory in cgroupfs. The cpu argument 12879 * designates the cpu on which to monitor threads from that 12880 * cgroup. 12881 */ 12882 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1)) 12883 return -EINVAL; 12884 12885 if (flags & PERF_FLAG_FD_CLOEXEC) 12886 f_flags |= O_CLOEXEC; 12887 12888 event_fd = get_unused_fd_flags(f_flags); 12889 if (event_fd < 0) 12890 return event_fd; 12891 12892 CLASS(fd, group)(group_fd); // group_fd == -1 => empty 12893 if (group_fd != -1) { 12894 if (!is_perf_file(group)) { 12895 err = -EBADF; 12896 goto err_fd; 12897 } 12898 group_leader = fd_file(group)->private_data; 12899 if (flags & PERF_FLAG_FD_OUTPUT) 12900 output_event = group_leader; 12901 if (flags & PERF_FLAG_FD_NO_GROUP) 12902 group_leader = NULL; 12903 } 12904 12905 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) { 12906 task = find_lively_task_by_vpid(pid); 12907 if (IS_ERR(task)) { 12908 err = PTR_ERR(task); 12909 goto err_fd; 12910 } 12911 } 12912 12913 if (task && group_leader && 12914 group_leader->attr.inherit != attr.inherit) { 12915 err = -EINVAL; 12916 goto err_task; 12917 } 12918 12919 if (flags & PERF_FLAG_PID_CGROUP) 12920 cgroup_fd = pid; 12921 12922 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL, 12923 NULL, NULL, cgroup_fd); 12924 if (IS_ERR(event)) { 12925 err = PTR_ERR(event); 12926 goto err_task; 12927 } 12928 12929 if (is_sampling_event(event)) { 12930 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) { 12931 err = -EOPNOTSUPP; 12932 goto err_alloc; 12933 } 12934 } 12935 12936 /* 12937 * Special case software events and allow them to be part of 12938 * any hardware group. 12939 */ 12940 pmu = event->pmu; 12941 12942 if (attr.use_clockid) { 12943 err = perf_event_set_clock(event, attr.clockid); 12944 if (err) 12945 goto err_alloc; 12946 } 12947 12948 if (pmu->task_ctx_nr == perf_sw_context) 12949 event->event_caps |= PERF_EV_CAP_SOFTWARE; 12950 12951 if (task) { 12952 err = down_read_interruptible(&task->signal->exec_update_lock); 12953 if (err) 12954 goto err_alloc; 12955 12956 /* 12957 * We must hold exec_update_lock across this and any potential 12958 * perf_install_in_context() call for this new event to 12959 * serialize against exec() altering our credentials (and the 12960 * perf_event_exit_task() that could imply). 12961 */ 12962 err = -EACCES; 12963 if (!perf_check_permission(&attr, task)) 12964 goto err_cred; 12965 } 12966 12967 /* 12968 * Get the target context (task or percpu): 12969 */ 12970 ctx = find_get_context(task, event); 12971 if (IS_ERR(ctx)) { 12972 err = PTR_ERR(ctx); 12973 goto err_cred; 12974 } 12975 12976 mutex_lock(&ctx->mutex); 12977 12978 if (ctx->task == TASK_TOMBSTONE) { 12979 err = -ESRCH; 12980 goto err_locked; 12981 } 12982 12983 if (!task) { 12984 /* 12985 * Check if the @cpu we're creating an event for is online. 12986 * 12987 * We use the perf_cpu_context::ctx::mutex to serialize against 12988 * the hotplug notifiers. See perf_event_{init,exit}_cpu(). 12989 */ 12990 struct perf_cpu_context *cpuctx = per_cpu_ptr(&perf_cpu_context, event->cpu); 12991 12992 if (!cpuctx->online) { 12993 err = -ENODEV; 12994 goto err_locked; 12995 } 12996 } 12997 12998 if (group_leader) { 12999 err = -EINVAL; 13000 13001 /* 13002 * Do not allow a recursive hierarchy (this new sibling 13003 * becoming part of another group-sibling): 13004 */ 13005 if (group_leader->group_leader != group_leader) 13006 goto err_locked; 13007 13008 /* All events in a group should have the same clock */ 13009 if (group_leader->clock != event->clock) 13010 goto err_locked; 13011 13012 /* 13013 * Make sure we're both events for the same CPU; 13014 * grouping events for different CPUs is broken; since 13015 * you can never concurrently schedule them anyhow. 13016 */ 13017 if (group_leader->cpu != event->cpu) 13018 goto err_locked; 13019 13020 /* 13021 * Make sure we're both on the same context; either task or cpu. 13022 */ 13023 if (group_leader->ctx != ctx) 13024 goto err_locked; 13025 13026 /* 13027 * Only a group leader can be exclusive or pinned 13028 */ 13029 if (attr.exclusive || attr.pinned) 13030 goto err_locked; 13031 13032 if (is_software_event(event) && 13033 !in_software_context(group_leader)) { 13034 /* 13035 * If the event is a sw event, but the group_leader 13036 * is on hw context. 13037 * 13038 * Allow the addition of software events to hw 13039 * groups, this is safe because software events 13040 * never fail to schedule. 13041 * 13042 * Note the comment that goes with struct 13043 * perf_event_pmu_context. 13044 */ 13045 pmu = group_leader->pmu_ctx->pmu; 13046 } else if (!is_software_event(event)) { 13047 if (is_software_event(group_leader) && 13048 (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) { 13049 /* 13050 * In case the group is a pure software group, and we 13051 * try to add a hardware event, move the whole group to 13052 * the hardware context. 13053 */ 13054 move_group = 1; 13055 } 13056 13057 /* Don't allow group of multiple hw events from different pmus */ 13058 if (!in_software_context(group_leader) && 13059 group_leader->pmu_ctx->pmu != pmu) 13060 goto err_locked; 13061 } 13062 } 13063 13064 /* 13065 * Now that we're certain of the pmu; find the pmu_ctx. 13066 */ 13067 pmu_ctx = find_get_pmu_context(pmu, ctx, event); 13068 if (IS_ERR(pmu_ctx)) { 13069 err = PTR_ERR(pmu_ctx); 13070 goto err_locked; 13071 } 13072 event->pmu_ctx = pmu_ctx; 13073 13074 if (output_event) { 13075 err = perf_event_set_output(event, output_event); 13076 if (err) 13077 goto err_context; 13078 } 13079 13080 if (!perf_event_validate_size(event)) { 13081 err = -E2BIG; 13082 goto err_context; 13083 } 13084 13085 if (perf_need_aux_event(event) && !perf_get_aux_event(event, group_leader)) { 13086 err = -EINVAL; 13087 goto err_context; 13088 } 13089 13090 /* 13091 * Must be under the same ctx::mutex as perf_install_in_context(), 13092 * because we need to serialize with concurrent event creation. 13093 */ 13094 if (!exclusive_event_installable(event, ctx)) { 13095 err = -EBUSY; 13096 goto err_context; 13097 } 13098 13099 WARN_ON_ONCE(ctx->parent_ctx); 13100 13101 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event, f_flags); 13102 if (IS_ERR(event_file)) { 13103 err = PTR_ERR(event_file); 13104 event_file = NULL; 13105 goto err_context; 13106 } 13107 13108 /* 13109 * This is the point on no return; we cannot fail hereafter. This is 13110 * where we start modifying current state. 13111 */ 13112 13113 if (move_group) { 13114 perf_remove_from_context(group_leader, 0); 13115 put_pmu_ctx(group_leader->pmu_ctx); 13116 13117 for_each_sibling_event(sibling, group_leader) { 13118 perf_remove_from_context(sibling, 0); 13119 put_pmu_ctx(sibling->pmu_ctx); 13120 } 13121 13122 /* 13123 * Install the group siblings before the group leader. 13124 * 13125 * Because a group leader will try and install the entire group 13126 * (through the sibling list, which is still in-tact), we can 13127 * end up with siblings installed in the wrong context. 13128 * 13129 * By installing siblings first we NO-OP because they're not 13130 * reachable through the group lists. 13131 */ 13132 for_each_sibling_event(sibling, group_leader) { 13133 sibling->pmu_ctx = pmu_ctx; 13134 get_pmu_ctx(pmu_ctx); 13135 perf_event__state_init(sibling); 13136 perf_install_in_context(ctx, sibling, sibling->cpu); 13137 } 13138 13139 /* 13140 * Removing from the context ends up with disabled 13141 * event. What we want here is event in the initial 13142 * startup state, ready to be add into new context. 13143 */ 13144 group_leader->pmu_ctx = pmu_ctx; 13145 get_pmu_ctx(pmu_ctx); 13146 perf_event__state_init(group_leader); 13147 perf_install_in_context(ctx, group_leader, group_leader->cpu); 13148 } 13149 13150 /* 13151 * Precalculate sample_data sizes; do while holding ctx::mutex such 13152 * that we're serialized against further additions and before 13153 * perf_install_in_context() which is the point the event is active and 13154 * can use these values. 13155 */ 13156 perf_event__header_size(event); 13157 perf_event__id_header_size(event); 13158 13159 event->owner = current; 13160 13161 perf_install_in_context(ctx, event, event->cpu); 13162 perf_unpin_context(ctx); 13163 13164 mutex_unlock(&ctx->mutex); 13165 13166 if (task) { 13167 up_read(&task->signal->exec_update_lock); 13168 put_task_struct(task); 13169 } 13170 13171 mutex_lock(¤t->perf_event_mutex); 13172 list_add_tail(&event->owner_entry, ¤t->perf_event_list); 13173 mutex_unlock(¤t->perf_event_mutex); 13174 13175 /* 13176 * File reference in group guarantees that group_leader has been 13177 * kept alive until we place the new event on the sibling_list. 13178 * This ensures destruction of the group leader will find 13179 * the pointer to itself in perf_group_detach(). 13180 */ 13181 fd_install(event_fd, event_file); 13182 return event_fd; 13183 13184 err_context: 13185 put_pmu_ctx(event->pmu_ctx); 13186 event->pmu_ctx = NULL; /* _free_event() */ 13187 err_locked: 13188 mutex_unlock(&ctx->mutex); 13189 perf_unpin_context(ctx); 13190 put_ctx(ctx); 13191 err_cred: 13192 if (task) 13193 up_read(&task->signal->exec_update_lock); 13194 err_alloc: 13195 free_event(event); 13196 err_task: 13197 if (task) 13198 put_task_struct(task); 13199 err_fd: 13200 put_unused_fd(event_fd); 13201 return err; 13202 } 13203 13204 /** 13205 * perf_event_create_kernel_counter 13206 * 13207 * @attr: attributes of the counter to create 13208 * @cpu: cpu in which the counter is bound 13209 * @task: task to profile (NULL for percpu) 13210 * @overflow_handler: callback to trigger when we hit the event 13211 * @context: context data could be used in overflow_handler callback 13212 */ 13213 struct perf_event * 13214 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu, 13215 struct task_struct *task, 13216 perf_overflow_handler_t overflow_handler, 13217 void *context) 13218 { 13219 struct perf_event_pmu_context *pmu_ctx; 13220 struct perf_event_context *ctx; 13221 struct perf_event *event; 13222 struct pmu *pmu; 13223 int err; 13224 13225 /* 13226 * Grouping is not supported for kernel events, neither is 'AUX', 13227 * make sure the caller's intentions are adjusted. 13228 */ 13229 if (attr->aux_output || attr->aux_action) 13230 return ERR_PTR(-EINVAL); 13231 13232 event = perf_event_alloc(attr, cpu, task, NULL, NULL, 13233 overflow_handler, context, -1); 13234 if (IS_ERR(event)) { 13235 err = PTR_ERR(event); 13236 goto err; 13237 } 13238 13239 /* Mark owner so we could distinguish it from user events. */ 13240 event->owner = TASK_TOMBSTONE; 13241 pmu = event->pmu; 13242 13243 if (pmu->task_ctx_nr == perf_sw_context) 13244 event->event_caps |= PERF_EV_CAP_SOFTWARE; 13245 13246 /* 13247 * Get the target context (task or percpu): 13248 */ 13249 ctx = find_get_context(task, event); 13250 if (IS_ERR(ctx)) { 13251 err = PTR_ERR(ctx); 13252 goto err_alloc; 13253 } 13254 13255 WARN_ON_ONCE(ctx->parent_ctx); 13256 mutex_lock(&ctx->mutex); 13257 if (ctx->task == TASK_TOMBSTONE) { 13258 err = -ESRCH; 13259 goto err_unlock; 13260 } 13261 13262 pmu_ctx = find_get_pmu_context(pmu, ctx, event); 13263 if (IS_ERR(pmu_ctx)) { 13264 err = PTR_ERR(pmu_ctx); 13265 goto err_unlock; 13266 } 13267 event->pmu_ctx = pmu_ctx; 13268 13269 if (!task) { 13270 /* 13271 * Check if the @cpu we're creating an event for is online. 13272 * 13273 * We use the perf_cpu_context::ctx::mutex to serialize against 13274 * the hotplug notifiers. See perf_event_{init,exit}_cpu(). 13275 */ 13276 struct perf_cpu_context *cpuctx = 13277 container_of(ctx, struct perf_cpu_context, ctx); 13278 if (!cpuctx->online) { 13279 err = -ENODEV; 13280 goto err_pmu_ctx; 13281 } 13282 } 13283 13284 if (!exclusive_event_installable(event, ctx)) { 13285 err = -EBUSY; 13286 goto err_pmu_ctx; 13287 } 13288 13289 perf_install_in_context(ctx, event, event->cpu); 13290 perf_unpin_context(ctx); 13291 mutex_unlock(&ctx->mutex); 13292 13293 return event; 13294 13295 err_pmu_ctx: 13296 put_pmu_ctx(pmu_ctx); 13297 event->pmu_ctx = NULL; /* _free_event() */ 13298 err_unlock: 13299 mutex_unlock(&ctx->mutex); 13300 perf_unpin_context(ctx); 13301 put_ctx(ctx); 13302 err_alloc: 13303 free_event(event); 13304 err: 13305 return ERR_PTR(err); 13306 } 13307 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter); 13308 13309 static void __perf_pmu_remove(struct perf_event_context *ctx, 13310 int cpu, struct pmu *pmu, 13311 struct perf_event_groups *groups, 13312 struct list_head *events) 13313 { 13314 struct perf_event *event, *sibling; 13315 13316 perf_event_groups_for_cpu_pmu(event, groups, cpu, pmu) { 13317 perf_remove_from_context(event, 0); 13318 put_pmu_ctx(event->pmu_ctx); 13319 list_add(&event->migrate_entry, events); 13320 13321 for_each_sibling_event(sibling, event) { 13322 perf_remove_from_context(sibling, 0); 13323 put_pmu_ctx(sibling->pmu_ctx); 13324 list_add(&sibling->migrate_entry, events); 13325 } 13326 } 13327 } 13328 13329 static void __perf_pmu_install_event(struct pmu *pmu, 13330 struct perf_event_context *ctx, 13331 int cpu, struct perf_event *event) 13332 { 13333 struct perf_event_pmu_context *epc; 13334 struct perf_event_context *old_ctx = event->ctx; 13335 13336 get_ctx(ctx); /* normally find_get_context() */ 13337 13338 event->cpu = cpu; 13339 epc = find_get_pmu_context(pmu, ctx, event); 13340 event->pmu_ctx = epc; 13341 13342 if (event->state >= PERF_EVENT_STATE_OFF) 13343 event->state = PERF_EVENT_STATE_INACTIVE; 13344 perf_install_in_context(ctx, event, cpu); 13345 13346 /* 13347 * Now that event->ctx is updated and visible, put the old ctx. 13348 */ 13349 put_ctx(old_ctx); 13350 } 13351 13352 static void __perf_pmu_install(struct perf_event_context *ctx, 13353 int cpu, struct pmu *pmu, struct list_head *events) 13354 { 13355 struct perf_event *event, *tmp; 13356 13357 /* 13358 * Re-instate events in 2 passes. 13359 * 13360 * Skip over group leaders and only install siblings on this first 13361 * pass, siblings will not get enabled without a leader, however a 13362 * leader will enable its siblings, even if those are still on the old 13363 * context. 13364 */ 13365 list_for_each_entry_safe(event, tmp, events, migrate_entry) { 13366 if (event->group_leader == event) 13367 continue; 13368 13369 list_del(&event->migrate_entry); 13370 __perf_pmu_install_event(pmu, ctx, cpu, event); 13371 } 13372 13373 /* 13374 * Once all the siblings are setup properly, install the group leaders 13375 * to make it go. 13376 */ 13377 list_for_each_entry_safe(event, tmp, events, migrate_entry) { 13378 list_del(&event->migrate_entry); 13379 __perf_pmu_install_event(pmu, ctx, cpu, event); 13380 } 13381 } 13382 13383 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu) 13384 { 13385 struct perf_event_context *src_ctx, *dst_ctx; 13386 LIST_HEAD(events); 13387 13388 /* 13389 * Since per-cpu context is persistent, no need to grab an extra 13390 * reference. 13391 */ 13392 src_ctx = &per_cpu_ptr(&perf_cpu_context, src_cpu)->ctx; 13393 dst_ctx = &per_cpu_ptr(&perf_cpu_context, dst_cpu)->ctx; 13394 13395 /* 13396 * See perf_event_ctx_lock() for comments on the details 13397 * of swizzling perf_event::ctx. 13398 */ 13399 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex); 13400 13401 __perf_pmu_remove(src_ctx, src_cpu, pmu, &src_ctx->pinned_groups, &events); 13402 __perf_pmu_remove(src_ctx, src_cpu, pmu, &src_ctx->flexible_groups, &events); 13403 13404 if (!list_empty(&events)) { 13405 /* 13406 * Wait for the events to quiesce before re-instating them. 13407 */ 13408 synchronize_rcu(); 13409 13410 __perf_pmu_install(dst_ctx, dst_cpu, pmu, &events); 13411 } 13412 13413 mutex_unlock(&dst_ctx->mutex); 13414 mutex_unlock(&src_ctx->mutex); 13415 } 13416 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context); 13417 13418 static void sync_child_event(struct perf_event *child_event) 13419 { 13420 struct perf_event *parent_event = child_event->parent; 13421 u64 child_val; 13422 13423 if (child_event->attr.inherit_stat) { 13424 struct task_struct *task = child_event->ctx->task; 13425 13426 if (task && task != TASK_TOMBSTONE) 13427 perf_event_read_event(child_event, task); 13428 } 13429 13430 child_val = perf_event_count(child_event, false); 13431 13432 /* 13433 * Add back the child's count to the parent's count: 13434 */ 13435 atomic64_add(child_val, &parent_event->child_count); 13436 atomic64_add(child_event->total_time_enabled, 13437 &parent_event->child_total_time_enabled); 13438 atomic64_add(child_event->total_time_running, 13439 &parent_event->child_total_time_running); 13440 } 13441 13442 static void 13443 perf_event_exit_event(struct perf_event *event, struct perf_event_context *ctx) 13444 { 13445 struct perf_event *parent_event = event->parent; 13446 unsigned long detach_flags = 0; 13447 13448 if (parent_event) { 13449 /* 13450 * Do not destroy the 'original' grouping; because of the 13451 * context switch optimization the original events could've 13452 * ended up in a random child task. 13453 * 13454 * If we were to destroy the original group, all group related 13455 * operations would cease to function properly after this 13456 * random child dies. 13457 * 13458 * Do destroy all inherited groups, we don't care about those 13459 * and being thorough is better. 13460 */ 13461 detach_flags = DETACH_GROUP | DETACH_CHILD; 13462 mutex_lock(&parent_event->child_mutex); 13463 } 13464 13465 perf_remove_from_context(event, detach_flags); 13466 13467 raw_spin_lock_irq(&ctx->lock); 13468 if (event->state > PERF_EVENT_STATE_EXIT) 13469 perf_event_set_state(event, PERF_EVENT_STATE_EXIT); 13470 raw_spin_unlock_irq(&ctx->lock); 13471 13472 /* 13473 * Child events can be freed. 13474 */ 13475 if (parent_event) { 13476 mutex_unlock(&parent_event->child_mutex); 13477 /* 13478 * Kick perf_poll() for is_event_hup(); 13479 */ 13480 perf_event_wakeup(parent_event); 13481 free_event(event); 13482 put_event(parent_event); 13483 return; 13484 } 13485 13486 /* 13487 * Parent events are governed by their filedesc, retain them. 13488 */ 13489 perf_event_wakeup(event); 13490 } 13491 13492 static void perf_event_exit_task_context(struct task_struct *child) 13493 { 13494 struct perf_event_context *child_ctx, *clone_ctx = NULL; 13495 struct perf_event *child_event, *next; 13496 13497 WARN_ON_ONCE(child != current); 13498 13499 child_ctx = perf_pin_task_context(child); 13500 if (!child_ctx) 13501 return; 13502 13503 /* 13504 * In order to reduce the amount of tricky in ctx tear-down, we hold 13505 * ctx::mutex over the entire thing. This serializes against almost 13506 * everything that wants to access the ctx. 13507 * 13508 * The exception is sys_perf_event_open() / 13509 * perf_event_create_kernel_count() which does find_get_context() 13510 * without ctx::mutex (it cannot because of the move_group double mutex 13511 * lock thing). See the comments in perf_install_in_context(). 13512 */ 13513 mutex_lock(&child_ctx->mutex); 13514 13515 /* 13516 * In a single ctx::lock section, de-schedule the events and detach the 13517 * context from the task such that we cannot ever get it scheduled back 13518 * in. 13519 */ 13520 raw_spin_lock_irq(&child_ctx->lock); 13521 task_ctx_sched_out(child_ctx, NULL, EVENT_ALL); 13522 13523 /* 13524 * Now that the context is inactive, destroy the task <-> ctx relation 13525 * and mark the context dead. 13526 */ 13527 RCU_INIT_POINTER(child->perf_event_ctxp, NULL); 13528 put_ctx(child_ctx); /* cannot be last */ 13529 WRITE_ONCE(child_ctx->task, TASK_TOMBSTONE); 13530 put_task_struct(current); /* cannot be last */ 13531 13532 clone_ctx = unclone_ctx(child_ctx); 13533 raw_spin_unlock_irq(&child_ctx->lock); 13534 13535 if (clone_ctx) 13536 put_ctx(clone_ctx); 13537 13538 /* 13539 * Report the task dead after unscheduling the events so that we 13540 * won't get any samples after PERF_RECORD_EXIT. We can however still 13541 * get a few PERF_RECORD_READ events. 13542 */ 13543 perf_event_task(child, child_ctx, 0); 13544 13545 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry) 13546 perf_event_exit_event(child_event, child_ctx); 13547 13548 mutex_unlock(&child_ctx->mutex); 13549 13550 put_ctx(child_ctx); 13551 } 13552 13553 /* 13554 * When a child task exits, feed back event values to parent events. 13555 * 13556 * Can be called with exec_update_lock held when called from 13557 * setup_new_exec(). 13558 */ 13559 void perf_event_exit_task(struct task_struct *child) 13560 { 13561 struct perf_event *event, *tmp; 13562 13563 mutex_lock(&child->perf_event_mutex); 13564 list_for_each_entry_safe(event, tmp, &child->perf_event_list, 13565 owner_entry) { 13566 list_del_init(&event->owner_entry); 13567 13568 /* 13569 * Ensure the list deletion is visible before we clear 13570 * the owner, closes a race against perf_release() where 13571 * we need to serialize on the owner->perf_event_mutex. 13572 */ 13573 smp_store_release(&event->owner, NULL); 13574 } 13575 mutex_unlock(&child->perf_event_mutex); 13576 13577 perf_event_exit_task_context(child); 13578 13579 /* 13580 * The perf_event_exit_task_context calls perf_event_task 13581 * with child's task_ctx, which generates EXIT events for 13582 * child contexts and sets child->perf_event_ctxp[] to NULL. 13583 * At this point we need to send EXIT events to cpu contexts. 13584 */ 13585 perf_event_task(child, NULL, 0); 13586 } 13587 13588 static void perf_free_event(struct perf_event *event, 13589 struct perf_event_context *ctx) 13590 { 13591 struct perf_event *parent = event->parent; 13592 13593 if (WARN_ON_ONCE(!parent)) 13594 return; 13595 13596 mutex_lock(&parent->child_mutex); 13597 list_del_init(&event->child_list); 13598 mutex_unlock(&parent->child_mutex); 13599 13600 put_event(parent); 13601 13602 raw_spin_lock_irq(&ctx->lock); 13603 perf_group_detach(event); 13604 list_del_event(event, ctx); 13605 raw_spin_unlock_irq(&ctx->lock); 13606 free_event(event); 13607 } 13608 13609 /* 13610 * Free a context as created by inheritance by perf_event_init_task() below, 13611 * used by fork() in case of fail. 13612 * 13613 * Even though the task has never lived, the context and events have been 13614 * exposed through the child_list, so we must take care tearing it all down. 13615 */ 13616 void perf_event_free_task(struct task_struct *task) 13617 { 13618 struct perf_event_context *ctx; 13619 struct perf_event *event, *tmp; 13620 13621 ctx = rcu_access_pointer(task->perf_event_ctxp); 13622 if (!ctx) 13623 return; 13624 13625 mutex_lock(&ctx->mutex); 13626 raw_spin_lock_irq(&ctx->lock); 13627 /* 13628 * Destroy the task <-> ctx relation and mark the context dead. 13629 * 13630 * This is important because even though the task hasn't been 13631 * exposed yet the context has been (through child_list). 13632 */ 13633 RCU_INIT_POINTER(task->perf_event_ctxp, NULL); 13634 WRITE_ONCE(ctx->task, TASK_TOMBSTONE); 13635 put_task_struct(task); /* cannot be last */ 13636 raw_spin_unlock_irq(&ctx->lock); 13637 13638 13639 list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry) 13640 perf_free_event(event, ctx); 13641 13642 mutex_unlock(&ctx->mutex); 13643 13644 /* 13645 * perf_event_release_kernel() could've stolen some of our 13646 * child events and still have them on its free_list. In that 13647 * case we must wait for these events to have been freed (in 13648 * particular all their references to this task must've been 13649 * dropped). 13650 * 13651 * Without this copy_process() will unconditionally free this 13652 * task (irrespective of its reference count) and 13653 * _free_event()'s put_task_struct(event->hw.target) will be a 13654 * use-after-free. 13655 * 13656 * Wait for all events to drop their context reference. 13657 */ 13658 wait_var_event(&ctx->refcount, refcount_read(&ctx->refcount) == 1); 13659 put_ctx(ctx); /* must be last */ 13660 } 13661 13662 void perf_event_delayed_put(struct task_struct *task) 13663 { 13664 WARN_ON_ONCE(task->perf_event_ctxp); 13665 } 13666 13667 struct file *perf_event_get(unsigned int fd) 13668 { 13669 struct file *file = fget(fd); 13670 if (!file) 13671 return ERR_PTR(-EBADF); 13672 13673 if (file->f_op != &perf_fops) { 13674 fput(file); 13675 return ERR_PTR(-EBADF); 13676 } 13677 13678 return file; 13679 } 13680 13681 const struct perf_event *perf_get_event(struct file *file) 13682 { 13683 if (file->f_op != &perf_fops) 13684 return ERR_PTR(-EINVAL); 13685 13686 return file->private_data; 13687 } 13688 13689 const struct perf_event_attr *perf_event_attrs(struct perf_event *event) 13690 { 13691 if (!event) 13692 return ERR_PTR(-EINVAL); 13693 13694 return &event->attr; 13695 } 13696 13697 int perf_allow_kernel(struct perf_event_attr *attr) 13698 { 13699 if (sysctl_perf_event_paranoid > 1 && !perfmon_capable()) 13700 return -EACCES; 13701 13702 return security_perf_event_open(attr, PERF_SECURITY_KERNEL); 13703 } 13704 EXPORT_SYMBOL_GPL(perf_allow_kernel); 13705 13706 /* 13707 * Inherit an event from parent task to child task. 13708 * 13709 * Returns: 13710 * - valid pointer on success 13711 * - NULL for orphaned events 13712 * - IS_ERR() on error 13713 */ 13714 static struct perf_event * 13715 inherit_event(struct perf_event *parent_event, 13716 struct task_struct *parent, 13717 struct perf_event_context *parent_ctx, 13718 struct task_struct *child, 13719 struct perf_event *group_leader, 13720 struct perf_event_context *child_ctx) 13721 { 13722 enum perf_event_state parent_state = parent_event->state; 13723 struct perf_event_pmu_context *pmu_ctx; 13724 struct perf_event *child_event; 13725 unsigned long flags; 13726 13727 /* 13728 * Instead of creating recursive hierarchies of events, 13729 * we link inherited events back to the original parent, 13730 * which has a filp for sure, which we use as the reference 13731 * count: 13732 */ 13733 if (parent_event->parent) 13734 parent_event = parent_event->parent; 13735 13736 child_event = perf_event_alloc(&parent_event->attr, 13737 parent_event->cpu, 13738 child, 13739 group_leader, parent_event, 13740 NULL, NULL, -1); 13741 if (IS_ERR(child_event)) 13742 return child_event; 13743 13744 pmu_ctx = find_get_pmu_context(child_event->pmu, child_ctx, child_event); 13745 if (IS_ERR(pmu_ctx)) { 13746 free_event(child_event); 13747 return ERR_CAST(pmu_ctx); 13748 } 13749 child_event->pmu_ctx = pmu_ctx; 13750 13751 /* 13752 * is_orphaned_event() and list_add_tail(&parent_event->child_list) 13753 * must be under the same lock in order to serialize against 13754 * perf_event_release_kernel(), such that either we must observe 13755 * is_orphaned_event() or they will observe us on the child_list. 13756 */ 13757 mutex_lock(&parent_event->child_mutex); 13758 if (is_orphaned_event(parent_event) || 13759 !atomic_long_inc_not_zero(&parent_event->refcount)) { 13760 mutex_unlock(&parent_event->child_mutex); 13761 /* task_ctx_data is freed with child_ctx */ 13762 free_event(child_event); 13763 return NULL; 13764 } 13765 13766 get_ctx(child_ctx); 13767 13768 /* 13769 * Make the child state follow the state of the parent event, 13770 * not its attr.disabled bit. We hold the parent's mutex, 13771 * so we won't race with perf_event_{en, dis}able_family. 13772 */ 13773 if (parent_state >= PERF_EVENT_STATE_INACTIVE) 13774 child_event->state = PERF_EVENT_STATE_INACTIVE; 13775 else 13776 child_event->state = PERF_EVENT_STATE_OFF; 13777 13778 if (parent_event->attr.freq) { 13779 u64 sample_period = parent_event->hw.sample_period; 13780 struct hw_perf_event *hwc = &child_event->hw; 13781 13782 hwc->sample_period = sample_period; 13783 hwc->last_period = sample_period; 13784 13785 local64_set(&hwc->period_left, sample_period); 13786 } 13787 13788 child_event->ctx = child_ctx; 13789 child_event->overflow_handler = parent_event->overflow_handler; 13790 child_event->overflow_handler_context 13791 = parent_event->overflow_handler_context; 13792 13793 /* 13794 * Precalculate sample_data sizes 13795 */ 13796 perf_event__header_size(child_event); 13797 perf_event__id_header_size(child_event); 13798 13799 /* 13800 * Link it up in the child's context: 13801 */ 13802 raw_spin_lock_irqsave(&child_ctx->lock, flags); 13803 add_event_to_ctx(child_event, child_ctx); 13804 child_event->attach_state |= PERF_ATTACH_CHILD; 13805 raw_spin_unlock_irqrestore(&child_ctx->lock, flags); 13806 13807 /* 13808 * Link this into the parent event's child list 13809 */ 13810 list_add_tail(&child_event->child_list, &parent_event->child_list); 13811 mutex_unlock(&parent_event->child_mutex); 13812 13813 return child_event; 13814 } 13815 13816 /* 13817 * Inherits an event group. 13818 * 13819 * This will quietly suppress orphaned events; !inherit_event() is not an error. 13820 * This matches with perf_event_release_kernel() removing all child events. 13821 * 13822 * Returns: 13823 * - 0 on success 13824 * - <0 on error 13825 */ 13826 static int inherit_group(struct perf_event *parent_event, 13827 struct task_struct *parent, 13828 struct perf_event_context *parent_ctx, 13829 struct task_struct *child, 13830 struct perf_event_context *child_ctx) 13831 { 13832 struct perf_event *leader; 13833 struct perf_event *sub; 13834 struct perf_event *child_ctr; 13835 13836 leader = inherit_event(parent_event, parent, parent_ctx, 13837 child, NULL, child_ctx); 13838 if (IS_ERR(leader)) 13839 return PTR_ERR(leader); 13840 /* 13841 * @leader can be NULL here because of is_orphaned_event(). In this 13842 * case inherit_event() will create individual events, similar to what 13843 * perf_group_detach() would do anyway. 13844 */ 13845 for_each_sibling_event(sub, parent_event) { 13846 child_ctr = inherit_event(sub, parent, parent_ctx, 13847 child, leader, child_ctx); 13848 if (IS_ERR(child_ctr)) 13849 return PTR_ERR(child_ctr); 13850 13851 if (sub->aux_event == parent_event && child_ctr && 13852 !perf_get_aux_event(child_ctr, leader)) 13853 return -EINVAL; 13854 } 13855 if (leader) 13856 leader->group_generation = parent_event->group_generation; 13857 return 0; 13858 } 13859 13860 /* 13861 * Creates the child task context and tries to inherit the event-group. 13862 * 13863 * Clears @inherited_all on !attr.inherited or error. Note that we'll leave 13864 * inherited_all set when we 'fail' to inherit an orphaned event; this is 13865 * consistent with perf_event_release_kernel() removing all child events. 13866 * 13867 * Returns: 13868 * - 0 on success 13869 * - <0 on error 13870 */ 13871 static int 13872 inherit_task_group(struct perf_event *event, struct task_struct *parent, 13873 struct perf_event_context *parent_ctx, 13874 struct task_struct *child, 13875 u64 clone_flags, int *inherited_all) 13876 { 13877 struct perf_event_context *child_ctx; 13878 int ret; 13879 13880 if (!event->attr.inherit || 13881 (event->attr.inherit_thread && !(clone_flags & CLONE_THREAD)) || 13882 /* Do not inherit if sigtrap and signal handlers were cleared. */ 13883 (event->attr.sigtrap && (clone_flags & CLONE_CLEAR_SIGHAND))) { 13884 *inherited_all = 0; 13885 return 0; 13886 } 13887 13888 child_ctx = child->perf_event_ctxp; 13889 if (!child_ctx) { 13890 /* 13891 * This is executed from the parent task context, so 13892 * inherit events that have been marked for cloning. 13893 * First allocate and initialize a context for the 13894 * child. 13895 */ 13896 child_ctx = alloc_perf_context(child); 13897 if (!child_ctx) 13898 return -ENOMEM; 13899 13900 child->perf_event_ctxp = child_ctx; 13901 } 13902 13903 ret = inherit_group(event, parent, parent_ctx, child, child_ctx); 13904 if (ret) 13905 *inherited_all = 0; 13906 13907 return ret; 13908 } 13909 13910 /* 13911 * Initialize the perf_event context in task_struct 13912 */ 13913 static int perf_event_init_context(struct task_struct *child, u64 clone_flags) 13914 { 13915 struct perf_event_context *child_ctx, *parent_ctx; 13916 struct perf_event_context *cloned_ctx; 13917 struct perf_event *event; 13918 struct task_struct *parent = current; 13919 int inherited_all = 1; 13920 unsigned long flags; 13921 int ret = 0; 13922 13923 if (likely(!parent->perf_event_ctxp)) 13924 return 0; 13925 13926 /* 13927 * If the parent's context is a clone, pin it so it won't get 13928 * swapped under us. 13929 */ 13930 parent_ctx = perf_pin_task_context(parent); 13931 if (!parent_ctx) 13932 return 0; 13933 13934 /* 13935 * No need to check if parent_ctx != NULL here; since we saw 13936 * it non-NULL earlier, the only reason for it to become NULL 13937 * is if we exit, and since we're currently in the middle of 13938 * a fork we can't be exiting at the same time. 13939 */ 13940 13941 /* 13942 * Lock the parent list. No need to lock the child - not PID 13943 * hashed yet and not running, so nobody can access it. 13944 */ 13945 mutex_lock(&parent_ctx->mutex); 13946 13947 /* 13948 * We dont have to disable NMIs - we are only looking at 13949 * the list, not manipulating it: 13950 */ 13951 perf_event_groups_for_each(event, &parent_ctx->pinned_groups) { 13952 ret = inherit_task_group(event, parent, parent_ctx, 13953 child, clone_flags, &inherited_all); 13954 if (ret) 13955 goto out_unlock; 13956 } 13957 13958 /* 13959 * We can't hold ctx->lock when iterating the ->flexible_group list due 13960 * to allocations, but we need to prevent rotation because 13961 * rotate_ctx() will change the list from interrupt context. 13962 */ 13963 raw_spin_lock_irqsave(&parent_ctx->lock, flags); 13964 parent_ctx->rotate_disable = 1; 13965 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags); 13966 13967 perf_event_groups_for_each(event, &parent_ctx->flexible_groups) { 13968 ret = inherit_task_group(event, parent, parent_ctx, 13969 child, clone_flags, &inherited_all); 13970 if (ret) 13971 goto out_unlock; 13972 } 13973 13974 raw_spin_lock_irqsave(&parent_ctx->lock, flags); 13975 parent_ctx->rotate_disable = 0; 13976 13977 child_ctx = child->perf_event_ctxp; 13978 13979 if (child_ctx && inherited_all) { 13980 /* 13981 * Mark the child context as a clone of the parent 13982 * context, or of whatever the parent is a clone of. 13983 * 13984 * Note that if the parent is a clone, the holding of 13985 * parent_ctx->lock avoids it from being uncloned. 13986 */ 13987 cloned_ctx = parent_ctx->parent_ctx; 13988 if (cloned_ctx) { 13989 child_ctx->parent_ctx = cloned_ctx; 13990 child_ctx->parent_gen = parent_ctx->parent_gen; 13991 } else { 13992 child_ctx->parent_ctx = parent_ctx; 13993 child_ctx->parent_gen = parent_ctx->generation; 13994 } 13995 get_ctx(child_ctx->parent_ctx); 13996 } 13997 13998 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags); 13999 out_unlock: 14000 mutex_unlock(&parent_ctx->mutex); 14001 14002 perf_unpin_context(parent_ctx); 14003 put_ctx(parent_ctx); 14004 14005 return ret; 14006 } 14007 14008 /* 14009 * Initialize the perf_event context in task_struct 14010 */ 14011 int perf_event_init_task(struct task_struct *child, u64 clone_flags) 14012 { 14013 int ret; 14014 14015 memset(child->perf_recursion, 0, sizeof(child->perf_recursion)); 14016 child->perf_event_ctxp = NULL; 14017 mutex_init(&child->perf_event_mutex); 14018 INIT_LIST_HEAD(&child->perf_event_list); 14019 14020 ret = perf_event_init_context(child, clone_flags); 14021 if (ret) { 14022 perf_event_free_task(child); 14023 return ret; 14024 } 14025 14026 return 0; 14027 } 14028 14029 static void __init perf_event_init_all_cpus(void) 14030 { 14031 struct swevent_htable *swhash; 14032 struct perf_cpu_context *cpuctx; 14033 int cpu; 14034 14035 zalloc_cpumask_var(&perf_online_mask, GFP_KERNEL); 14036 zalloc_cpumask_var(&perf_online_core_mask, GFP_KERNEL); 14037 zalloc_cpumask_var(&perf_online_die_mask, GFP_KERNEL); 14038 zalloc_cpumask_var(&perf_online_cluster_mask, GFP_KERNEL); 14039 zalloc_cpumask_var(&perf_online_pkg_mask, GFP_KERNEL); 14040 zalloc_cpumask_var(&perf_online_sys_mask, GFP_KERNEL); 14041 14042 14043 for_each_possible_cpu(cpu) { 14044 swhash = &per_cpu(swevent_htable, cpu); 14045 mutex_init(&swhash->hlist_mutex); 14046 14047 INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu)); 14048 raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu)); 14049 14050 INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu)); 14051 14052 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu); 14053 __perf_event_init_context(&cpuctx->ctx); 14054 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex); 14055 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock); 14056 cpuctx->online = cpumask_test_cpu(cpu, perf_online_mask); 14057 cpuctx->heap_size = ARRAY_SIZE(cpuctx->heap_default); 14058 cpuctx->heap = cpuctx->heap_default; 14059 } 14060 } 14061 14062 static void perf_swevent_init_cpu(unsigned int cpu) 14063 { 14064 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu); 14065 14066 mutex_lock(&swhash->hlist_mutex); 14067 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) { 14068 struct swevent_hlist *hlist; 14069 14070 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu)); 14071 WARN_ON(!hlist); 14072 rcu_assign_pointer(swhash->swevent_hlist, hlist); 14073 } 14074 mutex_unlock(&swhash->hlist_mutex); 14075 } 14076 14077 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE 14078 static void __perf_event_exit_context(void *__info) 14079 { 14080 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 14081 struct perf_event_context *ctx = __info; 14082 struct perf_event *event; 14083 14084 raw_spin_lock(&ctx->lock); 14085 ctx_sched_out(ctx, NULL, EVENT_TIME); 14086 list_for_each_entry(event, &ctx->event_list, event_entry) 14087 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP); 14088 raw_spin_unlock(&ctx->lock); 14089 } 14090 14091 static void perf_event_clear_cpumask(unsigned int cpu) 14092 { 14093 int target[PERF_PMU_MAX_SCOPE]; 14094 unsigned int scope; 14095 struct pmu *pmu; 14096 14097 cpumask_clear_cpu(cpu, perf_online_mask); 14098 14099 for (scope = PERF_PMU_SCOPE_NONE + 1; scope < PERF_PMU_MAX_SCOPE; scope++) { 14100 const struct cpumask *cpumask = perf_scope_cpu_topology_cpumask(scope, cpu); 14101 struct cpumask *pmu_cpumask = perf_scope_cpumask(scope); 14102 14103 target[scope] = -1; 14104 if (WARN_ON_ONCE(!pmu_cpumask || !cpumask)) 14105 continue; 14106 14107 if (!cpumask_test_and_clear_cpu(cpu, pmu_cpumask)) 14108 continue; 14109 target[scope] = cpumask_any_but(cpumask, cpu); 14110 if (target[scope] < nr_cpu_ids) 14111 cpumask_set_cpu(target[scope], pmu_cpumask); 14112 } 14113 14114 /* migrate */ 14115 list_for_each_entry(pmu, &pmus, entry) { 14116 if (pmu->scope == PERF_PMU_SCOPE_NONE || 14117 WARN_ON_ONCE(pmu->scope >= PERF_PMU_MAX_SCOPE)) 14118 continue; 14119 14120 if (target[pmu->scope] >= 0 && target[pmu->scope] < nr_cpu_ids) 14121 perf_pmu_migrate_context(pmu, cpu, target[pmu->scope]); 14122 } 14123 } 14124 14125 static void perf_event_exit_cpu_context(int cpu) 14126 { 14127 struct perf_cpu_context *cpuctx; 14128 struct perf_event_context *ctx; 14129 14130 // XXX simplify cpuctx->online 14131 mutex_lock(&pmus_lock); 14132 /* 14133 * Clear the cpumasks, and migrate to other CPUs if possible. 14134 * Must be invoked before the __perf_event_exit_context. 14135 */ 14136 perf_event_clear_cpumask(cpu); 14137 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu); 14138 ctx = &cpuctx->ctx; 14139 14140 mutex_lock(&ctx->mutex); 14141 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1); 14142 cpuctx->online = 0; 14143 mutex_unlock(&ctx->mutex); 14144 mutex_unlock(&pmus_lock); 14145 } 14146 #else 14147 14148 static void perf_event_exit_cpu_context(int cpu) { } 14149 14150 #endif 14151 14152 static void perf_event_setup_cpumask(unsigned int cpu) 14153 { 14154 struct cpumask *pmu_cpumask; 14155 unsigned int scope; 14156 14157 /* 14158 * Early boot stage, the cpumask hasn't been set yet. 14159 * The perf_online_<domain>_masks includes the first CPU of each domain. 14160 * Always unconditionally set the boot CPU for the perf_online_<domain>_masks. 14161 */ 14162 if (cpumask_empty(perf_online_mask)) { 14163 for (scope = PERF_PMU_SCOPE_NONE + 1; scope < PERF_PMU_MAX_SCOPE; scope++) { 14164 pmu_cpumask = perf_scope_cpumask(scope); 14165 if (WARN_ON_ONCE(!pmu_cpumask)) 14166 continue; 14167 cpumask_set_cpu(cpu, pmu_cpumask); 14168 } 14169 goto end; 14170 } 14171 14172 for (scope = PERF_PMU_SCOPE_NONE + 1; scope < PERF_PMU_MAX_SCOPE; scope++) { 14173 const struct cpumask *cpumask = perf_scope_cpu_topology_cpumask(scope, cpu); 14174 14175 pmu_cpumask = perf_scope_cpumask(scope); 14176 14177 if (WARN_ON_ONCE(!pmu_cpumask || !cpumask)) 14178 continue; 14179 14180 if (!cpumask_empty(cpumask) && 14181 cpumask_any_and(pmu_cpumask, cpumask) >= nr_cpu_ids) 14182 cpumask_set_cpu(cpu, pmu_cpumask); 14183 } 14184 end: 14185 cpumask_set_cpu(cpu, perf_online_mask); 14186 } 14187 14188 int perf_event_init_cpu(unsigned int cpu) 14189 { 14190 struct perf_cpu_context *cpuctx; 14191 struct perf_event_context *ctx; 14192 14193 perf_swevent_init_cpu(cpu); 14194 14195 mutex_lock(&pmus_lock); 14196 perf_event_setup_cpumask(cpu); 14197 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu); 14198 ctx = &cpuctx->ctx; 14199 14200 mutex_lock(&ctx->mutex); 14201 cpuctx->online = 1; 14202 mutex_unlock(&ctx->mutex); 14203 mutex_unlock(&pmus_lock); 14204 14205 return 0; 14206 } 14207 14208 int perf_event_exit_cpu(unsigned int cpu) 14209 { 14210 perf_event_exit_cpu_context(cpu); 14211 return 0; 14212 } 14213 14214 static int 14215 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v) 14216 { 14217 int cpu; 14218 14219 for_each_online_cpu(cpu) 14220 perf_event_exit_cpu(cpu); 14221 14222 return NOTIFY_OK; 14223 } 14224 14225 /* 14226 * Run the perf reboot notifier at the very last possible moment so that 14227 * the generic watchdog code runs as long as possible. 14228 */ 14229 static struct notifier_block perf_reboot_notifier = { 14230 .notifier_call = perf_reboot, 14231 .priority = INT_MIN, 14232 }; 14233 14234 void __init perf_event_init(void) 14235 { 14236 int ret; 14237 14238 idr_init(&pmu_idr); 14239 14240 perf_event_init_all_cpus(); 14241 init_srcu_struct(&pmus_srcu); 14242 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE); 14243 perf_pmu_register(&perf_cpu_clock, "cpu_clock", -1); 14244 perf_pmu_register(&perf_task_clock, "task_clock", -1); 14245 perf_tp_register(); 14246 perf_event_init_cpu(smp_processor_id()); 14247 register_reboot_notifier(&perf_reboot_notifier); 14248 14249 ret = init_hw_breakpoint(); 14250 WARN(ret, "hw_breakpoint initialization failed with: %d", ret); 14251 14252 perf_event_cache = KMEM_CACHE(perf_event, SLAB_PANIC); 14253 14254 /* 14255 * Build time assertion that we keep the data_head at the intended 14256 * location. IOW, validation we got the __reserved[] size right. 14257 */ 14258 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head)) 14259 != 1024); 14260 } 14261 14262 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr, 14263 char *page) 14264 { 14265 struct perf_pmu_events_attr *pmu_attr = 14266 container_of(attr, struct perf_pmu_events_attr, attr); 14267 14268 if (pmu_attr->event_str) 14269 return sprintf(page, "%s\n", pmu_attr->event_str); 14270 14271 return 0; 14272 } 14273 EXPORT_SYMBOL_GPL(perf_event_sysfs_show); 14274 14275 static int __init perf_event_sysfs_init(void) 14276 { 14277 struct pmu *pmu; 14278 int ret; 14279 14280 mutex_lock(&pmus_lock); 14281 14282 ret = bus_register(&pmu_bus); 14283 if (ret) 14284 goto unlock; 14285 14286 list_for_each_entry(pmu, &pmus, entry) { 14287 if (pmu->dev) 14288 continue; 14289 14290 ret = pmu_dev_alloc(pmu); 14291 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret); 14292 } 14293 pmu_bus_running = 1; 14294 ret = 0; 14295 14296 unlock: 14297 mutex_unlock(&pmus_lock); 14298 14299 return ret; 14300 } 14301 device_initcall(perf_event_sysfs_init); 14302 14303 #ifdef CONFIG_CGROUP_PERF 14304 static struct cgroup_subsys_state * 14305 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css) 14306 { 14307 struct perf_cgroup *jc; 14308 14309 jc = kzalloc(sizeof(*jc), GFP_KERNEL); 14310 if (!jc) 14311 return ERR_PTR(-ENOMEM); 14312 14313 jc->info = alloc_percpu(struct perf_cgroup_info); 14314 if (!jc->info) { 14315 kfree(jc); 14316 return ERR_PTR(-ENOMEM); 14317 } 14318 14319 return &jc->css; 14320 } 14321 14322 static void perf_cgroup_css_free(struct cgroup_subsys_state *css) 14323 { 14324 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css); 14325 14326 free_percpu(jc->info); 14327 kfree(jc); 14328 } 14329 14330 static int perf_cgroup_css_online(struct cgroup_subsys_state *css) 14331 { 14332 perf_event_cgroup(css->cgroup); 14333 return 0; 14334 } 14335 14336 static int __perf_cgroup_move(void *info) 14337 { 14338 struct task_struct *task = info; 14339 14340 preempt_disable(); 14341 perf_cgroup_switch(task); 14342 preempt_enable(); 14343 14344 return 0; 14345 } 14346 14347 static void perf_cgroup_attach(struct cgroup_taskset *tset) 14348 { 14349 struct task_struct *task; 14350 struct cgroup_subsys_state *css; 14351 14352 cgroup_taskset_for_each(task, css, tset) 14353 task_function_call(task, __perf_cgroup_move, task); 14354 } 14355 14356 struct cgroup_subsys perf_event_cgrp_subsys = { 14357 .css_alloc = perf_cgroup_css_alloc, 14358 .css_free = perf_cgroup_css_free, 14359 .css_online = perf_cgroup_css_online, 14360 .attach = perf_cgroup_attach, 14361 /* 14362 * Implicitly enable on dfl hierarchy so that perf events can 14363 * always be filtered by cgroup2 path as long as perf_event 14364 * controller is not mounted on a legacy hierarchy. 14365 */ 14366 .implicit_on_dfl = true, 14367 .threaded = true, 14368 }; 14369 #endif /* CONFIG_CGROUP_PERF */ 14370 14371 DEFINE_STATIC_CALL_RET0(perf_snapshot_branch_stack, perf_snapshot_branch_stack_t); 14372