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