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