1 /*-
2 * SPDX-License-Identifier: BSD-2-Clause
3 *
4 * Copyright (c) 2003-2008 Joseph Koshy
5 * Copyright (c) 2007 The FreeBSD Foundation
6 * Copyright (c) 2018 Matthew Macy
7 * All rights reserved.
8 *
9 * Portions of this software were developed by A. Joseph Koshy under
10 * sponsorship from the FreeBSD Foundation and Google, Inc.
11 *
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
34 #include <sys/param.h>
35 #include <sys/systm.h>
36 #include <sys/domainset.h>
37 #include <sys/eventhandler.h>
38 #include <sys/jail.h>
39 #include <sys/kernel.h>
40 #include <sys/kthread.h>
41 #include <sys/limits.h>
42 #include <sys/lock.h>
43 #include <sys/malloc.h>
44 #include <sys/module.h>
45 #include <sys/mount.h>
46 #include <sys/mutex.h>
47 #include <sys/pmc.h>
48 #include <sys/pmckern.h>
49 #include <sys/pmclog.h>
50 #include <sys/priv.h>
51 #include <sys/proc.h>
52 #include <sys/queue.h>
53 #include <sys/resourcevar.h>
54 #include <sys/rwlock.h>
55 #include <sys/sched.h>
56 #include <sys/signalvar.h>
57 #include <sys/smp.h>
58 #include <sys/sx.h>
59 #include <sys/sysctl.h>
60 #include <sys/sysent.h>
61 #include <sys/syslog.h>
62 #include <sys/taskqueue.h>
63 #include <sys/vnode.h>
64
65 #include <sys/linker.h> /* needs to be after <sys/malloc.h> */
66
67 #include <machine/atomic.h>
68 #include <machine/md_var.h>
69
70 #include <vm/vm.h>
71 #include <vm/vm_extern.h>
72 #include <vm/pmap.h>
73 #include <vm/vm_map.h>
74 #include <vm/vm_object.h>
75
76 #include "hwpmc_soft.h"
77
78 #define PMC_EPOCH_ENTER() \
79 struct epoch_tracker pmc_et; \
80 epoch_enter_preempt(global_epoch_preempt, &pmc_et)
81
82 #define PMC_EPOCH_EXIT() \
83 epoch_exit_preempt(global_epoch_preempt, &pmc_et)
84
85 /*
86 * Types
87 */
88
89 enum pmc_flags {
90 PMC_FLAG_NONE = 0x00, /* do nothing */
91 PMC_FLAG_REMOVE = 0x01, /* atomically remove entry from hash */
92 PMC_FLAG_ALLOCATE = 0x02, /* add entry to hash if not found */
93 PMC_FLAG_NOWAIT = 0x04, /* do not wait for mallocs */
94 };
95
96 /*
97 * The offset in sysent where the syscall is allocated.
98 */
99 static int pmc_syscall_num = NO_SYSCALL;
100
101 struct pmc_cpu **pmc_pcpu; /* per-cpu state */
102 pmc_value_t *pmc_pcpu_saved; /* saved PMC values: CSW handling */
103
104 #define PMC_PCPU_SAVED(C, R) pmc_pcpu_saved[(R) + md->pmd_npmc * (C)]
105
106 struct mtx_pool *pmc_mtxpool;
107 static int *pmc_pmcdisp; /* PMC row dispositions */
108
109 #define PMC_ROW_DISP_IS_FREE(R) (pmc_pmcdisp[(R)] == 0)
110 #define PMC_ROW_DISP_IS_THREAD(R) (pmc_pmcdisp[(R)] > 0)
111 #define PMC_ROW_DISP_IS_STANDALONE(R) (pmc_pmcdisp[(R)] < 0)
112
113 #define PMC_MARK_ROW_FREE(R) do { \
114 pmc_pmcdisp[(R)] = 0; \
115 } while (0)
116
117 #define PMC_MARK_ROW_STANDALONE(R) do { \
118 KASSERT(pmc_pmcdisp[(R)] <= 0, ("[pmc,%d] row disposition error", \
119 __LINE__)); \
120 atomic_add_int(&pmc_pmcdisp[(R)], -1); \
121 KASSERT(pmc_pmcdisp[(R)] >= (-pmc_cpu_max_active()), \
122 ("[pmc,%d] row disposition error", __LINE__)); \
123 } while (0)
124
125 #define PMC_UNMARK_ROW_STANDALONE(R) do { \
126 atomic_add_int(&pmc_pmcdisp[(R)], 1); \
127 KASSERT(pmc_pmcdisp[(R)] <= 0, ("[pmc,%d] row disposition error", \
128 __LINE__)); \
129 } while (0)
130
131 #define PMC_MARK_ROW_THREAD(R) do { \
132 KASSERT(pmc_pmcdisp[(R)] >= 0, ("[pmc,%d] row disposition error", \
133 __LINE__)); \
134 atomic_add_int(&pmc_pmcdisp[(R)], 1); \
135 } while (0)
136
137 #define PMC_UNMARK_ROW_THREAD(R) do { \
138 atomic_add_int(&pmc_pmcdisp[(R)], -1); \
139 KASSERT(pmc_pmcdisp[(R)] >= 0, ("[pmc,%d] row disposition error", \
140 __LINE__)); \
141 } while (0)
142
143 /* various event handlers */
144 static eventhandler_tag pmc_exit_tag, pmc_fork_tag, pmc_kld_load_tag,
145 pmc_kld_unload_tag;
146
147 /* Module statistics */
148 struct pmc_driverstats pmc_stats;
149
150 /* Machine/processor dependent operations */
151 static struct pmc_mdep *md;
152
153 /*
154 * Hash tables mapping owner processes and target threads to PMCs.
155 */
156 struct mtx pmc_processhash_mtx; /* spin mutex */
157 static u_long pmc_processhashmask;
158 static LIST_HEAD(pmc_processhash, pmc_process) *pmc_processhash;
159
160 /*
161 * Hash table of PMC owner descriptors. This table is protected by
162 * the shared PMC "sx" lock.
163 */
164 static u_long pmc_ownerhashmask;
165 static LIST_HEAD(pmc_ownerhash, pmc_owner) *pmc_ownerhash;
166
167 /*
168 * List of PMC owners with system-wide sampling PMCs.
169 */
170 static CK_LIST_HEAD(, pmc_owner) pmc_ss_owners;
171
172 /*
173 * List of free thread entries. This is protected by the spin
174 * mutex.
175 */
176 static struct mtx pmc_threadfreelist_mtx; /* spin mutex */
177 static LIST_HEAD(, pmc_thread) pmc_threadfreelist;
178 static int pmc_threadfreelist_entries = 0;
179 #define THREADENTRY_SIZE (sizeof(struct pmc_thread) + \
180 (md->pmd_npmc * sizeof(struct pmc_threadpmcstate)))
181
182 /*
183 * Task to free thread descriptors
184 */
185 static struct task free_task;
186
187 /*
188 * A map of row indices to classdep structures.
189 */
190 static struct pmc_classdep **pmc_rowindex_to_classdep;
191
192 /*
193 * Prototypes
194 */
195
196 #ifdef HWPMC_DEBUG
197 static int pmc_debugflags_sysctl_handler(SYSCTL_HANDLER_ARGS);
198 static int pmc_debugflags_parse(char *newstr, char *fence);
199 #endif
200
201 static bool pmc_is_multipart(struct pmc_sample *ps);
202 static void pmc_multipart_add(struct pmc_sample *ps, int type,
203 int length);
204 static void pmc_multipart_copydata(struct pmc_sample *ps,
205 struct pmc_multipart *mp);
206
207 static int load(struct module *module, int cmd, void *arg);
208 static int pmc_add_sample(ring_type_t ring, struct pmc *pm,
209 struct trapframe *tf, struct pmc_multipart *mp);
210 static void pmc_add_thread_descriptors_from_proc(struct proc *p,
211 struct pmc_process *pp);
212 static int pmc_attach_process(struct proc *p, struct pmc *pm);
213 static struct pmc *pmc_allocate_pmc_descriptor(void);
214 static struct pmc_owner *pmc_allocate_owner_descriptor(struct proc *p);
215 static int pmc_attach_one_process(struct proc *p, struct pmc *pm);
216 static bool pmc_can_allocate_row(int ri, enum pmc_mode mode);
217 static bool pmc_can_allocate_rowindex(struct proc *p, unsigned int ri,
218 int cpu);
219 static bool pmc_can_attach(struct pmc *pm, struct proc *p);
220 static void pmc_capture_user_callchain(int cpu, int soft,
221 struct trapframe *tf);
222 static void pmc_cleanup(void);
223 static int pmc_detach_process(struct proc *p, struct pmc *pm);
224 static int pmc_detach_one_process(struct proc *p, struct pmc *pm,
225 int flags);
226 static void pmc_destroy_owner_descriptor(struct pmc_owner *po);
227 static void pmc_destroy_pmc_descriptor(struct pmc *pm);
228 static void pmc_destroy_process_descriptor(struct pmc_process *pp);
229 static struct pmc_owner *pmc_find_owner_descriptor(struct proc *p);
230 static int pmc_find_pmc(pmc_id_t pmcid, struct pmc **pm);
231 static struct pmc *pmc_find_pmc_descriptor_in_process(struct pmc_owner *po,
232 pmc_id_t pmc);
233 static struct pmc_process *pmc_find_process_descriptor(struct proc *p,
234 uint32_t mode);
235 static struct pmc_thread *pmc_find_thread_descriptor(struct pmc_process *pp,
236 struct thread *td, uint32_t mode);
237 static void pmc_force_context_switch(void);
238 static void pmc_link_target_process(struct pmc *pm,
239 struct pmc_process *pp);
240 static void pmc_log_all_process_mappings(struct pmc_owner *po);
241 static void pmc_log_kernel_mappings(struct pmc *pm);
242 static void pmc_log_process_mappings(struct pmc_owner *po, struct proc *p);
243 static void pmc_maybe_remove_owner(struct pmc_owner *po);
244 static void pmc_post_callchain_callback(void);
245 static void pmc_process_allproc(struct pmc *pm);
246 static void pmc_process_csw_in(struct thread *td);
247 static void pmc_process_csw_out(struct thread *td);
248 static void pmc_process_exec(struct thread *td,
249 struct pmckern_procexec *pk);
250 static void pmc_process_exit(void *arg, struct proc *p);
251 static void pmc_process_fork(void *arg, struct proc *p1,
252 struct proc *p2, int n);
253 static void pmc_process_proccreate(struct proc *p);
254 static void pmc_process_samples(int cpu, ring_type_t soft);
255 static void pmc_process_threadcreate(struct thread *td);
256 static void pmc_process_threadexit(struct thread *td);
257 static void pmc_process_thread_add(struct thread *td);
258 static void pmc_process_thread_delete(struct thread *td);
259 static void pmc_process_thread_userret(struct thread *td);
260 static void pmc_release_pmc_descriptor(struct pmc *pmc);
261 static void pmc_remove_owner(struct pmc_owner *po);
262 static void pmc_remove_process_descriptor(struct pmc_process *pp);
263 static int pmc_start(struct pmc *pm);
264 static int pmc_stop(struct pmc *pm);
265 static int pmc_syscall_handler(struct thread *td, void *syscall_args);
266 static struct pmc_thread *pmc_thread_descriptor_pool_alloc(void);
267 static void pmc_thread_descriptor_pool_drain(void);
268 static void pmc_thread_descriptor_pool_free(struct pmc_thread *pt);
269 static void pmc_unlink_target_process(struct pmc *pmc,
270 struct pmc_process *pp);
271
272 static int generic_switch_in(struct pmc_cpu *pc, struct pmc_process *pp);
273 static int generic_switch_out(struct pmc_cpu *pc, struct pmc_process *pp);
274 static struct pmc_mdep *pmc_generic_cpu_initialize(void);
275 static void pmc_generic_cpu_finalize(struct pmc_mdep *md);
276
277 /*
278 * Kernel tunables and sysctl(8) interface.
279 */
280
281 SYSCTL_DECL(_kern_hwpmc);
282 SYSCTL_NODE(_kern_hwpmc, OID_AUTO, stats, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
283 "HWPMC stats");
284
285 /* Stats. */
286 SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, intr_ignored, CTLFLAG_RW,
287 &pmc_stats.pm_intr_ignored,
288 "# of interrupts ignored");
289 SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, intr_processed, CTLFLAG_RW,
290 &pmc_stats.pm_intr_processed,
291 "# of interrupts processed");
292 SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, intr_bufferfull, CTLFLAG_RW,
293 &pmc_stats.pm_intr_bufferfull,
294 "# of interrupts where buffer was full");
295 SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, syscalls, CTLFLAG_RW,
296 &pmc_stats.pm_syscalls,
297 "# of syscalls");
298 SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, syscall_errors, CTLFLAG_RW,
299 &pmc_stats.pm_syscall_errors,
300 "# of syscall_errors");
301 SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, buffer_requests, CTLFLAG_RW,
302 &pmc_stats.pm_buffer_requests,
303 "# of buffer requests");
304 SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, buffer_requests_failed,
305 CTLFLAG_RW, &pmc_stats.pm_buffer_requests_failed,
306 "# of buffer requests which failed");
307 SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, log_sweeps, CTLFLAG_RW,
308 &pmc_stats.pm_log_sweeps,
309 "# of times samples were processed");
310 SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, merges, CTLFLAG_RW,
311 &pmc_stats.pm_merges,
312 "# of times kernel stack was found for user trace");
313 SYSCTL_COUNTER_U64(_kern_hwpmc_stats, OID_AUTO, overwrites, CTLFLAG_RW,
314 &pmc_stats.pm_overwrites,
315 "# of times a sample was overwritten before being logged");
316
317 static int pmc_callchaindepth = PMC_CALLCHAIN_DEPTH;
318 SYSCTL_INT(_kern_hwpmc, OID_AUTO, callchaindepth, CTLFLAG_RDTUN,
319 &pmc_callchaindepth, 0,
320 "depth of call chain records");
321
322 char pmc_cpuid[PMC_CPUID_LEN];
323 SYSCTL_STRING(_kern_hwpmc, OID_AUTO, cpuid, CTLFLAG_RD,
324 pmc_cpuid, 0,
325 "cpu version string");
326
327 #ifdef HWPMC_DEBUG
328 struct pmc_debugflags pmc_debugflags = PMC_DEBUG_DEFAULT_FLAGS;
329 char pmc_debugstr[PMC_DEBUG_STRSIZE];
330 TUNABLE_STR(PMC_SYSCTL_NAME_PREFIX "debugflags", pmc_debugstr,
331 sizeof(pmc_debugstr));
332 SYSCTL_PROC(_kern_hwpmc, OID_AUTO, debugflags,
333 CTLTYPE_STRING | CTLFLAG_RWTUN | CTLFLAG_NOFETCH | CTLFLAG_MPSAFE,
334 0, 0, pmc_debugflags_sysctl_handler, "A",
335 "debug flags");
336 #endif
337
338 /*
339 * kern.hwpmc.hashsize -- determines the number of rows in the
340 * of the hash table used to look up threads
341 */
342 static int pmc_hashsize = PMC_HASH_SIZE;
343 SYSCTL_INT(_kern_hwpmc, OID_AUTO, hashsize, CTLFLAG_RDTUN,
344 &pmc_hashsize, 0,
345 "rows in hash tables");
346
347 /*
348 * kern.hwpmc.nsamples --- number of PC samples/callchain stacks per CPU
349 */
350 static int pmc_nsamples = PMC_NSAMPLES;
351 SYSCTL_INT(_kern_hwpmc, OID_AUTO, nsamples, CTLFLAG_RDTUN,
352 &pmc_nsamples, 0,
353 "number of PC samples per CPU");
354
355 static uint64_t pmc_sample_mask = PMC_NSAMPLES - 1;
356
357 /*
358 * kern.hwpmc.mtxpoolsize -- number of mutexes in the mutex pool.
359 */
360 static int pmc_mtxpool_size = PMC_MTXPOOL_SIZE;
361 SYSCTL_INT(_kern_hwpmc, OID_AUTO, mtxpoolsize, CTLFLAG_RDTUN,
362 &pmc_mtxpool_size, 0,
363 "size of spin mutex pool");
364
365 /*
366 * kern.hwpmc.threadfreelist_entries -- number of free entries
367 */
368 SYSCTL_INT(_kern_hwpmc, OID_AUTO, threadfreelist_entries, CTLFLAG_RD,
369 &pmc_threadfreelist_entries, 0,
370 "number of available thread entries");
371
372 /*
373 * kern.hwpmc.threadfreelist_max -- maximum number of free entries
374 */
375 static int pmc_threadfreelist_max = PMC_THREADLIST_MAX;
376 SYSCTL_INT(_kern_hwpmc, OID_AUTO, threadfreelist_max, CTLFLAG_RW,
377 &pmc_threadfreelist_max, 0,
378 "maximum number of available thread entries before freeing some");
379
380 /*
381 * kern.hwpmc.mincount -- minimum sample count
382 */
383 static u_int pmc_mincount = 1000;
384 SYSCTL_INT(_kern_hwpmc, OID_AUTO, mincount, CTLFLAG_RWTUN,
385 &pmc_mincount, 0,
386 "minimum count for sampling counters");
387
388 /*
389 * security.bsd.unprivileged_syspmcs -- allow non-root processes to
390 * allocate system-wide PMCs.
391 *
392 * Allowing unprivileged processes to allocate system PMCs is convenient
393 * if system-wide measurements need to be taken concurrently with other
394 * per-process measurements. This feature is turned off by default.
395 */
396 static int pmc_unprivileged_syspmcs = 0;
397 SYSCTL_INT(_security_bsd, OID_AUTO, unprivileged_syspmcs, CTLFLAG_RWTUN,
398 &pmc_unprivileged_syspmcs, 0,
399 "allow unprivileged process to allocate system PMCs");
400
401 /*
402 * Hash function. Discard the lower 2 bits of the pointer since
403 * these are always zero for our uses. The hash multiplier is
404 * round((2^LONG_BIT) * ((sqrt(5)-1)/2)).
405 */
406 #if LONG_BIT == 64
407 #define _PMC_HM 11400714819323198486u
408 #elif LONG_BIT == 32
409 #define _PMC_HM 2654435769u
410 #else
411 #error Must know the size of 'long' to compile
412 #endif
413
414 #define PMC_HASH_PTR(P,M) ((((unsigned long) (P) >> 2) * _PMC_HM) & (M))
415
416 /*
417 * Syscall structures
418 */
419
420 /* The `sysent' for the new syscall */
421 static struct sysent pmc_sysent = {
422 .sy_narg = 2,
423 .sy_call = pmc_syscall_handler,
424 };
425
426 static struct syscall_module_data pmc_syscall_mod = {
427 .chainevh = load,
428 .chainarg = NULL,
429 .offset = &pmc_syscall_num,
430 .new_sysent = &pmc_sysent,
431 .old_sysent = { .sy_narg = 0, .sy_call = NULL },
432 .flags = SY_THR_STATIC_KLD,
433 };
434
435 static moduledata_t pmc_mod = {
436 .name = PMC_MODULE_NAME,
437 .evhand = syscall_module_handler,
438 .priv = &pmc_syscall_mod,
439 };
440
441 #ifdef EARLY_AP_STARTUP
442 DECLARE_MODULE(pmc, pmc_mod, SI_SUB_SYSCALLS, SI_ORDER_ANY);
443 #else
444 DECLARE_MODULE(pmc, pmc_mod, SI_SUB_SMP, SI_ORDER_ANY);
445 #endif
446 MODULE_VERSION(pmc, PMC_VERSION);
447
448 #ifdef HWPMC_DEBUG
449 enum pmc_dbgparse_state {
450 PMCDS_WS, /* in whitespace */
451 PMCDS_MAJOR, /* seen a major keyword */
452 PMCDS_MINOR
453 };
454
455 static int
pmc_debugflags_parse(char * newstr,char * fence)456 pmc_debugflags_parse(char *newstr, char *fence)
457 {
458 struct pmc_debugflags *tmpflags;
459 size_t kwlen;
460 char c, *p, *q;
461 int error, *newbits, tmp;
462 int found;
463
464 tmpflags = malloc(sizeof(*tmpflags), M_PMC, M_WAITOK | M_ZERO);
465
466 error = 0;
467 for (p = newstr; p < fence && (c = *p); p++) {
468 /* skip white space */
469 if (c == ' ' || c == '\t')
470 continue;
471
472 /* look for a keyword followed by "=" */
473 for (q = p; p < fence && (c = *p) && c != '='; p++)
474 ;
475 if (c != '=') {
476 error = EINVAL;
477 goto done;
478 }
479
480 kwlen = p - q;
481 newbits = NULL;
482
483 /* lookup flag group name */
484 #define DBG_SET_FLAG_MAJ(S,F) \
485 if (kwlen == sizeof(S)-1 && strncmp(q, S, kwlen) == 0) \
486 newbits = &tmpflags->pdb_ ## F;
487
488 DBG_SET_FLAG_MAJ("cpu", CPU);
489 DBG_SET_FLAG_MAJ("csw", CSW);
490 DBG_SET_FLAG_MAJ("logging", LOG);
491 DBG_SET_FLAG_MAJ("module", MOD);
492 DBG_SET_FLAG_MAJ("md", MDP);
493 DBG_SET_FLAG_MAJ("owner", OWN);
494 DBG_SET_FLAG_MAJ("pmc", PMC);
495 DBG_SET_FLAG_MAJ("process", PRC);
496 DBG_SET_FLAG_MAJ("sampling", SAM);
497 #undef DBG_SET_FLAG_MAJ
498
499 if (newbits == NULL) {
500 error = EINVAL;
501 goto done;
502 }
503
504 p++; /* skip the '=' */
505
506 /* Now parse the individual flags */
507 tmp = 0;
508 newflag:
509 for (q = p; p < fence && (c = *p); p++)
510 if (c == ' ' || c == '\t' || c == ',')
511 break;
512
513 /* p == fence or c == ws or c == "," or c == 0 */
514
515 if ((kwlen = p - q) == 0) {
516 *newbits = tmp;
517 continue;
518 }
519
520 found = 0;
521 #define DBG_SET_FLAG_MIN(S,F) \
522 if (kwlen == sizeof(S)-1 && strncmp(q, S, kwlen) == 0) \
523 tmp |= found = (1 << PMC_DEBUG_MIN_ ## F)
524
525 /* a '*' denotes all possible flags in the group */
526 if (kwlen == 1 && *q == '*')
527 tmp = found = ~0;
528 /* look for individual flag names */
529 DBG_SET_FLAG_MIN("allocaterow", ALR);
530 DBG_SET_FLAG_MIN("allocate", ALL);
531 DBG_SET_FLAG_MIN("attach", ATT);
532 DBG_SET_FLAG_MIN("bind", BND);
533 DBG_SET_FLAG_MIN("config", CFG);
534 DBG_SET_FLAG_MIN("exec", EXC);
535 DBG_SET_FLAG_MIN("exit", EXT);
536 DBG_SET_FLAG_MIN("find", FND);
537 DBG_SET_FLAG_MIN("flush", FLS);
538 DBG_SET_FLAG_MIN("fork", FRK);
539 DBG_SET_FLAG_MIN("getbuf", GTB);
540 DBG_SET_FLAG_MIN("hook", PMH);
541 DBG_SET_FLAG_MIN("init", INI);
542 DBG_SET_FLAG_MIN("intr", INT);
543 DBG_SET_FLAG_MIN("linktarget", TLK);
544 DBG_SET_FLAG_MIN("mayberemove", OMR);
545 DBG_SET_FLAG_MIN("ops", OPS);
546 DBG_SET_FLAG_MIN("read", REA);
547 DBG_SET_FLAG_MIN("register", REG);
548 DBG_SET_FLAG_MIN("release", REL);
549 DBG_SET_FLAG_MIN("remove", ORM);
550 DBG_SET_FLAG_MIN("sample", SAM);
551 DBG_SET_FLAG_MIN("scheduleio", SIO);
552 DBG_SET_FLAG_MIN("select", SEL);
553 DBG_SET_FLAG_MIN("signal", SIG);
554 DBG_SET_FLAG_MIN("swi", SWI);
555 DBG_SET_FLAG_MIN("swo", SWO);
556 DBG_SET_FLAG_MIN("start", STA);
557 DBG_SET_FLAG_MIN("stop", STO);
558 DBG_SET_FLAG_MIN("syscall", PMS);
559 DBG_SET_FLAG_MIN("unlinktarget", TUL);
560 DBG_SET_FLAG_MIN("write", WRI);
561 #undef DBG_SET_FLAG_MIN
562 if (found == 0) {
563 /* unrecognized flag name */
564 error = EINVAL;
565 goto done;
566 }
567
568 if (c == 0 || c == ' ' || c == '\t') { /* end of flag group */
569 *newbits = tmp;
570 continue;
571 }
572
573 p++;
574 goto newflag;
575 }
576
577 /* save the new flag set */
578 bcopy(tmpflags, &pmc_debugflags, sizeof(pmc_debugflags));
579 done:
580 free(tmpflags, M_PMC);
581 return (error);
582 }
583
584 static int
pmc_debugflags_sysctl_handler(SYSCTL_HANDLER_ARGS)585 pmc_debugflags_sysctl_handler(SYSCTL_HANDLER_ARGS)
586 {
587 char *fence, *newstr;
588 int error;
589 u_int n;
590
591 n = sizeof(pmc_debugstr);
592 newstr = malloc(n, M_PMC, M_WAITOK | M_ZERO);
593 strlcpy(newstr, pmc_debugstr, n);
594
595 error = sysctl_handle_string(oidp, newstr, n, req);
596
597 /* if there is a new string, parse and copy it */
598 if (error == 0 && req->newptr != NULL) {
599 fence = newstr + (n < req->newlen ? n : req->newlen + 1);
600 error = pmc_debugflags_parse(newstr, fence);
601 if (error == 0)
602 strlcpy(pmc_debugstr, newstr, sizeof(pmc_debugstr));
603 }
604 free(newstr, M_PMC);
605
606 return (error);
607 }
608 #endif
609
610 /*
611 * Map a row index to a classdep structure and return the adjusted row
612 * index for the PMC class index.
613 */
614 static struct pmc_classdep *
pmc_ri_to_classdep(struct pmc_mdep * md __unused,int ri,int * adjri)615 pmc_ri_to_classdep(struct pmc_mdep *md __unused, int ri, int *adjri)
616 {
617 struct pmc_classdep *pcd;
618
619 KASSERT(ri >= 0 && ri < md->pmd_npmc,
620 ("[pmc,%d] illegal row-index %d", __LINE__, ri));
621
622 pcd = pmc_rowindex_to_classdep[ri];
623 KASSERT(pcd != NULL,
624 ("[pmc,%d] ri %d null pcd", __LINE__, ri));
625
626 *adjri = ri - pcd->pcd_ri;
627 KASSERT(*adjri >= 0 && *adjri < pcd->pcd_num,
628 ("[pmc,%d] adjusted row-index %d", __LINE__, *adjri));
629
630 return (pcd);
631 }
632
633 /*
634 * Concurrency Control
635 *
636 * The driver manages the following data structures:
637 *
638 * - target process descriptors, one per target process
639 * - owner process descriptors (and attached lists), one per owner process
640 * - lookup hash tables for owner and target processes
641 * - PMC descriptors (and attached lists)
642 * - per-cpu hardware state
643 * - the 'hook' variable through which the kernel calls into
644 * this module
645 * - the machine hardware state (managed by the MD layer)
646 *
647 * These data structures are accessed from:
648 *
649 * - thread context-switch code
650 * - interrupt handlers (possibly on multiple cpus)
651 * - kernel threads on multiple cpus running on behalf of user
652 * processes doing system calls
653 * - this driver's private kernel threads
654 *
655 * = Locks and Locking strategy =
656 *
657 * The driver uses four locking strategies for its operation:
658 *
659 * - The global SX lock "pmc_sx" is used to protect internal
660 * data structures.
661 *
662 * Calls into the module by syscall() start with this lock being
663 * held in exclusive mode. Depending on the requested operation,
664 * the lock may be downgraded to 'shared' mode to allow more
665 * concurrent readers into the module. Calls into the module from
666 * other parts of the kernel acquire the lock in shared mode.
667 *
668 * This SX lock is held in exclusive mode for any operations that
669 * modify the linkages between the driver's internal data structures.
670 *
671 * The 'pmc_hook' function pointer is also protected by this lock.
672 * It is only examined with the sx lock held in exclusive mode. The
673 * kernel module is allowed to be unloaded only with the sx lock held
674 * in exclusive mode. In normal syscall handling, after acquiring the
675 * pmc_sx lock we first check that 'pmc_hook' is non-null before
676 * proceeding. This prevents races between the thread unloading the module
677 * and other threads seeking to use the module.
678 *
679 * - Lookups of target process structures and owner process structures
680 * cannot use the global "pmc_sx" SX lock because these lookups need
681 * to happen during context switches and in other critical sections
682 * where sleeping is not allowed. We protect these lookup tables
683 * with their own private spin-mutexes, "pmc_processhash_mtx" and
684 * "pmc_ownerhash_mtx".
685 *
686 * - Interrupt handlers work in a lock free manner. At interrupt
687 * time, handlers look at the PMC pointer (phw->phw_pmc) configured
688 * when the PMC was started. If this pointer is NULL, the interrupt
689 * is ignored after updating driver statistics. We ensure that this
690 * pointer is set (using an atomic operation if necessary) before the
691 * PMC hardware is started. Conversely, this pointer is unset atomically
692 * only after the PMC hardware is stopped.
693 *
694 * We ensure that everything needed for the operation of an
695 * interrupt handler is available without it needing to acquire any
696 * locks. We also ensure that a PMC's software state is destroyed only
697 * after the PMC is taken off hardware (on all CPUs).
698 *
699 * - Context-switch handling with process-private PMCs needs more
700 * care.
701 *
702 * A given process may be the target of multiple PMCs. For example,
703 * PMCATTACH and PMCDETACH may be requested by a process on one CPU
704 * while the target process is running on another. A PMC could also
705 * be getting released because its owner is exiting. We tackle
706 * these situations in the following manner:
707 *
708 * - each target process structure 'pmc_process' has an array
709 * of 'struct pmc *' pointers, one for each hardware PMC.
710 *
711 * - At context switch IN time, each "target" PMC in RUNNING state
712 * gets started on hardware and a pointer to each PMC is copied into
713 * the per-cpu phw array. The 'runcount' for the PMC is
714 * incremented.
715 *
716 * - At context switch OUT time, all process-virtual PMCs are stopped
717 * on hardware. The saved value is added to the PMCs value field
718 * only if the PMC is in a non-deleted state (the PMCs state could
719 * have changed during the current time slice).
720 *
721 * Note that since in-between a switch IN on a processor and a switch
722 * OUT, the PMC could have been released on another CPU. Therefore
723 * context switch OUT always looks at the hardware state to turn
724 * OFF PMCs and will update a PMC's saved value only if reachable
725 * from the target process record.
726 *
727 * - OP PMCRELEASE could be called on a PMC at any time (the PMC could
728 * be attached to many processes at the time of the call and could
729 * be active on multiple CPUs).
730 *
731 * We prevent further scheduling of the PMC by marking it as in
732 * state 'DELETED'. If the runcount of the PMC is non-zero then
733 * this PMC is currently running on a CPU somewhere. The thread
734 * doing the PMCRELEASE operation waits by repeatedly doing a
735 * pause() till the runcount comes to zero.
736 *
737 * The contents of a PMC descriptor (struct pmc) are protected using
738 * a spin-mutex. In order to save space, we use a mutex pool.
739 *
740 * In terms of lock types used by witness(4), we use:
741 * - Type "pmc-sx", used by the global SX lock.
742 * - Type "pmc-sleep", for sleep mutexes used by logger threads.
743 * - Type "pmc-per-proc", for protecting PMC owner descriptors.
744 * - Type "pmc-leaf", used for all other spin mutexes.
745 */
746
747 /*
748 * Save the CPU binding of the current kthread.
749 */
750 void
pmc_save_cpu_binding(struct pmc_binding * pb)751 pmc_save_cpu_binding(struct pmc_binding *pb)
752 {
753 PMCDBG0(CPU,BND,2, "save-cpu");
754 thread_lock(curthread);
755 pb->pb_bound = sched_is_bound(curthread);
756 pb->pb_cpu = curthread->td_oncpu;
757 pb->pb_priority = curthread->td_priority;
758 thread_unlock(curthread);
759 PMCDBG1(CPU,BND,2, "save-cpu cpu=%d", pb->pb_cpu);
760 }
761
762 /*
763 * Restore the CPU binding of the current thread.
764 */
765 void
pmc_restore_cpu_binding(struct pmc_binding * pb)766 pmc_restore_cpu_binding(struct pmc_binding *pb)
767 {
768 PMCDBG2(CPU,BND,2, "restore-cpu curcpu=%d restore=%d",
769 curthread->td_oncpu, pb->pb_cpu);
770 thread_lock(curthread);
771 sched_bind(curthread, pb->pb_cpu);
772 if (!pb->pb_bound)
773 sched_unbind(curthread);
774 sched_prio(curthread, pb->pb_priority);
775 thread_unlock(curthread);
776 PMCDBG0(CPU,BND,2, "restore-cpu done");
777 }
778
779 /*
780 * Move execution over to the specified CPU and bind it there.
781 */
782 void
pmc_select_cpu(int cpu)783 pmc_select_cpu(int cpu)
784 {
785 KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
786 ("[pmc,%d] bad cpu number %d", __LINE__, cpu));
787
788 /* Never move to an inactive CPU. */
789 KASSERT(pmc_cpu_is_active(cpu), ("[pmc,%d] selecting inactive "
790 "CPU %d", __LINE__, cpu));
791
792 PMCDBG1(CPU,SEL,2, "select-cpu cpu=%d", cpu);
793 thread_lock(curthread);
794 sched_prio(curthread, PRI_MIN);
795 sched_bind(curthread, cpu);
796 thread_unlock(curthread);
797
798 KASSERT(curthread->td_oncpu == cpu,
799 ("[pmc,%d] CPU not bound [cpu=%d, curr=%d]", __LINE__,
800 cpu, curthread->td_oncpu));
801
802 PMCDBG1(CPU,SEL,2, "select-cpu cpu=%d ok", cpu);
803 }
804
805 /*
806 * Force a context switch.
807 *
808 * We do this by pause'ing for 1 tick -- invoking mi_switch() is not
809 * guaranteed to force a context switch.
810 */
811 static void
pmc_force_context_switch(void)812 pmc_force_context_switch(void)
813 {
814
815 pause("pmcctx", 1);
816 }
817
818 uint64_t
pmc_rdtsc(void)819 pmc_rdtsc(void)
820 {
821 #if defined(__i386__)
822 /* Unfortunately get_cyclecount on i386 uses cpu_ticks. */
823 return (rdtsc());
824 #else
825 return (get_cyclecount());
826 #endif
827 }
828
829 /*
830 * Get the file name for an executable. This is a simple wrapper
831 * around vn_fullpath(9).
832 */
833 static void
pmc_getfilename(struct vnode * v,char ** fullpath,char ** freepath)834 pmc_getfilename(struct vnode *v, char **fullpath, char **freepath)
835 {
836
837 *fullpath = "unknown";
838 *freepath = NULL;
839 vn_fullpath(v, fullpath, freepath);
840 }
841
842 /*
843 * Remove a process owning PMCs.
844 */
845 void
pmc_remove_owner(struct pmc_owner * po)846 pmc_remove_owner(struct pmc_owner *po)
847 {
848 struct pmc *pm, *tmp;
849
850 sx_assert(&pmc_sx, SX_XLOCKED);
851
852 PMCDBG1(OWN,ORM,1, "remove-owner po=%p", po);
853
854 /* Remove descriptor from the owner hash table */
855 LIST_REMOVE(po, po_next);
856
857 /* release all owned PMC descriptors */
858 LIST_FOREACH_SAFE(pm, &po->po_pmcs, pm_next, tmp) {
859 PMCDBG1(OWN,ORM,2, "pmc=%p", pm);
860 KASSERT(pm->pm_owner == po,
861 ("[pmc,%d] owner %p != po %p", __LINE__, pm->pm_owner, po));
862
863 pmc_release_pmc_descriptor(pm); /* will unlink from the list */
864 pmc_destroy_pmc_descriptor(pm);
865 }
866
867 KASSERT(po->po_sscount == 0,
868 ("[pmc,%d] SS count not zero", __LINE__));
869 KASSERT(LIST_EMPTY(&po->po_pmcs),
870 ("[pmc,%d] PMC list not empty", __LINE__));
871
872 /* de-configure the log file if present */
873 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
874 pmclog_deconfigure_log(po);
875 }
876
877 /*
878 * Remove an owner process record if all conditions are met.
879 */
880 static void
pmc_maybe_remove_owner(struct pmc_owner * po)881 pmc_maybe_remove_owner(struct pmc_owner *po)
882 {
883
884 PMCDBG1(OWN,OMR,1, "maybe-remove-owner po=%p", po);
885
886 /*
887 * Remove owner record if
888 * - this process does not own any PMCs
889 * - this process has not allocated a system-wide sampling buffer
890 */
891 if (LIST_EMPTY(&po->po_pmcs) &&
892 ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)) {
893 pmc_remove_owner(po);
894 pmc_destroy_owner_descriptor(po);
895 }
896 }
897
898 /*
899 * Add an association between a target process and a PMC.
900 */
901 static void
pmc_link_target_process(struct pmc * pm,struct pmc_process * pp)902 pmc_link_target_process(struct pmc *pm, struct pmc_process *pp)
903 {
904 struct pmc_target *pt;
905 struct pmc_thread *pt_td __diagused;
906 int ri;
907
908 sx_assert(&pmc_sx, SX_XLOCKED);
909 KASSERT(pm != NULL && pp != NULL,
910 ("[pmc,%d] Null pm %p or pp %p", __LINE__, pm, pp));
911 KASSERT(PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)),
912 ("[pmc,%d] Attaching a non-process-virtual pmc=%p to pid=%d",
913 __LINE__, pm, pp->pp_proc->p_pid));
914 KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt <= ((int) md->pmd_npmc - 1),
915 ("[pmc,%d] Illegal reference count %d for process record %p",
916 __LINE__, pp->pp_refcnt, (void *) pp));
917
918 ri = PMC_TO_ROWINDEX(pm);
919
920 PMCDBG3(PRC,TLK,1, "link-target pmc=%p ri=%d pmc-process=%p",
921 pm, ri, pp);
922
923 #ifdef HWPMC_DEBUG
924 LIST_FOREACH(pt, &pm->pm_targets, pt_next) {
925 if (pt->pt_process == pp)
926 KASSERT(0, ("[pmc,%d] pp %p already in pmc %p targets",
927 __LINE__, pp, pm));
928 }
929 #endif
930 pt = malloc(sizeof(struct pmc_target), M_PMC, M_WAITOK | M_ZERO);
931 pt->pt_process = pp;
932
933 LIST_INSERT_HEAD(&pm->pm_targets, pt, pt_next);
934
935 atomic_store_rel_ptr((uintptr_t *)&pp->pp_pmcs[ri].pp_pmc,
936 (uintptr_t)pm);
937
938 if (pm->pm_owner->po_owner == pp->pp_proc)
939 pm->pm_flags |= PMC_F_ATTACHED_TO_OWNER;
940
941 /*
942 * Initialize the per-process values at this row index.
943 */
944 pp->pp_pmcs[ri].pp_pmcval = PMC_TO_MODE(pm) == PMC_MODE_TS ?
945 pm->pm_sc.pm_reloadcount : 0;
946 pp->pp_refcnt++;
947
948 #ifdef INVARIANTS
949 /* Confirm that the per-thread values at this row index are cleared. */
950 if (PMC_TO_MODE(pm) == PMC_MODE_TS) {
951 mtx_lock_spin(pp->pp_tdslock);
952 LIST_FOREACH(pt_td, &pp->pp_tds, pt_next) {
953 KASSERT(pt_td->pt_pmcs[ri].pt_pmcval == (pmc_value_t) 0,
954 ("[pmc,%d] pt_pmcval not cleared for pid=%d at "
955 "ri=%d", __LINE__, pp->pp_proc->p_pid, ri));
956 }
957 mtx_unlock_spin(pp->pp_tdslock);
958 }
959 #endif
960 }
961
962 /*
963 * Removes the association between a target process and a PMC.
964 */
965 static void
pmc_unlink_target_process(struct pmc * pm,struct pmc_process * pp)966 pmc_unlink_target_process(struct pmc *pm, struct pmc_process *pp)
967 {
968 int ri;
969 struct proc *p;
970 struct pmc_target *ptgt;
971 struct pmc_thread *pt;
972
973 sx_assert(&pmc_sx, SX_XLOCKED);
974
975 KASSERT(pm != NULL && pp != NULL,
976 ("[pmc,%d] Null pm %p or pp %p", __LINE__, pm, pp));
977
978 KASSERT(pp->pp_refcnt >= 1 && pp->pp_refcnt <= (int) md->pmd_npmc,
979 ("[pmc,%d] Illegal ref count %d on process record %p",
980 __LINE__, pp->pp_refcnt, (void *) pp));
981
982 ri = PMC_TO_ROWINDEX(pm);
983
984 PMCDBG3(PRC,TUL,1, "unlink-target pmc=%p ri=%d pmc-process=%p",
985 pm, ri, pp);
986
987 KASSERT(pp->pp_pmcs[ri].pp_pmc == pm,
988 ("[pmc,%d] PMC ri %d mismatch pmc %p pp->[ri] %p", __LINE__,
989 ri, pm, pp->pp_pmcs[ri].pp_pmc));
990
991 pp->pp_pmcs[ri].pp_pmc = NULL;
992 pp->pp_pmcs[ri].pp_pmcval = (pmc_value_t)0;
993
994 /* Clear the per-thread values at this row index. */
995 if (PMC_TO_MODE(pm) == PMC_MODE_TS) {
996 mtx_lock_spin(pp->pp_tdslock);
997 LIST_FOREACH(pt, &pp->pp_tds, pt_next)
998 pt->pt_pmcs[ri].pt_pmcval = (pmc_value_t)0;
999 mtx_unlock_spin(pp->pp_tdslock);
1000 }
1001
1002 /* Remove owner-specific flags */
1003 if (pm->pm_owner->po_owner == pp->pp_proc) {
1004 pp->pp_flags &= ~PMC_PP_ENABLE_MSR_ACCESS;
1005 pm->pm_flags &= ~PMC_F_ATTACHED_TO_OWNER;
1006 }
1007
1008 pp->pp_refcnt--;
1009
1010 /* Remove the target process from the PMC structure */
1011 LIST_FOREACH(ptgt, &pm->pm_targets, pt_next)
1012 if (ptgt->pt_process == pp)
1013 break;
1014
1015 KASSERT(ptgt != NULL, ("[pmc,%d] process %p (pp: %p) not found "
1016 "in pmc %p", __LINE__, pp->pp_proc, pp, pm));
1017
1018 LIST_REMOVE(ptgt, pt_next);
1019 free(ptgt, M_PMC);
1020
1021 /* if the PMC now lacks targets, send the owner a SIGIO */
1022 if (LIST_EMPTY(&pm->pm_targets)) {
1023 p = pm->pm_owner->po_owner;
1024 PROC_LOCK(p);
1025 kern_psignal(p, SIGIO);
1026 PROC_UNLOCK(p);
1027
1028 PMCDBG2(PRC,SIG,2, "signalling proc=%p signal=%d", p, SIGIO);
1029 }
1030 }
1031
1032 /*
1033 * Check if PMC 'pm' may be attached to target process 't'.
1034 */
1035
1036 static bool
pmc_can_attach(struct pmc * pm,struct proc * t)1037 pmc_can_attach(struct pmc *pm, struct proc *t)
1038 {
1039 struct proc *o; /* pmc owner */
1040 struct ucred *oc, *tc; /* owner, target credentials */
1041 bool decline_attach;
1042
1043 /*
1044 * A PMC's owner can always attach that PMC to itself.
1045 */
1046
1047 if ((o = pm->pm_owner->po_owner) == t)
1048 return (true);
1049
1050 PROC_LOCK(o);
1051 oc = o->p_ucred;
1052 crhold(oc);
1053 PROC_UNLOCK(o);
1054
1055 PROC_LOCK(t);
1056 tc = t->p_ucred;
1057 crhold(tc);
1058 PROC_UNLOCK(t);
1059
1060 /*
1061 * The effective uid of the PMC owner should match at least one
1062 * of the {effective,real,saved} uids of the target process.
1063 */
1064
1065 decline_attach = oc->cr_uid != tc->cr_uid &&
1066 oc->cr_uid != tc->cr_svuid &&
1067 oc->cr_uid != tc->cr_ruid;
1068
1069 /*
1070 * Every one of the target's group ids, must be in the owner's
1071 * group list.
1072 */
1073 for (int i = 0; !decline_attach && i < tc->cr_ngroups; i++)
1074 decline_attach = !groupmember(tc->cr_groups[i], oc);
1075 if (!decline_attach)
1076 decline_attach = !groupmember(tc->cr_gid, oc) ||
1077 !groupmember(tc->cr_rgid, oc) ||
1078 !groupmember(tc->cr_svgid, oc);
1079
1080 crfree(tc);
1081 crfree(oc);
1082
1083 return (!decline_attach);
1084 }
1085
1086 /*
1087 * Attach a process to a PMC.
1088 */
1089 static int
pmc_attach_one_process(struct proc * p,struct pmc * pm)1090 pmc_attach_one_process(struct proc *p, struct pmc *pm)
1091 {
1092 int ri, error;
1093 char *fullpath, *freepath;
1094 struct pmc_process *pp;
1095
1096 sx_assert(&pmc_sx, SX_XLOCKED);
1097
1098 PMCDBG5(PRC,ATT,2, "attach-one pm=%p ri=%d proc=%p (%d, %s)", pm,
1099 PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
1100
1101 /*
1102 * Locate the process descriptor corresponding to process 'p',
1103 * allocating space as needed.
1104 *
1105 * Verify that rowindex 'pm_rowindex' is free in the process
1106 * descriptor.
1107 *
1108 * If not, allocate space for a descriptor and link the
1109 * process descriptor and PMC.
1110 */
1111 ri = PMC_TO_ROWINDEX(pm);
1112
1113 /* mark process as using HWPMCs */
1114 PROC_LOCK(p);
1115 p->p_flag |= P_HWPMC;
1116 PROC_UNLOCK(p);
1117
1118 if ((pp = pmc_find_process_descriptor(p, PMC_FLAG_ALLOCATE)) == NULL) {
1119 error = ENOMEM;
1120 goto fail;
1121 }
1122
1123 if (pp->pp_pmcs[ri].pp_pmc == pm) {/* already present at slot [ri] */
1124 error = EEXIST;
1125 goto fail;
1126 }
1127
1128 if (pp->pp_pmcs[ri].pp_pmc != NULL) {
1129 error = EBUSY;
1130 goto fail;
1131 }
1132
1133 pmc_link_target_process(pm, pp);
1134
1135 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)) &&
1136 (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) == 0)
1137 pm->pm_flags |= PMC_F_NEEDS_LOGFILE;
1138
1139 pm->pm_flags |= PMC_F_ATTACH_DONE; /* mark as attached */
1140
1141 /* issue an attach event to a configured log file */
1142 if (pm->pm_owner->po_flags & PMC_PO_OWNS_LOGFILE) {
1143 if (p->p_flag & P_KPROC) {
1144 fullpath = kernelname;
1145 freepath = NULL;
1146 } else {
1147 pmc_getfilename(p->p_textvp, &fullpath, &freepath);
1148 pmclog_process_pmcattach(pm, p->p_pid, fullpath);
1149 }
1150 free(freepath, M_TEMP);
1151 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
1152 pmc_log_process_mappings(pm->pm_owner, p);
1153 }
1154
1155 return (0);
1156 fail:
1157 PROC_LOCK(p);
1158 p->p_flag &= ~P_HWPMC;
1159 PROC_UNLOCK(p);
1160 return (error);
1161 }
1162
1163 /*
1164 * Attach a process and optionally its children
1165 */
1166 static int
pmc_attach_process(struct proc * p,struct pmc * pm)1167 pmc_attach_process(struct proc *p, struct pmc *pm)
1168 {
1169 int error;
1170 struct proc *top;
1171
1172 sx_assert(&pmc_sx, SX_XLOCKED);
1173
1174 PMCDBG5(PRC,ATT,1, "attach pm=%p ri=%d proc=%p (%d, %s)", pm,
1175 PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
1176
1177 /*
1178 * If this PMC successfully allowed a GETMSR operation
1179 * in the past, disallow further ATTACHes.
1180 */
1181 if ((pm->pm_flags & PMC_PP_ENABLE_MSR_ACCESS) != 0)
1182 return (EPERM);
1183
1184 if ((pm->pm_flags & PMC_F_DESCENDANTS) == 0)
1185 return (pmc_attach_one_process(p, pm));
1186
1187 /*
1188 * Traverse all child processes, attaching them to
1189 * this PMC.
1190 */
1191 sx_slock(&proctree_lock);
1192
1193 top = p;
1194 for (;;) {
1195 if ((error = pmc_attach_one_process(p, pm)) != 0)
1196 break;
1197 if (!LIST_EMPTY(&p->p_children))
1198 p = LIST_FIRST(&p->p_children);
1199 else for (;;) {
1200 if (p == top)
1201 goto done;
1202 if (LIST_NEXT(p, p_sibling)) {
1203 p = LIST_NEXT(p, p_sibling);
1204 break;
1205 }
1206 p = p->p_pptr;
1207 }
1208 }
1209
1210 if (error != 0)
1211 (void)pmc_detach_process(top, pm);
1212
1213 done:
1214 sx_sunlock(&proctree_lock);
1215 return (error);
1216 }
1217
1218 /*
1219 * Detach a process from a PMC. If there are no other PMCs tracking
1220 * this process, remove the process structure from its hash table. If
1221 * 'flags' contains PMC_FLAG_REMOVE, then free the process structure.
1222 */
1223 static int
pmc_detach_one_process(struct proc * p,struct pmc * pm,int flags)1224 pmc_detach_one_process(struct proc *p, struct pmc *pm, int flags)
1225 {
1226 int ri;
1227 struct pmc_process *pp;
1228
1229 sx_assert(&pmc_sx, SX_XLOCKED);
1230
1231 KASSERT(pm != NULL,
1232 ("[pmc,%d] null pm pointer", __LINE__));
1233
1234 ri = PMC_TO_ROWINDEX(pm);
1235
1236 PMCDBG6(PRC,ATT,2, "detach-one pm=%p ri=%d proc=%p (%d, %s) flags=0x%x",
1237 pm, ri, p, p->p_pid, p->p_comm, flags);
1238
1239 if ((pp = pmc_find_process_descriptor(p, 0)) == NULL)
1240 return (ESRCH);
1241
1242 if (pp->pp_pmcs[ri].pp_pmc != pm)
1243 return (EINVAL);
1244
1245 pmc_unlink_target_process(pm, pp);
1246
1247 /* Issue a detach entry if a log file is configured */
1248 if (pm->pm_owner->po_flags & PMC_PO_OWNS_LOGFILE)
1249 pmclog_process_pmcdetach(pm, p->p_pid);
1250
1251 /*
1252 * If there are no PMCs targeting this process, we remove its
1253 * descriptor from the target hash table and unset the P_HWPMC
1254 * flag in the struct proc.
1255 */
1256 KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt <= (int) md->pmd_npmc,
1257 ("[pmc,%d] Illegal refcnt %d for process struct %p",
1258 __LINE__, pp->pp_refcnt, pp));
1259
1260 if (pp->pp_refcnt != 0) /* still a target of some PMC */
1261 return (0);
1262
1263 pmc_remove_process_descriptor(pp);
1264
1265 if (flags & PMC_FLAG_REMOVE)
1266 pmc_destroy_process_descriptor(pp);
1267
1268 PROC_LOCK(p);
1269 p->p_flag &= ~P_HWPMC;
1270 PROC_UNLOCK(p);
1271
1272 return (0);
1273 }
1274
1275 /*
1276 * Detach a process and optionally its descendants from a PMC.
1277 */
1278 static int
pmc_detach_process(struct proc * p,struct pmc * pm)1279 pmc_detach_process(struct proc *p, struct pmc *pm)
1280 {
1281 struct proc *top;
1282
1283 sx_assert(&pmc_sx, SX_XLOCKED);
1284
1285 PMCDBG5(PRC,ATT,1, "detach pm=%p ri=%d proc=%p (%d, %s)", pm,
1286 PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
1287
1288 if ((pm->pm_flags & PMC_F_DESCENDANTS) == 0)
1289 return (pmc_detach_one_process(p, pm, PMC_FLAG_REMOVE));
1290
1291 /*
1292 * Traverse all children, detaching them from this PMC. We
1293 * ignore errors since we could be detaching a PMC from a
1294 * partially attached proc tree.
1295 */
1296 sx_slock(&proctree_lock);
1297
1298 top = p;
1299 for (;;) {
1300 (void)pmc_detach_one_process(p, pm, PMC_FLAG_REMOVE);
1301
1302 if (!LIST_EMPTY(&p->p_children)) {
1303 p = LIST_FIRST(&p->p_children);
1304 } else {
1305 for (;;) {
1306 if (p == top)
1307 goto done;
1308 if (LIST_NEXT(p, p_sibling)) {
1309 p = LIST_NEXT(p, p_sibling);
1310 break;
1311 }
1312 p = p->p_pptr;
1313 }
1314 }
1315 }
1316 done:
1317 sx_sunlock(&proctree_lock);
1318 if (LIST_EMPTY(&pm->pm_targets))
1319 pm->pm_flags &= ~PMC_F_ATTACH_DONE;
1320
1321 return (0);
1322 }
1323
1324 /*
1325 * Handle events after an exec() for a process:
1326 * - Inform log owners of the new exec() event
1327 * - Release any PMCs owned by the process before the exec()
1328 * - Detach PMCs from the target if required
1329 */
1330 static void
pmc_process_exec(struct thread * td,struct pmckern_procexec * pk)1331 pmc_process_exec(struct thread *td, struct pmckern_procexec *pk)
1332 {
1333 struct pmc *pm;
1334 struct pmc_owner *po;
1335 struct pmc_process *pp;
1336 struct proc *p;
1337 char *fullpath, *freepath;
1338 u_int ri;
1339 bool is_using_hwpmcs;
1340
1341 sx_assert(&pmc_sx, SX_XLOCKED);
1342
1343 p = td->td_proc;
1344 pmc_getfilename(p->p_textvp, &fullpath, &freepath);
1345
1346 PMC_EPOCH_ENTER();
1347 /* Inform owners of SS mode PMCs of the exec event. */
1348 CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext) {
1349 if ((po->po_flags & PMC_PO_OWNS_LOGFILE) != 0) {
1350 pmclog_process_procexec(po, PMC_ID_INVALID, p->p_pid,
1351 pk->pm_baseaddr, pk->pm_dynaddr, fullpath);
1352 }
1353 }
1354 PMC_EPOCH_EXIT();
1355
1356 PROC_LOCK(p);
1357 is_using_hwpmcs = (p->p_flag & P_HWPMC) != 0;
1358 PROC_UNLOCK(p);
1359
1360 if (!is_using_hwpmcs) {
1361 if (freepath != NULL)
1362 free(freepath, M_TEMP);
1363 return;
1364 }
1365
1366 /*
1367 * PMCs are not inherited across an exec(): remove any PMCs that this
1368 * process is the owner of.
1369 */
1370 if ((po = pmc_find_owner_descriptor(p)) != NULL) {
1371 pmc_remove_owner(po);
1372 pmc_destroy_owner_descriptor(po);
1373 }
1374
1375 /*
1376 * If the process being exec'ed is not the target of any PMC, we are
1377 * done.
1378 */
1379 if ((pp = pmc_find_process_descriptor(p, 0)) == NULL) {
1380 if (freepath != NULL)
1381 free(freepath, M_TEMP);
1382 return;
1383 }
1384
1385 /*
1386 * Log the exec event to all monitoring owners. Skip owners who have
1387 * already received the event because they had system sampling PMCs
1388 * active.
1389 */
1390 for (ri = 0; ri < md->pmd_npmc; ri++) {
1391 if ((pm = pp->pp_pmcs[ri].pp_pmc) == NULL)
1392 continue;
1393
1394 po = pm->pm_owner;
1395 if (po->po_sscount == 0 &&
1396 (po->po_flags & PMC_PO_OWNS_LOGFILE) != 0) {
1397 pmclog_process_procexec(po, pm->pm_id, p->p_pid,
1398 pk->pm_baseaddr, pk->pm_dynaddr, fullpath);
1399 }
1400 }
1401
1402 if (freepath != NULL)
1403 free(freepath, M_TEMP);
1404
1405 PMCDBG4(PRC,EXC,1, "exec proc=%p (%d, %s) cred-changed=%d",
1406 p, p->p_pid, p->p_comm, pk->pm_credentialschanged);
1407
1408 if (pk->pm_credentialschanged == 0) /* no change */
1409 return;
1410
1411 /*
1412 * If the newly exec()'ed process has a different credential
1413 * than before, allow it to be the target of a PMC only if
1414 * the PMC's owner has sufficient privilege.
1415 */
1416 for (ri = 0; ri < md->pmd_npmc; ri++) {
1417 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL) {
1418 if (pmc_can_attach(pm, td->td_proc)) {
1419 pmc_detach_one_process(td->td_proc, pm,
1420 PMC_FLAG_NONE);
1421 }
1422 }
1423 }
1424
1425 KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt <= md->pmd_npmc,
1426 ("[pmc,%d] Illegal ref count %u on pp %p", __LINE__,
1427 pp->pp_refcnt, pp));
1428
1429 /*
1430 * If this process is no longer the target of any
1431 * PMCs, we can remove the process entry and free
1432 * up space.
1433 */
1434 if (pp->pp_refcnt == 0) {
1435 pmc_remove_process_descriptor(pp);
1436 pmc_destroy_process_descriptor(pp);
1437 }
1438 }
1439
1440 /*
1441 * Thread context switch IN.
1442 */
1443 static void
pmc_process_csw_in(struct thread * td)1444 pmc_process_csw_in(struct thread *td)
1445 {
1446 struct pmc *pm;
1447 struct pmc_classdep *pcd;
1448 struct pmc_cpu *pc;
1449 struct pmc_hw *phw __diagused;
1450 struct pmc_process *pp;
1451 struct pmc_thread *pt;
1452 struct proc *p;
1453 pmc_value_t newvalue;
1454 int cpu;
1455 u_int adjri, ri;
1456
1457 p = td->td_proc;
1458 pt = NULL;
1459 if ((pp = pmc_find_process_descriptor(p, PMC_FLAG_NONE)) == NULL)
1460 return;
1461
1462 KASSERT(pp->pp_proc == td->td_proc,
1463 ("[pmc,%d] not my thread state", __LINE__));
1464
1465 critical_enter(); /* no preemption from this point */
1466
1467 cpu = PCPU_GET(cpuid); /* td->td_oncpu is invalid */
1468
1469 PMCDBG5(CSW,SWI,1, "cpu=%d proc=%p (%d, %s) pp=%p", cpu, p,
1470 p->p_pid, p->p_comm, pp);
1471
1472 KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
1473 ("[pmc,%d] weird CPU id %d", __LINE__, cpu));
1474
1475 pc = pmc_pcpu[cpu];
1476 for (ri = 0; ri < md->pmd_npmc; ri++) {
1477 if ((pm = pp->pp_pmcs[ri].pp_pmc) == NULL)
1478 continue;
1479
1480 KASSERT(PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)),
1481 ("[pmc,%d] Target PMC in non-virtual mode (%d)",
1482 __LINE__, PMC_TO_MODE(pm)));
1483 KASSERT(PMC_TO_ROWINDEX(pm) == ri,
1484 ("[pmc,%d] Row index mismatch pmc %d != ri %d",
1485 __LINE__, PMC_TO_ROWINDEX(pm), ri));
1486
1487 /*
1488 * Only PMCs that are marked as 'RUNNING' need
1489 * be placed on hardware.
1490 */
1491 if (pm->pm_state != PMC_STATE_RUNNING)
1492 continue;
1493
1494 KASSERT(counter_u64_fetch(pm->pm_runcount) >= 0,
1495 ("[pmc,%d] pm=%p runcount %ju", __LINE__, pm,
1496 (uintmax_t)counter_u64_fetch(pm->pm_runcount)));
1497
1498 /* increment PMC runcount */
1499 counter_u64_add(pm->pm_runcount, 1);
1500
1501 /* configure the HWPMC we are going to use. */
1502 pcd = pmc_ri_to_classdep(md, ri, &adjri);
1503 (void)pcd->pcd_config_pmc(cpu, adjri, pm);
1504
1505 phw = pc->pc_hwpmcs[ri];
1506
1507 KASSERT(phw != NULL,
1508 ("[pmc,%d] null hw pointer", __LINE__));
1509
1510 KASSERT(phw->phw_pmc == pm,
1511 ("[pmc,%d] hw->pmc %p != pmc %p", __LINE__,
1512 phw->phw_pmc, pm));
1513
1514 /*
1515 * Write out saved value and start the PMC.
1516 *
1517 * Sampling PMCs use a per-thread value, while
1518 * counting mode PMCs use a per-pmc value that is
1519 * inherited across descendants.
1520 */
1521 if (PMC_TO_MODE(pm) == PMC_MODE_TS) {
1522 if (pt == NULL)
1523 pt = pmc_find_thread_descriptor(pp, td,
1524 PMC_FLAG_NONE);
1525
1526 KASSERT(pt != NULL,
1527 ("[pmc,%d] No thread found for td=%p", __LINE__,
1528 td));
1529
1530 mtx_pool_lock_spin(pmc_mtxpool, pm);
1531
1532 /*
1533 * If we have a thread descriptor, use the per-thread
1534 * counter in the descriptor. If not, we will use
1535 * a per-process counter.
1536 *
1537 * TODO: Remove the per-process "safety net" once
1538 * we have thoroughly tested that we don't hit the
1539 * above assert.
1540 */
1541 if (pt != NULL) {
1542 if (pt->pt_pmcs[ri].pt_pmcval > 0)
1543 newvalue = pt->pt_pmcs[ri].pt_pmcval;
1544 else
1545 newvalue = pm->pm_sc.pm_reloadcount;
1546 } else {
1547 /*
1548 * Use the saved value calculated after the most
1549 * recent time a thread using the shared counter
1550 * switched out. Reset the saved count in case
1551 * another thread from this process switches in
1552 * before any threads switch out.
1553 */
1554 newvalue = pp->pp_pmcs[ri].pp_pmcval;
1555 pp->pp_pmcs[ri].pp_pmcval =
1556 pm->pm_sc.pm_reloadcount;
1557 }
1558 mtx_pool_unlock_spin(pmc_mtxpool, pm);
1559 KASSERT(newvalue > 0 && newvalue <=
1560 pm->pm_sc.pm_reloadcount,
1561 ("[pmc,%d] pmcval outside of expected range cpu=%d "
1562 "ri=%d pmcval=%jx pm_reloadcount=%jx", __LINE__,
1563 cpu, ri, newvalue, pm->pm_sc.pm_reloadcount));
1564 } else {
1565 KASSERT(PMC_TO_MODE(pm) == PMC_MODE_TC,
1566 ("[pmc,%d] illegal mode=%d", __LINE__,
1567 PMC_TO_MODE(pm)));
1568 mtx_pool_lock_spin(pmc_mtxpool, pm);
1569 newvalue = PMC_PCPU_SAVED(cpu, ri) =
1570 pm->pm_gv.pm_savedvalue;
1571 mtx_pool_unlock_spin(pmc_mtxpool, pm);
1572 }
1573
1574 PMCDBG3(CSW,SWI,1,"cpu=%d ri=%d new=%jd", cpu, ri, newvalue);
1575
1576 (void)pcd->pcd_write_pmc(cpu, adjri, pm, newvalue);
1577
1578 /* If a sampling mode PMC, reset stalled state. */
1579 if (PMC_TO_MODE(pm) == PMC_MODE_TS)
1580 pm->pm_pcpu_state[cpu].pps_stalled = 0;
1581
1582 /* Indicate that we desire this to run. */
1583 pm->pm_pcpu_state[cpu].pps_cpustate = 1;
1584
1585 /* Start the PMC. */
1586 (void)pcd->pcd_start_pmc(cpu, adjri, pm);
1587 }
1588
1589 /*
1590 * Perform any other architecture/cpu dependent thread
1591 * switch-in actions.
1592 */
1593 (void)(*md->pmd_switch_in)(pc, pp);
1594
1595 critical_exit();
1596 }
1597
1598 /*
1599 * Thread context switch OUT.
1600 */
1601 static void
pmc_process_csw_out(struct thread * td)1602 pmc_process_csw_out(struct thread *td)
1603 {
1604 struct pmc *pm;
1605 struct pmc_classdep *pcd;
1606 struct pmc_cpu *pc;
1607 struct pmc_process *pp;
1608 struct pmc_thread *pt = NULL;
1609 struct proc *p;
1610 pmc_value_t newvalue;
1611 int64_t tmp;
1612 enum pmc_mode mode;
1613 int cpu;
1614 u_int adjri, ri;
1615
1616 /*
1617 * Locate our process descriptor; this may be NULL if
1618 * this process is exiting and we have already removed
1619 * the process from the target process table.
1620 *
1621 * Note that due to kernel preemption, multiple
1622 * context switches may happen while the process is
1623 * exiting.
1624 *
1625 * Note also that if the target process cannot be
1626 * found we still need to deconfigure any PMCs that
1627 * are currently running on hardware.
1628 */
1629 p = td->td_proc;
1630 pp = pmc_find_process_descriptor(p, PMC_FLAG_NONE);
1631
1632 critical_enter();
1633
1634 cpu = PCPU_GET(cpuid); /* td->td_oncpu is invalid */
1635
1636 PMCDBG5(CSW,SWO,1, "cpu=%d proc=%p (%d, %s) pp=%p", cpu, p,
1637 p->p_pid, p->p_comm, pp);
1638
1639 KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
1640 ("[pmc,%d weird CPU id %d", __LINE__, cpu));
1641
1642 pc = pmc_pcpu[cpu];
1643
1644 /*
1645 * When a PMC gets unlinked from a target PMC, it will
1646 * be removed from the target's pp_pmc[] array.
1647 *
1648 * However, on a MP system, the target could have been
1649 * executing on another CPU at the time of the unlink.
1650 * So, at context switch OUT time, we need to look at
1651 * the hardware to determine if a PMC is scheduled on
1652 * it.
1653 */
1654 for (ri = 0; ri < md->pmd_npmc; ri++) {
1655 pcd = pmc_ri_to_classdep(md, ri, &adjri);
1656 pm = NULL;
1657 (void)(*pcd->pcd_get_config)(cpu, adjri, &pm);
1658
1659 if (pm == NULL) /* nothing at this row index */
1660 continue;
1661
1662 mode = PMC_TO_MODE(pm);
1663 if (!PMC_IS_VIRTUAL_MODE(mode))
1664 continue; /* not a process virtual PMC */
1665
1666 KASSERT(PMC_TO_ROWINDEX(pm) == ri,
1667 ("[pmc,%d] ri mismatch pmc(%d) ri(%d)",
1668 __LINE__, PMC_TO_ROWINDEX(pm), ri));
1669
1670 /*
1671 * Change desired state, and then stop if not stalled.
1672 * This two-step dance should avoid race conditions where
1673 * an interrupt re-enables the PMC after this code has
1674 * already checked the pm_stalled flag.
1675 */
1676 pm->pm_pcpu_state[cpu].pps_cpustate = 0;
1677 if (pm->pm_pcpu_state[cpu].pps_stalled == 0)
1678 (void)pcd->pcd_stop_pmc(cpu, adjri, pm);
1679
1680 KASSERT(counter_u64_fetch(pm->pm_runcount) > 0,
1681 ("[pmc,%d] pm=%p runcount %ju", __LINE__, pm,
1682 (uintmax_t)counter_u64_fetch(pm->pm_runcount)));
1683
1684 /* reduce this PMC's runcount */
1685 counter_u64_add(pm->pm_runcount, -1);
1686
1687 /*
1688 * If this PMC is associated with this process,
1689 * save the reading.
1690 */
1691 if (pm->pm_state != PMC_STATE_DELETED && pp != NULL &&
1692 pp->pp_pmcs[ri].pp_pmc != NULL) {
1693 KASSERT(pm == pp->pp_pmcs[ri].pp_pmc,
1694 ("[pmc,%d] pm %p != pp_pmcs[%d] %p", __LINE__,
1695 pm, ri, pp->pp_pmcs[ri].pp_pmc));
1696 KASSERT(pp->pp_refcnt > 0,
1697 ("[pmc,%d] pp refcnt = %d", __LINE__,
1698 pp->pp_refcnt));
1699
1700 (void)pcd->pcd_read_pmc(cpu, adjri, pm, &newvalue);
1701
1702 if (mode == PMC_MODE_TS) {
1703 PMCDBG3(CSW,SWO,1,"cpu=%d ri=%d val=%jd (samp)",
1704 cpu, ri, newvalue);
1705
1706 if (pt == NULL)
1707 pt = pmc_find_thread_descriptor(pp, td,
1708 PMC_FLAG_NONE);
1709
1710 KASSERT(pt != NULL,
1711 ("[pmc,%d] No thread found for td=%p",
1712 __LINE__, td));
1713
1714 mtx_pool_lock_spin(pmc_mtxpool, pm);
1715
1716 /*
1717 * If we have a thread descriptor, save the
1718 * per-thread counter in the descriptor. If not,
1719 * we will update the per-process counter.
1720 *
1721 * TODO: Remove the per-process "safety net"
1722 * once we have thoroughly tested that we
1723 * don't hit the above assert.
1724 */
1725 if (pt != NULL) {
1726 pt->pt_pmcs[ri].pt_pmcval = newvalue;
1727 } else {
1728 /*
1729 * For sampling process-virtual PMCs,
1730 * newvalue is the number of events to
1731 * be seen until the next sampling
1732 * interrupt. We can just add the events
1733 * left from this invocation to the
1734 * counter, then adjust in case we
1735 * overflow our range.
1736 *
1737 * (Recall that we reload the counter
1738 * every time we use it.)
1739 */
1740 pp->pp_pmcs[ri].pp_pmcval += newvalue;
1741 if (pp->pp_pmcs[ri].pp_pmcval >
1742 pm->pm_sc.pm_reloadcount) {
1743 pp->pp_pmcs[ri].pp_pmcval -=
1744 pm->pm_sc.pm_reloadcount;
1745 }
1746 }
1747 mtx_pool_unlock_spin(pmc_mtxpool, pm);
1748 } else {
1749 tmp = newvalue - PMC_PCPU_SAVED(cpu, ri);
1750
1751 PMCDBG3(CSW,SWO,1,"cpu=%d ri=%d tmp=%jd (count)",
1752 cpu, ri, tmp);
1753
1754 /*
1755 * For counting process-virtual PMCs,
1756 * we expect the count to be
1757 * increasing monotonically, modulo a 64
1758 * bit wraparound.
1759 */
1760 KASSERT(tmp >= 0,
1761 ("[pmc,%d] negative increment cpu=%d "
1762 "ri=%d newvalue=%jx saved=%jx "
1763 "incr=%jx", __LINE__, cpu, ri,
1764 newvalue, PMC_PCPU_SAVED(cpu, ri), tmp));
1765
1766 mtx_pool_lock_spin(pmc_mtxpool, pm);
1767 pm->pm_gv.pm_savedvalue += tmp;
1768 pp->pp_pmcs[ri].pp_pmcval += tmp;
1769 mtx_pool_unlock_spin(pmc_mtxpool, pm);
1770
1771 if (pm->pm_flags & PMC_F_LOG_PROCCSW)
1772 pmclog_process_proccsw(pm, pp, tmp, td);
1773 }
1774 }
1775
1776 /* Mark hardware as free. */
1777 (void)pcd->pcd_config_pmc(cpu, adjri, NULL);
1778 }
1779
1780 /*
1781 * Perform any other architecture/cpu dependent thread
1782 * switch out functions.
1783 */
1784 (void)(*md->pmd_switch_out)(pc, pp);
1785
1786 critical_exit();
1787 }
1788
1789 /*
1790 * A new thread for a process.
1791 */
1792 static void
pmc_process_thread_add(struct thread * td)1793 pmc_process_thread_add(struct thread *td)
1794 {
1795 struct pmc_process *pmc;
1796
1797 pmc = pmc_find_process_descriptor(td->td_proc, PMC_FLAG_NONE);
1798 if (pmc != NULL)
1799 pmc_find_thread_descriptor(pmc, td, PMC_FLAG_ALLOCATE);
1800 }
1801
1802 /*
1803 * A thread delete for a process.
1804 */
1805 static void
pmc_process_thread_delete(struct thread * td)1806 pmc_process_thread_delete(struct thread *td)
1807 {
1808 struct pmc_process *pmc;
1809
1810 pmc = pmc_find_process_descriptor(td->td_proc, PMC_FLAG_NONE);
1811 if (pmc != NULL)
1812 pmc_thread_descriptor_pool_free(pmc_find_thread_descriptor(pmc,
1813 td, PMC_FLAG_REMOVE));
1814 }
1815
1816 /*
1817 * A userret() call for a thread.
1818 */
1819 static void
pmc_process_thread_userret(struct thread * td)1820 pmc_process_thread_userret(struct thread *td)
1821 {
1822 sched_pin();
1823 pmc_capture_user_callchain(curcpu, PMC_UR, td->td_frame);
1824 sched_unpin();
1825 }
1826
1827 /*
1828 * A mapping change for a process.
1829 */
1830 static void
pmc_process_mmap(struct thread * td,struct pmckern_map_in * pkm)1831 pmc_process_mmap(struct thread *td, struct pmckern_map_in *pkm)
1832 {
1833 const struct pmc *pm;
1834 const struct pmc_process *pp;
1835 struct pmc_owner *po;
1836 char *fullpath, *freepath;
1837 pid_t pid;
1838 int ri;
1839
1840 MPASS(!in_epoch(global_epoch_preempt));
1841
1842 freepath = fullpath = NULL;
1843 pmc_getfilename((struct vnode *)pkm->pm_file, &fullpath, &freepath);
1844
1845 pid = td->td_proc->p_pid;
1846
1847 PMC_EPOCH_ENTER();
1848 /* Inform owners of all system-wide sampling PMCs. */
1849 CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext) {
1850 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1851 pmclog_process_map_in(po, pid, pkm->pm_address,
1852 fullpath);
1853 }
1854
1855 if ((pp = pmc_find_process_descriptor(td->td_proc, 0)) == NULL)
1856 goto done;
1857
1858 /*
1859 * Inform sampling PMC owners tracking this process.
1860 */
1861 for (ri = 0; ri < md->pmd_npmc; ri++) {
1862 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL &&
1863 PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm))) {
1864 pmclog_process_map_in(pm->pm_owner,
1865 pid, pkm->pm_address, fullpath);
1866 }
1867 }
1868
1869 done:
1870 if (freepath != NULL)
1871 free(freepath, M_TEMP);
1872 PMC_EPOCH_EXIT();
1873 }
1874
1875 /*
1876 * Log an munmap request.
1877 */
1878 static void
pmc_process_munmap(struct thread * td,struct pmckern_map_out * pkm)1879 pmc_process_munmap(struct thread *td, struct pmckern_map_out *pkm)
1880 {
1881 const struct pmc *pm;
1882 const struct pmc_process *pp;
1883 struct pmc_owner *po;
1884 pid_t pid;
1885 int ri;
1886
1887 pid = td->td_proc->p_pid;
1888
1889 PMC_EPOCH_ENTER();
1890 CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext) {
1891 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1892 pmclog_process_map_out(po, pid, pkm->pm_address,
1893 pkm->pm_address + pkm->pm_size);
1894 }
1895 PMC_EPOCH_EXIT();
1896
1897 if ((pp = pmc_find_process_descriptor(td->td_proc, 0)) == NULL)
1898 return;
1899
1900 for (ri = 0; ri < md->pmd_npmc; ri++) {
1901 pm = pp->pp_pmcs[ri].pp_pmc;
1902 if (pm != NULL && PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm))) {
1903 pmclog_process_map_out(pm->pm_owner, pid,
1904 pkm->pm_address, pkm->pm_address + pkm->pm_size);
1905 }
1906 }
1907 }
1908
1909 /*
1910 * Log mapping information about the kernel.
1911 */
1912 static void
pmc_log_kernel_mappings(struct pmc * pm)1913 pmc_log_kernel_mappings(struct pmc *pm)
1914 {
1915 struct pmc_owner *po;
1916 struct pmckern_map_in *km, *kmbase;
1917
1918 MPASS(in_epoch(global_epoch_preempt) || sx_xlocked(&pmc_sx));
1919 KASSERT(PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)),
1920 ("[pmc,%d] non-sampling PMC (%p) desires mapping information",
1921 __LINE__, (void *) pm));
1922
1923 po = pm->pm_owner;
1924 if ((po->po_flags & PMC_PO_INITIAL_MAPPINGS_DONE) != 0)
1925 return;
1926
1927 if (PMC_TO_MODE(pm) == PMC_MODE_SS)
1928 pmc_process_allproc(pm);
1929
1930 /*
1931 * Log the current set of kernel modules.
1932 */
1933 kmbase = linker_hwpmc_list_objects();
1934 for (km = kmbase; km->pm_file != NULL; km++) {
1935 PMCDBG2(LOG,REG,1,"%s %p", (char *)km->pm_file,
1936 (void *)km->pm_address);
1937 pmclog_process_map_in(po, (pid_t)-1, km->pm_address,
1938 km->pm_file);
1939 }
1940 free(kmbase, M_LINKER);
1941
1942 po->po_flags |= PMC_PO_INITIAL_MAPPINGS_DONE;
1943 }
1944
1945 /*
1946 * Log the mappings for a single process.
1947 */
1948 static void
pmc_log_process_mappings(struct pmc_owner * po,struct proc * p)1949 pmc_log_process_mappings(struct pmc_owner *po, struct proc *p)
1950 {
1951 vm_map_t map;
1952 vm_map_entry_t entry;
1953 vm_object_t obj, lobj, tobj;
1954 vm_offset_t last_end;
1955 vm_offset_t start_addr;
1956 struct vnode *vp, *last_vp;
1957 struct vmspace *vm;
1958 char *fullpath, *freepath;
1959 u_int last_timestamp;
1960
1961 last_vp = NULL;
1962 last_end = (vm_offset_t)0;
1963 fullpath = freepath = NULL;
1964
1965 if ((vm = vmspace_acquire_ref(p)) == NULL)
1966 return;
1967
1968 map = &vm->vm_map;
1969 vm_map_lock_read(map);
1970 VM_MAP_ENTRY_FOREACH(entry, map) {
1971 if (entry == NULL) {
1972 PMCDBG2(LOG,OPS,2, "hwpmc: vm_map entry unexpectedly "
1973 "NULL! pid=%d vm_map=%p\n", p->p_pid, map);
1974 break;
1975 }
1976
1977 /*
1978 * We only care about executable map entries.
1979 */
1980 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0 ||
1981 (entry->protection & VM_PROT_EXECUTE) == 0 ||
1982 entry->object.vm_object == NULL) {
1983 continue;
1984 }
1985
1986 obj = entry->object.vm_object;
1987 VM_OBJECT_RLOCK(obj);
1988
1989 /*
1990 * Walk the backing_object list to find the base (non-shadowed)
1991 * vm_object.
1992 */
1993 for (lobj = tobj = obj; tobj != NULL;
1994 tobj = tobj->backing_object) {
1995 if (tobj != obj)
1996 VM_OBJECT_RLOCK(tobj);
1997 if (lobj != obj)
1998 VM_OBJECT_RUNLOCK(lobj);
1999 lobj = tobj;
2000 }
2001
2002 /*
2003 * At this point lobj is the base vm_object and it is locked.
2004 */
2005 if (lobj == NULL) {
2006 PMCDBG3(LOG,OPS,2,
2007 "hwpmc: lobj unexpectedly NULL! pid=%d "
2008 "vm_map=%p vm_obj=%p\n", p->p_pid, map, obj);
2009 VM_OBJECT_RUNLOCK(obj);
2010 continue;
2011 }
2012
2013 vp = vm_object_vnode(lobj);
2014 if (vp == NULL) {
2015 if (lobj != obj)
2016 VM_OBJECT_RUNLOCK(lobj);
2017 VM_OBJECT_RUNLOCK(obj);
2018 continue;
2019 }
2020
2021 /*
2022 * Skip contiguous regions that point to the same vnode, so we
2023 * don't emit redundant MAP-IN directives.
2024 */
2025 if (entry->start == last_end && vp == last_vp) {
2026 last_end = entry->end;
2027 if (lobj != obj)
2028 VM_OBJECT_RUNLOCK(lobj);
2029 VM_OBJECT_RUNLOCK(obj);
2030 continue;
2031 }
2032
2033 /*
2034 * We don't want to keep the proc's vm_map or this vm_object
2035 * locked while we walk the pathname, since vn_fullpath() can
2036 * sleep. However, if we drop the lock, it's possible for
2037 * concurrent activity to modify the vm_map list. To protect
2038 * against this, we save the vm_map timestamp before we release
2039 * the lock, and check it after we reacquire the lock below.
2040 */
2041 start_addr = entry->start;
2042 last_end = entry->end;
2043 last_timestamp = map->timestamp;
2044 vm_map_unlock_read(map);
2045
2046 vref(vp);
2047 if (lobj != obj)
2048 VM_OBJECT_RUNLOCK(lobj);
2049 VM_OBJECT_RUNLOCK(obj);
2050
2051 freepath = NULL;
2052 pmc_getfilename(vp, &fullpath, &freepath);
2053 last_vp = vp;
2054
2055 vrele(vp);
2056
2057 vp = NULL;
2058 pmclog_process_map_in(po, p->p_pid, start_addr, fullpath);
2059 if (freepath != NULL)
2060 free(freepath, M_TEMP);
2061
2062 vm_map_lock_read(map);
2063
2064 /*
2065 * If our saved timestamp doesn't match, this means
2066 * that the vm_map was modified out from under us and
2067 * we can't trust our current "entry" pointer. Do a
2068 * new lookup for this entry. If there is no entry
2069 * for this address range, vm_map_lookup_entry() will
2070 * return the previous one, so we always want to go to
2071 * the next entry on the next loop iteration.
2072 *
2073 * There is an edge condition here that can occur if
2074 * there is no entry at or before this address. In
2075 * this situation, vm_map_lookup_entry returns
2076 * &map->header, which would cause our loop to abort
2077 * without processing the rest of the map. However,
2078 * in practice this will never happen for process
2079 * vm_map. This is because the executable's text
2080 * segment is the first mapping in the proc's address
2081 * space, and this mapping is never removed until the
2082 * process exits, so there will always be a non-header
2083 * entry at or before the requested address for
2084 * vm_map_lookup_entry to return.
2085 */
2086 if (map->timestamp != last_timestamp)
2087 vm_map_lookup_entry(map, last_end - 1, &entry);
2088 }
2089
2090 vm_map_unlock_read(map);
2091 vmspace_free(vm);
2092 return;
2093 }
2094
2095 /*
2096 * Log mappings for all processes in the system.
2097 */
2098 static void
pmc_log_all_process_mappings(struct pmc_owner * po)2099 pmc_log_all_process_mappings(struct pmc_owner *po)
2100 {
2101 struct proc *p, *top;
2102
2103 sx_assert(&pmc_sx, SX_XLOCKED);
2104
2105 if ((p = pfind(1)) == NULL)
2106 panic("[pmc,%d] Cannot find init", __LINE__);
2107
2108 PROC_UNLOCK(p);
2109
2110 sx_slock(&proctree_lock);
2111
2112 top = p;
2113 for (;;) {
2114 pmc_log_process_mappings(po, p);
2115 if (!LIST_EMPTY(&p->p_children))
2116 p = LIST_FIRST(&p->p_children);
2117 else for (;;) {
2118 if (p == top)
2119 goto done;
2120 if (LIST_NEXT(p, p_sibling)) {
2121 p = LIST_NEXT(p, p_sibling);
2122 break;
2123 }
2124 p = p->p_pptr;
2125 }
2126 }
2127 done:
2128 sx_sunlock(&proctree_lock);
2129 }
2130
2131 #ifdef HWPMC_DEBUG
2132 const char *pmc_hooknames[] = {
2133 /* these strings correspond to PMC_FN_* in <sys/pmckern.h> */
2134 "",
2135 "EXEC",
2136 "CSW-IN",
2137 "CSW-OUT",
2138 "SAMPLE",
2139 "UNUSED1",
2140 "UNUSED2",
2141 "MMAP",
2142 "MUNMAP",
2143 "CALLCHAIN-NMI",
2144 "CALLCHAIN-SOFT",
2145 "SOFTSAMPLING",
2146 "THR-CREATE",
2147 "THR-EXIT",
2148 "THR-USERRET",
2149 "THR-CREATE-LOG",
2150 "THR-EXIT-LOG",
2151 "PROC-CREATE-LOG"
2152 };
2153 #endif
2154
2155 /*
2156 * The 'hook' invoked from the kernel proper
2157 */
2158 static int
pmc_hook_handler(struct thread * td,int function,void * arg)2159 pmc_hook_handler(struct thread *td, int function, void *arg)
2160 {
2161 int cpu;
2162
2163 PMCDBG4(MOD,PMH,1, "hook td=%p func=%d \"%s\" arg=%p", td, function,
2164 pmc_hooknames[function], arg);
2165
2166 switch (function) {
2167 case PMC_FN_PROCESS_EXEC:
2168 pmc_process_exec(td, (struct pmckern_procexec *)arg);
2169 break;
2170
2171 case PMC_FN_CSW_IN:
2172 pmc_process_csw_in(td);
2173 break;
2174
2175 case PMC_FN_CSW_OUT:
2176 pmc_process_csw_out(td);
2177 break;
2178
2179 /*
2180 * Process accumulated PC samples.
2181 *
2182 * This function is expected to be called by hardclock() for
2183 * each CPU that has accumulated PC samples.
2184 *
2185 * This function is to be executed on the CPU whose samples
2186 * are being processed.
2187 */
2188 case PMC_FN_DO_SAMPLES:
2189 /*
2190 * Clear the cpu specific bit in the CPU mask before
2191 * do the rest of the processing. If the NMI handler
2192 * gets invoked after the "atomic_clear_int()" call
2193 * below but before "pmc_process_samples()" gets
2194 * around to processing the interrupt, then we will
2195 * come back here at the next hardclock() tick (and
2196 * may find nothing to do if "pmc_process_samples()"
2197 * had already processed the interrupt). We don't
2198 * lose the interrupt sample.
2199 */
2200 DPCPU_SET(pmc_sampled, 0);
2201 cpu = PCPU_GET(cpuid);
2202 pmc_process_samples(cpu, PMC_HR);
2203 pmc_process_samples(cpu, PMC_SR);
2204 pmc_process_samples(cpu, PMC_UR);
2205 break;
2206
2207 case PMC_FN_MMAP:
2208 pmc_process_mmap(td, (struct pmckern_map_in *)arg);
2209 break;
2210
2211 case PMC_FN_MUNMAP:
2212 MPASS(in_epoch(global_epoch_preempt) || sx_xlocked(&pmc_sx));
2213 pmc_process_munmap(td, (struct pmckern_map_out *)arg);
2214 break;
2215
2216 case PMC_FN_PROC_CREATE_LOG:
2217 pmc_process_proccreate((struct proc *)arg);
2218 break;
2219
2220 case PMC_FN_USER_CALLCHAIN:
2221 /*
2222 * Record a call chain.
2223 */
2224 KASSERT(td == curthread, ("[pmc,%d] td != curthread",
2225 __LINE__));
2226
2227 pmc_capture_user_callchain(PCPU_GET(cpuid), PMC_HR,
2228 (struct trapframe *)arg);
2229
2230 KASSERT(td->td_pinned == 1,
2231 ("[pmc,%d] invalid td_pinned value", __LINE__));
2232 sched_unpin(); /* Can migrate safely now. */
2233
2234 td->td_pflags &= ~TDP_CALLCHAIN;
2235 break;
2236
2237 case PMC_FN_USER_CALLCHAIN_SOFT:
2238 /*
2239 * Record a call chain.
2240 */
2241 KASSERT(td == curthread, ("[pmc,%d] td != curthread",
2242 __LINE__));
2243
2244 cpu = PCPU_GET(cpuid);
2245 pmc_capture_user_callchain(cpu, PMC_SR,
2246 (struct trapframe *) arg);
2247
2248 KASSERT(td->td_pinned == 1,
2249 ("[pmc,%d] invalid td_pinned value", __LINE__));
2250
2251 sched_unpin(); /* Can migrate safely now. */
2252
2253 td->td_pflags &= ~TDP_CALLCHAIN;
2254 break;
2255
2256 case PMC_FN_SOFT_SAMPLING:
2257 /*
2258 * Call soft PMC sampling intr.
2259 */
2260 pmc_soft_intr((struct pmckern_soft *)arg);
2261 break;
2262
2263 case PMC_FN_THR_CREATE:
2264 pmc_process_thread_add(td);
2265 pmc_process_threadcreate(td);
2266 break;
2267
2268 case PMC_FN_THR_CREATE_LOG:
2269 pmc_process_threadcreate(td);
2270 break;
2271
2272 case PMC_FN_THR_EXIT:
2273 KASSERT(td == curthread, ("[pmc,%d] td != curthread",
2274 __LINE__));
2275 pmc_process_thread_delete(td);
2276 pmc_process_threadexit(td);
2277 break;
2278 case PMC_FN_THR_EXIT_LOG:
2279 pmc_process_threadexit(td);
2280 break;
2281 case PMC_FN_THR_USERRET:
2282 KASSERT(td == curthread, ("[pmc,%d] td != curthread",
2283 __LINE__));
2284 pmc_process_thread_userret(td);
2285 break;
2286 default:
2287 #ifdef HWPMC_DEBUG
2288 KASSERT(0, ("[pmc,%d] unknown hook %d\n", __LINE__, function));
2289 #endif
2290 break;
2291 }
2292
2293 return (0);
2294 }
2295
2296 /*
2297 * Allocate a 'struct pmc_owner' descriptor in the owner hash table.
2298 */
2299 static struct pmc_owner *
pmc_allocate_owner_descriptor(struct proc * p)2300 pmc_allocate_owner_descriptor(struct proc *p)
2301 {
2302 struct pmc_owner *po;
2303 struct pmc_ownerhash *poh;
2304 uint32_t hindex;
2305
2306 hindex = PMC_HASH_PTR(p, pmc_ownerhashmask);
2307 poh = &pmc_ownerhash[hindex];
2308
2309 /* Allocate space for N pointers and one descriptor struct. */
2310 po = malloc(sizeof(struct pmc_owner), M_PMC, M_WAITOK | M_ZERO);
2311 po->po_owner = p;
2312 LIST_INSERT_HEAD(poh, po, po_next); /* insert into hash table */
2313
2314 TAILQ_INIT(&po->po_logbuffers);
2315 mtx_init(&po->po_mtx, "pmc-owner-mtx", "pmc-per-proc", MTX_SPIN);
2316
2317 PMCDBG4(OWN,ALL,1, "allocate-owner proc=%p (%d, %s) pmc-owner=%p",
2318 p, p->p_pid, p->p_comm, po);
2319
2320 return (po);
2321 }
2322
2323 static void
pmc_destroy_owner_descriptor(struct pmc_owner * po)2324 pmc_destroy_owner_descriptor(struct pmc_owner *po)
2325 {
2326
2327 PMCDBG4(OWN,REL,1, "destroy-owner po=%p proc=%p (%d, %s)",
2328 po, po->po_owner, po->po_owner->p_pid, po->po_owner->p_comm);
2329
2330 mtx_destroy(&po->po_mtx);
2331 free(po, M_PMC);
2332 }
2333
2334 /*
2335 * Allocate a thread descriptor from the free pool.
2336 *
2337 * NOTE: This *can* return NULL.
2338 */
2339 static struct pmc_thread *
pmc_thread_descriptor_pool_alloc(void)2340 pmc_thread_descriptor_pool_alloc(void)
2341 {
2342 struct pmc_thread *pt;
2343
2344 mtx_lock_spin(&pmc_threadfreelist_mtx);
2345 if ((pt = LIST_FIRST(&pmc_threadfreelist)) != NULL) {
2346 LIST_REMOVE(pt, pt_next);
2347 pmc_threadfreelist_entries--;
2348 }
2349 mtx_unlock_spin(&pmc_threadfreelist_mtx);
2350
2351 return (pt);
2352 }
2353
2354 /*
2355 * Add a thread descriptor to the free pool. We use this instead of free()
2356 * to maintain a cache of free entries. Additionally, we can safely call
2357 * this function when we cannot call free(), such as in a critical section.
2358 */
2359 static void
pmc_thread_descriptor_pool_free(struct pmc_thread * pt)2360 pmc_thread_descriptor_pool_free(struct pmc_thread *pt)
2361 {
2362
2363 if (pt == NULL)
2364 return;
2365
2366 memset(pt, 0, THREADENTRY_SIZE);
2367 mtx_lock_spin(&pmc_threadfreelist_mtx);
2368 LIST_INSERT_HEAD(&pmc_threadfreelist, pt, pt_next);
2369 pmc_threadfreelist_entries++;
2370 if (pmc_threadfreelist_entries > pmc_threadfreelist_max)
2371 taskqueue_enqueue(taskqueue_fast, &free_task);
2372 mtx_unlock_spin(&pmc_threadfreelist_mtx);
2373 }
2374
2375 /*
2376 * An asynchronous task to manage the free list.
2377 */
2378 static void
pmc_thread_descriptor_pool_free_task(void * arg __unused,int pending __unused)2379 pmc_thread_descriptor_pool_free_task(void *arg __unused, int pending __unused)
2380 {
2381 struct pmc_thread *pt;
2382 LIST_HEAD(, pmc_thread) tmplist;
2383 int delta;
2384
2385 LIST_INIT(&tmplist);
2386
2387 /* Determine what changes, if any, we need to make. */
2388 mtx_lock_spin(&pmc_threadfreelist_mtx);
2389 delta = pmc_threadfreelist_entries - pmc_threadfreelist_max;
2390 while (delta > 0 && (pt = LIST_FIRST(&pmc_threadfreelist)) != NULL) {
2391 delta--;
2392 pmc_threadfreelist_entries--;
2393 LIST_REMOVE(pt, pt_next);
2394 LIST_INSERT_HEAD(&tmplist, pt, pt_next);
2395 }
2396 mtx_unlock_spin(&pmc_threadfreelist_mtx);
2397
2398 /* If there are entries to free, free them. */
2399 while (!LIST_EMPTY(&tmplist)) {
2400 pt = LIST_FIRST(&tmplist);
2401 LIST_REMOVE(pt, pt_next);
2402 free(pt, M_PMC);
2403 }
2404 }
2405
2406 /*
2407 * Drain the thread free pool, freeing all allocations.
2408 */
2409 static void
pmc_thread_descriptor_pool_drain(void)2410 pmc_thread_descriptor_pool_drain(void)
2411 {
2412 struct pmc_thread *pt, *next;
2413
2414 LIST_FOREACH_SAFE(pt, &pmc_threadfreelist, pt_next, next) {
2415 LIST_REMOVE(pt, pt_next);
2416 free(pt, M_PMC);
2417 }
2418 }
2419
2420 /*
2421 * find the descriptor corresponding to thread 'td', adding or removing it
2422 * as specified by 'mode'.
2423 *
2424 * Note that this supports additional mode flags in addition to those
2425 * supported by pmc_find_process_descriptor():
2426 * PMC_FLAG_NOWAIT: Causes the function to not wait for mallocs.
2427 * This makes it safe to call while holding certain other locks.
2428 */
2429 static struct pmc_thread *
pmc_find_thread_descriptor(struct pmc_process * pp,struct thread * td,uint32_t mode)2430 pmc_find_thread_descriptor(struct pmc_process *pp, struct thread *td,
2431 uint32_t mode)
2432 {
2433 struct pmc_thread *pt = NULL, *ptnew = NULL;
2434 int wait_flag;
2435
2436 KASSERT(td != NULL, ("[pmc,%d] called to add NULL td", __LINE__));
2437
2438 /*
2439 * Pre-allocate memory in the PMC_FLAG_ALLOCATE case prior to
2440 * acquiring the lock.
2441 */
2442 if ((mode & PMC_FLAG_ALLOCATE) != 0) {
2443 if ((ptnew = pmc_thread_descriptor_pool_alloc()) == NULL) {
2444 wait_flag = M_WAITOK;
2445 if ((mode & PMC_FLAG_NOWAIT) != 0 ||
2446 in_epoch(global_epoch_preempt))
2447 wait_flag = M_NOWAIT;
2448
2449 ptnew = malloc(THREADENTRY_SIZE, M_PMC,
2450 wait_flag | M_ZERO);
2451 }
2452 }
2453
2454 mtx_lock_spin(pp->pp_tdslock);
2455 LIST_FOREACH(pt, &pp->pp_tds, pt_next) {
2456 if (pt->pt_td == td)
2457 break;
2458 }
2459
2460 if ((mode & PMC_FLAG_REMOVE) != 0 && pt != NULL)
2461 LIST_REMOVE(pt, pt_next);
2462
2463 if ((mode & PMC_FLAG_ALLOCATE) != 0 && pt == NULL && ptnew != NULL) {
2464 pt = ptnew;
2465 ptnew = NULL;
2466 pt->pt_td = td;
2467 LIST_INSERT_HEAD(&pp->pp_tds, pt, pt_next);
2468 }
2469
2470 mtx_unlock_spin(pp->pp_tdslock);
2471
2472 if (ptnew != NULL) {
2473 free(ptnew, M_PMC);
2474 }
2475
2476 return (pt);
2477 }
2478
2479 /*
2480 * Try to add thread descriptors for each thread in a process.
2481 */
2482 static void
pmc_add_thread_descriptors_from_proc(struct proc * p,struct pmc_process * pp)2483 pmc_add_thread_descriptors_from_proc(struct proc *p, struct pmc_process *pp)
2484 {
2485 struct pmc_thread **tdlist;
2486 struct thread *curtd;
2487 int i, tdcnt, tdlistsz;
2488
2489 KASSERT(!PROC_LOCKED(p), ("[pmc,%d] proc unexpectedly locked",
2490 __LINE__));
2491 tdcnt = 32;
2492 restart:
2493 tdlistsz = roundup2(tdcnt, 32);
2494
2495 tdcnt = 0;
2496 tdlist = malloc(sizeof(struct pmc_thread *) * tdlistsz, M_TEMP,
2497 M_WAITOK);
2498
2499 PROC_LOCK(p);
2500 FOREACH_THREAD_IN_PROC(p, curtd)
2501 tdcnt++;
2502 if (tdcnt >= tdlistsz) {
2503 PROC_UNLOCK(p);
2504 free(tdlist, M_TEMP);
2505 goto restart;
2506 }
2507
2508 /*
2509 * Try to add each thread to the list without sleeping. If unable,
2510 * add to a queue to retry after dropping the process lock.
2511 */
2512 tdcnt = 0;
2513 FOREACH_THREAD_IN_PROC(p, curtd) {
2514 tdlist[tdcnt] = pmc_find_thread_descriptor(pp, curtd,
2515 PMC_FLAG_ALLOCATE | PMC_FLAG_NOWAIT);
2516 if (tdlist[tdcnt] == NULL) {
2517 PROC_UNLOCK(p);
2518 for (i = 0; i <= tdcnt; i++)
2519 pmc_thread_descriptor_pool_free(tdlist[i]);
2520 free(tdlist, M_TEMP);
2521 goto restart;
2522 }
2523 tdcnt++;
2524 }
2525 PROC_UNLOCK(p);
2526 free(tdlist, M_TEMP);
2527 }
2528
2529 /*
2530 * Find the descriptor corresponding to process 'p', adding or removing it
2531 * as specified by 'mode'.
2532 */
2533 static struct pmc_process *
pmc_find_process_descriptor(struct proc * p,uint32_t mode)2534 pmc_find_process_descriptor(struct proc *p, uint32_t mode)
2535 {
2536 struct pmc_process *pp, *ppnew;
2537 struct pmc_processhash *pph;
2538 uint32_t hindex;
2539
2540 hindex = PMC_HASH_PTR(p, pmc_processhashmask);
2541 pph = &pmc_processhash[hindex];
2542
2543 ppnew = NULL;
2544
2545 /*
2546 * Pre-allocate memory in the PMC_FLAG_ALLOCATE case since we
2547 * cannot call malloc(9) once we hold a spin lock.
2548 */
2549 if ((mode & PMC_FLAG_ALLOCATE) != 0)
2550 ppnew = malloc(sizeof(struct pmc_process) + md->pmd_npmc *
2551 sizeof(struct pmc_targetstate), M_PMC, M_WAITOK | M_ZERO);
2552
2553 mtx_lock_spin(&pmc_processhash_mtx);
2554 LIST_FOREACH(pp, pph, pp_next) {
2555 if (pp->pp_proc == p)
2556 break;
2557 }
2558
2559 if ((mode & PMC_FLAG_REMOVE) != 0 && pp != NULL)
2560 LIST_REMOVE(pp, pp_next);
2561
2562 if ((mode & PMC_FLAG_ALLOCATE) != 0 && pp == NULL && ppnew != NULL) {
2563 ppnew->pp_proc = p;
2564 LIST_INIT(&ppnew->pp_tds);
2565 ppnew->pp_tdslock = mtx_pool_find(pmc_mtxpool, ppnew);
2566 LIST_INSERT_HEAD(pph, ppnew, pp_next);
2567 mtx_unlock_spin(&pmc_processhash_mtx);
2568 pp = ppnew;
2569 ppnew = NULL;
2570
2571 /* Add thread descriptors for this process' current threads. */
2572 pmc_add_thread_descriptors_from_proc(p, pp);
2573 } else
2574 mtx_unlock_spin(&pmc_processhash_mtx);
2575
2576 if (ppnew != NULL)
2577 free(ppnew, M_PMC);
2578 return (pp);
2579 }
2580
2581 /*
2582 * Remove a process descriptor from the process hash table.
2583 */
2584 static void
pmc_remove_process_descriptor(struct pmc_process * pp)2585 pmc_remove_process_descriptor(struct pmc_process *pp)
2586 {
2587 KASSERT(pp->pp_refcnt == 0,
2588 ("[pmc,%d] Removing process descriptor %p with count %d",
2589 __LINE__, pp, pp->pp_refcnt));
2590
2591 mtx_lock_spin(&pmc_processhash_mtx);
2592 LIST_REMOVE(pp, pp_next);
2593 mtx_unlock_spin(&pmc_processhash_mtx);
2594 }
2595
2596 /*
2597 * Destroy a process descriptor.
2598 */
2599 static void
pmc_destroy_process_descriptor(struct pmc_process * pp)2600 pmc_destroy_process_descriptor(struct pmc_process *pp)
2601 {
2602 struct pmc_thread *pmc_td;
2603
2604 while ((pmc_td = LIST_FIRST(&pp->pp_tds)) != NULL) {
2605 LIST_REMOVE(pmc_td, pt_next);
2606 pmc_thread_descriptor_pool_free(pmc_td);
2607 }
2608 free(pp, M_PMC);
2609 }
2610
2611 /*
2612 * Find an owner descriptor corresponding to proc 'p'.
2613 */
2614 static struct pmc_owner *
pmc_find_owner_descriptor(struct proc * p)2615 pmc_find_owner_descriptor(struct proc *p)
2616 {
2617 struct pmc_owner *po;
2618 struct pmc_ownerhash *poh;
2619 uint32_t hindex;
2620
2621 hindex = PMC_HASH_PTR(p, pmc_ownerhashmask);
2622 poh = &pmc_ownerhash[hindex];
2623
2624 po = NULL;
2625 LIST_FOREACH(po, poh, po_next) {
2626 if (po->po_owner == p)
2627 break;
2628 }
2629
2630 PMCDBG5(OWN,FND,1, "find-owner proc=%p (%d, %s) hindex=0x%x -> "
2631 "pmc-owner=%p", p, p->p_pid, p->p_comm, hindex, po);
2632
2633 return (po);
2634 }
2635
2636 /*
2637 * Allocate a pmc descriptor and initialize its fields.
2638 */
2639 static struct pmc *
pmc_allocate_pmc_descriptor(void)2640 pmc_allocate_pmc_descriptor(void)
2641 {
2642 struct pmc *pmc;
2643
2644 pmc = malloc(sizeof(struct pmc), M_PMC, M_WAITOK | M_ZERO);
2645 pmc->pm_runcount = counter_u64_alloc(M_WAITOK);
2646 pmc->pm_pcpu_state = malloc(sizeof(struct pmc_pcpu_state) * mp_ncpus,
2647 M_PMC, M_WAITOK | M_ZERO);
2648 PMCDBG1(PMC,ALL,1, "allocate-pmc -> pmc=%p", pmc);
2649
2650 return (pmc);
2651 }
2652
2653 /*
2654 * Destroy a pmc descriptor.
2655 */
2656 static void
pmc_destroy_pmc_descriptor(struct pmc * pm)2657 pmc_destroy_pmc_descriptor(struct pmc *pm)
2658 {
2659
2660 KASSERT(pm->pm_state == PMC_STATE_DELETED ||
2661 pm->pm_state == PMC_STATE_FREE,
2662 ("[pmc,%d] destroying non-deleted PMC", __LINE__));
2663 KASSERT(LIST_EMPTY(&pm->pm_targets),
2664 ("[pmc,%d] destroying pmc with targets", __LINE__));
2665 KASSERT(pm->pm_owner == NULL,
2666 ("[pmc,%d] destroying pmc attached to an owner", __LINE__));
2667 KASSERT(counter_u64_fetch(pm->pm_runcount) == 0,
2668 ("[pmc,%d] pmc has non-zero run count %ju", __LINE__,
2669 (uintmax_t)counter_u64_fetch(pm->pm_runcount)));
2670
2671 counter_u64_free(pm->pm_runcount);
2672 free(pm->pm_pcpu_state, M_PMC);
2673 free(pm, M_PMC);
2674 }
2675
2676 static void
pmc_wait_for_pmc_idle(struct pmc * pm)2677 pmc_wait_for_pmc_idle(struct pmc *pm)
2678 {
2679 #ifdef INVARIANTS
2680 volatile int maxloop;
2681
2682 maxloop = 100 * pmc_cpu_max();
2683 #endif
2684 /*
2685 * Loop (with a forced context switch) till the PMC's runcount
2686 * comes down to zero.
2687 */
2688 pmclog_flush(pm->pm_owner, 1);
2689 while (counter_u64_fetch(pm->pm_runcount) > 0) {
2690 pmclog_flush(pm->pm_owner, 1);
2691 #ifdef INVARIANTS
2692 maxloop--;
2693 KASSERT(maxloop > 0,
2694 ("[pmc,%d] (ri%d, rc%ju) waiting too long for "
2695 "pmc to be free", __LINE__, PMC_TO_ROWINDEX(pm),
2696 (uintmax_t)counter_u64_fetch(pm->pm_runcount)));
2697 #endif
2698 pmc_force_context_switch();
2699 }
2700 }
2701
2702 /*
2703 * This function does the following things:
2704 *
2705 * - detaches the PMC from hardware
2706 * - unlinks all target threads that were attached to it
2707 * - removes the PMC from its owner's list
2708 * - destroys the PMC private mutex
2709 *
2710 * Once this function completes, the given pmc pointer can be freed by
2711 * calling pmc_destroy_pmc_descriptor().
2712 */
2713 static void
pmc_release_pmc_descriptor(struct pmc * pm)2714 pmc_release_pmc_descriptor(struct pmc *pm)
2715 {
2716 struct pmc_binding pb;
2717 struct pmc_classdep *pcd;
2718 struct pmc_hw *phw __diagused;
2719 struct pmc_owner *po;
2720 struct pmc_process *pp;
2721 struct pmc_target *ptgt, *tmp;
2722 enum pmc_mode mode;
2723 u_int adjri, ri, cpu;
2724
2725 sx_assert(&pmc_sx, SX_XLOCKED);
2726 KASSERT(pm, ("[pmc,%d] null pmc", __LINE__));
2727
2728 ri = PMC_TO_ROWINDEX(pm);
2729 pcd = pmc_ri_to_classdep(md, ri, &adjri);
2730 mode = PMC_TO_MODE(pm);
2731
2732 PMCDBG3(PMC,REL,1, "release-pmc pmc=%p ri=%d mode=%d", pm, ri,
2733 mode);
2734
2735 /*
2736 * First, we take the PMC off hardware.
2737 */
2738 cpu = 0;
2739 if (PMC_IS_SYSTEM_MODE(mode)) {
2740 /*
2741 * A system mode PMC runs on a specific CPU. Switch
2742 * to this CPU and turn hardware off.
2743 */
2744 pmc_save_cpu_binding(&pb);
2745 cpu = PMC_TO_CPU(pm);
2746 pmc_select_cpu(cpu);
2747
2748 /* switch off non-stalled CPUs */
2749 pm->pm_pcpu_state[cpu].pps_cpustate = 0;
2750 if (pm->pm_state == PMC_STATE_RUNNING &&
2751 pm->pm_pcpu_state[cpu].pps_stalled == 0) {
2752
2753 phw = pmc_pcpu[cpu]->pc_hwpmcs[ri];
2754
2755 KASSERT(phw->phw_pmc == pm,
2756 ("[pmc, %d] pmc ptr ri(%d) hw(%p) pm(%p)",
2757 __LINE__, ri, phw->phw_pmc, pm));
2758 PMCDBG2(PMC,REL,2, "stopping cpu=%d ri=%d", cpu, ri);
2759
2760 critical_enter();
2761 (void)pcd->pcd_stop_pmc(cpu, adjri, pm);
2762 critical_exit();
2763 }
2764
2765 PMCDBG2(PMC,REL,2, "decfg cpu=%d ri=%d", cpu, ri);
2766
2767 critical_enter();
2768 (void)pcd->pcd_config_pmc(cpu, adjri, NULL);
2769 critical_exit();
2770
2771 /* adjust the global and process count of SS mode PMCs */
2772 if (mode == PMC_MODE_SS && pm->pm_state == PMC_STATE_RUNNING) {
2773 po = pm->pm_owner;
2774 po->po_sscount--;
2775 if (po->po_sscount == 0) {
2776 atomic_subtract_rel_int(&pmc_ss_count, 1);
2777 CK_LIST_REMOVE(po, po_ssnext);
2778 epoch_wait_preempt(global_epoch_preempt);
2779 }
2780 }
2781 pm->pm_state = PMC_STATE_DELETED;
2782
2783 pmc_restore_cpu_binding(&pb);
2784
2785 /*
2786 * We could have references to this PMC structure in the
2787 * per-cpu sample queues. Wait for the queue to drain.
2788 */
2789 pmc_wait_for_pmc_idle(pm);
2790
2791 } else if (PMC_IS_VIRTUAL_MODE(mode)) {
2792 /*
2793 * A virtual PMC could be running on multiple CPUs at a given
2794 * instant.
2795 *
2796 * By marking its state as DELETED, we ensure that this PMC is
2797 * never further scheduled on hardware.
2798 *
2799 * Then we wait till all CPUs are done with this PMC.
2800 */
2801 pm->pm_state = PMC_STATE_DELETED;
2802
2803 /* Wait for the PMCs runcount to come to zero. */
2804 pmc_wait_for_pmc_idle(pm);
2805
2806 /*
2807 * At this point the PMC is off all CPUs and cannot be freshly
2808 * scheduled onto a CPU. It is now safe to unlink all targets
2809 * from this PMC. If a process-record's refcount falls to zero,
2810 * we remove it from the hash table. The module-wide SX lock
2811 * protects us from races.
2812 */
2813 LIST_FOREACH_SAFE(ptgt, &pm->pm_targets, pt_next, tmp) {
2814 pp = ptgt->pt_process;
2815 pmc_unlink_target_process(pm, pp); /* frees 'ptgt' */
2816
2817 PMCDBG1(PMC,REL,3, "pp->refcnt=%d", pp->pp_refcnt);
2818
2819 /*
2820 * If the target process record shows that no PMCs are
2821 * attached to it, reclaim its space.
2822 */
2823 if (pp->pp_refcnt == 0) {
2824 pmc_remove_process_descriptor(pp);
2825 pmc_destroy_process_descriptor(pp);
2826 }
2827 }
2828
2829 cpu = curthread->td_oncpu; /* setup cpu for pmd_release() */
2830 }
2831
2832 /*
2833 * Release any MD resources.
2834 */
2835 (void)pcd->pcd_release_pmc(cpu, adjri, pm);
2836
2837 /*
2838 * Update row disposition.
2839 */
2840 if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pm)))
2841 PMC_UNMARK_ROW_STANDALONE(ri);
2842 else
2843 PMC_UNMARK_ROW_THREAD(ri);
2844
2845 /* Unlink from the owner's list. */
2846 if (pm->pm_owner != NULL) {
2847 LIST_REMOVE(pm, pm_next);
2848 pm->pm_owner = NULL;
2849 }
2850 }
2851
2852 /*
2853 * Register an owner and a pmc.
2854 */
2855 static int
pmc_register_owner(struct proc * p,struct pmc * pmc)2856 pmc_register_owner(struct proc *p, struct pmc *pmc)
2857 {
2858 struct pmc_owner *po;
2859
2860 sx_assert(&pmc_sx, SX_XLOCKED);
2861
2862 if ((po = pmc_find_owner_descriptor(p)) == NULL) {
2863 if ((po = pmc_allocate_owner_descriptor(p)) == NULL)
2864 return (ENOMEM);
2865 }
2866
2867 KASSERT(pmc->pm_owner == NULL,
2868 ("[pmc,%d] attempting to own an initialized PMC", __LINE__));
2869 pmc->pm_owner = po;
2870
2871 LIST_INSERT_HEAD(&po->po_pmcs, pmc, pm_next);
2872
2873 PROC_LOCK(p);
2874 p->p_flag |= P_HWPMC;
2875 PROC_UNLOCK(p);
2876
2877 if ((po->po_flags & PMC_PO_OWNS_LOGFILE) != 0)
2878 pmclog_process_pmcallocate(pmc);
2879
2880 PMCDBG2(PMC,REG,1, "register-owner pmc-owner=%p pmc=%p",
2881 po, pmc);
2882
2883 return (0);
2884 }
2885
2886 /*
2887 * Return the current row disposition:
2888 * == 0 => FREE
2889 * > 0 => PROCESS MODE
2890 * < 0 => SYSTEM MODE
2891 */
2892 int
pmc_getrowdisp(int ri)2893 pmc_getrowdisp(int ri)
2894 {
2895 return (pmc_pmcdisp[ri]);
2896 }
2897
2898 /*
2899 * Check if a PMC at row index 'ri' can be allocated to the current
2900 * process.
2901 *
2902 * Allocation can fail if:
2903 * - the current process is already being profiled by a PMC at index 'ri',
2904 * attached to it via OP_PMCATTACH.
2905 * - the current process has already allocated a PMC at index 'ri'
2906 * via OP_ALLOCATE.
2907 */
2908 static bool
pmc_can_allocate_rowindex(struct proc * p,unsigned int ri,int cpu)2909 pmc_can_allocate_rowindex(struct proc *p, unsigned int ri, int cpu)
2910 {
2911 struct pmc *pm;
2912 struct pmc_owner *po;
2913 struct pmc_process *pp;
2914 enum pmc_mode mode;
2915
2916 PMCDBG5(PMC,ALR,1, "can-allocate-rowindex proc=%p (%d, %s) ri=%d "
2917 "cpu=%d", p, p->p_pid, p->p_comm, ri, cpu);
2918
2919 /*
2920 * We shouldn't have already allocated a process-mode PMC at
2921 * row index 'ri'.
2922 *
2923 * We shouldn't have allocated a system-wide PMC on the same
2924 * CPU and same RI.
2925 */
2926 if ((po = pmc_find_owner_descriptor(p)) != NULL) {
2927 LIST_FOREACH(pm, &po->po_pmcs, pm_next) {
2928 if (PMC_TO_ROWINDEX(pm) == ri) {
2929 mode = PMC_TO_MODE(pm);
2930 if (PMC_IS_VIRTUAL_MODE(mode))
2931 return (false);
2932 if (PMC_IS_SYSTEM_MODE(mode) &&
2933 PMC_TO_CPU(pm) == cpu)
2934 return (false);
2935 }
2936 }
2937 }
2938
2939 /*
2940 * We also shouldn't be the target of any PMC at this index
2941 * since otherwise a PMC_ATTACH to ourselves will fail.
2942 */
2943 if ((pp = pmc_find_process_descriptor(p, 0)) != NULL)
2944 if (pp->pp_pmcs[ri].pp_pmc != NULL)
2945 return (false);
2946
2947 PMCDBG4(PMC,ALR,2, "can-allocate-rowindex proc=%p (%d, %s) ri=%d ok",
2948 p, p->p_pid, p->p_comm, ri);
2949 return (true);
2950 }
2951
2952 /*
2953 * Check if a given PMC at row index 'ri' can be currently used in
2954 * mode 'mode'.
2955 */
2956 static bool
pmc_can_allocate_row(int ri,enum pmc_mode mode)2957 pmc_can_allocate_row(int ri, enum pmc_mode mode)
2958 {
2959 enum pmc_disp disp;
2960
2961 sx_assert(&pmc_sx, SX_XLOCKED);
2962
2963 PMCDBG2(PMC,ALR,1, "can-allocate-row ri=%d mode=%d", ri, mode);
2964
2965 if (PMC_IS_SYSTEM_MODE(mode))
2966 disp = PMC_DISP_STANDALONE;
2967 else
2968 disp = PMC_DISP_THREAD;
2969
2970 /*
2971 * check disposition for PMC row 'ri':
2972 *
2973 * Expected disposition Row-disposition Result
2974 *
2975 * STANDALONE STANDALONE or FREE proceed
2976 * STANDALONE THREAD fail
2977 * THREAD THREAD or FREE proceed
2978 * THREAD STANDALONE fail
2979 */
2980 if (!PMC_ROW_DISP_IS_FREE(ri) &&
2981 !(disp == PMC_DISP_THREAD && PMC_ROW_DISP_IS_THREAD(ri)) &&
2982 !(disp == PMC_DISP_STANDALONE && PMC_ROW_DISP_IS_STANDALONE(ri)))
2983 return (false);
2984
2985 /*
2986 * All OK
2987 */
2988 PMCDBG2(PMC,ALR,2, "can-allocate-row ri=%d mode=%d ok", ri, mode);
2989 return (true);
2990 }
2991
2992 /*
2993 * Find a PMC descriptor with user handle 'pmcid' for thread 'td'.
2994 */
2995 static struct pmc *
pmc_find_pmc_descriptor_in_process(struct pmc_owner * po,pmc_id_t pmcid)2996 pmc_find_pmc_descriptor_in_process(struct pmc_owner *po, pmc_id_t pmcid)
2997 {
2998 struct pmc *pm;
2999
3000 KASSERT(PMC_ID_TO_ROWINDEX(pmcid) < md->pmd_npmc,
3001 ("[pmc,%d] Illegal pmc index %d (max %d)", __LINE__,
3002 PMC_ID_TO_ROWINDEX(pmcid), md->pmd_npmc));
3003
3004 LIST_FOREACH(pm, &po->po_pmcs, pm_next) {
3005 if (pm->pm_id == pmcid)
3006 return (pm);
3007 }
3008
3009 return (NULL);
3010 }
3011
3012 static int
pmc_find_pmc(pmc_id_t pmcid,struct pmc ** pmc)3013 pmc_find_pmc(pmc_id_t pmcid, struct pmc **pmc)
3014 {
3015 struct pmc *pm, *opm;
3016 struct pmc_owner *po;
3017 struct pmc_process *pp;
3018
3019 PMCDBG1(PMC,FND,1, "find-pmc id=%d", pmcid);
3020 if (PMC_ID_TO_ROWINDEX(pmcid) >= md->pmd_npmc)
3021 return (EINVAL);
3022
3023 if ((po = pmc_find_owner_descriptor(curthread->td_proc)) == NULL) {
3024 /*
3025 * In case of PMC_F_DESCENDANTS child processes we will not find
3026 * the current process in the owners hash list. Find the owner
3027 * process first and from there lookup the po.
3028 */
3029 pp = pmc_find_process_descriptor(curthread->td_proc,
3030 PMC_FLAG_NONE);
3031 if (pp == NULL)
3032 return (ESRCH);
3033 opm = pp->pp_pmcs[PMC_ID_TO_ROWINDEX(pmcid)].pp_pmc;
3034 if (opm == NULL)
3035 return (ESRCH);
3036 if ((opm->pm_flags &
3037 (PMC_F_ATTACHED_TO_OWNER | PMC_F_DESCENDANTS)) !=
3038 (PMC_F_ATTACHED_TO_OWNER | PMC_F_DESCENDANTS))
3039 return (ESRCH);
3040
3041 po = opm->pm_owner;
3042 }
3043
3044 if ((pm = pmc_find_pmc_descriptor_in_process(po, pmcid)) == NULL)
3045 return (EINVAL);
3046
3047 PMCDBG2(PMC,FND,2, "find-pmc id=%d -> pmc=%p", pmcid, pm);
3048
3049 *pmc = pm;
3050 return (0);
3051 }
3052
3053 /*
3054 * Start a PMC.
3055 */
3056 static int
pmc_start(struct pmc * pm)3057 pmc_start(struct pmc *pm)
3058 {
3059 struct pmc_binding pb;
3060 struct pmc_classdep *pcd;
3061 struct pmc_owner *po;
3062 pmc_value_t v;
3063 enum pmc_mode mode;
3064 int adjri, error, cpu, ri;
3065
3066 KASSERT(pm != NULL,
3067 ("[pmc,%d] null pm", __LINE__));
3068
3069 mode = PMC_TO_MODE(pm);
3070 ri = PMC_TO_ROWINDEX(pm);
3071 pcd = pmc_ri_to_classdep(md, ri, &adjri);
3072
3073 error = 0;
3074 po = pm->pm_owner;
3075
3076 PMCDBG3(PMC,OPS,1, "start pmc=%p mode=%d ri=%d", pm, mode, ri);
3077
3078 po = pm->pm_owner;
3079
3080 /*
3081 * Disallow PMCSTART if a logfile is required but has not been
3082 * configured yet.
3083 */
3084 if ((pm->pm_flags & PMC_F_NEEDS_LOGFILE) != 0 &&
3085 (po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)
3086 return (EDOOFUS); /* programming error */
3087
3088 /*
3089 * If this is a sampling mode PMC, log mapping information for
3090 * the kernel modules that are currently loaded.
3091 */
3092 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
3093 pmc_log_kernel_mappings(pm);
3094
3095 if (PMC_IS_VIRTUAL_MODE(mode)) {
3096 /*
3097 * If a PMCATTACH has never been done on this PMC,
3098 * attach it to its owner process.
3099 */
3100 if (LIST_EMPTY(&pm->pm_targets)) {
3101 error = (pm->pm_flags & PMC_F_ATTACH_DONE) != 0 ?
3102 ESRCH : pmc_attach_process(po->po_owner, pm);
3103 }
3104
3105 /*
3106 * If the PMC is attached to its owner, then force a context
3107 * switch to ensure that the MD state gets set correctly.
3108 */
3109 if (error == 0) {
3110 pm->pm_state = PMC_STATE_RUNNING;
3111 if ((pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) != 0)
3112 pmc_force_context_switch();
3113 }
3114
3115 return (error);
3116 }
3117
3118 /*
3119 * A system-wide PMC.
3120 *
3121 * Add the owner to the global list if this is a system-wide
3122 * sampling PMC.
3123 */
3124 if (mode == PMC_MODE_SS) {
3125 /*
3126 * Log mapping information for all existing processes in the
3127 * system. Subsequent mappings are logged as they happen;
3128 * see pmc_process_mmap().
3129 */
3130 if (po->po_logprocmaps == 0) {
3131 pmc_log_all_process_mappings(po);
3132 po->po_logprocmaps = 1;
3133 }
3134 po->po_sscount++;
3135 if (po->po_sscount == 1) {
3136 atomic_add_rel_int(&pmc_ss_count, 1);
3137 CK_LIST_INSERT_HEAD(&pmc_ss_owners, po, po_ssnext);
3138 PMCDBG1(PMC,OPS,1, "po=%p in global list", po);
3139 }
3140 }
3141
3142 /*
3143 * Move to the CPU associated with this
3144 * PMC, and start the hardware.
3145 */
3146 pmc_save_cpu_binding(&pb);
3147 cpu = PMC_TO_CPU(pm);
3148 if (!pmc_cpu_is_active(cpu))
3149 return (ENXIO);
3150 pmc_select_cpu(cpu);
3151
3152 /*
3153 * global PMCs are configured at allocation time
3154 * so write out the initial value and start the PMC.
3155 */
3156 pm->pm_state = PMC_STATE_RUNNING;
3157
3158 critical_enter();
3159 v = PMC_IS_SAMPLING_MODE(mode) ? pm->pm_sc.pm_reloadcount :
3160 pm->pm_sc.pm_initial;
3161 if ((error = pcd->pcd_write_pmc(cpu, adjri, pm, v)) == 0) {
3162 /* If a sampling mode PMC, reset stalled state. */
3163 if (PMC_IS_SAMPLING_MODE(mode))
3164 pm->pm_pcpu_state[cpu].pps_stalled = 0;
3165
3166 /* Indicate that we desire this to run. Start it. */
3167 pm->pm_pcpu_state[cpu].pps_cpustate = 1;
3168 error = pcd->pcd_start_pmc(cpu, adjri, pm);
3169 }
3170 critical_exit();
3171
3172 pmc_restore_cpu_binding(&pb);
3173 return (error);
3174 }
3175
3176 /*
3177 * Stop a PMC.
3178 */
3179 static int
pmc_stop(struct pmc * pm)3180 pmc_stop(struct pmc *pm)
3181 {
3182 struct pmc_binding pb;
3183 struct pmc_classdep *pcd;
3184 struct pmc_owner *po;
3185 int adjri, cpu, error, ri;
3186
3187 KASSERT(pm != NULL, ("[pmc,%d] null pmc", __LINE__));
3188
3189 PMCDBG3(PMC,OPS,1, "stop pmc=%p mode=%d ri=%d", pm, PMC_TO_MODE(pm),
3190 PMC_TO_ROWINDEX(pm));
3191
3192 pm->pm_state = PMC_STATE_STOPPED;
3193
3194 /*
3195 * If the PMC is a virtual mode one, changing the state to non-RUNNING
3196 * is enough to ensure that the PMC never gets scheduled.
3197 *
3198 * If this PMC is current running on a CPU, then it will handled
3199 * correctly at the time its target process is context switched out.
3200 */
3201 if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)))
3202 return (0);
3203
3204 /*
3205 * A system-mode PMC. Move to the CPU associated with this PMC, and
3206 * stop the hardware. We update the 'initial count' so that a
3207 * subsequent PMCSTART will resume counting from the current hardware
3208 * count.
3209 */
3210 pmc_save_cpu_binding(&pb);
3211
3212 cpu = PMC_TO_CPU(pm);
3213 KASSERT(cpu >= 0 && cpu < pmc_cpu_max(),
3214 ("[pmc,%d] illegal cpu=%d", __LINE__, cpu));
3215 if (!pmc_cpu_is_active(cpu))
3216 return (ENXIO);
3217
3218 pmc_select_cpu(cpu);
3219
3220 ri = PMC_TO_ROWINDEX(pm);
3221 pcd = pmc_ri_to_classdep(md, ri, &adjri);
3222
3223 pm->pm_pcpu_state[cpu].pps_cpustate = 0;
3224 critical_enter();
3225 if ((error = pcd->pcd_stop_pmc(cpu, adjri, pm)) == 0) {
3226 error = pcd->pcd_read_pmc(cpu, adjri, pm,
3227 &pm->pm_sc.pm_initial);
3228 }
3229 critical_exit();
3230
3231 pmc_restore_cpu_binding(&pb);
3232
3233 /* Remove this owner from the global list of SS PMC owners. */
3234 po = pm->pm_owner;
3235 if (PMC_TO_MODE(pm) == PMC_MODE_SS) {
3236 po->po_sscount--;
3237 if (po->po_sscount == 0) {
3238 atomic_subtract_rel_int(&pmc_ss_count, 1);
3239 CK_LIST_REMOVE(po, po_ssnext);
3240 epoch_wait_preempt(global_epoch_preempt);
3241 PMCDBG1(PMC,OPS,2,"po=%p removed from global list", po);
3242 }
3243 }
3244
3245 return (error);
3246 }
3247
3248 static struct pmc_classdep *
pmc_class_to_classdep(enum pmc_class class)3249 pmc_class_to_classdep(enum pmc_class class)
3250 {
3251 int n;
3252
3253 for (n = 0; n < md->pmd_nclass; n++) {
3254 if (md->pmd_classdep[n].pcd_class == class)
3255 return (&md->pmd_classdep[n]);
3256 }
3257 return (NULL);
3258 }
3259
3260 #if defined(HWPMC_DEBUG) && defined(KTR)
3261 static const char *pmc_op_to_name[] = {
3262 #undef __PMC_OP
3263 #define __PMC_OP(N, D) #N ,
3264 __PMC_OPS()
3265 NULL
3266 };
3267 #endif
3268
3269 /*
3270 * The syscall interface
3271 */
3272
3273 #define PMC_GET_SX_XLOCK(...) do { \
3274 sx_xlock(&pmc_sx); \
3275 if (pmc_hook == NULL) { \
3276 sx_xunlock(&pmc_sx); \
3277 return __VA_ARGS__; \
3278 } \
3279 } while (0)
3280
3281 #define PMC_DOWNGRADE_SX() do { \
3282 sx_downgrade(&pmc_sx); \
3283 is_sx_downgraded = true; \
3284 } while (0)
3285
3286 /*
3287 * Main body of PMC_OP_PMCALLOCATE.
3288 */
3289 static int
pmc_do_op_pmcallocate(struct thread * td,struct pmc_op_pmcallocate * pa)3290 pmc_do_op_pmcallocate(struct thread *td, struct pmc_op_pmcallocate *pa)
3291 {
3292 struct proc *p;
3293 struct pmc *pmc;
3294 struct pmc_binding pb;
3295 struct pmc_classdep *pcd;
3296 struct pmc_hw *phw;
3297 enum pmc_mode mode;
3298 enum pmc_class class;
3299 uint32_t caps, flags;
3300 u_int cpu;
3301 int adjri, n;
3302 int error;
3303
3304 class = pa->pm_class;
3305 caps = pa->pm_caps;
3306 flags = pa->pm_flags;
3307 mode = pa->pm_mode;
3308 cpu = pa->pm_cpu;
3309
3310 p = td->td_proc;
3311
3312 /* Requested mode must exist. */
3313 if ((mode != PMC_MODE_SS && mode != PMC_MODE_SC &&
3314 mode != PMC_MODE_TS && mode != PMC_MODE_TC))
3315 return (EINVAL);
3316
3317 /* Requested CPU must be valid. */
3318 if (cpu != PMC_CPU_ANY && cpu >= pmc_cpu_max())
3319 return (EINVAL);
3320
3321 /*
3322 * Virtual PMCs should only ask for a default CPU.
3323 * System mode PMCs need to specify a non-default CPU.
3324 */
3325 if ((PMC_IS_VIRTUAL_MODE(mode) && cpu != PMC_CPU_ANY) ||
3326 (PMC_IS_SYSTEM_MODE(mode) && cpu == PMC_CPU_ANY))
3327 return (EINVAL);
3328
3329 /*
3330 * Check that an inactive CPU is not being asked for.
3331 */
3332 if (PMC_IS_SYSTEM_MODE(mode) && !pmc_cpu_is_active(cpu))
3333 return (ENXIO);
3334
3335 /*
3336 * Refuse an allocation for a system-wide PMC if this process has been
3337 * jailed, or if this process lacks super-user credentials and the
3338 * sysctl tunable 'security.bsd.unprivileged_syspmcs' is zero.
3339 */
3340 if (PMC_IS_SYSTEM_MODE(mode)) {
3341 if (jailed(td->td_ucred))
3342 return (EPERM);
3343 if (!pmc_unprivileged_syspmcs) {
3344 error = priv_check(td, PRIV_PMC_SYSTEM);
3345 if (error != 0)
3346 return (error);
3347 }
3348 }
3349
3350 /*
3351 * Look for valid values for 'pm_flags'.
3352 */
3353 if ((flags & ~(PMC_F_DESCENDANTS | PMC_F_LOG_PROCCSW |
3354 PMC_F_LOG_PROCEXIT | PMC_F_CALLCHAIN | PMC_F_USERCALLCHAIN |
3355 PMC_F_EV_PMU)) != 0)
3356 return (EINVAL);
3357
3358 /* PMC_F_USERCALLCHAIN is only valid with PMC_F_CALLCHAIN. */
3359 if ((flags & (PMC_F_CALLCHAIN | PMC_F_USERCALLCHAIN)) ==
3360 PMC_F_USERCALLCHAIN)
3361 return (EINVAL);
3362
3363 /* PMC_F_USERCALLCHAIN is only valid for sampling mode. */
3364 if ((flags & PMC_F_USERCALLCHAIN) != 0 && mode != PMC_MODE_TS &&
3365 mode != PMC_MODE_SS)
3366 return (EINVAL);
3367
3368 /* Process logging options are not allowed for system PMCs. */
3369 if (PMC_IS_SYSTEM_MODE(mode) &&
3370 (flags & (PMC_F_LOG_PROCCSW | PMC_F_LOG_PROCEXIT)) != 0)
3371 return (EINVAL);
3372
3373 /*
3374 * All sampling mode PMCs need to be able to interrupt the CPU.
3375 */
3376 if (PMC_IS_SAMPLING_MODE(mode))
3377 caps |= PMC_CAP_INTERRUPT;
3378
3379 /* A valid class specifier should have been passed in. */
3380 pcd = pmc_class_to_classdep(class);
3381 if (pcd == NULL)
3382 return (EINVAL);
3383
3384 /* The requested PMC capabilities should be feasible. */
3385 if ((pcd->pcd_caps & caps) != caps)
3386 return (EOPNOTSUPP);
3387
3388 PMCDBG4(PMC,ALL,2, "event=%d caps=0x%x mode=%d cpu=%d", pa->pm_ev,
3389 caps, mode, cpu);
3390
3391 pmc = pmc_allocate_pmc_descriptor();
3392 pmc->pm_id = PMC_ID_MAKE_ID(cpu, pa->pm_mode, class, PMC_ID_INVALID);
3393 pmc->pm_event = pa->pm_ev;
3394 pmc->pm_state = PMC_STATE_FREE;
3395 pmc->pm_caps = caps;
3396 pmc->pm_flags = flags;
3397
3398 /* XXX set lower bound on sampling for process counters */
3399 if (PMC_IS_SAMPLING_MODE(mode)) {
3400 /*
3401 * Don't permit requested sample rate to be less than
3402 * pmc_mincount.
3403 */
3404 if (pa->pm_count < MAX(1, pmc_mincount))
3405 log(LOG_WARNING, "pmcallocate: passed sample "
3406 "rate %ju - setting to %u\n",
3407 (uintmax_t)pa->pm_count,
3408 MAX(1, pmc_mincount));
3409 pmc->pm_sc.pm_reloadcount = MAX(MAX(1, pmc_mincount),
3410 pa->pm_count);
3411 } else
3412 pmc->pm_sc.pm_initial = pa->pm_count;
3413
3414 /* switch thread to CPU 'cpu' */
3415 pmc_save_cpu_binding(&pb);
3416
3417 #define PMC_IS_SHAREABLE_PMC(cpu, n) \
3418 (pmc_pcpu[(cpu)]->pc_hwpmcs[(n)]->phw_state & \
3419 PMC_PHW_FLAG_IS_SHAREABLE)
3420 #define PMC_IS_UNALLOCATED(cpu, n) \
3421 (pmc_pcpu[(cpu)]->pc_hwpmcs[(n)]->phw_pmc == NULL)
3422
3423 if (PMC_IS_SYSTEM_MODE(mode)) {
3424 pmc_select_cpu(cpu);
3425 for (n = pcd->pcd_ri; n < md->pmd_npmc; n++) {
3426 pcd = pmc_ri_to_classdep(md, n, &adjri);
3427
3428 if (!pmc_can_allocate_row(n, mode) ||
3429 !pmc_can_allocate_rowindex(p, n, cpu))
3430 continue;
3431 if (!PMC_IS_UNALLOCATED(cpu, n) &&
3432 !PMC_IS_SHAREABLE_PMC(cpu, n))
3433 continue;
3434
3435 if (pcd->pcd_allocate_pmc(cpu, adjri, pmc, pa) == 0) {
3436 /* Success. */
3437 break;
3438 }
3439 }
3440 } else {
3441 /* Process virtual mode */
3442 for (n = pcd->pcd_ri; n < md->pmd_npmc; n++) {
3443 pcd = pmc_ri_to_classdep(md, n, &adjri);
3444
3445 if (!pmc_can_allocate_row(n, mode) ||
3446 !pmc_can_allocate_rowindex(p, n, PMC_CPU_ANY))
3447 continue;
3448
3449 if (pcd->pcd_allocate_pmc(td->td_oncpu, adjri, pmc,
3450 pa) == 0) {
3451 /* Success. */
3452 break;
3453 }
3454 }
3455 }
3456
3457 #undef PMC_IS_UNALLOCATED
3458 #undef PMC_IS_SHAREABLE_PMC
3459
3460 pmc_restore_cpu_binding(&pb);
3461
3462 if (n == md->pmd_npmc) {
3463 pmc_destroy_pmc_descriptor(pmc);
3464 return (EINVAL);
3465 }
3466
3467 /* Fill in the correct value in the ID field. */
3468 pmc->pm_id = PMC_ID_MAKE_ID(cpu, mode, class, n);
3469
3470 PMCDBG5(PMC,ALL,2, "ev=%d class=%d mode=%d n=%d -> pmcid=%x",
3471 pmc->pm_event, class, mode, n, pmc->pm_id);
3472
3473 /* Process mode PMCs with logging enabled need log files. */
3474 if ((pmc->pm_flags & (PMC_F_LOG_PROCEXIT | PMC_F_LOG_PROCCSW)) != 0)
3475 pmc->pm_flags |= PMC_F_NEEDS_LOGFILE;
3476
3477 /* All system mode sampling PMCs require a log file. */
3478 if (PMC_IS_SAMPLING_MODE(mode) && PMC_IS_SYSTEM_MODE(mode))
3479 pmc->pm_flags |= PMC_F_NEEDS_LOGFILE;
3480
3481 /*
3482 * Configure global pmc's immediately.
3483 */
3484 if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pmc))) {
3485 pmc_save_cpu_binding(&pb);
3486 pmc_select_cpu(cpu);
3487
3488 phw = pmc_pcpu[cpu]->pc_hwpmcs[n];
3489 pcd = pmc_ri_to_classdep(md, n, &adjri);
3490
3491 if ((phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0 ||
3492 (error = pcd->pcd_config_pmc(cpu, adjri, pmc)) != 0) {
3493 (void)pcd->pcd_release_pmc(cpu, adjri, pmc);
3494 pmc_destroy_pmc_descriptor(pmc);
3495 pmc_restore_cpu_binding(&pb);
3496 return (EPERM);
3497 }
3498
3499 pmc_restore_cpu_binding(&pb);
3500 }
3501
3502 pmc->pm_state = PMC_STATE_ALLOCATED;
3503 pmc->pm_class = class;
3504
3505 /*
3506 * Mark row disposition.
3507 */
3508 if (PMC_IS_SYSTEM_MODE(mode))
3509 PMC_MARK_ROW_STANDALONE(n);
3510 else
3511 PMC_MARK_ROW_THREAD(n);
3512
3513 /*
3514 * Register this PMC with the current thread as its owner.
3515 */
3516 error = pmc_register_owner(p, pmc);
3517 if (error != 0) {
3518 pmc_release_pmc_descriptor(pmc);
3519 pmc_destroy_pmc_descriptor(pmc);
3520 return (error);
3521 }
3522
3523 /*
3524 * Return the allocated index.
3525 */
3526 pa->pm_pmcid = pmc->pm_id;
3527 return (0);
3528 }
3529
3530 /*
3531 * Main body of PMC_OP_PMCATTACH.
3532 */
3533 static int
pmc_do_op_pmcattach(struct thread * td,struct pmc_op_pmcattach a)3534 pmc_do_op_pmcattach(struct thread *td, struct pmc_op_pmcattach a)
3535 {
3536 struct pmc *pm;
3537 struct proc *p;
3538 int error;
3539
3540 sx_assert(&pmc_sx, SX_XLOCKED);
3541
3542 if (a.pm_pid < 0) {
3543 return (EINVAL);
3544 } else if (a.pm_pid == 0) {
3545 a.pm_pid = td->td_proc->p_pid;
3546 }
3547
3548 error = pmc_find_pmc(a.pm_pmc, &pm);
3549 if (error != 0)
3550 return (error);
3551
3552 if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pm)))
3553 return (EINVAL);
3554
3555 /* PMCs may be (re)attached only when allocated or stopped */
3556 if (pm->pm_state == PMC_STATE_RUNNING) {
3557 return (EBUSY);
3558 } else if (pm->pm_state != PMC_STATE_ALLOCATED &&
3559 pm->pm_state != PMC_STATE_STOPPED) {
3560 return (EINVAL);
3561 }
3562
3563 /* lookup pid */
3564 if ((p = pfind(a.pm_pid)) == NULL)
3565 return (ESRCH);
3566
3567 /*
3568 * Ignore processes that are working on exiting.
3569 */
3570 if ((p->p_flag & P_WEXIT) != 0) {
3571 PROC_UNLOCK(p); /* pfind() returns a locked process */
3572 return (ESRCH);
3573 }
3574
3575 /*
3576 * We are allowed to attach a PMC to a process if we can debug it.
3577 */
3578 error = p_candebug(curthread, p);
3579
3580 PROC_UNLOCK(p);
3581
3582 if (error == 0)
3583 error = pmc_attach_process(p, pm);
3584
3585 return (error);
3586 }
3587
3588 /*
3589 * Main body of PMC_OP_PMCDETACH.
3590 */
3591 static int
pmc_do_op_pmcdetach(struct thread * td,struct pmc_op_pmcattach a)3592 pmc_do_op_pmcdetach(struct thread *td, struct pmc_op_pmcattach a)
3593 {
3594 struct pmc *pm;
3595 struct proc *p;
3596 int error;
3597
3598 if (a.pm_pid < 0) {
3599 return (EINVAL);
3600 } else if (a.pm_pid == 0)
3601 a.pm_pid = td->td_proc->p_pid;
3602
3603 error = pmc_find_pmc(a.pm_pmc, &pm);
3604 if (error != 0)
3605 return (error);
3606
3607 if ((p = pfind(a.pm_pid)) == NULL)
3608 return (ESRCH);
3609
3610 /*
3611 * Treat processes that are in the process of exiting as if they were
3612 * not present.
3613 */
3614 if ((p->p_flag & P_WEXIT) != 0) {
3615 PROC_UNLOCK(p);
3616 return (ESRCH);
3617 }
3618
3619 PROC_UNLOCK(p); /* pfind() returns a locked process */
3620
3621 if (error == 0)
3622 error = pmc_detach_process(p, pm);
3623
3624 return (error);
3625 }
3626
3627 /*
3628 * Main body of PMC_OP_PMCRELEASE.
3629 */
3630 static int
pmc_do_op_pmcrelease(pmc_id_t pmcid)3631 pmc_do_op_pmcrelease(pmc_id_t pmcid)
3632 {
3633 struct pmc_owner *po;
3634 struct pmc *pm;
3635 int error;
3636
3637 /*
3638 * Find PMC pointer for the named PMC.
3639 *
3640 * Use pmc_release_pmc_descriptor() to switch off the
3641 * PMC, remove all its target threads, and remove the
3642 * PMC from its owner's list.
3643 *
3644 * Remove the owner record if this is the last PMC
3645 * owned.
3646 *
3647 * Free up space.
3648 */
3649 error = pmc_find_pmc(pmcid, &pm);
3650 if (error != 0)
3651 return (error);
3652
3653 po = pm->pm_owner;
3654 pmc_release_pmc_descriptor(pm);
3655 pmc_maybe_remove_owner(po);
3656 pmc_destroy_pmc_descriptor(pm);
3657
3658 return (error);
3659 }
3660
3661 /*
3662 * Main body of PMC_OP_PMCRW.
3663 */
3664 static int
pmc_do_op_pmcrw(const struct pmc_op_pmcrw * prw,pmc_value_t * valp)3665 pmc_do_op_pmcrw(const struct pmc_op_pmcrw *prw, pmc_value_t *valp)
3666 {
3667 struct pmc_binding pb;
3668 struct pmc_classdep *pcd;
3669 struct pmc *pm;
3670 u_int cpu, ri, adjri;
3671 int error;
3672
3673 PMCDBG2(PMC,OPS,1, "rw id=%d flags=0x%x", prw->pm_pmcid, prw->pm_flags);
3674
3675 /* Must have at least one flag set. */
3676 if ((prw->pm_flags & (PMC_F_OLDVALUE | PMC_F_NEWVALUE)) == 0)
3677 return (EINVAL);
3678
3679 /* Locate PMC descriptor. */
3680 error = pmc_find_pmc(prw->pm_pmcid, &pm);
3681 if (error != 0)
3682 return (error);
3683
3684 /* Can't read a PMC that hasn't been started. */
3685 if (pm->pm_state != PMC_STATE_ALLOCATED &&
3686 pm->pm_state != PMC_STATE_STOPPED &&
3687 pm->pm_state != PMC_STATE_RUNNING)
3688 return (EINVAL);
3689
3690 /* Writing a new value is allowed only for 'STOPPED' PMCs. */
3691 if (pm->pm_state == PMC_STATE_RUNNING &&
3692 (prw->pm_flags & PMC_F_NEWVALUE) != 0)
3693 return (EBUSY);
3694
3695 if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm))) {
3696 /*
3697 * If this PMC is attached to its owner (i.e., the process
3698 * requesting this operation) and is running, then attempt to
3699 * get an upto-date reading from hardware for a READ. Writes
3700 * are only allowed when the PMC is stopped, so only update the
3701 * saved value field.
3702 *
3703 * If the PMC is not running, or is not attached to its owner,
3704 * read/write to the savedvalue field.
3705 */
3706
3707 ri = PMC_TO_ROWINDEX(pm);
3708 pcd = pmc_ri_to_classdep(md, ri, &adjri);
3709
3710 mtx_pool_lock_spin(pmc_mtxpool, pm);
3711 cpu = curthread->td_oncpu;
3712
3713 if ((prw->pm_flags & PMC_F_OLDVALUE) != 0) {
3714 if ((pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) &&
3715 (pm->pm_state == PMC_STATE_RUNNING)) {
3716 error = (*pcd->pcd_read_pmc)(cpu, adjri, pm,
3717 valp);
3718 } else {
3719 *valp = pm->pm_gv.pm_savedvalue;
3720 }
3721 }
3722
3723 if ((prw->pm_flags & PMC_F_NEWVALUE) != 0)
3724 pm->pm_gv.pm_savedvalue = prw->pm_value;
3725
3726 mtx_pool_unlock_spin(pmc_mtxpool, pm);
3727 } else { /* System mode PMCs */
3728 cpu = PMC_TO_CPU(pm);
3729 ri = PMC_TO_ROWINDEX(pm);
3730 pcd = pmc_ri_to_classdep(md, ri, &adjri);
3731
3732 if (!pmc_cpu_is_active(cpu))
3733 return (ENXIO);
3734
3735 /* Move this thread to CPU 'cpu'. */
3736 pmc_save_cpu_binding(&pb);
3737 pmc_select_cpu(cpu);
3738 critical_enter();
3739
3740 /* Save old value. */
3741 if ((prw->pm_flags & PMC_F_OLDVALUE) != 0)
3742 error = (*pcd->pcd_read_pmc)(cpu, adjri, pm, valp);
3743
3744 /* Write out new value. */
3745 if (error == 0 && (prw->pm_flags & PMC_F_NEWVALUE) != 0)
3746 error = (*pcd->pcd_write_pmc)(cpu, adjri, pm,
3747 prw->pm_value);
3748
3749 critical_exit();
3750 pmc_restore_cpu_binding(&pb);
3751 if (error != 0)
3752 return (error);
3753 }
3754
3755 #ifdef HWPMC_DEBUG
3756 if ((prw->pm_flags & PMC_F_NEWVALUE) != 0)
3757 PMCDBG3(PMC,OPS,2, "rw id=%d new %jx -> old %jx",
3758 ri, prw->pm_value, *valp);
3759 else
3760 PMCDBG2(PMC,OPS,2, "rw id=%d -> old %jx", ri, *valp);
3761 #endif
3762 return (error);
3763 }
3764
3765 static int
pmc_syscall_handler(struct thread * td,void * syscall_args)3766 pmc_syscall_handler(struct thread *td, void *syscall_args)
3767 {
3768 struct pmc_syscall_args *c;
3769 void *pmclog_proc_handle;
3770 void *arg;
3771 int error, op;
3772 bool is_sx_downgraded;
3773
3774 c = (struct pmc_syscall_args *)syscall_args;
3775 op = c->pmop_code;
3776 arg = c->pmop_data;
3777
3778 /* PMC isn't set up yet */
3779 if (pmc_hook == NULL)
3780 return (EINVAL);
3781
3782 if (op == PMC_OP_CONFIGURELOG) {
3783 /*
3784 * We cannot create the logging process inside
3785 * pmclog_configure_log() because there is a LOR
3786 * between pmc_sx and process structure locks.
3787 * Instead, pre-create the process and ignite the loop
3788 * if everything is fine, otherwise direct the process
3789 * to exit.
3790 */
3791 error = pmclog_proc_create(td, &pmclog_proc_handle);
3792 if (error != 0)
3793 goto done_syscall;
3794 }
3795
3796 PMC_GET_SX_XLOCK(ENOSYS);
3797 is_sx_downgraded = false;
3798 PMCDBG3(MOD,PMS,1, "syscall op=%d \"%s\" arg=%p", op,
3799 pmc_op_to_name[op], arg);
3800
3801 error = 0;
3802 counter_u64_add(pmc_stats.pm_syscalls, 1);
3803
3804 switch (op) {
3805
3806
3807 /*
3808 * Configure a log file.
3809 *
3810 * XXX This OP will be reworked.
3811 */
3812
3813 case PMC_OP_CONFIGURELOG:
3814 {
3815 struct proc *p;
3816 struct pmc *pm;
3817 struct pmc_owner *po;
3818 struct pmc_op_configurelog cl;
3819
3820 if ((error = copyin(arg, &cl, sizeof(cl))) != 0) {
3821 pmclog_proc_ignite(pmclog_proc_handle, NULL);
3822 break;
3823 }
3824
3825 /* No flags currently implemented */
3826 if (cl.pm_flags != 0) {
3827 pmclog_proc_ignite(pmclog_proc_handle, NULL);
3828 error = EINVAL;
3829 break;
3830 }
3831
3832 /* mark this process as owning a log file */
3833 p = td->td_proc;
3834 if ((po = pmc_find_owner_descriptor(p)) == NULL)
3835 if ((po = pmc_allocate_owner_descriptor(p)) == NULL) {
3836 pmclog_proc_ignite(pmclog_proc_handle, NULL);
3837 error = ENOMEM;
3838 break;
3839 }
3840
3841 /*
3842 * If a valid fd was passed in, try to configure that,
3843 * otherwise if 'fd' was less than zero and there was
3844 * a log file configured, flush its buffers and
3845 * de-configure it.
3846 */
3847 if (cl.pm_logfd >= 0) {
3848 error = pmclog_configure_log(md, po, cl.pm_logfd);
3849 pmclog_proc_ignite(pmclog_proc_handle, error == 0 ?
3850 po : NULL);
3851 } else if (po->po_flags & PMC_PO_OWNS_LOGFILE) {
3852 pmclog_proc_ignite(pmclog_proc_handle, NULL);
3853 error = pmclog_close(po);
3854 if (error == 0) {
3855 LIST_FOREACH(pm, &po->po_pmcs, pm_next)
3856 if (pm->pm_flags & PMC_F_NEEDS_LOGFILE &&
3857 pm->pm_state == PMC_STATE_RUNNING)
3858 pmc_stop(pm);
3859 error = pmclog_deconfigure_log(po);
3860 }
3861 } else {
3862 pmclog_proc_ignite(pmclog_proc_handle, NULL);
3863 error = EINVAL;
3864 }
3865 }
3866 break;
3867
3868 /*
3869 * Flush a log file.
3870 */
3871
3872 case PMC_OP_FLUSHLOG:
3873 {
3874 struct pmc_owner *po;
3875
3876 sx_assert(&pmc_sx, SX_XLOCKED);
3877
3878 if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
3879 error = EINVAL;
3880 break;
3881 }
3882
3883 error = pmclog_flush(po, 0);
3884 }
3885 break;
3886
3887 /*
3888 * Close a log file.
3889 */
3890
3891 case PMC_OP_CLOSELOG:
3892 {
3893 struct pmc_owner *po;
3894
3895 sx_assert(&pmc_sx, SX_XLOCKED);
3896
3897 if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
3898 error = EINVAL;
3899 break;
3900 }
3901
3902 error = pmclog_close(po);
3903 }
3904 break;
3905
3906 /*
3907 * Retrieve hardware configuration.
3908 */
3909
3910 case PMC_OP_GETCPUINFO: /* CPU information */
3911 {
3912 struct pmc_op_getcpuinfo gci;
3913 struct pmc_classinfo *pci;
3914 struct pmc_classdep *pcd;
3915 int cl;
3916
3917 memset(&gci, 0, sizeof(gci));
3918 gci.pm_cputype = md->pmd_cputype;
3919 gci.pm_ncpu = pmc_cpu_max();
3920 gci.pm_npmc = md->pmd_npmc;
3921 gci.pm_nclass = md->pmd_nclass;
3922 pci = gci.pm_classes;
3923 pcd = md->pmd_classdep;
3924 for (cl = 0; cl < md->pmd_nclass; cl++, pci++, pcd++) {
3925 pci->pm_caps = pcd->pcd_caps;
3926 pci->pm_class = pcd->pcd_class;
3927 pci->pm_width = pcd->pcd_width;
3928 pci->pm_num = pcd->pcd_num;
3929 }
3930 error = copyout(&gci, arg, sizeof(gci));
3931 }
3932 break;
3933
3934 /*
3935 * Retrieve soft events list.
3936 */
3937 case PMC_OP_GETDYNEVENTINFO:
3938 {
3939 enum pmc_class cl;
3940 enum pmc_event ev;
3941 struct pmc_op_getdyneventinfo *gei;
3942 struct pmc_dyn_event_descr dev;
3943 struct pmc_soft *ps;
3944 uint32_t nevent;
3945
3946 sx_assert(&pmc_sx, SX_LOCKED);
3947
3948 gei = (struct pmc_op_getdyneventinfo *) arg;
3949
3950 if ((error = copyin(&gei->pm_class, &cl, sizeof(cl))) != 0)
3951 break;
3952
3953 /* Only SOFT class is dynamic. */
3954 if (cl != PMC_CLASS_SOFT) {
3955 error = EINVAL;
3956 break;
3957 }
3958
3959 nevent = 0;
3960 for (ev = PMC_EV_SOFT_FIRST; (int)ev <= PMC_EV_SOFT_LAST; ev++) {
3961 ps = pmc_soft_ev_acquire(ev);
3962 if (ps == NULL)
3963 continue;
3964 bcopy(&ps->ps_ev, &dev, sizeof(dev));
3965 pmc_soft_ev_release(ps);
3966
3967 error = copyout(&dev,
3968 &gei->pm_events[nevent],
3969 sizeof(struct pmc_dyn_event_descr));
3970 if (error != 0)
3971 break;
3972 nevent++;
3973 }
3974 if (error != 0)
3975 break;
3976
3977 error = copyout(&nevent, &gei->pm_nevent,
3978 sizeof(nevent));
3979 }
3980 break;
3981
3982 /*
3983 * Get module statistics
3984 */
3985
3986 case PMC_OP_GETDRIVERSTATS:
3987 {
3988 struct pmc_op_getdriverstats gms;
3989 #define CFETCH(a, b, field) a.field = counter_u64_fetch(b.field)
3990 CFETCH(gms, pmc_stats, pm_intr_ignored);
3991 CFETCH(gms, pmc_stats, pm_intr_processed);
3992 CFETCH(gms, pmc_stats, pm_intr_bufferfull);
3993 CFETCH(gms, pmc_stats, pm_syscalls);
3994 CFETCH(gms, pmc_stats, pm_syscall_errors);
3995 CFETCH(gms, pmc_stats, pm_buffer_requests);
3996 CFETCH(gms, pmc_stats, pm_buffer_requests_failed);
3997 CFETCH(gms, pmc_stats, pm_log_sweeps);
3998 #undef CFETCH
3999 error = copyout(&gms, arg, sizeof(gms));
4000 }
4001 break;
4002
4003
4004 /*
4005 * Retrieve module version number
4006 */
4007
4008 case PMC_OP_GETMODULEVERSION:
4009 {
4010 uint32_t cv, modv;
4011
4012 /* retrieve the client's idea of the ABI version */
4013 if ((error = copyin(arg, &cv, sizeof(uint32_t))) != 0)
4014 break;
4015 /* don't service clients newer than our driver */
4016 modv = PMC_VERSION;
4017 if ((cv & 0xFFFF0000) > (modv & 0xFFFF0000)) {
4018 error = EPROGMISMATCH;
4019 break;
4020 }
4021 error = copyout(&modv, arg, sizeof(int));
4022 }
4023 break;
4024
4025
4026 /*
4027 * Retrieve the state of all the PMCs on a given
4028 * CPU.
4029 */
4030
4031 case PMC_OP_GETPMCINFO:
4032 {
4033 int ari;
4034 struct pmc *pm;
4035 size_t pmcinfo_size;
4036 uint32_t cpu, n, npmc;
4037 struct pmc_owner *po;
4038 struct pmc_binding pb;
4039 struct pmc_classdep *pcd;
4040 struct pmc_info *p, *pmcinfo;
4041 struct pmc_op_getpmcinfo *gpi;
4042
4043 PMC_DOWNGRADE_SX();
4044
4045 gpi = (struct pmc_op_getpmcinfo *) arg;
4046
4047 if ((error = copyin(&gpi->pm_cpu, &cpu, sizeof(cpu))) != 0)
4048 break;
4049
4050 if (cpu >= pmc_cpu_max()) {
4051 error = EINVAL;
4052 break;
4053 }
4054
4055 if (!pmc_cpu_is_active(cpu)) {
4056 error = ENXIO;
4057 break;
4058 }
4059
4060 /* switch to CPU 'cpu' */
4061 pmc_save_cpu_binding(&pb);
4062 pmc_select_cpu(cpu);
4063
4064 npmc = md->pmd_npmc;
4065
4066 pmcinfo_size = npmc * sizeof(struct pmc_info);
4067 pmcinfo = malloc(pmcinfo_size, M_PMC, M_WAITOK | M_ZERO);
4068
4069 p = pmcinfo;
4070
4071 for (n = 0; n < md->pmd_npmc; n++, p++) {
4072
4073 pcd = pmc_ri_to_classdep(md, n, &ari);
4074
4075 KASSERT(pcd != NULL,
4076 ("[pmc,%d] null pcd ri=%d", __LINE__, n));
4077
4078 if ((error = pcd->pcd_describe(cpu, ari, p, &pm)) != 0)
4079 break;
4080
4081 if (PMC_ROW_DISP_IS_STANDALONE(n))
4082 p->pm_rowdisp = PMC_DISP_STANDALONE;
4083 else if (PMC_ROW_DISP_IS_THREAD(n))
4084 p->pm_rowdisp = PMC_DISP_THREAD;
4085 else
4086 p->pm_rowdisp = PMC_DISP_FREE;
4087
4088 p->pm_ownerpid = -1;
4089
4090 if (pm == NULL) /* no PMC associated */
4091 continue;
4092
4093 po = pm->pm_owner;
4094
4095 KASSERT(po->po_owner != NULL,
4096 ("[pmc,%d] pmc_owner had a null proc pointer",
4097 __LINE__));
4098
4099 p->pm_ownerpid = po->po_owner->p_pid;
4100 p->pm_mode = PMC_TO_MODE(pm);
4101 p->pm_event = pm->pm_event;
4102 p->pm_flags = pm->pm_flags;
4103
4104 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
4105 p->pm_reloadcount =
4106 pm->pm_sc.pm_reloadcount;
4107 }
4108
4109 pmc_restore_cpu_binding(&pb);
4110
4111 /* now copy out the PMC info collected */
4112 if (error == 0)
4113 error = copyout(pmcinfo, &gpi->pm_pmcs, pmcinfo_size);
4114
4115 free(pmcinfo, M_PMC);
4116 }
4117 break;
4118
4119
4120 /*
4121 * Set the administrative state of a PMC. I.e. whether
4122 * the PMC is to be used or not.
4123 */
4124
4125 case PMC_OP_PMCADMIN:
4126 {
4127 int cpu, ri;
4128 enum pmc_state request;
4129 struct pmc_cpu *pc;
4130 struct pmc_hw *phw;
4131 struct pmc_op_pmcadmin pma;
4132 struct pmc_binding pb;
4133
4134 sx_assert(&pmc_sx, SX_XLOCKED);
4135
4136 KASSERT(td == curthread,
4137 ("[pmc,%d] td != curthread", __LINE__));
4138
4139 error = priv_check(td, PRIV_PMC_MANAGE);
4140 if (error)
4141 break;
4142
4143 if ((error = copyin(arg, &pma, sizeof(pma))) != 0)
4144 break;
4145
4146 cpu = pma.pm_cpu;
4147
4148 if (cpu < 0 || cpu >= (int) pmc_cpu_max()) {
4149 error = EINVAL;
4150 break;
4151 }
4152
4153 if (!pmc_cpu_is_active(cpu)) {
4154 error = ENXIO;
4155 break;
4156 }
4157
4158 request = pma.pm_state;
4159
4160 if (request != PMC_STATE_DISABLED &&
4161 request != PMC_STATE_FREE) {
4162 error = EINVAL;
4163 break;
4164 }
4165
4166 ri = pma.pm_pmc; /* pmc id == row index */
4167 if (ri < 0 || ri >= (int) md->pmd_npmc) {
4168 error = EINVAL;
4169 break;
4170 }
4171
4172 /*
4173 * We can't disable a PMC with a row-index allocated
4174 * for process virtual PMCs.
4175 */
4176
4177 if (PMC_ROW_DISP_IS_THREAD(ri) &&
4178 request == PMC_STATE_DISABLED) {
4179 error = EBUSY;
4180 break;
4181 }
4182
4183 /*
4184 * otherwise, this PMC on this CPU is either free or
4185 * in system-wide mode.
4186 */
4187
4188 pmc_save_cpu_binding(&pb);
4189 pmc_select_cpu(cpu);
4190
4191 pc = pmc_pcpu[cpu];
4192 phw = pc->pc_hwpmcs[ri];
4193
4194 /*
4195 * XXX do we need some kind of 'forced' disable?
4196 */
4197
4198 if (phw->phw_pmc == NULL) {
4199 if (request == PMC_STATE_DISABLED &&
4200 (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED)) {
4201 phw->phw_state &= ~PMC_PHW_FLAG_IS_ENABLED;
4202 PMC_MARK_ROW_STANDALONE(ri);
4203 } else if (request == PMC_STATE_FREE &&
4204 (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0) {
4205 phw->phw_state |= PMC_PHW_FLAG_IS_ENABLED;
4206 PMC_UNMARK_ROW_STANDALONE(ri);
4207 }
4208 /* other cases are a no-op */
4209 } else
4210 error = EBUSY;
4211
4212 pmc_restore_cpu_binding(&pb);
4213 }
4214 break;
4215
4216
4217 /*
4218 * Allocate a PMC.
4219 */
4220 case PMC_OP_PMCALLOCATE:
4221 {
4222 struct pmc_op_pmcallocate pa;
4223
4224 error = copyin(arg, &pa, sizeof(pa));
4225 if (error != 0)
4226 break;
4227
4228 error = pmc_do_op_pmcallocate(td, &pa);
4229 if (error != 0)
4230 break;
4231
4232 error = copyout(&pa, arg, sizeof(pa));
4233 }
4234 break;
4235
4236 /*
4237 * Attach a PMC to a process.
4238 */
4239 case PMC_OP_PMCATTACH:
4240 {
4241 struct pmc_op_pmcattach a;
4242
4243 error = copyin(arg, &a, sizeof(a));
4244 if (error != 0)
4245 break;
4246
4247 error = pmc_do_op_pmcattach(td, a);
4248 }
4249 break;
4250
4251 /*
4252 * Detach an attached PMC from a process.
4253 */
4254 case PMC_OP_PMCDETACH:
4255 {
4256 struct pmc_op_pmcattach a;
4257
4258 error = copyin(arg, &a, sizeof(a));
4259 if (error != 0)
4260 break;
4261
4262 error = pmc_do_op_pmcdetach(td, a);
4263 }
4264 break;
4265
4266
4267 /*
4268 * Retrieve the MSR number associated with the counter
4269 * 'pmc_id'. This allows processes to directly use RDPMC
4270 * instructions to read their PMCs, without the overhead of a
4271 * system call.
4272 */
4273
4274 case PMC_OP_PMCGETMSR:
4275 {
4276 int adjri, ri;
4277 struct pmc *pm;
4278 struct pmc_target *pt;
4279 struct pmc_op_getmsr gm;
4280 struct pmc_classdep *pcd;
4281
4282 PMC_DOWNGRADE_SX();
4283
4284 if ((error = copyin(arg, &gm, sizeof(gm))) != 0)
4285 break;
4286
4287 if ((error = pmc_find_pmc(gm.pm_pmcid, &pm)) != 0)
4288 break;
4289
4290 /*
4291 * The allocated PMC has to be a process virtual PMC,
4292 * i.e., of type MODE_T[CS]. Global PMCs can only be
4293 * read using the PMCREAD operation since they may be
4294 * allocated on a different CPU than the one we could
4295 * be running on at the time of the RDPMC instruction.
4296 *
4297 * The GETMSR operation is not allowed for PMCs that
4298 * are inherited across processes.
4299 */
4300
4301 if (!PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)) ||
4302 (pm->pm_flags & PMC_F_DESCENDANTS)) {
4303 error = EINVAL;
4304 break;
4305 }
4306
4307 /*
4308 * It only makes sense to use a RDPMC (or its
4309 * equivalent instruction on non-x86 architectures) on
4310 * a process that has allocated and attached a PMC to
4311 * itself. Conversely the PMC is only allowed to have
4312 * one process attached to it -- its owner.
4313 */
4314
4315 if ((pt = LIST_FIRST(&pm->pm_targets)) == NULL ||
4316 LIST_NEXT(pt, pt_next) != NULL ||
4317 pt->pt_process->pp_proc != pm->pm_owner->po_owner) {
4318 error = EINVAL;
4319 break;
4320 }
4321
4322 ri = PMC_TO_ROWINDEX(pm);
4323 pcd = pmc_ri_to_classdep(md, ri, &adjri);
4324
4325 /* PMC class has no 'GETMSR' support */
4326 if (pcd->pcd_get_msr == NULL) {
4327 error = ENOSYS;
4328 break;
4329 }
4330
4331 if ((error = (*pcd->pcd_get_msr)(adjri, &gm.pm_msr)) < 0)
4332 break;
4333
4334 if ((error = copyout(&gm, arg, sizeof(gm))) < 0)
4335 break;
4336
4337 /*
4338 * Mark our process as using MSRs. Update machine
4339 * state using a forced context switch.
4340 */
4341
4342 pt->pt_process->pp_flags |= PMC_PP_ENABLE_MSR_ACCESS;
4343 pmc_force_context_switch();
4344
4345 }
4346 break;
4347
4348 /*
4349 * Release an allocated PMC.
4350 */
4351 case PMC_OP_PMCRELEASE:
4352 {
4353 struct pmc_op_simple sp;
4354
4355 error = copyin(arg, &sp, sizeof(sp));
4356 if (error != 0)
4357 break;
4358
4359 error = pmc_do_op_pmcrelease(sp.pm_pmcid);
4360 }
4361 break;
4362
4363 /*
4364 * Read and/or write a PMC.
4365 */
4366 case PMC_OP_PMCRW:
4367 {
4368 struct pmc_op_pmcrw prw;
4369 struct pmc_op_pmcrw *pprw;
4370 pmc_value_t oldvalue;
4371
4372 PMC_DOWNGRADE_SX();
4373
4374 error = copyin(arg, &prw, sizeof(prw));
4375 if (error != 0)
4376 break;
4377
4378 error = pmc_do_op_pmcrw(&prw, &oldvalue);
4379 if (error != 0)
4380 break;
4381
4382 /* Return old value if requested. */
4383 if ((prw.pm_flags & PMC_F_OLDVALUE) != 0) {
4384 pprw = arg;
4385 error = copyout(&oldvalue, &pprw->pm_value,
4386 sizeof(prw.pm_value));
4387 }
4388 }
4389 break;
4390
4391
4392 /*
4393 * Set the sampling rate for a sampling mode PMC and the
4394 * initial count for a counting mode PMC.
4395 */
4396
4397 case PMC_OP_PMCSETCOUNT:
4398 {
4399 struct pmc *pm;
4400 struct pmc_op_pmcsetcount sc;
4401
4402 PMC_DOWNGRADE_SX();
4403
4404 if ((error = copyin(arg, &sc, sizeof(sc))) != 0)
4405 break;
4406
4407 if ((error = pmc_find_pmc(sc.pm_pmcid, &pm)) != 0)
4408 break;
4409
4410 if (pm->pm_state == PMC_STATE_RUNNING) {
4411 error = EBUSY;
4412 break;
4413 }
4414
4415 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm))) {
4416 /*
4417 * Don't permit requested sample rate to be
4418 * less than pmc_mincount.
4419 */
4420 if (sc.pm_count < MAX(1, pmc_mincount))
4421 log(LOG_WARNING, "pmcsetcount: passed sample "
4422 "rate %ju - setting to %u\n",
4423 (uintmax_t)sc.pm_count,
4424 MAX(1, pmc_mincount));
4425 pm->pm_sc.pm_reloadcount = MAX(MAX(1, pmc_mincount),
4426 sc.pm_count);
4427 } else
4428 pm->pm_sc.pm_initial = sc.pm_count;
4429 }
4430 break;
4431
4432
4433 /*
4434 * Start a PMC.
4435 */
4436
4437 case PMC_OP_PMCSTART:
4438 {
4439 pmc_id_t pmcid;
4440 struct pmc *pm;
4441 struct pmc_op_simple sp;
4442
4443 sx_assert(&pmc_sx, SX_XLOCKED);
4444
4445 if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
4446 break;
4447
4448 pmcid = sp.pm_pmcid;
4449
4450 if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
4451 break;
4452
4453 KASSERT(pmcid == pm->pm_id,
4454 ("[pmc,%d] pmcid %x != id %x", __LINE__,
4455 pm->pm_id, pmcid));
4456
4457 if (pm->pm_state == PMC_STATE_RUNNING) /* already running */
4458 break;
4459 else if (pm->pm_state != PMC_STATE_STOPPED &&
4460 pm->pm_state != PMC_STATE_ALLOCATED) {
4461 error = EINVAL;
4462 break;
4463 }
4464
4465 error = pmc_start(pm);
4466 }
4467 break;
4468
4469
4470 /*
4471 * Stop a PMC.
4472 */
4473
4474 case PMC_OP_PMCSTOP:
4475 {
4476 pmc_id_t pmcid;
4477 struct pmc *pm;
4478 struct pmc_op_simple sp;
4479
4480 PMC_DOWNGRADE_SX();
4481
4482 if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
4483 break;
4484
4485 pmcid = sp.pm_pmcid;
4486
4487 /*
4488 * Mark the PMC as inactive and invoke the MD stop
4489 * routines if needed.
4490 */
4491
4492 if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
4493 break;
4494
4495 KASSERT(pmcid == pm->pm_id,
4496 ("[pmc,%d] pmc id %x != pmcid %x", __LINE__,
4497 pm->pm_id, pmcid));
4498
4499 if (pm->pm_state == PMC_STATE_STOPPED) /* already stopped */
4500 break;
4501 else if (pm->pm_state != PMC_STATE_RUNNING) {
4502 error = EINVAL;
4503 break;
4504 }
4505
4506 error = pmc_stop(pm);
4507 }
4508 break;
4509
4510
4511 /*
4512 * Write a user supplied value to the log file.
4513 */
4514
4515 case PMC_OP_WRITELOG:
4516 {
4517 struct pmc_op_writelog wl;
4518 struct pmc_owner *po;
4519
4520 PMC_DOWNGRADE_SX();
4521
4522 if ((error = copyin(arg, &wl, sizeof(wl))) != 0)
4523 break;
4524
4525 if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
4526 error = EINVAL;
4527 break;
4528 }
4529
4530 if ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0) {
4531 error = EINVAL;
4532 break;
4533 }
4534
4535 error = pmclog_process_userlog(po, &wl);
4536 }
4537 break;
4538
4539 /*
4540 * Get the PMC capabilities
4541 */
4542
4543 case PMC_OP_GETCAPS:
4544 {
4545 struct pmc_op_caps c;
4546 struct pmc *pm;
4547 struct pmc_classdep *pcd;
4548 pmc_id_t pmcid;
4549 int adjri, ri;
4550
4551 PMC_DOWNGRADE_SX();
4552
4553 if ((error = copyin(arg, &c, sizeof(c))) != 0)
4554 break;
4555
4556 pmcid = c.pm_pmcid;
4557
4558 if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
4559 break;
4560
4561 KASSERT(pmcid == pm->pm_id,
4562 ("[pmc,%d] pmc id %x != pmcid %x", __LINE__,
4563 pm->pm_id, pmcid));
4564
4565 ri = PMC_TO_ROWINDEX(pm);
4566 pcd = pmc_ri_to_classdep(md, ri, &adjri);
4567
4568 /*
4569 * If PMC class has no GETCAPS return the class capabilities
4570 * otherwise get the per counter capabilities.
4571 */
4572 if (pcd->pcd_get_caps == NULL) {
4573 c.pm_caps = pcd->pcd_caps;
4574 } else {
4575 error = (*pcd->pcd_get_caps)(adjri, &c.pm_caps);
4576 if (error < 0)
4577 break;
4578 }
4579
4580 if ((error = copyout(&c, arg, sizeof(c))) < 0)
4581 break;
4582 }
4583 break;
4584
4585 default:
4586 error = EINVAL;
4587 break;
4588 }
4589
4590 if (is_sx_downgraded)
4591 sx_sunlock(&pmc_sx);
4592 else
4593 sx_xunlock(&pmc_sx);
4594 done_syscall:
4595 if (error)
4596 counter_u64_add(pmc_stats.pm_syscall_errors, 1);
4597
4598 return (error);
4599 }
4600
4601 /*
4602 * Helper functions
4603 */
4604
4605 /*
4606 * Mark the thread as needing callchain capture and post an AST. The
4607 * actual callchain capture will be done in a context where it is safe
4608 * to take page faults.
4609 */
4610 static void
pmc_post_callchain_callback(void)4611 pmc_post_callchain_callback(void)
4612 {
4613 struct thread *td;
4614
4615 td = curthread;
4616
4617 /*
4618 * If there is multiple PMCs for the same interrupt ignore new post
4619 */
4620 if ((td->td_pflags & TDP_CALLCHAIN) != 0)
4621 return;
4622
4623 /*
4624 * Mark this thread as needing callchain capture.
4625 * `td->td_pflags' will be safe to touch because this thread
4626 * was in user space when it was interrupted.
4627 */
4628 td->td_pflags |= TDP_CALLCHAIN;
4629
4630 /*
4631 * Don't let this thread migrate between CPUs until callchain
4632 * capture completes.
4633 */
4634 sched_pin();
4635
4636 return;
4637 }
4638
4639 static bool
pmc_is_multipart(struct pmc_sample * ps)4640 pmc_is_multipart(struct pmc_sample *ps)
4641 {
4642 return ((ps->ps_flags & PMC_CC_F_MULTIPART) != 0);
4643 }
4644
4645 static void
pmc_multipart_add(struct pmc_sample * ps,int type,int length)4646 pmc_multipart_add(struct pmc_sample *ps, int type, int length)
4647 {
4648 int i;
4649 uint8_t *hdr;
4650
4651 MPASS(ps->ps_pc != NULL);
4652 MPASS(ps->ps_nsamples_actual != 0);
4653
4654 hdr = (uint8_t *)ps->ps_pc;
4655
4656 for (i = 0; i < PMC_MULTIPART_HEADER_ENTRIES; i++) {
4657 if (hdr[2 * i] == PMC_CC_MULTIPART_NONE) {
4658 hdr[2 * i] = type;
4659 hdr[2 * i + 1] = length;
4660 ps->ps_nsamples_actual += length;
4661 return;
4662 }
4663 }
4664
4665 KASSERT(false, ("Too many parts in the multipart header!"));
4666 }
4667
4668 static void
pmc_multipart_copydata(struct pmc_sample * ps,struct pmc_multipart * mp)4669 pmc_multipart_copydata(struct pmc_sample *ps, struct pmc_multipart *mp)
4670 {
4671 int i, scale;
4672 uint64_t *ps_pc;
4673
4674 MPASS(ps->ps_pc != NULL);
4675 MPASS(ps->ps_nsamples_actual != 0);
4676
4677 ps_pc = (uint64_t *)ps->ps_pc;
4678
4679 for (i = 0; i < mp->pl_length; i++)
4680 ps_pc[i + 1] = mp->pl_mpdata[i];
4681
4682 scale = sizeof(uint64_t) / sizeof(uintptr_t);
4683 pmc_multipart_add(ps, mp->pl_type, scale * mp->pl_length);
4684 }
4685
4686 /*
4687 * Find a free slot in the per-cpu array of samples and capture the
4688 * current callchain there. If a sample was successfully added, a bit
4689 * is set in mask 'pmc_cpumask' denoting that the DO_SAMPLES hook
4690 * needs to be invoked from the clock handler.
4691 *
4692 * This function is meant to be called from an NMI handler. It cannot
4693 * use any of the locking primitives supplied by the OS.
4694 */
4695 static int
pmc_add_sample(ring_type_t ring,struct pmc * pm,struct trapframe * tf,struct pmc_multipart * mp)4696 pmc_add_sample(ring_type_t ring, struct pmc *pm, struct trapframe *tf,
4697 struct pmc_multipart *mp)
4698 {
4699 struct pmc_sample *ps;
4700 struct pmc_samplebuffer *psb;
4701 struct thread *td;
4702 int error, cpu, callchaindepth;
4703 bool inuserspace;
4704
4705 error = 0;
4706
4707 /*
4708 * Allocate space for a sample buffer.
4709 */
4710 cpu = curcpu;
4711 psb = pmc_pcpu[cpu]->pc_sb[ring];
4712 inuserspace = TRAPF_USERMODE(tf);
4713 ps = PMC_PROD_SAMPLE(psb);
4714 if (psb->ps_considx != psb->ps_prodidx &&
4715 ps->ps_nsamples) { /* in use, reader hasn't caught up */
4716 pm->pm_pcpu_state[cpu].pps_stalled = 1;
4717 counter_u64_add(pmc_stats.pm_intr_bufferfull, 1);
4718 PMCDBG6(SAM,INT,1,"(spc) cpu=%d pm=%p tf=%p um=%d wr=%d rd=%d",
4719 cpu, pm, tf, inuserspace,
4720 (int)(psb->ps_prodidx & pmc_sample_mask),
4721 (int)(psb->ps_considx & pmc_sample_mask));
4722 callchaindepth = 1;
4723 error = ENOMEM;
4724 goto done;
4725 }
4726
4727 /* Fill in entry. */
4728 PMCDBG6(SAM,INT,1,"cpu=%d pm=%p tf=%p um=%d wr=%d rd=%d", cpu, pm, tf,
4729 inuserspace, (int)(psb->ps_prodidx & pmc_sample_mask),
4730 (int)(psb->ps_considx & pmc_sample_mask));
4731
4732 td = curthread;
4733 ps->ps_pmc = pm;
4734 ps->ps_td = td;
4735 ps->ps_pid = td->td_proc->p_pid;
4736 ps->ps_tid = td->td_tid;
4737 ps->ps_tsc = pmc_rdtsc();
4738 ps->ps_ticks = ticks;
4739 ps->ps_cpu = cpu;
4740 ps->ps_flags = inuserspace ? PMC_CC_F_USERSPACE : 0;
4741 ps->ps_nsamples_actual = 0;
4742
4743 callchaindepth = (pm->pm_flags & PMC_F_CALLCHAIN) ?
4744 pmc_callchaindepth : 1;
4745
4746 MPASS(ps->ps_pc != NULL);
4747
4748 if (mp != NULL) {
4749 /* Set multipart flag, clear header and copy data */
4750 ps->ps_flags |= PMC_CC_F_MULTIPART;
4751 ps->ps_pc[0] = 0;
4752 ps->ps_nsamples_actual = 1;
4753 pmc_multipart_copydata(ps, mp);
4754 }
4755
4756 if (callchaindepth == 1) {
4757 ps->ps_pc[ps->ps_nsamples_actual] = PMC_TRAPFRAME_TO_PC(tf);
4758 } else {
4759 /*
4760 * Kernel stack traversals can be done immediately, while we
4761 * defer to an AST for user space traversals.
4762 */
4763 if (!inuserspace) {
4764 callchaindepth = pmc_save_kernel_callchain(
4765 ps->ps_pc + ps->ps_nsamples_actual,
4766 callchaindepth - ps->ps_nsamples_actual, tf);
4767 callchaindepth += ps->ps_nsamples_actual;
4768 } else {
4769 pmc_post_callchain_callback();
4770 callchaindepth = PMC_USER_CALLCHAIN_PENDING;
4771 }
4772 }
4773
4774 ps->ps_nsamples = callchaindepth; /* mark entry as in-use */
4775 if (ring == PMC_UR) {
4776 ps->ps_nsamples_actual = ps->ps_nsamples;
4777 ps->ps_nsamples = PMC_USER_CALLCHAIN_PENDING;
4778 }
4779
4780 KASSERT(counter_u64_fetch(pm->pm_runcount) >= 0,
4781 ("[pmc,%d] pm=%p runcount %ju", __LINE__, pm,
4782 (uintmax_t)counter_u64_fetch(pm->pm_runcount)));
4783
4784 counter_u64_add(pm->pm_runcount, 1); /* hold onto PMC */
4785 /* increment write pointer */
4786 psb->ps_prodidx++;
4787 done:
4788 /* mark CPU as needing processing */
4789 if (callchaindepth != PMC_USER_CALLCHAIN_PENDING)
4790 DPCPU_SET(pmc_sampled, 1);
4791
4792 return (error);
4793 }
4794
4795 /*
4796 * Interrupt processing.
4797 *
4798 * This function may be called from an NMI handler. It cannot use any of the
4799 * locking primitives supplied by the OS.
4800 */
4801 int
pmc_process_interrupt_mp(int ring,struct pmc * pm,struct trapframe * tf,struct pmc_multipart * mp)4802 pmc_process_interrupt_mp(int ring, struct pmc *pm, struct trapframe *tf,
4803 struct pmc_multipart *mp)
4804 {
4805 struct thread *td;
4806
4807 td = curthread;
4808 if ((pm->pm_flags & PMC_F_USERCALLCHAIN) &&
4809 (td->td_proc->p_flag & P_KPROC) == 0 && !TRAPF_USERMODE(tf)) {
4810 atomic_add_int(&td->td_pmcpend, 1);
4811 return (pmc_add_sample(PMC_UR, pm, tf, mp));
4812 }
4813 return (pmc_add_sample(ring, pm, tf, mp));
4814 }
4815
4816 int
pmc_process_interrupt(int ring,struct pmc * pm,struct trapframe * tf)4817 pmc_process_interrupt(int ring, struct pmc *pm, struct trapframe *tf)
4818 {
4819 return (pmc_process_interrupt_mp(ring, pm, tf, NULL));
4820 }
4821
4822 /*
4823 * Capture a user call chain. This function will be called from ast()
4824 * before control returns to userland and before the process gets
4825 * rescheduled.
4826 */
4827 static void
pmc_capture_user_callchain(int cpu,int ring,struct trapframe * tf)4828 pmc_capture_user_callchain(int cpu, int ring, struct trapframe *tf)
4829 {
4830 struct pmc *pm;
4831 struct pmc_sample *ps;
4832 struct pmc_samplebuffer *psb;
4833 struct thread *td;
4834 uint64_t considx, prodidx;
4835 int nsamples, nrecords, pass, iter;
4836 int start_ticks __diagused;
4837
4838 psb = pmc_pcpu[cpu]->pc_sb[ring];
4839 td = curthread;
4840 nrecords = INT_MAX;
4841 pass = 0;
4842 start_ticks = ticks;
4843
4844 KASSERT(td->td_pflags & TDP_CALLCHAIN,
4845 ("[pmc,%d] Retrieving callchain for thread that doesn't want it",
4846 __LINE__));
4847 restart:
4848 if (ring == PMC_UR)
4849 nrecords = atomic_readandclear_32(&td->td_pmcpend);
4850
4851 for (iter = 0, considx = psb->ps_considx, prodidx = psb->ps_prodidx;
4852 considx < prodidx && iter < pmc_nsamples; considx++, iter++) {
4853 ps = PMC_CONS_SAMPLE_OFF(psb, considx);
4854
4855 /*
4856 * Iterate through all deferred callchain requests. Walk from
4857 * the current read pointer to the current write pointer.
4858 */
4859 #ifdef INVARIANTS
4860 if (ps->ps_nsamples == PMC_SAMPLE_FREE) {
4861 continue;
4862 }
4863 #endif
4864 if (ps->ps_td != td ||
4865 ps->ps_nsamples != PMC_USER_CALLCHAIN_PENDING ||
4866 ps->ps_pmc->pm_state != PMC_STATE_RUNNING)
4867 continue;
4868
4869 KASSERT(ps->ps_cpu == cpu,
4870 ("[pmc,%d] cpu mismatch ps_cpu=%d pcpu=%d", __LINE__,
4871 ps->ps_cpu, PCPU_GET(cpuid)));
4872
4873 pm = ps->ps_pmc;
4874 KASSERT(pm->pm_flags & PMC_F_CALLCHAIN,
4875 ("[pmc,%d] Retrieving callchain for PMC that doesn't "
4876 "want it", __LINE__));
4877 KASSERT(counter_u64_fetch(pm->pm_runcount) > 0,
4878 ("[pmc,%d] runcount %ju", __LINE__,
4879 (uintmax_t)counter_u64_fetch(pm->pm_runcount)));
4880
4881 if (ring == PMC_UR) {
4882 counter_u64_add(pmc_stats.pm_merges, 1);
4883 }
4884 nsamples = ps->ps_nsamples_actual;
4885
4886 /*
4887 * Retrieve the callchain and mark the sample buffer
4888 * as 'processable' by the timer tick sweep code.
4889 */
4890 if (__predict_true(nsamples < pmc_callchaindepth - 1))
4891 nsamples += pmc_save_user_callchain(ps->ps_pc + nsamples,
4892 pmc_callchaindepth - nsamples - 1, tf);
4893
4894 /*
4895 * We have to prevent hardclock from potentially overwriting
4896 * this sample between when we read the value and when we set
4897 * it.
4898 */
4899 spinlock_enter();
4900
4901 /*
4902 * Verify that the sample hasn't been dropped in the meantime.
4903 */
4904 if (ps->ps_nsamples == PMC_USER_CALLCHAIN_PENDING) {
4905 ps->ps_nsamples = nsamples;
4906 /*
4907 * If we couldn't get a sample, simply drop the
4908 * reference.
4909 */
4910 if (nsamples == 0)
4911 counter_u64_add(pm->pm_runcount, -1);
4912 }
4913 spinlock_exit();
4914 if (nrecords-- == 1)
4915 break;
4916 }
4917 if (__predict_false(ring == PMC_UR && td->td_pmcpend)) {
4918 if (pass == 0) {
4919 pass = 1;
4920 goto restart;
4921 }
4922 /* only collect samples for this part once */
4923 td->td_pmcpend = 0;
4924 }
4925
4926 #ifdef INVARIANTS
4927 if ((ticks - start_ticks) > hz)
4928 log(LOG_ERR, "%s took %d ticks\n", __func__, (ticks - start_ticks));
4929 #endif
4930 /* mark CPU as needing processing */
4931 DPCPU_SET(pmc_sampled, 1);
4932 }
4933
4934 /*
4935 * Process saved PC samples.
4936 */
4937 static void
pmc_process_samples(int cpu,ring_type_t ring)4938 pmc_process_samples(int cpu, ring_type_t ring)
4939 {
4940 struct pmc *pm;
4941 struct thread *td;
4942 struct pmc_owner *po;
4943 struct pmc_sample *ps;
4944 struct pmc_classdep *pcd;
4945 struct pmc_samplebuffer *psb;
4946 uint64_t delta __diagused;
4947 int adjri, n;
4948
4949 KASSERT(PCPU_GET(cpuid) == cpu,
4950 ("[pmc,%d] not on the correct CPU pcpu=%d cpu=%d", __LINE__,
4951 PCPU_GET(cpuid), cpu));
4952
4953 psb = pmc_pcpu[cpu]->pc_sb[ring];
4954 delta = psb->ps_prodidx - psb->ps_considx;
4955 MPASS(delta <= pmc_nsamples);
4956 MPASS(psb->ps_considx <= psb->ps_prodidx);
4957 for (n = 0; psb->ps_considx < psb->ps_prodidx; psb->ps_considx++, n++) {
4958 ps = PMC_CONS_SAMPLE(psb);
4959
4960 if (__predict_false(ps->ps_nsamples == PMC_SAMPLE_FREE))
4961 continue;
4962
4963 /* skip non-running samples */
4964 pm = ps->ps_pmc;
4965 if (pm->pm_state != PMC_STATE_RUNNING)
4966 goto entrydone;
4967
4968 KASSERT(counter_u64_fetch(pm->pm_runcount) > 0,
4969 ("[pmc,%d] pm=%p runcount %ju", __LINE__, pm,
4970 (uintmax_t)counter_u64_fetch(pm->pm_runcount)));
4971 KASSERT(PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)),
4972 ("[pmc,%d] pmc=%p non-sampling mode=%d", __LINE__,
4973 pm, PMC_TO_MODE(pm)));
4974
4975 po = pm->pm_owner;
4976
4977 /* If there is a pending AST wait for completion */
4978 if (ps->ps_nsamples == PMC_USER_CALLCHAIN_PENDING) {
4979 /*
4980 * If we've been waiting more than 1 tick to
4981 * collect a callchain for this record then
4982 * drop it and move on.
4983 */
4984 if (ticks - ps->ps_ticks > 1) {
4985 /*
4986 * Track how often we hit this as it will
4987 * preferentially lose user samples
4988 * for long running system calls.
4989 */
4990 counter_u64_add(pmc_stats.pm_overwrites, 1);
4991 goto entrydone;
4992 }
4993 /* Need a rescan at a later time. */
4994 DPCPU_SET(pmc_sampled, 1);
4995 break;
4996 }
4997
4998 PMCDBG6(SAM,OPS,1,"cpu=%d pm=%p n=%d fl=%x wr=%d rd=%d", cpu,
4999 pm, ps->ps_nsamples, ps->ps_flags,
5000 (int)(psb->ps_prodidx & pmc_sample_mask),
5001 (int)(psb->ps_considx & pmc_sample_mask));
5002
5003 /*
5004 * If this is a process-mode PMC that is attached to
5005 * its owner, and if the PC is in user mode, update
5006 * profiling statistics like timer-based profiling
5007 * would have done.
5008 *
5009 * Otherwise, this is either a sampling-mode PMC that
5010 * is attached to a different process than its owner,
5011 * or a system-wide sampling PMC. Dispatch a log
5012 * entry to the PMC's owner process.
5013 */
5014 if (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) {
5015 if (ps->ps_flags & PMC_CC_F_USERSPACE) {
5016 td = FIRST_THREAD_IN_PROC(po->po_owner);
5017 addupc_intr(td, ps->ps_pc[0], 1);
5018 }
5019 } else
5020 pmclog_process_callchain(pm, ps);
5021
5022 entrydone:
5023 ps->ps_nsamples = 0; /* mark entry as free */
5024 KASSERT(counter_u64_fetch(pm->pm_runcount) > 0,
5025 ("[pmc,%d] pm=%p runcount %ju", __LINE__, pm,
5026 (uintmax_t)counter_u64_fetch(pm->pm_runcount)));
5027
5028 counter_u64_add(pm->pm_runcount, -1);
5029 }
5030
5031 counter_u64_add(pmc_stats.pm_log_sweeps, 1);
5032
5033 /* Do not re-enable stalled PMCs if we failed to process any samples */
5034 if (n == 0)
5035 return;
5036
5037 /*
5038 * Restart any stalled sampling PMCs on this CPU.
5039 *
5040 * If the NMI handler sets the pm_stalled field of a PMC after
5041 * the check below, we'll end up processing the stalled PMC at
5042 * the next hardclock tick.
5043 */
5044 for (n = 0; n < md->pmd_npmc; n++) {
5045 pcd = pmc_ri_to_classdep(md, n, &adjri);
5046 KASSERT(pcd != NULL,
5047 ("[pmc,%d] null pcd ri=%d", __LINE__, n));
5048 (void)(*pcd->pcd_get_config)(cpu, adjri, &pm);
5049
5050 if (pm == NULL || /* !cfg'ed */
5051 pm->pm_state != PMC_STATE_RUNNING || /* !active */
5052 !PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)) || /* !sampling */
5053 !pm->pm_pcpu_state[cpu].pps_cpustate || /* !desired */
5054 !pm->pm_pcpu_state[cpu].pps_stalled) /* !stalled */
5055 continue;
5056
5057 pm->pm_pcpu_state[cpu].pps_stalled = 0;
5058 (void)(*pcd->pcd_start_pmc)(cpu, adjri, pm);
5059 }
5060 }
5061
5062 /*
5063 * Event handlers.
5064 */
5065
5066 /*
5067 * Handle a process exit.
5068 *
5069 * Remove this process from all hash tables. If this process
5070 * owned any PMCs, turn off those PMCs and deallocate them,
5071 * removing any associations with target processes.
5072 *
5073 * This function will be called by the last 'thread' of a
5074 * process.
5075 *
5076 * XXX This eventhandler gets called early in the exit process.
5077 * Consider using a 'hook' invocation from thread_exit() or equivalent
5078 * spot. Another negative is that kse_exit doesn't seem to call
5079 * exit1() [??].
5080 */
5081 static void
pmc_process_exit(void * arg __unused,struct proc * p)5082 pmc_process_exit(void *arg __unused, struct proc *p)
5083 {
5084 struct pmc *pm;
5085 struct pmc_owner *po;
5086 struct pmc_process *pp;
5087 struct pmc_classdep *pcd;
5088 pmc_value_t newvalue, tmp;
5089 int ri, adjri, cpu;
5090 bool is_using_hwpmcs;
5091
5092 PROC_LOCK(p);
5093 is_using_hwpmcs = (p->p_flag & P_HWPMC) != 0;
5094 PROC_UNLOCK(p);
5095
5096 /*
5097 * Log a sysexit event to all SS PMC owners.
5098 */
5099 PMC_EPOCH_ENTER();
5100 CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext) {
5101 if ((po->po_flags & PMC_PO_OWNS_LOGFILE) != 0)
5102 pmclog_process_sysexit(po, p->p_pid);
5103 }
5104 PMC_EPOCH_EXIT();
5105
5106 PMC_GET_SX_XLOCK();
5107 PMCDBG3(PRC,EXT,1,"process-exit proc=%p (%d, %s)", p, p->p_pid,
5108 p->p_comm);
5109
5110 if (!is_using_hwpmcs)
5111 goto out;
5112
5113 /*
5114 * Since this code is invoked by the last thread in an exiting process,
5115 * we would have context switched IN at some prior point. However, with
5116 * PREEMPTION, kernel mode context switches may happen any time, so we
5117 * want to disable a context switch OUT till we get any PMCs targeting
5118 * this process off the hardware.
5119 *
5120 * We also need to atomically remove this process' entry from our
5121 * target process hash table, using PMC_FLAG_REMOVE.
5122 */
5123 PMCDBG3(PRC,EXT,1, "process-exit proc=%p (%d, %s)", p, p->p_pid,
5124 p->p_comm);
5125
5126 critical_enter(); /* no preemption */
5127
5128 cpu = curthread->td_oncpu;
5129
5130 pp = pmc_find_process_descriptor(p, PMC_FLAG_REMOVE);
5131 if (pp == NULL) {
5132 critical_exit();
5133 goto out;
5134 }
5135
5136 PMCDBG2(PRC,EXT,2, "process-exit proc=%p pmc-process=%p", p, pp);
5137
5138 /*
5139 * The exiting process could be the target of some PMCs which will be
5140 * running on currently executing CPU.
5141 *
5142 * We need to turn these PMCs off like we would do at context switch
5143 * OUT time.
5144 */
5145 for (ri = 0; ri < md->pmd_npmc; ri++) {
5146 /*
5147 * Pick up the pmc pointer from hardware state similar to the
5148 * CSW_OUT code.
5149 */
5150 pm = NULL;
5151 pcd = pmc_ri_to_classdep(md, ri, &adjri);
5152
5153 (void)(*pcd->pcd_get_config)(cpu, adjri, &pm);
5154
5155 PMCDBG2(PRC,EXT,2, "ri=%d pm=%p", ri, pm);
5156
5157 if (pm == NULL || !PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)))
5158 continue;
5159
5160 PMCDBG4(PRC,EXT,2, "ppmcs[%d]=%p pm=%p state=%d", ri,
5161 pp->pp_pmcs[ri].pp_pmc, pm, pm->pm_state);
5162
5163 KASSERT(PMC_TO_ROWINDEX(pm) == ri,
5164 ("[pmc,%d] ri mismatch pmc(%d) ri(%d)", __LINE__,
5165 PMC_TO_ROWINDEX(pm), ri));
5166 KASSERT(pm == pp->pp_pmcs[ri].pp_pmc,
5167 ("[pmc,%d] pm %p != pp_pmcs[%d] %p", __LINE__, pm, ri,
5168 pp->pp_pmcs[ri].pp_pmc));
5169 KASSERT(counter_u64_fetch(pm->pm_runcount) > 0,
5170 ("[pmc,%d] bad runcount ri %d rc %ju", __LINE__, ri,
5171 (uintmax_t)counter_u64_fetch(pm->pm_runcount)));
5172
5173 /*
5174 * Change desired state, and then stop if not stalled. This
5175 * two-step dance should avoid race conditions where an
5176 * interrupt re-enables the PMC after this code has already
5177 * checked the pm_stalled flag.
5178 */
5179 if (pm->pm_pcpu_state[cpu].pps_cpustate) {
5180 pm->pm_pcpu_state[cpu].pps_cpustate = 0;
5181 if (!pm->pm_pcpu_state[cpu].pps_stalled) {
5182 (void)pcd->pcd_stop_pmc(cpu, adjri, pm);
5183
5184 if (PMC_TO_MODE(pm) == PMC_MODE_TC) {
5185 pcd->pcd_read_pmc(cpu, adjri, pm,
5186 &newvalue);
5187 tmp = newvalue - PMC_PCPU_SAVED(cpu, ri);
5188
5189 mtx_pool_lock_spin(pmc_mtxpool, pm);
5190 pm->pm_gv.pm_savedvalue += tmp;
5191 pp->pp_pmcs[ri].pp_pmcval += tmp;
5192 mtx_pool_unlock_spin(pmc_mtxpool, pm);
5193 }
5194 }
5195 }
5196
5197 KASSERT(counter_u64_fetch(pm->pm_runcount) > 0,
5198 ("[pmc,%d] runcount is %d", __LINE__, ri));
5199
5200 counter_u64_add(pm->pm_runcount, -1);
5201 (void)pcd->pcd_config_pmc(cpu, adjri, NULL);
5202 }
5203
5204 /*
5205 * Inform the MD layer of this pseudo "context switch out".
5206 */
5207 (void)md->pmd_switch_out(pmc_pcpu[cpu], pp);
5208
5209 critical_exit(); /* ok to be pre-empted now */
5210
5211 /*
5212 * Unlink this process from the PMCs that are targeting it. This will
5213 * send a signal to all PMC owner's whose PMCs are orphaned.
5214 *
5215 * Log PMC value at exit time if requested.
5216 */
5217 for (ri = 0; ri < md->pmd_npmc; ri++) {
5218 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL) {
5219 if ((pm->pm_flags & PMC_F_NEEDS_LOGFILE) != 0 &&
5220 PMC_IS_COUNTING_MODE(PMC_TO_MODE(pm))) {
5221 pmclog_process_procexit(pm, pp);
5222 }
5223 pmc_unlink_target_process(pm, pp);
5224 }
5225 }
5226 free(pp, M_PMC);
5227
5228 out:
5229 /*
5230 * If the process owned PMCs, free them up and free up memory.
5231 */
5232 if ((po = pmc_find_owner_descriptor(p)) != NULL) {
5233 if ((po->po_flags & PMC_PO_OWNS_LOGFILE) != 0)
5234 pmclog_close(po);
5235 pmc_remove_owner(po);
5236 pmc_destroy_owner_descriptor(po);
5237 }
5238
5239 sx_xunlock(&pmc_sx);
5240 }
5241
5242 /*
5243 * Handle a process fork.
5244 *
5245 * If the parent process 'p1' is under HWPMC monitoring, then copy
5246 * over any attached PMCs that have 'do_descendants' semantics.
5247 */
5248 static void
pmc_process_fork(void * arg __unused,struct proc * p1,struct proc * newproc,int flags __unused)5249 pmc_process_fork(void *arg __unused, struct proc *p1, struct proc *newproc,
5250 int flags __unused)
5251 {
5252 struct pmc *pm;
5253 struct pmc_owner *po;
5254 struct pmc_process *ppnew, *ppold;
5255 unsigned int ri;
5256 bool is_using_hwpmcs, do_descendants;
5257
5258 PROC_LOCK(p1);
5259 is_using_hwpmcs = (p1->p_flag & P_HWPMC) != 0;
5260 PROC_UNLOCK(p1);
5261
5262 /*
5263 * If there are system-wide sampling PMCs active, we need to
5264 * log all fork events to their owner's logs.
5265 */
5266 PMC_EPOCH_ENTER();
5267 CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext) {
5268 if (po->po_flags & PMC_PO_OWNS_LOGFILE) {
5269 pmclog_process_procfork(po, p1->p_pid, newproc->p_pid);
5270 pmclog_process_proccreate(po, newproc, 1);
5271 }
5272 }
5273 PMC_EPOCH_EXIT();
5274
5275 if (!is_using_hwpmcs)
5276 return;
5277
5278 PMC_GET_SX_XLOCK();
5279 PMCDBG4(PMC,FRK,1, "process-fork proc=%p (%d, %s) -> %p", p1,
5280 p1->p_pid, p1->p_comm, newproc);
5281
5282 /*
5283 * If the parent process (curthread->td_proc) is a
5284 * target of any PMCs, look for PMCs that are to be
5285 * inherited, and link these into the new process
5286 * descriptor.
5287 */
5288 ppold = pmc_find_process_descriptor(curthread->td_proc, PMC_FLAG_NONE);
5289 if (ppold == NULL)
5290 goto done; /* nothing to do */
5291
5292 do_descendants = false;
5293 for (ri = 0; ri < md->pmd_npmc; ri++) {
5294 if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL &&
5295 (pm->pm_flags & PMC_F_DESCENDANTS) != 0) {
5296 do_descendants = true;
5297 break;
5298 }
5299 }
5300 if (!do_descendants) /* nothing to do */
5301 goto done;
5302
5303 /*
5304 * Now mark the new process as being tracked by this driver.
5305 */
5306 PROC_LOCK(newproc);
5307 newproc->p_flag |= P_HWPMC;
5308 PROC_UNLOCK(newproc);
5309
5310 /* Allocate a descriptor for the new process. */
5311 ppnew = pmc_find_process_descriptor(newproc, PMC_FLAG_ALLOCATE);
5312 if (ppnew == NULL)
5313 goto done;
5314
5315 /*
5316 * Run through all PMCs that were targeting the old process
5317 * and which specified F_DESCENDANTS and attach them to the
5318 * new process.
5319 *
5320 * Log the fork event to all owners of PMCs attached to this
5321 * process, if not already logged.
5322 */
5323 for (ri = 0; ri < md->pmd_npmc; ri++) {
5324 if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL &&
5325 (pm->pm_flags & PMC_F_DESCENDANTS) != 0) {
5326 pmc_link_target_process(pm, ppnew);
5327 po = pm->pm_owner;
5328 if (po->po_sscount == 0 &&
5329 (po->po_flags & PMC_PO_OWNS_LOGFILE) != 0) {
5330 pmclog_process_procfork(po, p1->p_pid,
5331 newproc->p_pid);
5332 }
5333 }
5334 }
5335
5336 done:
5337 sx_xunlock(&pmc_sx);
5338 }
5339
5340 static void
pmc_process_threadcreate(struct thread * td)5341 pmc_process_threadcreate(struct thread *td)
5342 {
5343 struct pmc_owner *po;
5344
5345 PMC_EPOCH_ENTER();
5346 CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext) {
5347 if ((po->po_flags & PMC_PO_OWNS_LOGFILE) != 0)
5348 pmclog_process_threadcreate(po, td, 1);
5349 }
5350 PMC_EPOCH_EXIT();
5351 }
5352
5353 static void
pmc_process_threadexit(struct thread * td)5354 pmc_process_threadexit(struct thread *td)
5355 {
5356 struct pmc_owner *po;
5357
5358 PMC_EPOCH_ENTER();
5359 CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext) {
5360 if ((po->po_flags & PMC_PO_OWNS_LOGFILE) != 0)
5361 pmclog_process_threadexit(po, td);
5362 }
5363 PMC_EPOCH_EXIT();
5364 }
5365
5366 static void
pmc_process_proccreate(struct proc * p)5367 pmc_process_proccreate(struct proc *p)
5368 {
5369 struct pmc_owner *po;
5370
5371 PMC_EPOCH_ENTER();
5372 CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext) {
5373 if ((po->po_flags & PMC_PO_OWNS_LOGFILE) != 0)
5374 pmclog_process_proccreate(po, p, 1 /* sync */);
5375 }
5376 PMC_EPOCH_EXIT();
5377 }
5378
5379 static void
pmc_process_allproc(struct pmc * pm)5380 pmc_process_allproc(struct pmc *pm)
5381 {
5382 struct pmc_owner *po;
5383 struct thread *td;
5384 struct proc *p;
5385
5386 po = pm->pm_owner;
5387 if ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)
5388 return;
5389
5390 sx_slock(&allproc_lock);
5391 FOREACH_PROC_IN_SYSTEM(p) {
5392 pmclog_process_proccreate(po, p, 0 /* sync */);
5393 PROC_LOCK(p);
5394 FOREACH_THREAD_IN_PROC(p, td)
5395 pmclog_process_threadcreate(po, td, 0 /* sync */);
5396 PROC_UNLOCK(p);
5397 }
5398 sx_sunlock(&allproc_lock);
5399 pmclog_flush(po, 0);
5400 }
5401
5402 static void
pmc_kld_load(void * arg __unused,linker_file_t lf)5403 pmc_kld_load(void *arg __unused, linker_file_t lf)
5404 {
5405 struct pmc_owner *po;
5406
5407 /*
5408 * Notify owners of system sampling PMCs about KLD operations.
5409 */
5410 PMC_EPOCH_ENTER();
5411 CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext) {
5412 if (po->po_flags & PMC_PO_OWNS_LOGFILE)
5413 pmclog_process_map_in(po, (pid_t) -1,
5414 (uintfptr_t) lf->address, lf->pathname);
5415 }
5416 PMC_EPOCH_EXIT();
5417
5418 /*
5419 * TODO: Notify owners of (all) process-sampling PMCs too.
5420 */
5421 }
5422
5423 static void
pmc_kld_unload(void * arg __unused,const char * filename __unused,caddr_t address,size_t size)5424 pmc_kld_unload(void *arg __unused, const char *filename __unused,
5425 caddr_t address, size_t size)
5426 {
5427 struct pmc_owner *po;
5428
5429 PMC_EPOCH_ENTER();
5430 CK_LIST_FOREACH(po, &pmc_ss_owners, po_ssnext) {
5431 if ((po->po_flags & PMC_PO_OWNS_LOGFILE) != 0) {
5432 pmclog_process_map_out(po, (pid_t)-1,
5433 (uintfptr_t)address, (uintfptr_t)address + size);
5434 }
5435 }
5436 PMC_EPOCH_EXIT();
5437
5438 /*
5439 * TODO: Notify owners of process-sampling PMCs.
5440 */
5441 }
5442
5443 /*
5444 * initialization
5445 */
5446 static const char *
pmc_name_of_pmcclass(enum pmc_class class)5447 pmc_name_of_pmcclass(enum pmc_class class)
5448 {
5449
5450 switch (class) {
5451 #undef __PMC_CLASS
5452 #define __PMC_CLASS(S,V,D) \
5453 case PMC_CLASS_##S: \
5454 return #S;
5455 __PMC_CLASSES();
5456 default:
5457 return ("<unknown>");
5458 }
5459 }
5460
5461 /*
5462 * Base class initializer: allocate structure and set default classes.
5463 */
5464 struct pmc_mdep *
pmc_mdep_alloc(int nclasses)5465 pmc_mdep_alloc(int nclasses)
5466 {
5467 struct pmc_mdep *md;
5468 int n;
5469
5470 /* SOFT + md classes */
5471 n = 1 + nclasses;
5472 md = malloc(sizeof(struct pmc_mdep) + n * sizeof(struct pmc_classdep),
5473 M_PMC, M_WAITOK | M_ZERO);
5474 md->pmd_nclass = n;
5475
5476 /* Default methods */
5477 md->pmd_switch_in = generic_switch_in;
5478 md->pmd_switch_out = generic_switch_out;
5479
5480 /* Add base class. */
5481 pmc_soft_initialize(md);
5482 return (md);
5483 }
5484
5485 void
pmc_mdep_free(struct pmc_mdep * md)5486 pmc_mdep_free(struct pmc_mdep *md)
5487 {
5488 pmc_soft_finalize(md);
5489 free(md, M_PMC);
5490 }
5491
5492 static int
generic_switch_in(struct pmc_cpu * pc __unused,struct pmc_process * pp __unused)5493 generic_switch_in(struct pmc_cpu *pc __unused, struct pmc_process *pp __unused)
5494 {
5495
5496 return (0);
5497 }
5498
5499 static int
generic_switch_out(struct pmc_cpu * pc __unused,struct pmc_process * pp __unused)5500 generic_switch_out(struct pmc_cpu *pc __unused, struct pmc_process *pp __unused)
5501 {
5502
5503 return (0);
5504 }
5505
5506 static struct pmc_mdep *
pmc_generic_cpu_initialize(void)5507 pmc_generic_cpu_initialize(void)
5508 {
5509 struct pmc_mdep *md;
5510
5511 md = pmc_mdep_alloc(0);
5512
5513 md->pmd_cputype = PMC_CPU_GENERIC;
5514
5515 return (md);
5516 }
5517
5518 static void
pmc_generic_cpu_finalize(struct pmc_mdep * md __unused)5519 pmc_generic_cpu_finalize(struct pmc_mdep *md __unused)
5520 {
5521
5522 }
5523
5524 static int
pmc_initialize(void)5525 pmc_initialize(void)
5526 {
5527 struct pcpu *pc;
5528 struct pmc_binding pb;
5529 struct pmc_classdep *pcd;
5530 struct pmc_sample *ps;
5531 struct pmc_samplebuffer *sb;
5532 int c, cpu, error, n, ri;
5533 u_int maxcpu, domain;
5534
5535 md = NULL;
5536 error = 0;
5537
5538 pmc_stats.pm_intr_ignored = counter_u64_alloc(M_WAITOK);
5539 pmc_stats.pm_intr_processed = counter_u64_alloc(M_WAITOK);
5540 pmc_stats.pm_intr_bufferfull = counter_u64_alloc(M_WAITOK);
5541 pmc_stats.pm_syscalls = counter_u64_alloc(M_WAITOK);
5542 pmc_stats.pm_syscall_errors = counter_u64_alloc(M_WAITOK);
5543 pmc_stats.pm_buffer_requests = counter_u64_alloc(M_WAITOK);
5544 pmc_stats.pm_buffer_requests_failed = counter_u64_alloc(M_WAITOK);
5545 pmc_stats.pm_log_sweeps = counter_u64_alloc(M_WAITOK);
5546 pmc_stats.pm_merges = counter_u64_alloc(M_WAITOK);
5547 pmc_stats.pm_overwrites = counter_u64_alloc(M_WAITOK);
5548
5549 #ifdef HWPMC_DEBUG
5550 /* parse debug flags first */
5551 if (TUNABLE_STR_FETCH(PMC_SYSCTL_NAME_PREFIX "debugflags",
5552 pmc_debugstr, sizeof(pmc_debugstr))) {
5553 pmc_debugflags_parse(pmc_debugstr, pmc_debugstr +
5554 strlen(pmc_debugstr));
5555 }
5556 #endif
5557
5558 PMCDBG1(MOD,INI,0, "PMC Initialize (version %x)", PMC_VERSION);
5559
5560 /* check kernel version */
5561 if (pmc_kernel_version != PMC_VERSION) {
5562 if (pmc_kernel_version == 0)
5563 printf("hwpmc: this kernel has not been compiled with "
5564 "'options HWPMC_HOOKS'.\n");
5565 else
5566 printf("hwpmc: kernel version (0x%x) does not match "
5567 "module version (0x%x).\n", pmc_kernel_version,
5568 PMC_VERSION);
5569 return (EPROGMISMATCH);
5570 }
5571
5572 /*
5573 * check sysctl parameters
5574 */
5575 if (pmc_hashsize <= 0) {
5576 printf("hwpmc: tunable \"hashsize\"=%d must be "
5577 "greater than zero.\n", pmc_hashsize);
5578 pmc_hashsize = PMC_HASH_SIZE;
5579 }
5580
5581 if (pmc_nsamples <= 0 || pmc_nsamples > 65535) {
5582 printf("hwpmc: tunable \"nsamples\"=%d out of "
5583 "range.\n", pmc_nsamples);
5584 pmc_nsamples = PMC_NSAMPLES;
5585 }
5586 pmc_sample_mask = pmc_nsamples - 1;
5587
5588 if (pmc_callchaindepth <= 0 ||
5589 pmc_callchaindepth > PMC_CALLCHAIN_DEPTH_MAX) {
5590 printf("hwpmc: tunable \"callchaindepth\"=%d out of "
5591 "range - using %d.\n", pmc_callchaindepth,
5592 PMC_CALLCHAIN_DEPTH_MAX);
5593 pmc_callchaindepth = PMC_CALLCHAIN_DEPTH_MAX;
5594 }
5595
5596 md = pmc_md_initialize();
5597 if (md == NULL) {
5598 /* Default to generic CPU. */
5599 md = pmc_generic_cpu_initialize();
5600 if (md == NULL)
5601 return (ENOSYS);
5602 }
5603
5604 /*
5605 * Refresh classes base ri. Optional classes may come in different
5606 * order.
5607 */
5608 for (ri = c = 0; c < md->pmd_nclass; c++) {
5609 pcd = &md->pmd_classdep[c];
5610 pcd->pcd_ri = ri;
5611 ri += pcd->pcd_num;
5612 }
5613
5614 KASSERT(md->pmd_nclass >= 1 && md->pmd_npmc >= 1,
5615 ("[pmc,%d] no classes or pmcs", __LINE__));
5616
5617 /* Compute the map from row-indices to classdep pointers. */
5618 pmc_rowindex_to_classdep = malloc(sizeof(struct pmc_classdep *) *
5619 md->pmd_npmc, M_PMC, M_WAITOK | M_ZERO);
5620
5621 for (n = 0; n < md->pmd_npmc; n++)
5622 pmc_rowindex_to_classdep[n] = NULL;
5623
5624 for (ri = c = 0; c < md->pmd_nclass; c++) {
5625 pcd = &md->pmd_classdep[c];
5626 for (n = 0; n < pcd->pcd_num; n++, ri++)
5627 pmc_rowindex_to_classdep[ri] = pcd;
5628 }
5629
5630 KASSERT(ri == md->pmd_npmc,
5631 ("[pmc,%d] npmc miscomputed: ri=%d, md->npmc=%d", __LINE__,
5632 ri, md->pmd_npmc));
5633
5634 maxcpu = pmc_cpu_max();
5635
5636 /* allocate space for the per-cpu array */
5637 pmc_pcpu = malloc(maxcpu * sizeof(struct pmc_cpu *), M_PMC,
5638 M_WAITOK | M_ZERO);
5639
5640 /* per-cpu 'saved values' for managing process-mode PMCs */
5641 pmc_pcpu_saved = malloc(sizeof(pmc_value_t) * maxcpu * md->pmd_npmc,
5642 M_PMC, M_WAITOK);
5643
5644 /* Perform CPU-dependent initialization. */
5645 pmc_save_cpu_binding(&pb);
5646 error = 0;
5647 for (cpu = 0; error == 0 && cpu < maxcpu; cpu++) {
5648 if (!pmc_cpu_is_active(cpu))
5649 continue;
5650 pmc_select_cpu(cpu);
5651 pmc_pcpu[cpu] = malloc(sizeof(struct pmc_cpu) +
5652 md->pmd_npmc * sizeof(struct pmc_hw *), M_PMC,
5653 M_WAITOK | M_ZERO);
5654 for (n = 0; error == 0 && n < md->pmd_nclass; n++)
5655 if (md->pmd_classdep[n].pcd_num > 0)
5656 error = md->pmd_classdep[n].pcd_pcpu_init(md,
5657 cpu);
5658 }
5659 pmc_restore_cpu_binding(&pb);
5660
5661 if (error != 0)
5662 return (error);
5663
5664 /* allocate space for the sample array */
5665 for (cpu = 0; cpu < maxcpu; cpu++) {
5666 if (!pmc_cpu_is_active(cpu))
5667 continue;
5668 pc = pcpu_find(cpu);
5669 domain = pc->pc_domain;
5670 sb = malloc_domainset(sizeof(struct pmc_samplebuffer) +
5671 pmc_nsamples * sizeof(struct pmc_sample), M_PMC,
5672 DOMAINSET_PREF(domain), M_WAITOK | M_ZERO);
5673
5674 KASSERT(pmc_pcpu[cpu] != NULL,
5675 ("[pmc,%d] cpu=%d Null per-cpu data", __LINE__, cpu));
5676
5677 sb->ps_callchains = malloc_domainset(pmc_callchaindepth *
5678 pmc_nsamples * sizeof(uintptr_t), M_PMC,
5679 DOMAINSET_PREF(domain), M_WAITOK | M_ZERO);
5680
5681 for (n = 0, ps = sb->ps_samples; n < pmc_nsamples; n++, ps++)
5682 ps->ps_pc = sb->ps_callchains +
5683 (n * pmc_callchaindepth);
5684
5685 pmc_pcpu[cpu]->pc_sb[PMC_HR] = sb;
5686
5687 sb = malloc_domainset(sizeof(struct pmc_samplebuffer) +
5688 pmc_nsamples * sizeof(struct pmc_sample), M_PMC,
5689 DOMAINSET_PREF(domain), M_WAITOK | M_ZERO);
5690
5691 sb->ps_callchains = malloc_domainset(pmc_callchaindepth *
5692 pmc_nsamples * sizeof(uintptr_t), M_PMC,
5693 DOMAINSET_PREF(domain), M_WAITOK | M_ZERO);
5694 for (n = 0, ps = sb->ps_samples; n < pmc_nsamples; n++, ps++)
5695 ps->ps_pc = sb->ps_callchains +
5696 (n * pmc_callchaindepth);
5697
5698 pmc_pcpu[cpu]->pc_sb[PMC_SR] = sb;
5699
5700 sb = malloc_domainset(sizeof(struct pmc_samplebuffer) +
5701 pmc_nsamples * sizeof(struct pmc_sample), M_PMC,
5702 DOMAINSET_PREF(domain), M_WAITOK | M_ZERO);
5703 sb->ps_callchains = malloc_domainset(pmc_callchaindepth *
5704 pmc_nsamples * sizeof(uintptr_t), M_PMC,
5705 DOMAINSET_PREF(domain), M_WAITOK | M_ZERO);
5706 for (n = 0, ps = sb->ps_samples; n < pmc_nsamples; n++, ps++)
5707 ps->ps_pc = sb->ps_callchains + n * pmc_callchaindepth;
5708
5709 pmc_pcpu[cpu]->pc_sb[PMC_UR] = sb;
5710 }
5711
5712 /* allocate space for the row disposition array */
5713 pmc_pmcdisp = malloc(sizeof(enum pmc_mode) * md->pmd_npmc,
5714 M_PMC, M_WAITOK | M_ZERO);
5715
5716 /* mark all PMCs as available */
5717 for (n = 0; n < md->pmd_npmc; n++)
5718 PMC_MARK_ROW_FREE(n);
5719
5720 /* allocate thread hash tables */
5721 pmc_ownerhash = hashinit(pmc_hashsize, M_PMC,
5722 &pmc_ownerhashmask);
5723
5724 pmc_processhash = hashinit(pmc_hashsize, M_PMC,
5725 &pmc_processhashmask);
5726 mtx_init(&pmc_processhash_mtx, "pmc-process-hash", "pmc-leaf",
5727 MTX_SPIN);
5728
5729 CK_LIST_INIT(&pmc_ss_owners);
5730 pmc_ss_count = 0;
5731
5732 /* allocate a pool of spin mutexes */
5733 pmc_mtxpool = mtx_pool_create("pmc-leaf", pmc_mtxpool_size,
5734 MTX_SPIN);
5735
5736 PMCDBG4(MOD,INI,1, "pmc_ownerhash=%p, mask=0x%lx "
5737 "targethash=%p mask=0x%lx", pmc_ownerhash, pmc_ownerhashmask,
5738 pmc_processhash, pmc_processhashmask);
5739
5740 /* Initialize a spin mutex for the thread free list. */
5741 mtx_init(&pmc_threadfreelist_mtx, "pmc-threadfreelist", "pmc-leaf",
5742 MTX_SPIN);
5743
5744 /* Initialize the task to prune the thread free list. */
5745 TASK_INIT(&free_task, 0, pmc_thread_descriptor_pool_free_task, NULL);
5746
5747 /* register process {exit,fork,exec} handlers */
5748 pmc_exit_tag = EVENTHANDLER_REGISTER(process_exit,
5749 pmc_process_exit, NULL, EVENTHANDLER_PRI_ANY);
5750 pmc_fork_tag = EVENTHANDLER_REGISTER(process_fork,
5751 pmc_process_fork, NULL, EVENTHANDLER_PRI_ANY);
5752
5753 /* register kld event handlers */
5754 pmc_kld_load_tag = EVENTHANDLER_REGISTER(kld_load, pmc_kld_load,
5755 NULL, EVENTHANDLER_PRI_ANY);
5756 pmc_kld_unload_tag = EVENTHANDLER_REGISTER(kld_unload, pmc_kld_unload,
5757 NULL, EVENTHANDLER_PRI_ANY);
5758
5759 /* initialize logging */
5760 pmclog_initialize();
5761
5762 /* set hook functions */
5763 pmc_intr = md->pmd_intr;
5764 wmb();
5765 pmc_hook = pmc_hook_handler;
5766
5767 if (error == 0) {
5768 printf(PMC_MODULE_NAME ":");
5769 for (n = 0; n < md->pmd_nclass; n++) {
5770 if (md->pmd_classdep[n].pcd_num == 0)
5771 continue;
5772 pcd = &md->pmd_classdep[n];
5773 printf(" %s/%d/%d/0x%b",
5774 pmc_name_of_pmcclass(pcd->pcd_class),
5775 pcd->pcd_num,
5776 pcd->pcd_width,
5777 pcd->pcd_caps,
5778 "\20"
5779 "\1INT\2USR\3SYS\4EDG\5THR"
5780 "\6REA\7WRI\10INV\11QUA\12PRC"
5781 "\13TAG\14CSC");
5782 }
5783 printf("\n");
5784 }
5785
5786 return (error);
5787 }
5788
5789 /* prepare to be unloaded */
5790 static void
pmc_cleanup(void)5791 pmc_cleanup(void)
5792 {
5793 struct pmc_binding pb;
5794 struct pmc_owner *po, *tmp;
5795 struct pmc_ownerhash *ph;
5796 struct pmc_processhash *prh __pmcdbg_used;
5797 u_int maxcpu;
5798 int cpu, c;
5799
5800 PMCDBG0(MOD,INI,0, "cleanup");
5801
5802 /* switch off sampling */
5803 CPU_FOREACH(cpu)
5804 DPCPU_ID_SET(cpu, pmc_sampled, 0);
5805 pmc_intr = NULL;
5806
5807 sx_xlock(&pmc_sx);
5808 if (pmc_hook == NULL) { /* being unloaded already */
5809 sx_xunlock(&pmc_sx);
5810 return;
5811 }
5812
5813 pmc_hook = NULL; /* prevent new threads from entering module */
5814
5815 /* deregister event handlers */
5816 EVENTHANDLER_DEREGISTER(process_fork, pmc_fork_tag);
5817 EVENTHANDLER_DEREGISTER(process_exit, pmc_exit_tag);
5818 EVENTHANDLER_DEREGISTER(kld_load, pmc_kld_load_tag);
5819 EVENTHANDLER_DEREGISTER(kld_unload, pmc_kld_unload_tag);
5820
5821 /* send SIGBUS to all owner threads, free up allocations */
5822 if (pmc_ownerhash != NULL) {
5823 for (ph = pmc_ownerhash;
5824 ph <= &pmc_ownerhash[pmc_ownerhashmask];
5825 ph++) {
5826 LIST_FOREACH_SAFE(po, ph, po_next, tmp) {
5827 pmc_remove_owner(po);
5828
5829 PMCDBG3(MOD,INI,2,
5830 "cleanup signal proc=%p (%d, %s)",
5831 po->po_owner, po->po_owner->p_pid,
5832 po->po_owner->p_comm);
5833
5834 PROC_LOCK(po->po_owner);
5835 kern_psignal(po->po_owner, SIGBUS);
5836 PROC_UNLOCK(po->po_owner);
5837
5838 pmc_destroy_owner_descriptor(po);
5839 }
5840 }
5841 }
5842
5843 /* reclaim allocated data structures */
5844 taskqueue_drain(taskqueue_fast, &free_task);
5845 mtx_destroy(&pmc_threadfreelist_mtx);
5846 pmc_thread_descriptor_pool_drain();
5847
5848 if (pmc_mtxpool != NULL)
5849 mtx_pool_destroy(&pmc_mtxpool);
5850
5851 mtx_destroy(&pmc_processhash_mtx);
5852 if (pmc_processhash != NULL) {
5853 #ifdef HWPMC_DEBUG
5854 struct pmc_process *pp;
5855
5856 PMCDBG0(MOD,INI,3, "destroy process hash");
5857 for (prh = pmc_processhash;
5858 prh <= &pmc_processhash[pmc_processhashmask];
5859 prh++)
5860 LIST_FOREACH(pp, prh, pp_next)
5861 PMCDBG1(MOD,INI,3, "pid=%d", pp->pp_proc->p_pid);
5862 #endif
5863
5864 hashdestroy(pmc_processhash, M_PMC, pmc_processhashmask);
5865 pmc_processhash = NULL;
5866 }
5867
5868 if (pmc_ownerhash != NULL) {
5869 PMCDBG0(MOD,INI,3, "destroy owner hash");
5870 hashdestroy(pmc_ownerhash, M_PMC, pmc_ownerhashmask);
5871 pmc_ownerhash = NULL;
5872 }
5873
5874 KASSERT(CK_LIST_EMPTY(&pmc_ss_owners),
5875 ("[pmc,%d] Global SS owner list not empty", __LINE__));
5876 KASSERT(pmc_ss_count == 0,
5877 ("[pmc,%d] Global SS count not empty", __LINE__));
5878
5879 /* do processor and pmc-class dependent cleanup */
5880 maxcpu = pmc_cpu_max();
5881
5882 PMCDBG0(MOD,INI,3, "md cleanup");
5883 if (md) {
5884 pmc_save_cpu_binding(&pb);
5885 for (cpu = 0; cpu < maxcpu; cpu++) {
5886 PMCDBG2(MOD,INI,1,"pmc-cleanup cpu=%d pcs=%p",
5887 cpu, pmc_pcpu[cpu]);
5888 if (!pmc_cpu_is_active(cpu) || pmc_pcpu[cpu] == NULL)
5889 continue;
5890
5891 pmc_select_cpu(cpu);
5892 for (c = 0; c < md->pmd_nclass; c++) {
5893 if (md->pmd_classdep[c].pcd_num > 0) {
5894 md->pmd_classdep[c].pcd_pcpu_fini(md,
5895 cpu);
5896 }
5897 }
5898 }
5899
5900 if (md->pmd_cputype == PMC_CPU_GENERIC)
5901 pmc_generic_cpu_finalize(md);
5902 else
5903 pmc_md_finalize(md);
5904
5905 pmc_mdep_free(md);
5906 md = NULL;
5907 pmc_restore_cpu_binding(&pb);
5908 }
5909
5910 /* Free per-cpu descriptors. */
5911 for (cpu = 0; cpu < maxcpu; cpu++) {
5912 if (!pmc_cpu_is_active(cpu))
5913 continue;
5914 KASSERT(pmc_pcpu[cpu]->pc_sb[PMC_HR] != NULL,
5915 ("[pmc,%d] Null hw cpu sample buffer cpu=%d", __LINE__,
5916 cpu));
5917 KASSERT(pmc_pcpu[cpu]->pc_sb[PMC_SR] != NULL,
5918 ("[pmc,%d] Null sw cpu sample buffer cpu=%d", __LINE__,
5919 cpu));
5920 KASSERT(pmc_pcpu[cpu]->pc_sb[PMC_UR] != NULL,
5921 ("[pmc,%d] Null userret cpu sample buffer cpu=%d", __LINE__,
5922 cpu));
5923 free(pmc_pcpu[cpu]->pc_sb[PMC_HR]->ps_callchains, M_PMC);
5924 free(pmc_pcpu[cpu]->pc_sb[PMC_HR], M_PMC);
5925 free(pmc_pcpu[cpu]->pc_sb[PMC_SR]->ps_callchains, M_PMC);
5926 free(pmc_pcpu[cpu]->pc_sb[PMC_SR], M_PMC);
5927 free(pmc_pcpu[cpu]->pc_sb[PMC_UR]->ps_callchains, M_PMC);
5928 free(pmc_pcpu[cpu]->pc_sb[PMC_UR], M_PMC);
5929 free(pmc_pcpu[cpu], M_PMC);
5930 }
5931
5932 free(pmc_pcpu, M_PMC);
5933 pmc_pcpu = NULL;
5934
5935 free(pmc_pcpu_saved, M_PMC);
5936 pmc_pcpu_saved = NULL;
5937
5938 if (pmc_pmcdisp != NULL) {
5939 free(pmc_pmcdisp, M_PMC);
5940 pmc_pmcdisp = NULL;
5941 }
5942
5943 if (pmc_rowindex_to_classdep != NULL) {
5944 free(pmc_rowindex_to_classdep, M_PMC);
5945 pmc_rowindex_to_classdep = NULL;
5946 }
5947
5948 pmclog_shutdown();
5949 counter_u64_free(pmc_stats.pm_intr_ignored);
5950 counter_u64_free(pmc_stats.pm_intr_processed);
5951 counter_u64_free(pmc_stats.pm_intr_bufferfull);
5952 counter_u64_free(pmc_stats.pm_syscalls);
5953 counter_u64_free(pmc_stats.pm_syscall_errors);
5954 counter_u64_free(pmc_stats.pm_buffer_requests);
5955 counter_u64_free(pmc_stats.pm_buffer_requests_failed);
5956 counter_u64_free(pmc_stats.pm_log_sweeps);
5957 counter_u64_free(pmc_stats.pm_merges);
5958 counter_u64_free(pmc_stats.pm_overwrites);
5959 sx_xunlock(&pmc_sx); /* we are done */
5960 }
5961
5962 /*
5963 * The function called at load/unload.
5964 */
5965 static int
load(struct module * module __unused,int cmd,void * arg __unused)5966 load(struct module *module __unused, int cmd, void *arg __unused)
5967 {
5968 int error;
5969
5970 error = 0;
5971
5972 switch (cmd) {
5973 case MOD_LOAD:
5974 /* initialize the subsystem */
5975 error = pmc_initialize();
5976 if (error != 0)
5977 break;
5978 PMCDBG2(MOD,INI,1, "syscall=%d maxcpu=%d", pmc_syscall_num,
5979 pmc_cpu_max());
5980 break;
5981 case MOD_UNLOAD:
5982 case MOD_SHUTDOWN:
5983 pmc_cleanup();
5984 PMCDBG0(MOD,INI,1, "unloaded");
5985 break;
5986 default:
5987 error = EINVAL;
5988 break;
5989 }
5990
5991 return (error);
5992 }
5993