]> CyberLeo.Net >> Repos - FreeBSD/releng/7.2.git/blob - sys/dev/hwpmc/hwpmc_mod.c
Create releng/7.2 from stable/7 in preparation for 7.2-RELEASE.
[FreeBSD/releng/7.2.git] / sys / dev / hwpmc / hwpmc_mod.c
1 /*-
2  * Copyright (c) 2003-2006 Joseph Koshy
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  */
27
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30
31 #include <sys/param.h>
32 #include <sys/eventhandler.h>
33 #include <sys/jail.h>
34 #include <sys/kernel.h>
35 #include <sys/kthread.h>
36 #include <sys/limits.h>
37 #include <sys/lock.h>
38 #include <sys/malloc.h>
39 #include <sys/module.h>
40 #include <sys/mutex.h>
41 #include <sys/pmc.h>
42 #include <sys/pmckern.h>
43 #include <sys/pmclog.h>
44 #include <sys/priv.h>
45 #include <sys/proc.h>
46 #include <sys/queue.h>
47 #include <sys/resourcevar.h>
48 #include <sys/sched.h>
49 #include <sys/signalvar.h>
50 #include <sys/smp.h>
51 #include <sys/sx.h>
52 #include <sys/sysctl.h>
53 #include <sys/sysent.h>
54 #include <sys/systm.h>
55 #include <sys/vnode.h>
56
57 #include <sys/linker.h>         /* needs to be after <sys/malloc.h> */
58
59 #include <machine/atomic.h>
60 #include <machine/md_var.h>
61
62 /*
63  * Types
64  */
65
66 enum pmc_flags {
67         PMC_FLAG_NONE     = 0x00, /* do nothing */
68         PMC_FLAG_REMOVE   = 0x01, /* atomically remove entry from hash */
69         PMC_FLAG_ALLOCATE = 0x02, /* add entry to hash if not found */
70 };
71
72 /*
73  * The offset in sysent where the syscall is allocated.
74  */
75
76 static int pmc_syscall_num = NO_SYSCALL;
77 struct pmc_cpu          **pmc_pcpu;      /* per-cpu state */
78 pmc_value_t             *pmc_pcpu_saved; /* saved PMC values: CSW handling */
79
80 #define PMC_PCPU_SAVED(C,R)     pmc_pcpu_saved[(R) + md->pmd_npmc*(C)]
81
82 struct mtx_pool         *pmc_mtxpool;
83 static int              *pmc_pmcdisp;    /* PMC row dispositions */
84
85 #define PMC_ROW_DISP_IS_FREE(R)         (pmc_pmcdisp[(R)] == 0)
86 #define PMC_ROW_DISP_IS_THREAD(R)       (pmc_pmcdisp[(R)] > 0)
87 #define PMC_ROW_DISP_IS_STANDALONE(R)   (pmc_pmcdisp[(R)] < 0)
88
89 #define PMC_MARK_ROW_FREE(R) do {                                         \
90         pmc_pmcdisp[(R)] = 0;                                             \
91 } while (0)
92
93 #define PMC_MARK_ROW_STANDALONE(R) do {                                   \
94         KASSERT(pmc_pmcdisp[(R)] <= 0, ("[pmc,%d] row disposition error", \
95                     __LINE__));                                           \
96         atomic_add_int(&pmc_pmcdisp[(R)], -1);                            \
97         KASSERT(pmc_pmcdisp[(R)] >= (-mp_ncpus), ("[pmc,%d] row "         \
98                 "disposition error", __LINE__));                          \
99 } while (0)
100
101 #define PMC_UNMARK_ROW_STANDALONE(R) do {                                 \
102         atomic_add_int(&pmc_pmcdisp[(R)], 1);                             \
103         KASSERT(pmc_pmcdisp[(R)] <= 0, ("[pmc,%d] row disposition error", \
104                     __LINE__));                                           \
105 } while (0)
106
107 #define PMC_MARK_ROW_THREAD(R) do {                                       \
108         KASSERT(pmc_pmcdisp[(R)] >= 0, ("[pmc,%d] row disposition error", \
109                     __LINE__));                                           \
110         atomic_add_int(&pmc_pmcdisp[(R)], 1);                             \
111 } while (0)
112
113 #define PMC_UNMARK_ROW_THREAD(R) do {                                     \
114         atomic_add_int(&pmc_pmcdisp[(R)], -1);                            \
115         KASSERT(pmc_pmcdisp[(R)] >= 0, ("[pmc,%d] row disposition error", \
116                     __LINE__));                                           \
117 } while (0)
118
119
120 /* various event handlers */
121 static eventhandler_tag pmc_exit_tag, pmc_fork_tag;
122
123 /* Module statistics */
124 struct pmc_op_getdriverstats pmc_stats;
125
126 /* Machine/processor dependent operations */
127 struct pmc_mdep  *md;
128
129 /*
130  * Hash tables mapping owner processes and target threads to PMCs.
131  */
132
133 struct mtx pmc_processhash_mtx;         /* spin mutex */
134 static u_long pmc_processhashmask;
135 static LIST_HEAD(pmc_processhash, pmc_process)  *pmc_processhash;
136
137 /*
138  * Hash table of PMC owner descriptors.  This table is protected by
139  * the shared PMC "sx" lock.
140  */
141
142 static u_long pmc_ownerhashmask;
143 static LIST_HEAD(pmc_ownerhash, pmc_owner)      *pmc_ownerhash;
144
145 /*
146  * List of PMC owners with system-wide sampling PMCs.
147  */
148
149 static LIST_HEAD(, pmc_owner)                   pmc_ss_owners;
150
151
152 /*
153  * Prototypes
154  */
155
156 #ifdef  DEBUG
157 static int      pmc_debugflags_sysctl_handler(SYSCTL_HANDLER_ARGS);
158 static int      pmc_debugflags_parse(char *newstr, char *fence);
159 #endif
160
161 static int      load(struct module *module, int cmd, void *arg);
162 static int      pmc_attach_process(struct proc *p, struct pmc *pm);
163 static struct pmc *pmc_allocate_pmc_descriptor(void);
164 static struct pmc_owner *pmc_allocate_owner_descriptor(struct proc *p);
165 static int      pmc_attach_one_process(struct proc *p, struct pmc *pm);
166 static int      pmc_can_allocate_rowindex(struct proc *p, unsigned int ri,
167     int cpu);
168 static int      pmc_can_attach(struct pmc *pm, struct proc *p);
169 static void     pmc_cleanup(void);
170 static int      pmc_detach_process(struct proc *p, struct pmc *pm);
171 static int      pmc_detach_one_process(struct proc *p, struct pmc *pm,
172     int flags);
173 static void     pmc_destroy_owner_descriptor(struct pmc_owner *po);
174 static struct pmc_owner *pmc_find_owner_descriptor(struct proc *p);
175 static int      pmc_find_pmc(pmc_id_t pmcid, struct pmc **pm);
176 static struct pmc *pmc_find_pmc_descriptor_in_process(struct pmc_owner *po,
177     pmc_id_t pmc);
178 static struct pmc_process *pmc_find_process_descriptor(struct proc *p,
179     uint32_t mode);
180 static void     pmc_force_context_switch(void);
181 static void     pmc_link_target_process(struct pmc *pm,
182     struct pmc_process *pp);
183 static void     pmc_maybe_remove_owner(struct pmc_owner *po);
184 static void     pmc_process_csw_in(struct thread *td);
185 static void     pmc_process_csw_out(struct thread *td);
186 static void     pmc_process_exit(void *arg, struct proc *p);
187 static void     pmc_process_fork(void *arg, struct proc *p1,
188     struct proc *p2, int n);
189 static void     pmc_process_samples(int cpu);
190 static void     pmc_release_pmc_descriptor(struct pmc *pmc);
191 static void     pmc_remove_owner(struct pmc_owner *po);
192 static void     pmc_remove_process_descriptor(struct pmc_process *pp);
193 static void     pmc_restore_cpu_binding(struct pmc_binding *pb);
194 static void     pmc_save_cpu_binding(struct pmc_binding *pb);
195 static void     pmc_select_cpu(int cpu);
196 static int      pmc_start(struct pmc *pm);
197 static int      pmc_stop(struct pmc *pm);
198 static int      pmc_syscall_handler(struct thread *td, void *syscall_args);
199 static void     pmc_unlink_target_process(struct pmc *pmc,
200     struct pmc_process *pp);
201
202 /*
203  * Kernel tunables and sysctl(8) interface.
204  */
205
206 SYSCTL_NODE(_kern, OID_AUTO, hwpmc, CTLFLAG_RW, 0, "HWPMC parameters");
207
208 #ifdef  DEBUG
209 struct pmc_debugflags pmc_debugflags = PMC_DEBUG_DEFAULT_FLAGS;
210 char    pmc_debugstr[PMC_DEBUG_STRSIZE];
211 TUNABLE_STR(PMC_SYSCTL_NAME_PREFIX "debugflags", pmc_debugstr,
212     sizeof(pmc_debugstr));
213 SYSCTL_PROC(_kern_hwpmc, OID_AUTO, debugflags,
214     CTLTYPE_STRING|CTLFLAG_RW|CTLFLAG_TUN,
215     0, 0, pmc_debugflags_sysctl_handler, "A", "debug flags");
216 #endif
217
218 /*
219  * kern.hwpmc.hashrows -- determines the number of rows in the
220  * of the hash table used to look up threads
221  */
222
223 static int pmc_hashsize = PMC_HASH_SIZE;
224 TUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "hashsize", &pmc_hashsize);
225 SYSCTL_INT(_kern_hwpmc, OID_AUTO, hashsize, CTLFLAG_TUN|CTLFLAG_RD,
226     &pmc_hashsize, 0, "rows in hash tables");
227
228 /*
229  * kern.hwpmc.nsamples --- number of PC samples per CPU
230  */
231
232 static int pmc_nsamples = PMC_NSAMPLES;
233 TUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "nsamples", &pmc_nsamples);
234 SYSCTL_INT(_kern_hwpmc, OID_AUTO, nsamples, CTLFLAG_TUN|CTLFLAG_RD,
235     &pmc_nsamples, 0, "number of PC samples per CPU");
236
237 /*
238  * kern.hwpmc.mtxpoolsize -- number of mutexes in the mutex pool.
239  */
240
241 static int pmc_mtxpool_size = PMC_MTXPOOL_SIZE;
242 TUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "mtxpoolsize", &pmc_mtxpool_size);
243 SYSCTL_INT(_kern_hwpmc, OID_AUTO, mtxpoolsize, CTLFLAG_TUN|CTLFLAG_RD,
244     &pmc_mtxpool_size, 0, "size of spin mutex pool");
245
246
247 /*
248  * security.bsd.unprivileged_syspmcs -- allow non-root processes to
249  * allocate system-wide PMCs.
250  *
251  * Allowing unprivileged processes to allocate system PMCs is convenient
252  * if system-wide measurements need to be taken concurrently with other
253  * per-process measurements.  This feature is turned off by default.
254  */
255
256 static int pmc_unprivileged_syspmcs = 0;
257 TUNABLE_INT("security.bsd.unprivileged_syspmcs", &pmc_unprivileged_syspmcs);
258 SYSCTL_INT(_security_bsd, OID_AUTO, unprivileged_syspmcs, CTLFLAG_RW,
259     &pmc_unprivileged_syspmcs, 0,
260     "allow unprivileged process to allocate system PMCs");
261
262 /*
263  * Hash function.  Discard the lower 2 bits of the pointer since
264  * these are always zero for our uses.  The hash multiplier is
265  * round((2^LONG_BIT) * ((sqrt(5)-1)/2)).
266  */
267
268 #if     LONG_BIT == 64
269 #define _PMC_HM         11400714819323198486u
270 #elif   LONG_BIT == 32
271 #define _PMC_HM         2654435769u
272 #else
273 #error  Must know the size of 'long' to compile
274 #endif
275
276 #define PMC_HASH_PTR(P,M)       ((((unsigned long) (P) >> 2) * _PMC_HM) & (M))
277
278 /*
279  * Syscall structures
280  */
281
282 /* The `sysent' for the new syscall */
283 static struct sysent pmc_sysent = {
284         2,                      /* sy_narg */
285         pmc_syscall_handler     /* sy_call */
286 };
287
288 static struct syscall_module_data pmc_syscall_mod = {
289         load,
290         NULL,
291         &pmc_syscall_num,
292         &pmc_sysent,
293         { 0, NULL }
294 };
295
296 static moduledata_t pmc_mod = {
297         PMC_MODULE_NAME,
298         syscall_module_handler,
299         &pmc_syscall_mod
300 };
301
302 DECLARE_MODULE(pmc, pmc_mod, SI_SUB_SMP, SI_ORDER_ANY);
303 MODULE_VERSION(pmc, PMC_VERSION);
304
305 #ifdef  DEBUG
306 enum pmc_dbgparse_state {
307         PMCDS_WS,               /* in whitespace */
308         PMCDS_MAJOR,            /* seen a major keyword */
309         PMCDS_MINOR
310 };
311
312 static int
313 pmc_debugflags_parse(char *newstr, char *fence)
314 {
315         char c, *p, *q;
316         struct pmc_debugflags *tmpflags;
317         int error, found, *newbits, tmp;
318         size_t kwlen;
319
320         MALLOC(tmpflags, struct pmc_debugflags *, sizeof(*tmpflags),
321             M_PMC, M_WAITOK|M_ZERO);
322
323         p = newstr;
324         error = 0;
325
326         for (; p < fence && (c = *p); p++) {
327
328                 /* skip white space */
329                 if (c == ' ' || c == '\t')
330                         continue;
331
332                 /* look for a keyword followed by "=" */
333                 for (q = p; p < fence && (c = *p) && c != '='; p++)
334                         ;
335                 if (c != '=') {
336                         error = EINVAL;
337                         goto done;
338                 }
339
340                 kwlen = p - q;
341                 newbits = NULL;
342
343                 /* lookup flag group name */
344 #define DBG_SET_FLAG_MAJ(S,F)                                           \
345                 if (kwlen == sizeof(S)-1 && strncmp(q, S, kwlen) == 0)  \
346                         newbits = &tmpflags->pdb_ ## F;
347
348                 DBG_SET_FLAG_MAJ("cpu",         CPU);
349                 DBG_SET_FLAG_MAJ("csw",         CSW);
350                 DBG_SET_FLAG_MAJ("logging",     LOG);
351                 DBG_SET_FLAG_MAJ("module",      MOD);
352                 DBG_SET_FLAG_MAJ("md",          MDP);
353                 DBG_SET_FLAG_MAJ("owner",       OWN);
354                 DBG_SET_FLAG_MAJ("pmc",         PMC);
355                 DBG_SET_FLAG_MAJ("process",     PRC);
356                 DBG_SET_FLAG_MAJ("sampling",    SAM);
357
358                 if (newbits == NULL) {
359                         error = EINVAL;
360                         goto done;
361                 }
362
363                 p++;            /* skip the '=' */
364
365                 /* Now parse the individual flags */
366                 tmp = 0;
367         newflag:
368                 for (q = p; p < fence && (c = *p); p++)
369                         if (c == ' ' || c == '\t' || c == ',')
370                                 break;
371
372                 /* p == fence or c == ws or c == "," or c == 0 */
373
374                 if ((kwlen = p - q) == 0) {
375                         *newbits = tmp;
376                         continue;
377                 }
378
379                 found = 0;
380 #define DBG_SET_FLAG_MIN(S,F)                                           \
381                 if (kwlen == sizeof(S)-1 && strncmp(q, S, kwlen) == 0)  \
382                         tmp |= found = (1 << PMC_DEBUG_MIN_ ## F)
383
384                 /* a '*' denotes all possible flags in the group */
385                 if (kwlen == 1 && *q == '*')
386                         tmp = found = ~0;
387                 /* look for individual flag names */
388                 DBG_SET_FLAG_MIN("allocaterow", ALR);
389                 DBG_SET_FLAG_MIN("allocate",    ALL);
390                 DBG_SET_FLAG_MIN("attach",      ATT);
391                 DBG_SET_FLAG_MIN("bind",        BND);
392                 DBG_SET_FLAG_MIN("config",      CFG);
393                 DBG_SET_FLAG_MIN("exec",        EXC);
394                 DBG_SET_FLAG_MIN("exit",        EXT);
395                 DBG_SET_FLAG_MIN("find",        FND);
396                 DBG_SET_FLAG_MIN("flush",       FLS);
397                 DBG_SET_FLAG_MIN("fork",        FRK);
398                 DBG_SET_FLAG_MIN("getbuf",      GTB);
399                 DBG_SET_FLAG_MIN("hook",        PMH);
400                 DBG_SET_FLAG_MIN("init",        INI);
401                 DBG_SET_FLAG_MIN("intr",        INT);
402                 DBG_SET_FLAG_MIN("linktarget",  TLK);
403                 DBG_SET_FLAG_MIN("mayberemove", OMR);
404                 DBG_SET_FLAG_MIN("ops",         OPS);
405                 DBG_SET_FLAG_MIN("read",        REA);
406                 DBG_SET_FLAG_MIN("register",    REG);
407                 DBG_SET_FLAG_MIN("release",     REL);
408                 DBG_SET_FLAG_MIN("remove",      ORM);
409                 DBG_SET_FLAG_MIN("sample",      SAM);
410                 DBG_SET_FLAG_MIN("scheduleio",  SIO);
411                 DBG_SET_FLAG_MIN("select",      SEL);
412                 DBG_SET_FLAG_MIN("signal",      SIG);
413                 DBG_SET_FLAG_MIN("swi",         SWI);
414                 DBG_SET_FLAG_MIN("swo",         SWO);
415                 DBG_SET_FLAG_MIN("start",       STA);
416                 DBG_SET_FLAG_MIN("stop",        STO);
417                 DBG_SET_FLAG_MIN("syscall",     PMS);
418                 DBG_SET_FLAG_MIN("unlinktarget", TUL);
419                 DBG_SET_FLAG_MIN("write",       WRI);
420                 if (found == 0) {
421                         /* unrecognized flag name */
422                         error = EINVAL;
423                         goto done;
424                 }
425
426                 if (c == 0 || c == ' ' || c == '\t') {  /* end of flag group */
427                         *newbits = tmp;
428                         continue;
429                 }
430
431                 p++;
432                 goto newflag;
433         }
434
435         /* save the new flag set */
436         bcopy(tmpflags, &pmc_debugflags, sizeof(pmc_debugflags));
437
438  done:
439         FREE(tmpflags, M_PMC);
440         return error;
441 }
442
443 static int
444 pmc_debugflags_sysctl_handler(SYSCTL_HANDLER_ARGS)
445 {
446         char *fence, *newstr;
447         int error;
448         unsigned int n;
449
450         (void) arg1; (void) arg2; /* unused parameters */
451
452         n = sizeof(pmc_debugstr);
453         MALLOC(newstr, char *, n, M_PMC, M_ZERO|M_WAITOK);
454         (void) strlcpy(newstr, pmc_debugstr, n);
455
456         error = sysctl_handle_string(oidp, newstr, n, req);
457
458         /* if there is a new string, parse and copy it */
459         if (error == 0 && req->newptr != NULL) {
460                 fence = newstr + (n < req->newlen ? n : req->newlen + 1);
461                 if ((error = pmc_debugflags_parse(newstr, fence)) == 0)
462                         (void) strlcpy(pmc_debugstr, newstr,
463                             sizeof(pmc_debugstr));
464         }
465
466         FREE(newstr, M_PMC);
467
468         return error;
469 }
470 #endif
471
472 /*
473  * Concurrency Control
474  *
475  * The driver manages the following data structures:
476  *
477  *   - target process descriptors, one per target process
478  *   - owner process descriptors (and attached lists), one per owner process
479  *   - lookup hash tables for owner and target processes
480  *   - PMC descriptors (and attached lists)
481  *   - per-cpu hardware state
482  *   - the 'hook' variable through which the kernel calls into
483  *     this module
484  *   - the machine hardware state (managed by the MD layer)
485  *
486  * These data structures are accessed from:
487  *
488  * - thread context-switch code
489  * - interrupt handlers (possibly on multiple cpus)
490  * - kernel threads on multiple cpus running on behalf of user
491  *   processes doing system calls
492  * - this driver's private kernel threads
493  *
494  * = Locks and Locking strategy =
495  *
496  * The driver uses four locking strategies for its operation:
497  *
498  * - The global SX lock "pmc_sx" is used to protect internal
499  *   data structures.
500  *
501  *   Calls into the module by syscall() start with this lock being
502  *   held in exclusive mode.  Depending on the requested operation,
503  *   the lock may be downgraded to 'shared' mode to allow more
504  *   concurrent readers into the module.  Calls into the module from
505  *   other parts of the kernel acquire the lock in shared mode.
506  *
507  *   This SX lock is held in exclusive mode for any operations that
508  *   modify the linkages between the driver's internal data structures.
509  *
510  *   The 'pmc_hook' function pointer is also protected by this lock.
511  *   It is only examined with the sx lock held in exclusive mode.  The
512  *   kernel module is allowed to be unloaded only with the sx lock held
513  *   in exclusive mode.  In normal syscall handling, after acquiring the
514  *   pmc_sx lock we first check that 'pmc_hook' is non-null before
515  *   proceeding.  This prevents races between the thread unloading the module
516  *   and other threads seeking to use the module.
517  *
518  * - Lookups of target process structures and owner process structures
519  *   cannot use the global "pmc_sx" SX lock because these lookups need
520  *   to happen during context switches and in other critical sections
521  *   where sleeping is not allowed.  We protect these lookup tables
522  *   with their own private spin-mutexes, "pmc_processhash_mtx" and
523  *   "pmc_ownerhash_mtx".
524  *
525  * - Interrupt handlers work in a lock free manner.  At interrupt
526  *   time, handlers look at the PMC pointer (phw->phw_pmc) configured
527  *   when the PMC was started.  If this pointer is NULL, the interrupt
528  *   is ignored after updating driver statistics.  We ensure that this
529  *   pointer is set (using an atomic operation if necessary) before the
530  *   PMC hardware is started.  Conversely, this pointer is unset atomically
531  *   only after the PMC hardware is stopped.
532  *
533  *   We ensure that everything needed for the operation of an
534  *   interrupt handler is available without it needing to acquire any
535  *   locks.  We also ensure that a PMC's software state is destroyed only
536  *   after the PMC is taken off hardware (on all CPUs).
537  *
538  * - Context-switch handling with process-private PMCs needs more
539  *   care.
540  *
541  *   A given process may be the target of multiple PMCs.  For example,
542  *   PMCATTACH and PMCDETACH may be requested by a process on one CPU
543  *   while the target process is running on another.  A PMC could also
544  *   be getting released because its owner is exiting.  We tackle
545  *   these situations in the following manner:
546  *
547  *   - each target process structure 'pmc_process' has an array
548  *     of 'struct pmc *' pointers, one for each hardware PMC.
549  *
550  *   - At context switch IN time, each "target" PMC in RUNNING state
551  *     gets started on hardware and a pointer to each PMC is copied into
552  *     the per-cpu phw array.  The 'runcount' for the PMC is
553  *     incremented.
554  *
555  *   - At context switch OUT time, all process-virtual PMCs are stopped
556  *     on hardware.  The saved value is added to the PMCs value field
557  *     only if the PMC is in a non-deleted state (the PMCs state could
558  *     have changed during the current time slice).
559  *
560  *     Note that since in-between a switch IN on a processor and a switch
561  *     OUT, the PMC could have been released on another CPU.  Therefore
562  *     context switch OUT always looks at the hardware state to turn
563  *     OFF PMCs and will update a PMC's saved value only if reachable
564  *     from the target process record.
565  *
566  *   - OP PMCRELEASE could be called on a PMC at any time (the PMC could
567  *     be attached to many processes at the time of the call and could
568  *     be active on multiple CPUs).
569  *
570  *     We prevent further scheduling of the PMC by marking it as in
571  *     state 'DELETED'.  If the runcount of the PMC is non-zero then
572  *     this PMC is currently running on a CPU somewhere.  The thread
573  *     doing the PMCRELEASE operation waits by repeatedly doing a
574  *     pause() till the runcount comes to zero.
575  *
576  * The contents of a PMC descriptor (struct pmc) are protected using
577  * a spin-mutex.  In order to save space, we use a mutex pool.
578  *
579  * In terms of lock types used by witness(4), we use:
580  * - Type "pmc-sx", used by the global SX lock.
581  * - Type "pmc-sleep", for sleep mutexes used by logger threads.
582  * - Type "pmc-per-proc", for protecting PMC owner descriptors.
583  * - Type "pmc-leaf", used for all other spin mutexes.
584  */
585
586 /*
587  * save the cpu binding of the current kthread
588  */
589
590 static void
591 pmc_save_cpu_binding(struct pmc_binding *pb)
592 {
593         PMCDBG(CPU,BND,2, "%s", "save-cpu");
594         thread_lock(curthread);
595         pb->pb_bound = sched_is_bound(curthread);
596         pb->pb_cpu   = curthread->td_oncpu;
597         thread_unlock(curthread);
598         PMCDBG(CPU,BND,2, "save-cpu cpu=%d", pb->pb_cpu);
599 }
600
601 /*
602  * restore the cpu binding of the current thread
603  */
604
605 static void
606 pmc_restore_cpu_binding(struct pmc_binding *pb)
607 {
608         PMCDBG(CPU,BND,2, "restore-cpu curcpu=%d restore=%d",
609             curthread->td_oncpu, pb->pb_cpu);
610         thread_lock(curthread);
611         if (pb->pb_bound)
612                 sched_bind(curthread, pb->pb_cpu);
613         else
614                 sched_unbind(curthread);
615         thread_unlock(curthread);
616         PMCDBG(CPU,BND,2, "%s", "restore-cpu done");
617 }
618
619 /*
620  * move execution over the specified cpu and bind it there.
621  */
622
623 static void
624 pmc_select_cpu(int cpu)
625 {
626         KASSERT(cpu >= 0 && cpu < mp_ncpus,
627             ("[pmc,%d] bad cpu number %d", __LINE__, cpu));
628
629         /* never move to a disabled CPU */
630         KASSERT(pmc_cpu_is_disabled(cpu) == 0, ("[pmc,%d] selecting "
631             "disabled CPU %d", __LINE__, cpu));
632
633         PMCDBG(CPU,SEL,2, "select-cpu cpu=%d", cpu);
634         thread_lock(curthread);
635         sched_bind(curthread, cpu);
636         thread_unlock(curthread);
637
638         KASSERT(curthread->td_oncpu == cpu,
639             ("[pmc,%d] CPU not bound [cpu=%d, curr=%d]", __LINE__,
640                 cpu, curthread->td_oncpu));
641
642         PMCDBG(CPU,SEL,2, "select-cpu cpu=%d ok", cpu);
643 }
644
645 /*
646  * Force a context switch.
647  *
648  * We do this by pause'ing for 1 tick -- invoking mi_switch() is not
649  * guaranteed to force a context switch.
650  */
651
652 static void
653 pmc_force_context_switch(void)
654 {
655
656         pause("pmcctx", 1);
657 }
658
659 /*
660  * Get the file name for an executable.  This is a simple wrapper
661  * around vn_fullpath(9).
662  */
663
664 static void
665 pmc_getfilename(struct vnode *v, char **fullpath, char **freepath)
666 {
667         struct thread *td;
668
669         td = curthread;
670         *fullpath = "unknown";
671         *freepath = NULL;
672         vn_fullpath(td, v, fullpath, freepath);
673 }
674
675 /*
676  * remove an process owning PMCs
677  */
678
679 void
680 pmc_remove_owner(struct pmc_owner *po)
681 {
682         struct pmc *pm, *tmp;
683
684         sx_assert(&pmc_sx, SX_XLOCKED);
685
686         PMCDBG(OWN,ORM,1, "remove-owner po=%p", po);
687
688         /* Remove descriptor from the owner hash table */
689         LIST_REMOVE(po, po_next);
690
691         /* release all owned PMC descriptors */
692         LIST_FOREACH_SAFE(pm, &po->po_pmcs, pm_next, tmp) {
693                 PMCDBG(OWN,ORM,2, "pmc=%p", pm);
694                 KASSERT(pm->pm_owner == po,
695                     ("[pmc,%d] owner %p != po %p", __LINE__, pm->pm_owner, po));
696
697                 pmc_release_pmc_descriptor(pm); /* will unlink from the list */
698         }
699
700         KASSERT(po->po_sscount == 0,
701             ("[pmc,%d] SS count not zero", __LINE__));
702         KASSERT(LIST_EMPTY(&po->po_pmcs),
703             ("[pmc,%d] PMC list not empty", __LINE__));
704
705         /* de-configure the log file if present */
706         if (po->po_flags & PMC_PO_OWNS_LOGFILE)
707                 pmclog_deconfigure_log(po);
708 }
709
710 /*
711  * remove an owner process record if all conditions are met.
712  */
713
714 static void
715 pmc_maybe_remove_owner(struct pmc_owner *po)
716 {
717
718         PMCDBG(OWN,OMR,1, "maybe-remove-owner po=%p", po);
719
720         /*
721          * Remove owner record if
722          * - this process does not own any PMCs
723          * - this process has not allocated a system-wide sampling buffer
724          */
725
726         if (LIST_EMPTY(&po->po_pmcs) &&
727             ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)) {
728                 pmc_remove_owner(po);
729                 pmc_destroy_owner_descriptor(po);
730         }
731 }
732
733 /*
734  * Add an association between a target process and a PMC.
735  */
736
737 static void
738 pmc_link_target_process(struct pmc *pm, struct pmc_process *pp)
739 {
740         int ri;
741         struct pmc_target *pt;
742
743         sx_assert(&pmc_sx, SX_XLOCKED);
744
745         KASSERT(pm != NULL && pp != NULL,
746             ("[pmc,%d] Null pm %p or pp %p", __LINE__, pm, pp));
747         KASSERT(PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)),
748             ("[pmc,%d] Attaching a non-process-virtual pmc=%p to pid=%d",
749                 __LINE__, pm, pp->pp_proc->p_pid));
750         KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt < ((int) md->pmd_npmc - 1),
751             ("[pmc,%d] Illegal reference count %d for process record %p",
752                 __LINE__, pp->pp_refcnt, (void *) pp));
753
754         ri = PMC_TO_ROWINDEX(pm);
755
756         PMCDBG(PRC,TLK,1, "link-target pmc=%p ri=%d pmc-process=%p",
757             pm, ri, pp);
758
759 #ifdef  DEBUG
760         LIST_FOREACH(pt, &pm->pm_targets, pt_next)
761             if (pt->pt_process == pp)
762                     KASSERT(0, ("[pmc,%d] pp %p already in pmc %p targets",
763                                 __LINE__, pp, pm));
764 #endif
765
766         MALLOC(pt, struct pmc_target *, sizeof(struct pmc_target),
767             M_PMC, M_ZERO|M_WAITOK);
768
769         pt->pt_process = pp;
770
771         LIST_INSERT_HEAD(&pm->pm_targets, pt, pt_next);
772
773         atomic_store_rel_ptr((uintptr_t *)&pp->pp_pmcs[ri].pp_pmc,
774             (uintptr_t)pm);
775
776         if (pm->pm_owner->po_owner == pp->pp_proc)
777                 pm->pm_flags |= PMC_F_ATTACHED_TO_OWNER;
778
779         /*
780          * Initialize the per-process values at this row index.
781          */
782         pp->pp_pmcs[ri].pp_pmcval = PMC_TO_MODE(pm) == PMC_MODE_TS ?
783             pm->pm_sc.pm_reloadcount : 0;
784
785         pp->pp_refcnt++;
786
787 }
788
789 /*
790  * Removes the association between a target process and a PMC.
791  */
792
793 static void
794 pmc_unlink_target_process(struct pmc *pm, struct pmc_process *pp)
795 {
796         int ri;
797         struct proc *p;
798         struct pmc_target *ptgt;
799
800         sx_assert(&pmc_sx, SX_XLOCKED);
801
802         KASSERT(pm != NULL && pp != NULL,
803             ("[pmc,%d] Null pm %p or pp %p", __LINE__, pm, pp));
804
805         KASSERT(pp->pp_refcnt >= 1 && pp->pp_refcnt < (int) md->pmd_npmc,
806             ("[pmc,%d] Illegal ref count %d on process record %p",
807                 __LINE__, pp->pp_refcnt, (void *) pp));
808
809         ri = PMC_TO_ROWINDEX(pm);
810
811         PMCDBG(PRC,TUL,1, "unlink-target pmc=%p ri=%d pmc-process=%p",
812             pm, ri, pp);
813
814         KASSERT(pp->pp_pmcs[ri].pp_pmc == pm,
815             ("[pmc,%d] PMC ri %d mismatch pmc %p pp->[ri] %p", __LINE__,
816                 ri, pm, pp->pp_pmcs[ri].pp_pmc));
817
818         pp->pp_pmcs[ri].pp_pmc = NULL;
819         pp->pp_pmcs[ri].pp_pmcval = (pmc_value_t) 0;
820
821         /* Remove owner-specific flags */
822         if (pm->pm_owner->po_owner == pp->pp_proc) {
823                 pp->pp_flags &= ~PMC_PP_ENABLE_MSR_ACCESS;
824                 pm->pm_flags &= ~PMC_F_ATTACHED_TO_OWNER;
825         }
826
827         pp->pp_refcnt--;
828
829         /* Remove the target process from the PMC structure */
830         LIST_FOREACH(ptgt, &pm->pm_targets, pt_next)
831                 if (ptgt->pt_process == pp)
832                         break;
833
834         KASSERT(ptgt != NULL, ("[pmc,%d] process %p (pp: %p) not found "
835                     "in pmc %p", __LINE__, pp->pp_proc, pp, pm));
836
837         LIST_REMOVE(ptgt, pt_next);
838         FREE(ptgt, M_PMC);
839
840         /* if the PMC now lacks targets, send the owner a SIGIO */
841         if (LIST_EMPTY(&pm->pm_targets)) {
842                 p = pm->pm_owner->po_owner;
843                 PROC_LOCK(p);
844                 psignal(p, SIGIO);
845                 PROC_UNLOCK(p);
846
847                 PMCDBG(PRC,SIG,2, "signalling proc=%p signal=%d", p,
848                     SIGIO);
849         }
850 }
851
852 /*
853  * Check if PMC 'pm' may be attached to target process 't'.
854  */
855
856 static int
857 pmc_can_attach(struct pmc *pm, struct proc *t)
858 {
859         struct proc *o;         /* pmc owner */
860         struct ucred *oc, *tc;  /* owner, target credentials */
861         int decline_attach, i;
862
863         /*
864          * A PMC's owner can always attach that PMC to itself.
865          */
866
867         if ((o = pm->pm_owner->po_owner) == t)
868                 return 0;
869
870         PROC_LOCK(o);
871         oc = o->p_ucred;
872         crhold(oc);
873         PROC_UNLOCK(o);
874
875         PROC_LOCK(t);
876         tc = t->p_ucred;
877         crhold(tc);
878         PROC_UNLOCK(t);
879
880         /*
881          * The effective uid of the PMC owner should match at least one
882          * of the {effective,real,saved} uids of the target process.
883          */
884
885         decline_attach = oc->cr_uid != tc->cr_uid &&
886             oc->cr_uid != tc->cr_svuid &&
887             oc->cr_uid != tc->cr_ruid;
888
889         /*
890          * Every one of the target's group ids, must be in the owner's
891          * group list.
892          */
893         for (i = 0; !decline_attach && i < tc->cr_ngroups; i++)
894                 decline_attach = !groupmember(tc->cr_groups[i], oc);
895
896         /* check the read and saved gids too */
897         if (decline_attach == 0)
898                 decline_attach = !groupmember(tc->cr_rgid, oc) ||
899                     !groupmember(tc->cr_svgid, oc);
900
901         crfree(tc);
902         crfree(oc);
903
904         return !decline_attach;
905 }
906
907 /*
908  * Attach a process to a PMC.
909  */
910
911 static int
912 pmc_attach_one_process(struct proc *p, struct pmc *pm)
913 {
914         int ri;
915         char *fullpath, *freepath;
916         struct pmc_process      *pp;
917
918         sx_assert(&pmc_sx, SX_XLOCKED);
919
920         PMCDBG(PRC,ATT,2, "attach-one pm=%p ri=%d proc=%p (%d, %s)", pm,
921             PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
922
923         /*
924          * Locate the process descriptor corresponding to process 'p',
925          * allocating space as needed.
926          *
927          * Verify that rowindex 'pm_rowindex' is free in the process
928          * descriptor.
929          *
930          * If not, allocate space for a descriptor and link the
931          * process descriptor and PMC.
932          */
933         ri = PMC_TO_ROWINDEX(pm);
934
935         if ((pp = pmc_find_process_descriptor(p, PMC_FLAG_ALLOCATE)) == NULL)
936                 return ENOMEM;
937
938         if (pp->pp_pmcs[ri].pp_pmc == pm) /* already present at slot [ri] */
939                 return EEXIST;
940
941         if (pp->pp_pmcs[ri].pp_pmc != NULL)
942                 return EBUSY;
943
944         pmc_link_target_process(pm, pp);
945
946         if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)) &&
947             (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) == 0)
948                 pm->pm_flags |= PMC_F_NEEDS_LOGFILE;
949
950         pm->pm_flags |= PMC_F_ATTACH_DONE; /* mark as attached */
951
952         /* issue an attach event to a configured log file */
953         if (pm->pm_owner->po_flags & PMC_PO_OWNS_LOGFILE) {
954                 pmc_getfilename(p->p_textvp, &fullpath, &freepath);
955                 pmclog_process_pmcattach(pm, p->p_pid, fullpath);
956                 if (freepath)
957                         FREE(freepath, M_TEMP);
958         }
959         /* mark process as using HWPMCs */
960         PROC_LOCK(p);
961         p->p_flag |= P_HWPMC;
962         PROC_UNLOCK(p);
963
964         return 0;
965 }
966
967 /*
968  * Attach a process and optionally its children
969  */
970
971 static int
972 pmc_attach_process(struct proc *p, struct pmc *pm)
973 {
974         int error;
975         struct proc *top;
976
977         sx_assert(&pmc_sx, SX_XLOCKED);
978
979         PMCDBG(PRC,ATT,1, "attach pm=%p ri=%d proc=%p (%d, %s)", pm,
980             PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
981
982
983         /*
984          * If this PMC successfully allowed a GETMSR operation
985          * in the past, disallow further ATTACHes.
986          */
987
988         if ((pm->pm_flags & PMC_PP_ENABLE_MSR_ACCESS) != 0)
989                 return EPERM;
990
991         if ((pm->pm_flags & PMC_F_DESCENDANTS) == 0)
992                 return pmc_attach_one_process(p, pm);
993
994         /*
995          * Traverse all child processes, attaching them to
996          * this PMC.
997          */
998
999         sx_slock(&proctree_lock);
1000
1001         top = p;
1002
1003         for (;;) {
1004                 if ((error = pmc_attach_one_process(p, pm)) != 0)
1005                         break;
1006                 if (!LIST_EMPTY(&p->p_children))
1007                         p = LIST_FIRST(&p->p_children);
1008                 else for (;;) {
1009                         if (p == top)
1010                                 goto done;
1011                         if (LIST_NEXT(p, p_sibling)) {
1012                                 p = LIST_NEXT(p, p_sibling);
1013                                 break;
1014                         }
1015                         p = p->p_pptr;
1016                 }
1017         }
1018
1019         if (error)
1020                 (void) pmc_detach_process(top, pm);
1021
1022  done:
1023         sx_sunlock(&proctree_lock);
1024         return error;
1025 }
1026
1027 /*
1028  * Detach a process from a PMC.  If there are no other PMCs tracking
1029  * this process, remove the process structure from its hash table.  If
1030  * 'flags' contains PMC_FLAG_REMOVE, then free the process structure.
1031  */
1032
1033 static int
1034 pmc_detach_one_process(struct proc *p, struct pmc *pm, int flags)
1035 {
1036         int ri;
1037         struct pmc_process *pp;
1038
1039         sx_assert(&pmc_sx, SX_XLOCKED);
1040
1041         KASSERT(pm != NULL,
1042             ("[pmc,%d] null pm pointer", __LINE__));
1043
1044         ri = PMC_TO_ROWINDEX(pm);
1045
1046         PMCDBG(PRC,ATT,2, "detach-one pm=%p ri=%d proc=%p (%d, %s) flags=0x%x",
1047             pm, ri, p, p->p_pid, p->p_comm, flags);
1048
1049         if ((pp = pmc_find_process_descriptor(p, 0)) == NULL)
1050                 return ESRCH;
1051
1052         if (pp->pp_pmcs[ri].pp_pmc != pm)
1053                 return EINVAL;
1054
1055         pmc_unlink_target_process(pm, pp);
1056
1057         /* Issue a detach entry if a log file is configured */
1058         if (pm->pm_owner->po_flags & PMC_PO_OWNS_LOGFILE)
1059                 pmclog_process_pmcdetach(pm, p->p_pid);
1060
1061         /*
1062          * If there are no PMCs targetting this process, we remove its
1063          * descriptor from the target hash table and unset the P_HWPMC
1064          * flag in the struct proc.
1065          */
1066         KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt < (int) md->pmd_npmc,
1067             ("[pmc,%d] Illegal refcnt %d for process struct %p",
1068                 __LINE__, pp->pp_refcnt, pp));
1069
1070         if (pp->pp_refcnt != 0) /* still a target of some PMC */
1071                 return 0;
1072
1073         pmc_remove_process_descriptor(pp);
1074
1075         if (flags & PMC_FLAG_REMOVE)
1076                 FREE(pp, M_PMC);
1077
1078         PROC_LOCK(p);
1079         p->p_flag &= ~P_HWPMC;
1080         PROC_UNLOCK(p);
1081
1082         return 0;
1083 }
1084
1085 /*
1086  * Detach a process and optionally its descendants from a PMC.
1087  */
1088
1089 static int
1090 pmc_detach_process(struct proc *p, struct pmc *pm)
1091 {
1092         struct proc *top;
1093
1094         sx_assert(&pmc_sx, SX_XLOCKED);
1095
1096         PMCDBG(PRC,ATT,1, "detach pm=%p ri=%d proc=%p (%d, %s)", pm,
1097             PMC_TO_ROWINDEX(pm), p, p->p_pid, p->p_comm);
1098
1099         if ((pm->pm_flags & PMC_F_DESCENDANTS) == 0)
1100                 return pmc_detach_one_process(p, pm, PMC_FLAG_REMOVE);
1101
1102         /*
1103          * Traverse all children, detaching them from this PMC.  We
1104          * ignore errors since we could be detaching a PMC from a
1105          * partially attached proc tree.
1106          */
1107
1108         sx_slock(&proctree_lock);
1109
1110         top = p;
1111
1112         for (;;) {
1113                 (void) pmc_detach_one_process(p, pm, PMC_FLAG_REMOVE);
1114
1115                 if (!LIST_EMPTY(&p->p_children))
1116                         p = LIST_FIRST(&p->p_children);
1117                 else for (;;) {
1118                         if (p == top)
1119                                 goto done;
1120                         if (LIST_NEXT(p, p_sibling)) {
1121                                 p = LIST_NEXT(p, p_sibling);
1122                                 break;
1123                         }
1124                         p = p->p_pptr;
1125                 }
1126         }
1127
1128  done:
1129         sx_sunlock(&proctree_lock);
1130
1131         if (LIST_EMPTY(&pm->pm_targets))
1132                 pm->pm_flags &= ~PMC_F_ATTACH_DONE;
1133
1134         return 0;
1135 }
1136
1137
1138 /*
1139  * Thread context switch IN
1140  */
1141
1142 static void
1143 pmc_process_csw_in(struct thread *td)
1144 {
1145         int cpu;
1146         unsigned int ri;
1147         struct pmc *pm;
1148         struct proc *p;
1149         struct pmc_cpu *pc;
1150         struct pmc_hw *phw;
1151         struct pmc_process *pp;
1152         pmc_value_t newvalue;
1153
1154         p = td->td_proc;
1155
1156         if ((pp = pmc_find_process_descriptor(p, PMC_FLAG_NONE)) == NULL)
1157                 return;
1158
1159         KASSERT(pp->pp_proc == td->td_proc,
1160             ("[pmc,%d] not my thread state", __LINE__));
1161
1162         critical_enter(); /* no preemption from this point */
1163
1164         cpu = PCPU_GET(cpuid); /* td->td_oncpu is invalid */
1165
1166         PMCDBG(CSW,SWI,1, "cpu=%d proc=%p (%d, %s) pp=%p", cpu, p,
1167             p->p_pid, p->p_comm, pp);
1168
1169         KASSERT(cpu >= 0 && cpu < mp_ncpus,
1170             ("[pmc,%d] wierd CPU id %d", __LINE__, cpu));
1171
1172         pc = pmc_pcpu[cpu];
1173
1174         for (ri = 0; ri < md->pmd_npmc; ri++) {
1175
1176                 if ((pm = pp->pp_pmcs[ri].pp_pmc) == NULL)
1177                         continue;
1178
1179                 KASSERT(PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)),
1180                     ("[pmc,%d] Target PMC in non-virtual mode (%d)",
1181                         __LINE__, PMC_TO_MODE(pm)));
1182
1183                 KASSERT(PMC_TO_ROWINDEX(pm) == ri,
1184                     ("[pmc,%d] Row index mismatch pmc %d != ri %d",
1185                         __LINE__, PMC_TO_ROWINDEX(pm), ri));
1186
1187                 /*
1188                  * Only PMCs that are marked as 'RUNNING' need
1189                  * be placed on hardware.
1190                  */
1191
1192                 if (pm->pm_state != PMC_STATE_RUNNING)
1193                         continue;
1194
1195                 /* increment PMC runcount */
1196                 atomic_add_rel_32(&pm->pm_runcount, 1);
1197
1198                 /* configure the HWPMC we are going to use. */
1199                 md->pmd_config_pmc(cpu, ri, pm);
1200
1201                 phw = pc->pc_hwpmcs[ri];
1202
1203                 KASSERT(phw != NULL,
1204                     ("[pmc,%d] null hw pointer", __LINE__));
1205
1206                 KASSERT(phw->phw_pmc == pm,
1207                     ("[pmc,%d] hw->pmc %p != pmc %p", __LINE__,
1208                         phw->phw_pmc, pm));
1209
1210                 /*
1211                  * Write out saved value and start the PMC.
1212                  *
1213                  * Sampling PMCs use a per-process value, while
1214                  * counting mode PMCs use a per-pmc value that is
1215                  * inherited across descendants.
1216                  */
1217                 if (PMC_TO_MODE(pm) == PMC_MODE_TS) {
1218                         mtx_pool_lock_spin(pmc_mtxpool, pm);
1219                         newvalue = PMC_PCPU_SAVED(cpu,ri) =
1220                             pp->pp_pmcs[ri].pp_pmcval;
1221                         mtx_pool_unlock_spin(pmc_mtxpool, pm);
1222                 } else {
1223                         KASSERT(PMC_TO_MODE(pm) == PMC_MODE_TC,
1224                             ("[pmc,%d] illegal mode=%d", __LINE__,
1225                             PMC_TO_MODE(pm)));
1226                         mtx_pool_lock_spin(pmc_mtxpool, pm);
1227                         newvalue = PMC_PCPU_SAVED(cpu, ri) =
1228                             pm->pm_gv.pm_savedvalue;
1229                         mtx_pool_unlock_spin(pmc_mtxpool, pm);
1230                 }
1231
1232                 PMCDBG(CSW,SWI,1,"cpu=%d ri=%d new=%jd", cpu, ri, newvalue);
1233
1234                 md->pmd_write_pmc(cpu, ri, newvalue);
1235                 md->pmd_start_pmc(cpu, ri);
1236         }
1237
1238         /*
1239          * perform any other architecture/cpu dependent thread
1240          * switch-in actions.
1241          */
1242
1243         (void) (*md->pmd_switch_in)(pc, pp);
1244
1245         critical_exit();
1246
1247 }
1248
1249 /*
1250  * Thread context switch OUT.
1251  */
1252
1253 static void
1254 pmc_process_csw_out(struct thread *td)
1255 {
1256         int cpu;
1257         enum pmc_mode mode;
1258         unsigned int ri;
1259         struct pmc *pm;
1260         struct proc *p;
1261         struct pmc_cpu *pc;
1262         struct pmc_process *pp;
1263         int64_t tmp;
1264         pmc_value_t newvalue;
1265
1266         /*
1267          * Locate our process descriptor; this may be NULL if
1268          * this process is exiting and we have already removed
1269          * the process from the target process table.
1270          *
1271          * Note that due to kernel preemption, multiple
1272          * context switches may happen while the process is
1273          * exiting.
1274          *
1275          * Note also that if the target process cannot be
1276          * found we still need to deconfigure any PMCs that
1277          * are currently running on hardware.
1278          */
1279
1280         p = td->td_proc;
1281         pp = pmc_find_process_descriptor(p, PMC_FLAG_NONE);
1282
1283         /*
1284          * save PMCs
1285          */
1286
1287         critical_enter();
1288
1289         cpu = PCPU_GET(cpuid); /* td->td_oncpu is invalid */
1290
1291         PMCDBG(CSW,SWO,1, "cpu=%d proc=%p (%d, %s) pp=%p", cpu, p,
1292             p->p_pid, p->p_comm, pp);
1293
1294         KASSERT(cpu >= 0 && cpu < mp_ncpus,
1295             ("[pmc,%d wierd CPU id %d", __LINE__, cpu));
1296
1297         pc = pmc_pcpu[cpu];
1298
1299         /*
1300          * When a PMC gets unlinked from a target PMC, it will
1301          * be removed from the target's pp_pmc[] array.
1302          *
1303          * However, on a MP system, the target could have been
1304          * executing on another CPU at the time of the unlink.
1305          * So, at context switch OUT time, we need to look at
1306          * the hardware to determine if a PMC is scheduled on
1307          * it.
1308          */
1309
1310         for (ri = 0; ri < md->pmd_npmc; ri++) {
1311
1312                 pm = NULL;
1313                 (void) (*md->pmd_get_config)(cpu, ri, &pm);
1314
1315                 if (pm == NULL) /* nothing at this row index */
1316                         continue;
1317
1318                 mode = PMC_TO_MODE(pm);
1319                 if (!PMC_IS_VIRTUAL_MODE(mode))
1320                         continue; /* not a process virtual PMC */
1321
1322                 KASSERT(PMC_TO_ROWINDEX(pm) == ri,
1323                     ("[pmc,%d] ri mismatch pmc(%d) ri(%d)",
1324                         __LINE__, PMC_TO_ROWINDEX(pm), ri));
1325
1326                 /* Stop hardware if not already stopped */
1327                 if (pm->pm_stalled == 0)
1328                         md->pmd_stop_pmc(cpu, ri);
1329
1330                 /* reduce this PMC's runcount */
1331                 atomic_subtract_rel_32(&pm->pm_runcount, 1);
1332
1333                 /*
1334                  * If this PMC is associated with this process,
1335                  * save the reading.
1336                  */
1337
1338                 if (pp != NULL && pp->pp_pmcs[ri].pp_pmc != NULL) {
1339
1340                         KASSERT(pm == pp->pp_pmcs[ri].pp_pmc,
1341                             ("[pmc,%d] pm %p != pp_pmcs[%d] %p", __LINE__,
1342                                 pm, ri, pp->pp_pmcs[ri].pp_pmc));
1343
1344                         KASSERT(pp->pp_refcnt > 0,
1345                             ("[pmc,%d] pp refcnt = %d", __LINE__,
1346                                 pp->pp_refcnt));
1347
1348                         md->pmd_read_pmc(cpu, ri, &newvalue);
1349
1350                         tmp = newvalue - PMC_PCPU_SAVED(cpu,ri);
1351
1352                         PMCDBG(CSW,SWI,1,"cpu=%d ri=%d tmp=%jd", cpu, ri,
1353                             tmp);
1354
1355                         if (mode == PMC_MODE_TS) {
1356
1357                                 /*
1358                                  * For sampling process-virtual PMCs,
1359                                  * we expect the count to be
1360                                  * decreasing as the 'value'
1361                                  * programmed into the PMC is the
1362                                  * number of events to be seen till
1363                                  * the next sampling interrupt.
1364                                  */
1365                                 if (tmp < 0)
1366                                         tmp += pm->pm_sc.pm_reloadcount;
1367                                 mtx_pool_lock_spin(pmc_mtxpool, pm);
1368                                 pp->pp_pmcs[ri].pp_pmcval -= tmp;
1369                                 if ((int64_t) pp->pp_pmcs[ri].pp_pmcval < 0)
1370                                         pp->pp_pmcs[ri].pp_pmcval +=
1371                                             pm->pm_sc.pm_reloadcount;
1372                                 mtx_pool_unlock_spin(pmc_mtxpool, pm);
1373
1374                         } else {
1375
1376                                 /*
1377                                  * For counting process-virtual PMCs,
1378                                  * we expect the count to be
1379                                  * increasing monotonically, modulo a 64
1380                                  * bit wraparound.
1381                                  */
1382                                 KASSERT((int64_t) tmp >= 0,
1383                                     ("[pmc,%d] negative increment cpu=%d "
1384                                      "ri=%d newvalue=%jx saved=%jx "
1385                                      "incr=%jx", __LINE__, cpu, ri,
1386                                      newvalue, PMC_PCPU_SAVED(cpu,ri), tmp));
1387
1388                                 mtx_pool_lock_spin(pmc_mtxpool, pm);
1389                                 pm->pm_gv.pm_savedvalue += tmp;
1390                                 pp->pp_pmcs[ri].pp_pmcval += tmp;
1391                                 mtx_pool_unlock_spin(pmc_mtxpool, pm);
1392
1393                                 if (pm->pm_flags & PMC_F_LOG_PROCCSW)
1394                                         pmclog_process_proccsw(pm, pp, tmp);
1395                         }
1396                 }
1397
1398                 /* mark hardware as free */
1399                 md->pmd_config_pmc(cpu, ri, NULL);
1400         }
1401
1402         /*
1403          * perform any other architecture/cpu dependent thread
1404          * switch out functions.
1405          */
1406
1407         (void) (*md->pmd_switch_out)(pc, pp);
1408
1409         critical_exit();
1410 }
1411
1412 /*
1413  * Log a KLD operation.
1414  */
1415
1416 static void
1417 pmc_process_kld_load(struct pmckern_map_in *pkm)
1418 {
1419         struct pmc_owner *po;
1420
1421         sx_assert(&pmc_sx, SX_LOCKED);
1422
1423         /*
1424          * Notify owners of system sampling PMCs about KLD operations.
1425          */
1426
1427         LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1428             if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1429                 pmclog_process_map_in(po, (pid_t) -1, pkm->pm_address,
1430                     (char *) pkm->pm_file);
1431
1432         /*
1433          * TODO: Notify owners of (all) process-sampling PMCs too.
1434          */
1435
1436         return;
1437 }
1438
1439 static void
1440 pmc_process_kld_unload(struct pmckern_map_out *pkm)
1441 {
1442         struct pmc_owner *po;
1443
1444         sx_assert(&pmc_sx, SX_LOCKED);
1445
1446         LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1447             if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1448                 pmclog_process_map_out(po, (pid_t) -1,
1449                     pkm->pm_address, pkm->pm_address + pkm->pm_size);
1450                     
1451         /*
1452          * TODO: Notify owners of process-sampling PMCs.
1453          */
1454 }
1455
1456 /*
1457  * A mapping change for a process.
1458  */
1459
1460 static void
1461 pmc_process_mmap(struct thread *td, struct pmckern_map_in *pkm)
1462 {
1463         int ri;
1464         pid_t pid;
1465         char *fullpath, *freepath;
1466         const struct pmc *pm;
1467         struct pmc_owner *po;
1468         const struct pmc_process *pp;
1469
1470         freepath = fullpath = NULL;
1471         pmc_getfilename((struct vnode *) pkm->pm_file, &fullpath, &freepath);
1472
1473         pid = td->td_proc->p_pid;
1474
1475         /* Inform owners of all system-wide sampling PMCs. */
1476         LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1477             if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1478                 pmclog_process_map_in(po, pid, pkm->pm_address, fullpath);
1479
1480         if ((pp = pmc_find_process_descriptor(td->td_proc, 0)) == NULL)
1481                 goto done;
1482
1483         /*
1484          * Inform sampling PMC owners tracking this process.
1485          */
1486         for (ri = 0; ri < md->pmd_npmc; ri++)
1487                 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL &&
1488                     PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
1489                         pmclog_process_map_in(pm->pm_owner,
1490                             pid, pkm->pm_address, fullpath);
1491
1492   done:
1493         if (freepath)
1494                 FREE(freepath, M_TEMP);
1495 }
1496
1497
1498 /*
1499  * Log an munmap request.
1500  */
1501
1502 static void
1503 pmc_process_munmap(struct thread *td, struct pmckern_map_out *pkm)
1504 {
1505         int ri;
1506         pid_t pid;
1507         struct pmc_owner *po;
1508         const struct pmc *pm;
1509         const struct pmc_process *pp;
1510
1511         pid = td->td_proc->p_pid;
1512
1513         LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1514             if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1515                 pmclog_process_map_out(po, pid, pkm->pm_address,
1516                     pkm->pm_address + pkm->pm_size);
1517
1518         if ((pp = pmc_find_process_descriptor(td->td_proc, 0)) == NULL)
1519                 return;
1520
1521         for (ri = 0; ri < md->pmd_npmc; ri++)
1522                 if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL &&
1523                     PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
1524                         pmclog_process_map_out(pm->pm_owner, pid,
1525                             pkm->pm_address, pkm->pm_address + pkm->pm_size);
1526 }
1527
1528 /*
1529  * The 'hook' invoked from the kernel proper
1530  */
1531
1532
1533 #ifdef  DEBUG
1534 const char *pmc_hooknames[] = {
1535         /* these strings correspond to PMC_FN_* in <sys/pmckern.h> */
1536         "",
1537         "EXEC",
1538         "CSW-IN",
1539         "CSW-OUT",
1540         "SAMPLE",
1541         "KLDLOAD",
1542         "KLDUNLOAD",
1543         "MMAP",
1544         "MUNMAP"
1545 };
1546 #endif
1547
1548 static int
1549 pmc_hook_handler(struct thread *td, int function, void *arg)
1550 {
1551
1552         PMCDBG(MOD,PMH,1, "hook td=%p func=%d \"%s\" arg=%p", td, function,
1553             pmc_hooknames[function], arg);
1554
1555         switch (function)
1556         {
1557
1558         /*
1559          * Process exec()
1560          */
1561
1562         case PMC_FN_PROCESS_EXEC:
1563         {
1564                 char *fullpath, *freepath;
1565                 unsigned int ri;
1566                 int is_using_hwpmcs;
1567                 struct pmc *pm;
1568                 struct proc *p;
1569                 struct pmc_owner *po;
1570                 struct pmc_process *pp;
1571                 struct pmckern_procexec *pk;
1572
1573                 sx_assert(&pmc_sx, SX_XLOCKED);
1574
1575                 p = td->td_proc;
1576                 pmc_getfilename(p->p_textvp, &fullpath, &freepath);
1577
1578                 pk = (struct pmckern_procexec *) arg;
1579
1580                 /* Inform owners of SS mode PMCs of the exec event. */
1581                 LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
1582                     if (po->po_flags & PMC_PO_OWNS_LOGFILE)
1583                             pmclog_process_procexec(po, PMC_ID_INVALID,
1584                                 p->p_pid, pk->pm_entryaddr, fullpath);
1585
1586                 PROC_LOCK(p);
1587                 is_using_hwpmcs = p->p_flag & P_HWPMC;
1588                 PROC_UNLOCK(p);
1589
1590                 if (!is_using_hwpmcs) {
1591                         if (freepath)
1592                                 FREE(freepath, M_TEMP);
1593                         break;
1594                 }
1595
1596                 /*
1597                  * PMCs are not inherited across an exec():  remove any
1598                  * PMCs that this process is the owner of.
1599                  */
1600
1601                 if ((po = pmc_find_owner_descriptor(p)) != NULL) {
1602                         pmc_remove_owner(po);
1603                         pmc_destroy_owner_descriptor(po);
1604                 }
1605
1606                 /*
1607                  * If the process being exec'ed is not the target of any
1608                  * PMC, we are done.
1609                  */
1610                 if ((pp = pmc_find_process_descriptor(p, 0)) == NULL) {
1611                         if (freepath)
1612                                 FREE(freepath, M_TEMP);
1613                         break;
1614                 }
1615
1616                 /*
1617                  * Log the exec event to all monitoring owners.  Skip
1618                  * owners who have already recieved the event because
1619                  * they had system sampling PMCs active.
1620                  */
1621                 for (ri = 0; ri < md->pmd_npmc; ri++)
1622                         if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL) {
1623                                 po = pm->pm_owner;
1624                                 if (po->po_sscount == 0 &&
1625                                     po->po_flags & PMC_PO_OWNS_LOGFILE)
1626                                         pmclog_process_procexec(po, pm->pm_id,
1627                                             p->p_pid, pk->pm_entryaddr,
1628                                             fullpath);
1629                         }
1630
1631                 if (freepath)
1632                         FREE(freepath, M_TEMP);
1633
1634
1635                 PMCDBG(PRC,EXC,1, "exec proc=%p (%d, %s) cred-changed=%d",
1636                     p, p->p_pid, p->p_comm, pk->pm_credentialschanged);
1637
1638                 if (pk->pm_credentialschanged == 0) /* no change */
1639                         break;
1640
1641                 /*
1642                  * If the newly exec()'ed process has a different credential
1643                  * than before, allow it to be the target of a PMC only if
1644                  * the PMC's owner has sufficient priviledge.
1645                  */
1646
1647                 for (ri = 0; ri < md->pmd_npmc; ri++)
1648                         if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL)
1649                                 if (pmc_can_attach(pm, td->td_proc) != 0)
1650                                         pmc_detach_one_process(td->td_proc,
1651                                             pm, PMC_FLAG_NONE);
1652
1653                 KASSERT(pp->pp_refcnt >= 0 && pp->pp_refcnt < (int) md->pmd_npmc,
1654                     ("[pmc,%d] Illegal ref count %d on pp %p", __LINE__,
1655                         pp->pp_refcnt, pp));
1656
1657                 /*
1658                  * If this process is no longer the target of any
1659                  * PMCs, we can remove the process entry and free
1660                  * up space.
1661                  */
1662
1663                 if (pp->pp_refcnt == 0) {
1664                         pmc_remove_process_descriptor(pp);
1665                         FREE(pp, M_PMC);
1666                         break;
1667                 }
1668
1669         }
1670         break;
1671
1672         case PMC_FN_CSW_IN:
1673                 pmc_process_csw_in(td);
1674                 break;
1675
1676         case PMC_FN_CSW_OUT:
1677                 pmc_process_csw_out(td);
1678                 break;
1679
1680         /*
1681          * Process accumulated PC samples.
1682          *
1683          * This function is expected to be called by hardclock() for
1684          * each CPU that has accumulated PC samples.
1685          *
1686          * This function is to be executed on the CPU whose samples
1687          * are being processed.
1688          */
1689         case PMC_FN_DO_SAMPLES:
1690
1691                 /*
1692                  * Clear the cpu specific bit in the CPU mask before
1693                  * do the rest of the processing.  If the NMI handler
1694                  * gets invoked after the "atomic_clear_int()" call
1695                  * below but before "pmc_process_samples()" gets
1696                  * around to processing the interrupt, then we will
1697                  * come back here at the next hardclock() tick (and
1698                  * may find nothing to do if "pmc_process_samples()"
1699                  * had already processed the interrupt).  We don't
1700                  * lose the interrupt sample.
1701                  */
1702                 atomic_clear_int(&pmc_cpumask, (1 << PCPU_GET(cpuid)));
1703                 pmc_process_samples(PCPU_GET(cpuid));
1704                 break;
1705
1706
1707         case PMC_FN_KLD_LOAD:
1708                 sx_assert(&pmc_sx, SX_LOCKED);
1709                 pmc_process_kld_load((struct pmckern_map_in *) arg);
1710                 break;
1711
1712         case PMC_FN_KLD_UNLOAD:
1713                 sx_assert(&pmc_sx, SX_LOCKED);
1714                 pmc_process_kld_unload((struct pmckern_map_out *) arg);
1715                 break;
1716
1717         case PMC_FN_MMAP:
1718                 sx_assert(&pmc_sx, SX_LOCKED);
1719                 pmc_process_mmap(td, (struct pmckern_map_in *) arg);
1720                 break;
1721
1722         case PMC_FN_MUNMAP:
1723                 sx_assert(&pmc_sx, SX_LOCKED);
1724                 pmc_process_munmap(td, (struct pmckern_map_out *) arg);
1725                 break;
1726
1727         default:
1728 #ifdef  DEBUG
1729                 KASSERT(0, ("[pmc,%d] unknown hook %d\n", __LINE__, function));
1730 #endif
1731                 break;
1732
1733         }
1734
1735         return 0;
1736 }
1737
1738 /*
1739  * allocate a 'struct pmc_owner' descriptor in the owner hash table.
1740  */
1741
1742 static struct pmc_owner *
1743 pmc_allocate_owner_descriptor(struct proc *p)
1744 {
1745         uint32_t hindex;
1746         struct pmc_owner *po;
1747         struct pmc_ownerhash *poh;
1748
1749         hindex = PMC_HASH_PTR(p, pmc_ownerhashmask);
1750         poh = &pmc_ownerhash[hindex];
1751
1752         /* allocate space for N pointers and one descriptor struct */
1753         MALLOC(po, struct pmc_owner *, sizeof(struct pmc_owner),
1754             M_PMC, M_ZERO|M_WAITOK);
1755
1756         po->po_sscount = po->po_error = po->po_flags = 0;
1757         po->po_file  = NULL;
1758         po->po_owner = p;
1759         po->po_kthread = NULL;
1760         LIST_INIT(&po->po_pmcs);
1761         LIST_INSERT_HEAD(poh, po, po_next); /* insert into hash table */
1762
1763         TAILQ_INIT(&po->po_logbuffers);
1764         mtx_init(&po->po_mtx, "pmc-owner-mtx", "pmc-per-proc", MTX_SPIN);
1765
1766         PMCDBG(OWN,ALL,1, "allocate-owner proc=%p (%d, %s) pmc-owner=%p",
1767             p, p->p_pid, p->p_comm, po);
1768
1769         return po;
1770 }
1771
1772 static void
1773 pmc_destroy_owner_descriptor(struct pmc_owner *po)
1774 {
1775
1776         PMCDBG(OWN,REL,1, "destroy-owner po=%p proc=%p (%d, %s)",
1777             po, po->po_owner, po->po_owner->p_pid, po->po_owner->p_comm);
1778
1779         mtx_destroy(&po->po_mtx);
1780         FREE(po, M_PMC);
1781 }
1782
1783 /*
1784  * find the descriptor corresponding to process 'p', adding or removing it
1785  * as specified by 'mode'.
1786  */
1787
1788 static struct pmc_process *
1789 pmc_find_process_descriptor(struct proc *p, uint32_t mode)
1790 {
1791         uint32_t hindex;
1792         struct pmc_process *pp, *ppnew;
1793         struct pmc_processhash *pph;
1794
1795         hindex = PMC_HASH_PTR(p, pmc_processhashmask);
1796         pph = &pmc_processhash[hindex];
1797
1798         ppnew = NULL;
1799
1800         /*
1801          * Pre-allocate memory in the FIND_ALLOCATE case since we
1802          * cannot call malloc(9) once we hold a spin lock.
1803          */
1804
1805         if (mode & PMC_FLAG_ALLOCATE) {
1806                 /* allocate additional space for 'n' pmc pointers */
1807                 MALLOC(ppnew, struct pmc_process *,
1808                     sizeof(struct pmc_process) + md->pmd_npmc *
1809                     sizeof(struct pmc_targetstate), M_PMC, M_ZERO|M_WAITOK);
1810         }
1811
1812         mtx_lock_spin(&pmc_processhash_mtx);
1813         LIST_FOREACH(pp, pph, pp_next)
1814             if (pp->pp_proc == p)
1815                     break;
1816
1817         if ((mode & PMC_FLAG_REMOVE) && pp != NULL)
1818                 LIST_REMOVE(pp, pp_next);
1819
1820         if ((mode & PMC_FLAG_ALLOCATE) && pp == NULL &&
1821             ppnew != NULL) {
1822                 ppnew->pp_proc = p;
1823                 LIST_INSERT_HEAD(pph, ppnew, pp_next);
1824                 pp = ppnew;
1825                 ppnew = NULL;
1826         }
1827         mtx_unlock_spin(&pmc_processhash_mtx);
1828
1829         if (pp != NULL && ppnew != NULL)
1830                 FREE(ppnew, M_PMC);
1831
1832         return pp;
1833 }
1834
1835 /*
1836  * remove a process descriptor from the process hash table.
1837  */
1838
1839 static void
1840 pmc_remove_process_descriptor(struct pmc_process *pp)
1841 {
1842         KASSERT(pp->pp_refcnt == 0,
1843             ("[pmc,%d] Removing process descriptor %p with count %d",
1844                 __LINE__, pp, pp->pp_refcnt));
1845
1846         mtx_lock_spin(&pmc_processhash_mtx);
1847         LIST_REMOVE(pp, pp_next);
1848         mtx_unlock_spin(&pmc_processhash_mtx);
1849 }
1850
1851
1852 /*
1853  * find an owner descriptor corresponding to proc 'p'
1854  */
1855
1856 static struct pmc_owner *
1857 pmc_find_owner_descriptor(struct proc *p)
1858 {
1859         uint32_t hindex;
1860         struct pmc_owner *po;
1861         struct pmc_ownerhash *poh;
1862
1863         hindex = PMC_HASH_PTR(p, pmc_ownerhashmask);
1864         poh = &pmc_ownerhash[hindex];
1865
1866         po = NULL;
1867         LIST_FOREACH(po, poh, po_next)
1868             if (po->po_owner == p)
1869                     break;
1870
1871         PMCDBG(OWN,FND,1, "find-owner proc=%p (%d, %s) hindex=0x%x -> "
1872             "pmc-owner=%p", p, p->p_pid, p->p_comm, hindex, po);
1873
1874         return po;
1875 }
1876
1877 /*
1878  * pmc_allocate_pmc_descriptor
1879  *
1880  * Allocate a pmc descriptor and initialize its
1881  * fields.
1882  */
1883
1884 static struct pmc *
1885 pmc_allocate_pmc_descriptor(void)
1886 {
1887         struct pmc *pmc;
1888
1889         MALLOC(pmc, struct pmc *, sizeof(struct pmc), M_PMC, M_ZERO|M_WAITOK);
1890
1891         if (pmc != NULL) {
1892                 pmc->pm_owner = NULL;
1893                 LIST_INIT(&pmc->pm_targets);
1894         }
1895
1896         PMCDBG(PMC,ALL,1, "allocate-pmc -> pmc=%p", pmc);
1897
1898         return pmc;
1899 }
1900
1901 /*
1902  * Destroy a pmc descriptor.
1903  */
1904
1905 static void
1906 pmc_destroy_pmc_descriptor(struct pmc *pm)
1907 {
1908         (void) pm;
1909
1910 #ifdef  DEBUG
1911         KASSERT(pm->pm_state == PMC_STATE_DELETED ||
1912             pm->pm_state == PMC_STATE_FREE,
1913             ("[pmc,%d] destroying non-deleted PMC", __LINE__));
1914         KASSERT(LIST_EMPTY(&pm->pm_targets),
1915             ("[pmc,%d] destroying pmc with targets", __LINE__));
1916         KASSERT(pm->pm_owner == NULL,
1917             ("[pmc,%d] destroying pmc attached to an owner", __LINE__));
1918         KASSERT(pm->pm_runcount == 0,
1919             ("[pmc,%d] pmc has non-zero run count %d", __LINE__,
1920                 pm->pm_runcount));
1921 #endif
1922 }
1923
1924 static void
1925 pmc_wait_for_pmc_idle(struct pmc *pm)
1926 {
1927 #ifdef  DEBUG
1928         volatile int maxloop;
1929
1930         maxloop = 100 * mp_ncpus;
1931 #endif
1932
1933         /*
1934          * Loop (with a forced context switch) till the PMC's runcount
1935          * comes down to zero.
1936          */
1937         while (atomic_load_acq_32(&pm->pm_runcount) > 0) {
1938 #ifdef  DEBUG
1939                 maxloop--;
1940                 KASSERT(maxloop > 0,
1941                     ("[pmc,%d] (ri%d, rc%d) waiting too long for "
1942                         "pmc to be free", __LINE__,
1943                         PMC_TO_ROWINDEX(pm), pm->pm_runcount));
1944 #endif
1945                 pmc_force_context_switch();
1946         }
1947 }
1948
1949 /*
1950  * This function does the following things:
1951  *
1952  *  - detaches the PMC from hardware
1953  *  - unlinks all target threads that were attached to it
1954  *  - removes the PMC from its owner's list
1955  *  - destroy's the PMC private mutex
1956  *
1957  * Once this function completes, the given pmc pointer can be safely
1958  * FREE'd by the caller.
1959  */
1960
1961 static void
1962 pmc_release_pmc_descriptor(struct pmc *pm)
1963 {
1964         u_int ri, cpu;
1965         enum pmc_mode mode;
1966         struct pmc_hw *phw;
1967         struct pmc_owner *po;
1968         struct pmc_process *pp;
1969         struct pmc_target *ptgt, *tmp;
1970         struct pmc_binding pb;
1971
1972         sx_assert(&pmc_sx, SX_XLOCKED);
1973
1974         KASSERT(pm, ("[pmc,%d] null pmc", __LINE__));
1975
1976         ri   = PMC_TO_ROWINDEX(pm);
1977         mode = PMC_TO_MODE(pm);
1978
1979         PMCDBG(PMC,REL,1, "release-pmc pmc=%p ri=%d mode=%d", pm, ri,
1980             mode);
1981
1982         /*
1983          * First, we take the PMC off hardware.
1984          */
1985         cpu = 0;
1986         if (PMC_IS_SYSTEM_MODE(mode)) {
1987
1988                 /*
1989                  * A system mode PMC runs on a specific CPU.  Switch
1990                  * to this CPU and turn hardware off.
1991                  */
1992                 pmc_save_cpu_binding(&pb);
1993
1994                 cpu = PMC_TO_CPU(pm);
1995
1996                 pmc_select_cpu(cpu);
1997
1998                 /* switch off non-stalled CPUs */
1999                 if (pm->pm_state == PMC_STATE_RUNNING &&
2000                     pm->pm_stalled == 0) {
2001
2002                         phw = pmc_pcpu[cpu]->pc_hwpmcs[ri];
2003
2004                         KASSERT(phw->phw_pmc == pm,
2005                             ("[pmc, %d] pmc ptr ri(%d) hw(%p) pm(%p)",
2006                                 __LINE__, ri, phw->phw_pmc, pm));
2007                         PMCDBG(PMC,REL,2, "stopping cpu=%d ri=%d", cpu, ri);
2008
2009                         critical_enter();
2010                         md->pmd_stop_pmc(cpu, ri);
2011                         critical_exit();
2012                 }
2013
2014                 PMCDBG(PMC,REL,2, "decfg cpu=%d ri=%d", cpu, ri);
2015
2016                 critical_enter();
2017                 md->pmd_config_pmc(cpu, ri, NULL);
2018                 critical_exit();
2019
2020                 /* adjust the global and process count of SS mode PMCs */
2021                 if (mode == PMC_MODE_SS && pm->pm_state == PMC_STATE_RUNNING) {
2022                         po = pm->pm_owner;
2023                         po->po_sscount--;
2024                         if (po->po_sscount == 0) {
2025                                 atomic_subtract_rel_int(&pmc_ss_count, 1);
2026                                 LIST_REMOVE(po, po_ssnext);
2027                         }
2028                 }
2029
2030                 pm->pm_state = PMC_STATE_DELETED;
2031
2032                 pmc_restore_cpu_binding(&pb);
2033
2034                 /*
2035                  * We could have references to this PMC structure in
2036                  * the per-cpu sample queues.  Wait for the queue to
2037                  * drain.
2038                  */
2039                 pmc_wait_for_pmc_idle(pm);
2040
2041         } else if (PMC_IS_VIRTUAL_MODE(mode)) {
2042
2043                 /*
2044                  * A virtual PMC could be running on multiple CPUs at
2045                  * a given instant.
2046                  *
2047                  * By marking its state as DELETED, we ensure that
2048                  * this PMC is never further scheduled on hardware.
2049                  *
2050                  * Then we wait till all CPUs are done with this PMC.
2051                  */
2052                 pm->pm_state = PMC_STATE_DELETED;
2053
2054
2055                 /* Wait for the PMCs runcount to come to zero. */
2056                 pmc_wait_for_pmc_idle(pm);
2057
2058                 /*
2059                  * At this point the PMC is off all CPUs and cannot be
2060                  * freshly scheduled onto a CPU.  It is now safe to
2061                  * unlink all targets from this PMC.  If a
2062                  * process-record's refcount falls to zero, we remove
2063                  * it from the hash table.  The module-wide SX lock
2064                  * protects us from races.
2065                  */
2066                 LIST_FOREACH_SAFE(ptgt, &pm->pm_targets, pt_next, tmp) {
2067                         pp = ptgt->pt_process;
2068                         pmc_unlink_target_process(pm, pp); /* frees 'ptgt' */
2069
2070                         PMCDBG(PMC,REL,3, "pp->refcnt=%d", pp->pp_refcnt);
2071
2072                         /*
2073                          * If the target process record shows that no
2074                          * PMCs are attached to it, reclaim its space.
2075                          */
2076
2077                         if (pp->pp_refcnt == 0) {
2078                                 pmc_remove_process_descriptor(pp);
2079                                 FREE(pp, M_PMC);
2080                         }
2081                 }
2082
2083                 cpu = curthread->td_oncpu; /* setup cpu for pmd_release() */
2084
2085         }
2086
2087         /*
2088          * Release any MD resources
2089          */
2090
2091         (void) md->pmd_release_pmc(cpu, ri, pm);
2092
2093         /*
2094          * Update row disposition
2095          */
2096
2097         if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pm)))
2098                 PMC_UNMARK_ROW_STANDALONE(ri);
2099         else
2100                 PMC_UNMARK_ROW_THREAD(ri);
2101
2102         /* unlink from the owner's list */
2103         if (pm->pm_owner) {
2104                 LIST_REMOVE(pm, pm_next);
2105                 pm->pm_owner = NULL;
2106         }
2107
2108         pmc_destroy_pmc_descriptor(pm);
2109 }
2110
2111 /*
2112  * Register an owner and a pmc.
2113  */
2114
2115 static int
2116 pmc_register_owner(struct proc *p, struct pmc *pmc)
2117 {
2118         struct pmc_owner *po;
2119
2120         sx_assert(&pmc_sx, SX_XLOCKED);
2121
2122         if ((po = pmc_find_owner_descriptor(p)) == NULL)
2123                 if ((po = pmc_allocate_owner_descriptor(p)) == NULL)
2124                         return ENOMEM;
2125
2126         KASSERT(pmc->pm_owner == NULL,
2127             ("[pmc,%d] attempting to own an initialized PMC", __LINE__));
2128         pmc->pm_owner  = po;
2129
2130         LIST_INSERT_HEAD(&po->po_pmcs, pmc, pm_next);
2131
2132         PROC_LOCK(p);
2133         p->p_flag |= P_HWPMC;
2134         PROC_UNLOCK(p);
2135
2136         if (po->po_flags & PMC_PO_OWNS_LOGFILE)
2137                 pmclog_process_pmcallocate(pmc);
2138
2139         PMCDBG(PMC,REG,1, "register-owner pmc-owner=%p pmc=%p",
2140             po, pmc);
2141
2142         return 0;
2143 }
2144
2145 /*
2146  * Return the current row disposition:
2147  * == 0 => FREE
2148  *  > 0 => PROCESS MODE
2149  *  < 0 => SYSTEM MODE
2150  */
2151
2152 int
2153 pmc_getrowdisp(int ri)
2154 {
2155         return pmc_pmcdisp[ri];
2156 }
2157
2158 /*
2159  * Check if a PMC at row index 'ri' can be allocated to the current
2160  * process.
2161  *
2162  * Allocation can fail if:
2163  *   - the current process is already being profiled by a PMC at index 'ri',
2164  *     attached to it via OP_PMCATTACH.
2165  *   - the current process has already allocated a PMC at index 'ri'
2166  *     via OP_ALLOCATE.
2167  */
2168
2169 static int
2170 pmc_can_allocate_rowindex(struct proc *p, unsigned int ri, int cpu)
2171 {
2172         enum pmc_mode mode;
2173         struct pmc *pm;
2174         struct pmc_owner *po;
2175         struct pmc_process *pp;
2176
2177         PMCDBG(PMC,ALR,1, "can-allocate-rowindex proc=%p (%d, %s) ri=%d "
2178             "cpu=%d", p, p->p_pid, p->p_comm, ri, cpu);
2179
2180         /*
2181          * We shouldn't have already allocated a process-mode PMC at
2182          * row index 'ri'.
2183          *
2184          * We shouldn't have allocated a system-wide PMC on the same
2185          * CPU and same RI.
2186          */
2187         if ((po = pmc_find_owner_descriptor(p)) != NULL)
2188                 LIST_FOREACH(pm, &po->po_pmcs, pm_next) {
2189                     if (PMC_TO_ROWINDEX(pm) == ri) {
2190                             mode = PMC_TO_MODE(pm);
2191                             if (PMC_IS_VIRTUAL_MODE(mode))
2192                                     return EEXIST;
2193                             if (PMC_IS_SYSTEM_MODE(mode) &&
2194                                 (int) PMC_TO_CPU(pm) == cpu)
2195                                     return EEXIST;
2196                     }
2197                 }
2198
2199         /*
2200          * We also shouldn't be the target of any PMC at this index
2201          * since otherwise a PMC_ATTACH to ourselves will fail.
2202          */
2203         if ((pp = pmc_find_process_descriptor(p, 0)) != NULL)
2204                 if (pp->pp_pmcs[ri].pp_pmc)
2205                         return EEXIST;
2206
2207         PMCDBG(PMC,ALR,2, "can-allocate-rowindex proc=%p (%d, %s) ri=%d ok",
2208             p, p->p_pid, p->p_comm, ri);
2209
2210         return 0;
2211 }
2212
2213 /*
2214  * Check if a given PMC at row index 'ri' can be currently used in
2215  * mode 'mode'.
2216  */
2217
2218 static int
2219 pmc_can_allocate_row(int ri, enum pmc_mode mode)
2220 {
2221         enum pmc_disp   disp;
2222
2223         sx_assert(&pmc_sx, SX_XLOCKED);
2224
2225         PMCDBG(PMC,ALR,1, "can-allocate-row ri=%d mode=%d", ri, mode);
2226
2227         if (PMC_IS_SYSTEM_MODE(mode))
2228                 disp = PMC_DISP_STANDALONE;
2229         else
2230                 disp = PMC_DISP_THREAD;
2231
2232         /*
2233          * check disposition for PMC row 'ri':
2234          *
2235          * Expected disposition         Row-disposition         Result
2236          *
2237          * STANDALONE                   STANDALONE or FREE      proceed
2238          * STANDALONE                   THREAD                  fail
2239          * THREAD                       THREAD or FREE          proceed
2240          * THREAD                       STANDALONE              fail
2241          */
2242
2243         if (!PMC_ROW_DISP_IS_FREE(ri) &&
2244             !(disp == PMC_DISP_THREAD && PMC_ROW_DISP_IS_THREAD(ri)) &&
2245             !(disp == PMC_DISP_STANDALONE && PMC_ROW_DISP_IS_STANDALONE(ri)))
2246                 return EBUSY;
2247
2248         /*
2249          * All OK
2250          */
2251
2252         PMCDBG(PMC,ALR,2, "can-allocate-row ri=%d mode=%d ok", ri, mode);
2253
2254         return 0;
2255
2256 }
2257
2258 /*
2259  * Find a PMC descriptor with user handle 'pmcid' for thread 'td'.
2260  */
2261
2262 static struct pmc *
2263 pmc_find_pmc_descriptor_in_process(struct pmc_owner *po, pmc_id_t pmcid)
2264 {
2265         struct pmc *pm;
2266
2267         KASSERT(PMC_ID_TO_ROWINDEX(pmcid) < md->pmd_npmc,
2268             ("[pmc,%d] Illegal pmc index %d (max %d)", __LINE__,
2269                 PMC_ID_TO_ROWINDEX(pmcid), md->pmd_npmc));
2270
2271         LIST_FOREACH(pm, &po->po_pmcs, pm_next)
2272             if (pm->pm_id == pmcid)
2273                     return pm;
2274
2275         return NULL;
2276 }
2277
2278 static int
2279 pmc_find_pmc(pmc_id_t pmcid, struct pmc **pmc)
2280 {
2281
2282         struct pmc *pm;
2283         struct pmc_owner *po;
2284
2285         PMCDBG(PMC,FND,1, "find-pmc id=%d", pmcid);
2286
2287         if ((po = pmc_find_owner_descriptor(curthread->td_proc)) == NULL)
2288                 return ESRCH;
2289
2290         if ((pm = pmc_find_pmc_descriptor_in_process(po, pmcid)) == NULL)
2291                 return EINVAL;
2292
2293         PMCDBG(PMC,FND,2, "find-pmc id=%d -> pmc=%p", pmcid, pm);
2294
2295         *pmc = pm;
2296         return 0;
2297 }
2298
2299 /*
2300  * Start a PMC.
2301  */
2302
2303 static int
2304 pmc_start(struct pmc *pm)
2305 {
2306         int error, cpu, ri;
2307         enum pmc_mode mode;
2308         struct pmc_owner *po;
2309         struct pmc_binding pb;
2310
2311         KASSERT(pm != NULL,
2312             ("[pmc,%d] null pm", __LINE__));
2313
2314         mode = PMC_TO_MODE(pm);
2315         ri   = PMC_TO_ROWINDEX(pm);
2316         error = 0;
2317
2318         PMCDBG(PMC,OPS,1, "start pmc=%p mode=%d ri=%d", pm, mode, ri);
2319
2320         po = pm->pm_owner;
2321
2322         if (PMC_IS_VIRTUAL_MODE(mode)) {
2323
2324                 /*
2325                  * If a PMCATTACH has never been done on this PMC,
2326                  * attach it to its owner process.
2327                  */
2328
2329                 if (LIST_EMPTY(&pm->pm_targets))
2330                         error = (pm->pm_flags & PMC_F_ATTACH_DONE) ? ESRCH :
2331                             pmc_attach_process(po->po_owner, pm);
2332
2333                 /*
2334                  * Disallow PMCSTART if a logfile is required but has not
2335                  * been configured yet.
2336                  */
2337
2338                 if (error == 0 && (pm->pm_flags & PMC_F_NEEDS_LOGFILE) &&
2339                     (po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)
2340                         error = EDOOFUS;
2341
2342                 /*
2343                  * If the PMC is attached to its owner, then force a context
2344                  * switch to ensure that the MD state gets set correctly.
2345                  */
2346
2347                 if (error == 0) {
2348                         pm->pm_state = PMC_STATE_RUNNING;
2349                         if (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER)
2350                                 pmc_force_context_switch();
2351                 }
2352
2353                 return error;
2354         }
2355
2356
2357         /*
2358          * A system-wide PMC.
2359          */
2360
2361         if ((pm->pm_flags & PMC_F_NEEDS_LOGFILE) &&
2362             (po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)
2363                 return EDOOFUS; /* programming error */
2364
2365         /*
2366          * Add the owner to the global list if this is a system-wide
2367          * sampling PMC.
2368          */
2369
2370         if (mode == PMC_MODE_SS) {
2371                 if (po->po_sscount == 0) {
2372                         LIST_INSERT_HEAD(&pmc_ss_owners, po, po_ssnext);
2373                         atomic_add_rel_int(&pmc_ss_count, 1);
2374                         PMCDBG(PMC,OPS,1, "po=%p in global list", po);
2375                 }
2376                 po->po_sscount++;
2377         }
2378
2379         /* TODO: dump system wide process mappings to the log? */
2380
2381         /*
2382          * Move to the CPU associated with this
2383          * PMC, and start the hardware.
2384          */
2385
2386         pmc_save_cpu_binding(&pb);
2387
2388         cpu = PMC_TO_CPU(pm);
2389
2390         if (pmc_cpu_is_disabled(cpu))
2391                 return ENXIO;
2392
2393         pmc_select_cpu(cpu);
2394
2395         /*
2396          * global PMCs are configured at allocation time
2397          * so write out the initial value and start the PMC.
2398          */
2399
2400         pm->pm_state = PMC_STATE_RUNNING;
2401
2402         critical_enter();
2403         if ((error = md->pmd_write_pmc(cpu, ri,
2404                  PMC_IS_SAMPLING_MODE(mode) ?
2405                  pm->pm_sc.pm_reloadcount :
2406                  pm->pm_sc.pm_initial)) == 0)
2407                 error = md->pmd_start_pmc(cpu, ri);
2408         critical_exit();
2409
2410         pmc_restore_cpu_binding(&pb);
2411
2412         return error;
2413 }
2414
2415 /*
2416  * Stop a PMC.
2417  */
2418
2419 static int
2420 pmc_stop(struct pmc *pm)
2421 {
2422         int cpu, error, ri;
2423         struct pmc_owner *po;
2424         struct pmc_binding pb;
2425
2426         KASSERT(pm != NULL, ("[pmc,%d] null pmc", __LINE__));
2427
2428         PMCDBG(PMC,OPS,1, "stop pmc=%p mode=%d ri=%d", pm,
2429             PMC_TO_MODE(pm), PMC_TO_ROWINDEX(pm));
2430
2431         pm->pm_state = PMC_STATE_STOPPED;
2432
2433         /*
2434          * If the PMC is a virtual mode one, changing the state to
2435          * non-RUNNING is enough to ensure that the PMC never gets
2436          * scheduled.
2437          *
2438          * If this PMC is current running on a CPU, then it will
2439          * handled correctly at the time its target process is context
2440          * switched out.
2441          */
2442
2443         if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)))
2444                 return 0;
2445
2446         /*
2447          * A system-mode PMC.  Move to the CPU associated with
2448          * this PMC, and stop the hardware.  We update the
2449          * 'initial count' so that a subsequent PMCSTART will
2450          * resume counting from the current hardware count.
2451          */
2452
2453         pmc_save_cpu_binding(&pb);
2454
2455         cpu = PMC_TO_CPU(pm);
2456
2457         KASSERT(cpu >= 0 && cpu < mp_ncpus,
2458             ("[pmc,%d] illegal cpu=%d", __LINE__, cpu));
2459
2460         if (pmc_cpu_is_disabled(cpu))
2461                 return ENXIO;
2462
2463         pmc_select_cpu(cpu);
2464
2465         ri = PMC_TO_ROWINDEX(pm);
2466
2467         critical_enter();
2468         if ((error = md->pmd_stop_pmc(cpu, ri)) == 0)
2469                 error = md->pmd_read_pmc(cpu, ri, &pm->pm_sc.pm_initial);
2470         critical_exit();
2471
2472         pmc_restore_cpu_binding(&pb);
2473
2474         po = pm->pm_owner;
2475
2476         /* remove this owner from the global list of SS PMC owners */
2477         if (PMC_TO_MODE(pm) == PMC_MODE_SS) {
2478                 po->po_sscount--;
2479                 if (po->po_sscount == 0) {
2480                         atomic_subtract_rel_int(&pmc_ss_count, 1);
2481                         LIST_REMOVE(po, po_ssnext);
2482                         PMCDBG(PMC,OPS,2,"po=%p removed from global list", po);
2483                 }
2484         }
2485
2486         return error;
2487 }
2488
2489
2490 #ifdef  DEBUG
2491 static const char *pmc_op_to_name[] = {
2492 #undef  __PMC_OP
2493 #define __PMC_OP(N, D)  #N ,
2494         __PMC_OPS()
2495         NULL
2496 };
2497 #endif
2498
2499 /*
2500  * The syscall interface
2501  */
2502
2503 #define PMC_GET_SX_XLOCK(...) do {              \
2504         sx_xlock(&pmc_sx);                      \
2505         if (pmc_hook == NULL) {                 \
2506                 sx_xunlock(&pmc_sx);            \
2507                 return __VA_ARGS__;             \
2508         }                                       \
2509 } while (0)
2510
2511 #define PMC_DOWNGRADE_SX() do {                 \
2512         sx_downgrade(&pmc_sx);                  \
2513         is_sx_downgraded = 1;                   \
2514 } while (0)
2515
2516 static int
2517 pmc_syscall_handler(struct thread *td, void *syscall_args)
2518 {
2519         int error, is_sx_downgraded, op;
2520         struct pmc_syscall_args *c;
2521         void *arg;
2522
2523         PMC_GET_SX_XLOCK(ENOSYS);
2524
2525         DROP_GIANT();
2526
2527         is_sx_downgraded = 0;
2528
2529         c = (struct pmc_syscall_args *) syscall_args;
2530
2531         op = c->pmop_code;
2532         arg = c->pmop_data;
2533
2534         PMCDBG(MOD,PMS,1, "syscall op=%d \"%s\" arg=%p", op,
2535             pmc_op_to_name[op], arg);
2536
2537         error = 0;
2538         atomic_add_int(&pmc_stats.pm_syscalls, 1);
2539
2540         switch(op)
2541         {
2542
2543
2544         /*
2545          * Configure a log file.
2546          *
2547          * XXX This OP will be reworked.
2548          */
2549
2550         case PMC_OP_CONFIGURELOG:
2551         {
2552                 struct proc *p;
2553                 struct pmc *pm;
2554                 struct pmc_owner *po;
2555                 struct pmckern_map_in *km, *kmbase;
2556                 struct pmc_op_configurelog cl;
2557
2558                 sx_assert(&pmc_sx, SX_XLOCKED);
2559
2560                 if ((error = copyin(arg, &cl, sizeof(cl))) != 0)
2561                         break;
2562
2563                 /* mark this process as owning a log file */
2564                 p = td->td_proc;
2565                 if ((po = pmc_find_owner_descriptor(p)) == NULL)
2566                         if ((po = pmc_allocate_owner_descriptor(p)) == NULL) {
2567                                 error = ENOMEM;
2568                                 break;
2569                         }
2570
2571                 /*
2572                  * If a valid fd was passed in, try to configure that,
2573                  * otherwise if 'fd' was less than zero and there was
2574                  * a log file configured, flush its buffers and
2575                  * de-configure it.
2576                  */
2577                 if (cl.pm_logfd >= 0)
2578                         error = pmclog_configure_log(po, cl.pm_logfd);
2579                 else if (po->po_flags & PMC_PO_OWNS_LOGFILE) {
2580                         pmclog_process_closelog(po);
2581                         error = pmclog_flush(po);
2582                         if (error == 0) {
2583                                 LIST_FOREACH(pm, &po->po_pmcs, pm_next)
2584                                     if (pm->pm_flags & PMC_F_NEEDS_LOGFILE &&
2585                                         pm->pm_state == PMC_STATE_RUNNING)
2586                                             pmc_stop(pm);
2587                                 error = pmclog_deconfigure_log(po);
2588                         }
2589                 } else
2590                         error = EINVAL;
2591
2592                 if (error)
2593                         break;
2594
2595                 /*
2596                  * Log the current set of kernel modules.
2597                  */
2598                 kmbase = linker_hwpmc_list_objects();
2599                 for (km = kmbase; km->pm_file != NULL; km++) {
2600                         PMCDBG(LOG,REG,1,"%s %p", (char *) km->pm_file,
2601                             (void *) km->pm_address);
2602                         pmclog_process_map_in(po, (pid_t) -1, km->pm_address,
2603                             km->pm_file);
2604                 }
2605                 FREE(kmbase, M_LINKER);
2606         }
2607         break;
2608
2609
2610         /*
2611          * Flush a log file.
2612          */
2613
2614         case PMC_OP_FLUSHLOG:
2615         {
2616                 struct pmc_owner *po;
2617
2618                 sx_assert(&pmc_sx, SX_XLOCKED);
2619
2620                 if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
2621                         error = EINVAL;
2622                         break;
2623                 }
2624
2625                 error = pmclog_flush(po);
2626         }
2627         break;
2628
2629         /*
2630          * Retrieve hardware configuration.
2631          */
2632
2633         case PMC_OP_GETCPUINFO: /* CPU information */
2634         {
2635                 struct pmc_op_getcpuinfo gci;
2636
2637                 gci.pm_cputype = md->pmd_cputype;
2638                 gci.pm_ncpu    = mp_ncpus;
2639                 gci.pm_npmc    = md->pmd_npmc;
2640                 gci.pm_nclass  = md->pmd_nclass;
2641                 bcopy(md->pmd_classes, &gci.pm_classes,
2642                     sizeof(gci.pm_classes));
2643                 error = copyout(&gci, arg, sizeof(gci));
2644         }
2645         break;
2646
2647
2648         /*
2649          * Get module statistics
2650          */
2651
2652         case PMC_OP_GETDRIVERSTATS:
2653         {
2654                 struct pmc_op_getdriverstats gms;
2655
2656                 bcopy(&pmc_stats, &gms, sizeof(gms));
2657                 error = copyout(&gms, arg, sizeof(gms));
2658         }
2659         break;
2660
2661
2662         /*
2663          * Retrieve module version number
2664          */
2665
2666         case PMC_OP_GETMODULEVERSION:
2667         {
2668                 uint32_t cv, modv;
2669
2670                 /* retrieve the client's idea of the ABI version */
2671                 if ((error = copyin(arg, &cv, sizeof(uint32_t))) != 0)
2672                         break;
2673                 /* don't service clients newer than our driver */
2674                 modv = PMC_VERSION;
2675                 if ((cv & 0xFFFF0000) > (modv & 0xFFFF0000)) {
2676                         error = EPROGMISMATCH;
2677                         break;
2678                 }
2679                 error = copyout(&modv, arg, sizeof(int));
2680         }
2681         break;
2682
2683
2684         /*
2685          * Retrieve the state of all the PMCs on a given
2686          * CPU.
2687          */
2688
2689         case PMC_OP_GETPMCINFO:
2690         {
2691                 uint32_t cpu, n, npmc;
2692                 size_t pmcinfo_size;
2693                 struct pmc *pm;
2694                 struct pmc_info *p, *pmcinfo;
2695                 struct pmc_op_getpmcinfo *gpi;
2696                 struct pmc_owner *po;
2697                 struct pmc_binding pb;
2698
2699                 PMC_DOWNGRADE_SX();
2700
2701                 gpi = (struct pmc_op_getpmcinfo *) arg;
2702
2703                 if ((error = copyin(&gpi->pm_cpu, &cpu, sizeof(cpu))) != 0)
2704                         break;
2705
2706                 if (cpu >= (unsigned int) mp_ncpus) {
2707                         error = EINVAL;
2708                         break;
2709                 }
2710
2711                 if (pmc_cpu_is_disabled(cpu)) {
2712                         error = ENXIO;
2713                         break;
2714                 }
2715
2716                 /* switch to CPU 'cpu' */
2717                 pmc_save_cpu_binding(&pb);
2718                 pmc_select_cpu(cpu);
2719
2720                 npmc = md->pmd_npmc;
2721
2722                 pmcinfo_size = npmc * sizeof(struct pmc_info);
2723                 MALLOC(pmcinfo, struct pmc_info *, pmcinfo_size, M_PMC,
2724                     M_WAITOK);
2725
2726                 p = pmcinfo;
2727
2728                 for (n = 0; n < md->pmd_npmc; n++, p++) {
2729
2730                         if ((error = md->pmd_describe(cpu, n, p, &pm)) != 0)
2731                                 break;
2732
2733                         if (PMC_ROW_DISP_IS_STANDALONE(n))
2734                                 p->pm_rowdisp = PMC_DISP_STANDALONE;
2735                         else if (PMC_ROW_DISP_IS_THREAD(n))
2736                                 p->pm_rowdisp = PMC_DISP_THREAD;
2737                         else
2738                                 p->pm_rowdisp = PMC_DISP_FREE;
2739
2740                         p->pm_ownerpid = -1;
2741
2742                         if (pm == NULL) /* no PMC associated */
2743                                 continue;
2744
2745                         po = pm->pm_owner;
2746
2747                         KASSERT(po->po_owner != NULL,
2748                             ("[pmc,%d] pmc_owner had a null proc pointer",
2749                                 __LINE__));
2750
2751                         p->pm_ownerpid = po->po_owner->p_pid;
2752                         p->pm_mode     = PMC_TO_MODE(pm);
2753                         p->pm_event    = pm->pm_event;
2754                         p->pm_flags    = pm->pm_flags;
2755
2756                         if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
2757                                 p->pm_reloadcount =
2758                                     pm->pm_sc.pm_reloadcount;
2759                 }
2760
2761                 pmc_restore_cpu_binding(&pb);
2762
2763                 /* now copy out the PMC info collected */
2764                 if (error == 0)
2765                         error = copyout(pmcinfo, &gpi->pm_pmcs, pmcinfo_size);
2766
2767                 FREE(pmcinfo, M_PMC);
2768         }
2769         break;
2770
2771
2772         /*
2773          * Set the administrative state of a PMC.  I.e. whether
2774          * the PMC is to be used or not.
2775          */
2776
2777         case PMC_OP_PMCADMIN:
2778         {
2779                 int cpu, ri;
2780                 enum pmc_state request;
2781                 struct pmc_cpu *pc;
2782                 struct pmc_hw *phw;
2783                 struct pmc_op_pmcadmin pma;
2784                 struct pmc_binding pb;
2785
2786                 sx_assert(&pmc_sx, SX_XLOCKED);
2787
2788                 KASSERT(td == curthread,
2789                     ("[pmc,%d] td != curthread", __LINE__));
2790
2791                 error = priv_check(td, PRIV_PMC_MANAGE);
2792                 if (error)
2793                         break;
2794
2795                 if ((error = copyin(arg, &pma, sizeof(pma))) != 0)
2796                         break;
2797
2798                 cpu = pma.pm_cpu;
2799
2800                 if (cpu < 0 || cpu >= mp_ncpus) {
2801                         error = EINVAL;
2802                         break;
2803                 }
2804
2805                 if (pmc_cpu_is_disabled(cpu)) {
2806                         error = ENXIO;
2807                         break;
2808                 }
2809
2810                 request = pma.pm_state;
2811
2812                 if (request != PMC_STATE_DISABLED &&
2813                     request != PMC_STATE_FREE) {
2814                         error = EINVAL;
2815                         break;
2816                 }
2817
2818                 ri = pma.pm_pmc; /* pmc id == row index */
2819                 if (ri < 0 || ri >= (int) md->pmd_npmc) {
2820                         error = EINVAL;
2821                         break;
2822                 }
2823
2824                 /*
2825                  * We can't disable a PMC with a row-index allocated
2826                  * for process virtual PMCs.
2827                  */
2828
2829                 if (PMC_ROW_DISP_IS_THREAD(ri) &&
2830                     request == PMC_STATE_DISABLED) {
2831                         error = EBUSY;
2832                         break;
2833                 }
2834
2835                 /*
2836                  * otherwise, this PMC on this CPU is either free or
2837                  * in system-wide mode.
2838                  */
2839
2840                 pmc_save_cpu_binding(&pb);
2841                 pmc_select_cpu(cpu);
2842
2843                 pc  = pmc_pcpu[cpu];
2844                 phw = pc->pc_hwpmcs[ri];
2845
2846                 /*
2847                  * XXX do we need some kind of 'forced' disable?
2848                  */
2849
2850                 if (phw->phw_pmc == NULL) {
2851                         if (request == PMC_STATE_DISABLED &&
2852                             (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED)) {
2853                                 phw->phw_state &= ~PMC_PHW_FLAG_IS_ENABLED;
2854                                 PMC_MARK_ROW_STANDALONE(ri);
2855                         } else if (request == PMC_STATE_FREE &&
2856                             (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0) {
2857                                 phw->phw_state |=  PMC_PHW_FLAG_IS_ENABLED;
2858                                 PMC_UNMARK_ROW_STANDALONE(ri);
2859                         }
2860                         /* other cases are a no-op */
2861                 } else
2862                         error = EBUSY;
2863
2864                 pmc_restore_cpu_binding(&pb);
2865         }
2866         break;
2867
2868
2869         /*
2870          * Allocate a PMC.
2871          */
2872
2873         case PMC_OP_PMCALLOCATE:
2874         {
2875                 uint32_t caps;
2876                 u_int cpu;
2877                 int n;
2878                 enum pmc_mode mode;
2879                 struct pmc *pmc;
2880                 struct pmc_hw *phw;
2881                 struct pmc_op_pmcallocate pa;
2882                 struct pmc_binding pb;
2883
2884                 if ((error = copyin(arg, &pa, sizeof(pa))) != 0)
2885                         break;
2886
2887                 caps = pa.pm_caps;
2888                 mode = pa.pm_mode;
2889                 cpu  = pa.pm_cpu;
2890
2891                 if ((mode != PMC_MODE_SS  &&  mode != PMC_MODE_SC  &&
2892                      mode != PMC_MODE_TS  &&  mode != PMC_MODE_TC) ||
2893                     (cpu != (u_int) PMC_CPU_ANY && cpu >= (u_int) mp_ncpus)) {
2894                         error = EINVAL;
2895                         break;
2896                 }
2897
2898                 /*
2899                  * Virtual PMCs should only ask for a default CPU.
2900                  * System mode PMCs need to specify a non-default CPU.
2901                  */
2902
2903                 if ((PMC_IS_VIRTUAL_MODE(mode) && cpu != (u_int) PMC_CPU_ANY) ||
2904                     (PMC_IS_SYSTEM_MODE(mode) && cpu == (u_int) PMC_CPU_ANY)) {
2905                         error = EINVAL;
2906                         break;
2907                 }
2908
2909                 /*
2910                  * Check that a disabled CPU is not being asked for.
2911                  */
2912
2913                 if (PMC_IS_SYSTEM_MODE(mode) && pmc_cpu_is_disabled(cpu)) {
2914                         error = ENXIO;
2915                         break;
2916                 }
2917
2918                 /*
2919                  * Refuse an allocation for a system-wide PMC if this
2920                  * process has been jailed, or if this process lacks
2921                  * super-user credentials and the sysctl tunable
2922                  * 'security.bsd.unprivileged_syspmcs' is zero.
2923                  */
2924
2925                 if (PMC_IS_SYSTEM_MODE(mode)) {
2926                         if (jailed(curthread->td_ucred)) {
2927                                 error = EPERM;
2928                                 break;
2929                         }
2930                         if (!pmc_unprivileged_syspmcs) {
2931                                 error = priv_check(curthread,
2932                                     PRIV_PMC_SYSTEM);
2933                                 if (error)
2934                                         break;
2935                         }
2936                 }
2937
2938                 if (error)
2939                         break;
2940
2941                 /*
2942                  * Look for valid values for 'pm_flags'
2943                  */
2944
2945                 if ((pa.pm_flags & ~(PMC_F_DESCENDANTS | PMC_F_LOG_PROCCSW |
2946                     PMC_F_LOG_PROCEXIT)) != 0) {
2947                         error = EINVAL;
2948                         break;
2949                 }
2950
2951                 /* process logging options are not allowed for system PMCs */
2952                 if (PMC_IS_SYSTEM_MODE(mode) && (pa.pm_flags &
2953                     (PMC_F_LOG_PROCCSW | PMC_F_LOG_PROCEXIT))) {
2954                         error = EINVAL;
2955                         break;
2956                 }
2957
2958                 /*
2959                  * All sampling mode PMCs need to be able to interrupt the
2960                  * CPU.
2961                  */
2962                 if (PMC_IS_SAMPLING_MODE(mode))
2963                         caps |= PMC_CAP_INTERRUPT;
2964
2965                 /* A valid class specifier should have been passed in. */
2966                 for (n = 0; n < md->pmd_nclass; n++)
2967                         if (md->pmd_classes[n].pm_class == pa.pm_class)
2968                                 break;
2969                 if (n == md->pmd_nclass) {
2970                         error = EINVAL;
2971                         break;
2972                 }
2973
2974                 /* The requested PMC capabilities should be feasible. */
2975                 if ((md->pmd_classes[n].pm_caps & caps) != caps) {
2976                         error = EOPNOTSUPP;
2977                         break;
2978                 }
2979
2980                 PMCDBG(PMC,ALL,2, "event=%d caps=0x%x mode=%d cpu=%d",
2981                     pa.pm_ev, caps, mode, cpu);
2982
2983                 pmc = pmc_allocate_pmc_descriptor();
2984                 pmc->pm_id    = PMC_ID_MAKE_ID(cpu,pa.pm_mode,pa.pm_class,
2985                     PMC_ID_INVALID);
2986                 pmc->pm_event = pa.pm_ev;
2987                 pmc->pm_state = PMC_STATE_FREE;
2988                 pmc->pm_caps  = caps;
2989                 pmc->pm_flags = pa.pm_flags;
2990
2991                 /* switch thread to CPU 'cpu' */
2992                 pmc_save_cpu_binding(&pb);
2993
2994 #define PMC_IS_SHAREABLE_PMC(cpu, n)                            \
2995         (pmc_pcpu[(cpu)]->pc_hwpmcs[(n)]->phw_state &           \
2996          PMC_PHW_FLAG_IS_SHAREABLE)
2997 #define PMC_IS_UNALLOCATED(cpu, n)                              \
2998         (pmc_pcpu[(cpu)]->pc_hwpmcs[(n)]->phw_pmc == NULL)
2999
3000                 if (PMC_IS_SYSTEM_MODE(mode)) {
3001                         pmc_select_cpu(cpu);
3002                         for (n = 0; n < (int) md->pmd_npmc; n++)
3003                                 if (pmc_can_allocate_row(n, mode) == 0 &&
3004                                     pmc_can_allocate_rowindex(
3005                                             curthread->td_proc, n, cpu) == 0 &&
3006                                     (PMC_IS_UNALLOCATED(cpu, n) ||
3007                                      PMC_IS_SHAREABLE_PMC(cpu, n)) &&
3008                                     md->pmd_allocate_pmc(cpu, n, pmc,
3009                                         &pa) == 0)
3010                                         break;
3011                 } else {
3012                         /* Process virtual mode */
3013                         for (n = 0; n < (int) md->pmd_npmc; n++) {
3014                                 if (pmc_can_allocate_row(n, mode) == 0 &&
3015                                     pmc_can_allocate_rowindex(
3016                                             curthread->td_proc, n,
3017                                             PMC_CPU_ANY) == 0 &&
3018                                     md->pmd_allocate_pmc(curthread->td_oncpu,
3019                                         n, pmc, &pa) == 0)
3020                                         break;
3021                         }
3022                 }
3023
3024 #undef  PMC_IS_UNALLOCATED
3025 #undef  PMC_IS_SHAREABLE_PMC
3026
3027                 pmc_restore_cpu_binding(&pb);
3028
3029                 if (n == (int) md->pmd_npmc) {
3030                         pmc_destroy_pmc_descriptor(pmc);
3031                         FREE(pmc, M_PMC);
3032                         pmc = NULL;
3033                         error = EINVAL;
3034                         break;
3035                 }
3036
3037                 /* Fill in the correct value in the ID field */
3038                 pmc->pm_id = PMC_ID_MAKE_ID(cpu,mode,pa.pm_class,n);
3039
3040                 PMCDBG(PMC,ALL,2, "ev=%d class=%d mode=%d n=%d -> pmcid=%x",
3041                     pmc->pm_event, pa.pm_class, mode, n, pmc->pm_id);
3042
3043                 /* Process mode PMCs with logging enabled need log files */
3044                 if (pmc->pm_flags & (PMC_F_LOG_PROCEXIT | PMC_F_LOG_PROCCSW))
3045                         pmc->pm_flags |= PMC_F_NEEDS_LOGFILE;
3046
3047                 /* All system mode sampling PMCs require a log file */
3048                 if (PMC_IS_SAMPLING_MODE(mode) && PMC_IS_SYSTEM_MODE(mode))
3049                         pmc->pm_flags |= PMC_F_NEEDS_LOGFILE;
3050
3051                 /*
3052                  * Configure global pmc's immediately
3053                  */
3054
3055                 if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pmc))) {
3056
3057                         pmc_save_cpu_binding(&pb);
3058                         pmc_select_cpu(cpu);
3059
3060                         phw = pmc_pcpu[cpu]->pc_hwpmcs[n];
3061
3062                         if ((phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) == 0 ||
3063                             (error = md->pmd_config_pmc(cpu, n, pmc)) != 0) {
3064                                 (void) md->pmd_release_pmc(cpu, n, pmc);
3065                                 pmc_destroy_pmc_descriptor(pmc);
3066                                 FREE(pmc, M_PMC);
3067                                 pmc = NULL;
3068                                 pmc_restore_cpu_binding(&pb);
3069                                 error = EPERM;
3070                                 break;
3071                         }
3072
3073                         pmc_restore_cpu_binding(&pb);
3074                 }
3075
3076                 pmc->pm_state    = PMC_STATE_ALLOCATED;
3077
3078                 /*
3079                  * mark row disposition
3080                  */
3081
3082                 if (PMC_IS_SYSTEM_MODE(mode))
3083                         PMC_MARK_ROW_STANDALONE(n);
3084                 else
3085                         PMC_MARK_ROW_THREAD(n);
3086
3087                 /*
3088                  * Register this PMC with the current thread as its owner.
3089                  */
3090
3091                 if ((error =
3092                     pmc_register_owner(curthread->td_proc, pmc)) != 0) {
3093                         pmc_release_pmc_descriptor(pmc);
3094                         FREE(pmc, M_PMC);
3095                         pmc = NULL;
3096                         break;
3097                 }
3098
3099                 /*
3100                  * Return the allocated index.
3101                  */
3102
3103                 pa.pm_pmcid = pmc->pm_id;
3104
3105                 error = copyout(&pa, arg, sizeof(pa));
3106         }
3107         break;
3108
3109
3110         /*
3111          * Attach a PMC to a process.
3112          */
3113
3114         case PMC_OP_PMCATTACH:
3115         {
3116                 struct pmc *pm;
3117                 struct proc *p;
3118                 struct pmc_op_pmcattach a;
3119
3120                 sx_assert(&pmc_sx, SX_XLOCKED);
3121
3122                 if ((error = copyin(arg, &a, sizeof(a))) != 0)
3123                         break;
3124
3125                 if (a.pm_pid < 0) {
3126                         error = EINVAL;
3127                         break;
3128                 } else if (a.pm_pid == 0)
3129                         a.pm_pid = td->td_proc->p_pid;
3130
3131                 if ((error = pmc_find_pmc(a.pm_pmc, &pm)) != 0)
3132                         break;
3133
3134                 if (PMC_IS_SYSTEM_MODE(PMC_TO_MODE(pm))) {
3135                         error = EINVAL;
3136                         break;
3137                 }
3138
3139                 /* PMCs may be (re)attached only when allocated or stopped */
3140                 if (pm->pm_state == PMC_STATE_RUNNING) {
3141                         error = EBUSY;
3142                         break;
3143                 } else if (pm->pm_state != PMC_STATE_ALLOCATED &&
3144                     pm->pm_state != PMC_STATE_STOPPED) {
3145                         error = EINVAL;
3146                         break;
3147                 }
3148
3149                 /* lookup pid */
3150                 if ((p = pfind(a.pm_pid)) == NULL) {
3151                         error = ESRCH;
3152                         break;
3153                 }
3154
3155                 /*
3156                  * Ignore processes that are working on exiting.
3157                  */
3158                 if (p->p_flag & P_WEXIT) {
3159                         error = ESRCH;
3160                         PROC_UNLOCK(p); /* pfind() returns a locked process */
3161                         break;
3162                 }
3163
3164                 /*
3165                  * we are allowed to attach a PMC to a process if
3166                  * we can debug it.
3167                  */
3168                 error = p_candebug(curthread, p);
3169
3170                 PROC_UNLOCK(p);
3171
3172                 if (error == 0)
3173                         error = pmc_attach_process(p, pm);
3174         }
3175         break;
3176
3177
3178         /*
3179          * Detach an attached PMC from a process.
3180          */
3181
3182         case PMC_OP_PMCDETACH:
3183         {
3184                 struct pmc *pm;
3185                 struct proc *p;
3186                 struct pmc_op_pmcattach a;
3187
3188                 if ((error = copyin(arg, &a, sizeof(a))) != 0)
3189                         break;
3190
3191                 if (a.pm_pid < 0) {
3192                         error = EINVAL;
3193                         break;
3194                 } else if (a.pm_pid == 0)
3195                         a.pm_pid = td->td_proc->p_pid;
3196
3197                 if ((error = pmc_find_pmc(a.pm_pmc, &pm)) != 0)
3198                         break;
3199
3200                 if ((p = pfind(a.pm_pid)) == NULL) {
3201                         error = ESRCH;
3202                         break;
3203                 }
3204
3205                 /*
3206                  * Treat processes that are in the process of exiting
3207                  * as if they were not present.
3208                  */
3209
3210                 if (p->p_flag & P_WEXIT)
3211                         error = ESRCH;
3212
3213                 PROC_UNLOCK(p); /* pfind() returns a locked process */
3214
3215                 if (error == 0)
3216                         error = pmc_detach_process(p, pm);
3217         }
3218         break;
3219
3220
3221         /*
3222          * Retrieve the MSR number associated with the counter
3223          * 'pmc_id'.  This allows processes to directly use RDPMC
3224          * instructions to read their PMCs, without the overhead of a
3225          * system call.
3226          */
3227
3228         case PMC_OP_PMCGETMSR:
3229         {
3230                 int ri;
3231                 struct pmc      *pm;
3232                 struct pmc_target *pt;
3233                 struct pmc_op_getmsr gm;
3234
3235                 PMC_DOWNGRADE_SX();
3236
3237                 /* CPU has no 'GETMSR' support */
3238                 if (md->pmd_get_msr == NULL) {
3239                         error = ENOSYS;
3240                         break;
3241                 }
3242
3243                 if ((error = copyin(arg, &gm, sizeof(gm))) != 0)
3244                         break;
3245
3246                 if ((error = pmc_find_pmc(gm.pm_pmcid, &pm)) != 0)
3247                         break;
3248
3249                 /*
3250                  * The allocated PMC has to be a process virtual PMC,
3251                  * i.e., of type MODE_T[CS].  Global PMCs can only be
3252                  * read using the PMCREAD operation since they may be
3253                  * allocated on a different CPU than the one we could
3254                  * be running on at the time of the RDPMC instruction.
3255                  *
3256                  * The GETMSR operation is not allowed for PMCs that
3257                  * are inherited across processes.
3258                  */
3259
3260                 if (!PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)) ||
3261                     (pm->pm_flags & PMC_F_DESCENDANTS)) {
3262                         error = EINVAL;
3263                         break;
3264                 }
3265
3266                 /*
3267                  * It only makes sense to use a RDPMC (or its
3268                  * equivalent instruction on non-x86 architectures) on
3269                  * a process that has allocated and attached a PMC to
3270                  * itself.  Conversely the PMC is only allowed to have
3271                  * one process attached to it -- its owner.
3272                  */
3273
3274                 if ((pt = LIST_FIRST(&pm->pm_targets)) == NULL ||
3275                     LIST_NEXT(pt, pt_next) != NULL ||
3276                     pt->pt_process->pp_proc != pm->pm_owner->po_owner) {
3277                         error = EINVAL;
3278                         break;
3279                 }
3280
3281                 ri = PMC_TO_ROWINDEX(pm);
3282
3283                 if ((error = (*md->pmd_get_msr)(ri, &gm.pm_msr)) < 0)
3284                         break;
3285
3286                 if ((error = copyout(&gm, arg, sizeof(gm))) < 0)
3287                         break;
3288
3289                 /*
3290                  * Mark our process as using MSRs.  Update machine
3291                  * state using a forced context switch.
3292                  */
3293
3294                 pt->pt_process->pp_flags |= PMC_PP_ENABLE_MSR_ACCESS;
3295                 pmc_force_context_switch();
3296
3297         }
3298         break;
3299
3300         /*
3301          * Release an allocated PMC
3302          */
3303
3304         case PMC_OP_PMCRELEASE:
3305         {
3306                 pmc_id_t pmcid;
3307                 struct pmc *pm;
3308                 struct pmc_owner *po;
3309                 struct pmc_op_simple sp;
3310
3311                 /*
3312                  * Find PMC pointer for the named PMC.
3313                  *
3314                  * Use pmc_release_pmc_descriptor() to switch off the
3315                  * PMC, remove all its target threads, and remove the
3316                  * PMC from its owner's list.
3317                  *
3318                  * Remove the owner record if this is the last PMC
3319                  * owned.
3320                  *
3321                  * Free up space.
3322                  */
3323
3324                 if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
3325                         break;
3326
3327                 pmcid = sp.pm_pmcid;
3328
3329                 if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
3330                         break;
3331
3332                 po = pm->pm_owner;
3333                 pmc_release_pmc_descriptor(pm);
3334                 pmc_maybe_remove_owner(po);
3335
3336                 FREE(pm, M_PMC);
3337         }
3338         break;
3339
3340
3341         /*
3342          * Read and/or write a PMC.
3343          */
3344
3345         case PMC_OP_PMCRW:
3346         {
3347                 uint32_t cpu, ri;
3348                 struct pmc *pm;
3349                 struct pmc_op_pmcrw *pprw;
3350                 struct pmc_op_pmcrw prw;
3351                 struct pmc_binding pb;
3352                 pmc_value_t oldvalue;
3353
3354                 PMC_DOWNGRADE_SX();
3355
3356                 if ((error = copyin(arg, &prw, sizeof(prw))) != 0)
3357                         break;
3358
3359                 ri = 0;
3360                 PMCDBG(PMC,OPS,1, "rw id=%d flags=0x%x", prw.pm_pmcid,
3361                     prw.pm_flags);
3362
3363                 /* must have at least one flag set */
3364                 if ((prw.pm_flags & (PMC_F_OLDVALUE|PMC_F_NEWVALUE)) == 0) {
3365                         error = EINVAL;
3366                         break;
3367                 }
3368
3369                 /* locate pmc descriptor */
3370                 if ((error = pmc_find_pmc(prw.pm_pmcid, &pm)) != 0)
3371                         break;
3372
3373                 /* Can't read a PMC that hasn't been started. */
3374                 if (pm->pm_state != PMC_STATE_ALLOCATED &&
3375                     pm->pm_state != PMC_STATE_STOPPED &&
3376                     pm->pm_state != PMC_STATE_RUNNING) {
3377                         error = EINVAL;
3378                         break;
3379                 }
3380
3381                 /* writing a new value is allowed only for 'STOPPED' pmcs */
3382                 if (pm->pm_state == PMC_STATE_RUNNING &&
3383                     (prw.pm_flags & PMC_F_NEWVALUE)) {
3384                         error = EBUSY;
3385                         break;
3386                 }
3387
3388                 if (PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm))) {
3389
3390                         /*
3391                          * If this PMC is attached to its owner (i.e.,
3392                          * the process requesting this operation) and
3393                          * is running, then attempt to get an
3394                          * upto-date reading from hardware for a READ.
3395                          * Writes are only allowed when the PMC is
3396                          * stopped, so only update the saved value
3397                          * field.
3398                          *
3399                          * If the PMC is not running, or is not
3400                          * attached to its owner, read/write to the
3401                          * savedvalue field.
3402                          */
3403
3404                         ri = PMC_TO_ROWINDEX(pm);
3405
3406                         mtx_pool_lock_spin(pmc_mtxpool, pm);
3407                         cpu = curthread->td_oncpu;
3408
3409                         if (prw.pm_flags & PMC_F_OLDVALUE) {
3410                                 if ((pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) &&
3411                                     (pm->pm_state == PMC_STATE_RUNNING))
3412                                         error = (*md->pmd_read_pmc)(cpu, ri,
3413                                             &oldvalue);
3414                                 else
3415                                         oldvalue = pm->pm_gv.pm_savedvalue;
3416                         }
3417                         if (prw.pm_flags & PMC_F_NEWVALUE)
3418                                 pm->pm_gv.pm_savedvalue = prw.pm_value;
3419
3420                         mtx_pool_unlock_spin(pmc_mtxpool, pm);
3421
3422                 } else { /* System mode PMCs */
3423                         cpu = PMC_TO_CPU(pm);
3424                         ri  = PMC_TO_ROWINDEX(pm);
3425
3426                         if (pmc_cpu_is_disabled(cpu)) {
3427                                 error = ENXIO;
3428                                 break;
3429                         }
3430
3431                         /* move this thread to CPU 'cpu' */
3432                         pmc_save_cpu_binding(&pb);
3433                         pmc_select_cpu(cpu);
3434
3435                         critical_enter();
3436                         /* save old value */
3437                         if (prw.pm_flags & PMC_F_OLDVALUE)
3438                                 if ((error = (*md->pmd_read_pmc)(cpu, ri,
3439                                          &oldvalue)))
3440                                         goto error;
3441                         /* write out new value */
3442                         if (prw.pm_flags & PMC_F_NEWVALUE)
3443                                 error = (*md->pmd_write_pmc)(cpu, ri,
3444                                     prw.pm_value);
3445                 error:
3446                         critical_exit();
3447                         pmc_restore_cpu_binding(&pb);
3448                         if (error)
3449                                 break;
3450                 }
3451
3452                 pprw = (struct pmc_op_pmcrw *) arg;
3453
3454 #ifdef  DEBUG
3455                 if (prw.pm_flags & PMC_F_NEWVALUE)
3456                         PMCDBG(PMC,OPS,2, "rw id=%d new %jx -> old %jx",
3457                             ri, prw.pm_value, oldvalue);
3458                 else if (prw.pm_flags & PMC_F_OLDVALUE)
3459                         PMCDBG(PMC,OPS,2, "rw id=%d -> old %jx", ri, oldvalue);
3460 #endif
3461
3462                 /* return old value if requested */
3463                 if (prw.pm_flags & PMC_F_OLDVALUE)
3464                         if ((error = copyout(&oldvalue, &pprw->pm_value,
3465                                  sizeof(prw.pm_value))))
3466                                 break;
3467
3468         }
3469         break;
3470
3471
3472         /*
3473          * Set the sampling rate for a sampling mode PMC and the
3474          * initial count for a counting mode PMC.
3475          */
3476
3477         case PMC_OP_PMCSETCOUNT:
3478         {
3479                 struct pmc *pm;
3480                 struct pmc_op_pmcsetcount sc;
3481
3482                 PMC_DOWNGRADE_SX();
3483
3484                 if ((error = copyin(arg, &sc, sizeof(sc))) != 0)
3485                         break;
3486
3487                 if ((error = pmc_find_pmc(sc.pm_pmcid, &pm)) != 0)
3488                         break;
3489
3490                 if (pm->pm_state == PMC_STATE_RUNNING) {
3491                         error = EBUSY;
3492                         break;
3493                 }
3494
3495                 if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
3496                         pm->pm_sc.pm_reloadcount = sc.pm_count;
3497                 else
3498                         pm->pm_sc.pm_initial = sc.pm_count;
3499         }
3500         break;
3501
3502
3503         /*
3504          * Start a PMC.
3505          */
3506
3507         case PMC_OP_PMCSTART:
3508         {
3509                 pmc_id_t pmcid;
3510                 struct pmc *pm;
3511                 struct pmc_op_simple sp;
3512
3513                 sx_assert(&pmc_sx, SX_XLOCKED);
3514
3515                 if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
3516                         break;
3517
3518                 pmcid = sp.pm_pmcid;
3519
3520                 if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
3521                         break;
3522
3523                 KASSERT(pmcid == pm->pm_id,
3524                     ("[pmc,%d] pmcid %x != id %x", __LINE__,
3525                         pm->pm_id, pmcid));
3526
3527                 if (pm->pm_state == PMC_STATE_RUNNING) /* already running */
3528                         break;
3529                 else if (pm->pm_state != PMC_STATE_STOPPED &&
3530                     pm->pm_state != PMC_STATE_ALLOCATED) {
3531                         error = EINVAL;
3532                         break;
3533                 }
3534
3535                 error = pmc_start(pm);
3536         }
3537         break;
3538
3539
3540         /*
3541          * Stop a PMC.
3542          */
3543
3544         case PMC_OP_PMCSTOP:
3545         {
3546                 pmc_id_t pmcid;
3547                 struct pmc *pm;
3548                 struct pmc_op_simple sp;
3549
3550                 PMC_DOWNGRADE_SX();
3551
3552                 if ((error = copyin(arg, &sp, sizeof(sp))) != 0)
3553                         break;
3554
3555                 pmcid = sp.pm_pmcid;
3556
3557                 /*
3558                  * Mark the PMC as inactive and invoke the MD stop
3559                  * routines if needed.
3560                  */
3561
3562                 if ((error = pmc_find_pmc(pmcid, &pm)) != 0)
3563                         break;
3564
3565                 KASSERT(pmcid == pm->pm_id,
3566                     ("[pmc,%d] pmc id %x != pmcid %x", __LINE__,
3567                         pm->pm_id, pmcid));
3568
3569                 if (pm->pm_state == PMC_STATE_STOPPED) /* already stopped */
3570                         break;
3571                 else if (pm->pm_state != PMC_STATE_RUNNING) {
3572                         error = EINVAL;
3573                         break;
3574                 }
3575
3576                 error = pmc_stop(pm);
3577         }
3578         break;
3579
3580
3581         /*
3582          * Write a user supplied value to the log file.
3583          */
3584
3585         case PMC_OP_WRITELOG:
3586         {
3587                 struct pmc_op_writelog wl;
3588                 struct pmc_owner *po;
3589
3590                 PMC_DOWNGRADE_SX();
3591
3592                 if ((error = copyin(arg, &wl, sizeof(wl))) != 0)
3593                         break;
3594
3595                 if ((po = pmc_find_owner_descriptor(td->td_proc)) == NULL) {
3596                         error = EINVAL;
3597                         break;
3598                 }
3599
3600                 if ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0) {
3601                         error = EINVAL;
3602                         break;
3603                 }
3604
3605                 error = pmclog_process_userlog(po, &wl);
3606         }
3607         break;
3608
3609
3610         default:
3611                 error = EINVAL;
3612                 break;
3613         }
3614
3615         if (is_sx_downgraded)
3616                 sx_sunlock(&pmc_sx);
3617         else
3618                 sx_xunlock(&pmc_sx);
3619
3620         if (error)
3621                 atomic_add_int(&pmc_stats.pm_syscall_errors, 1);
3622
3623         PICKUP_GIANT();
3624
3625         return error;
3626 }
3627
3628 /*
3629  * Helper functions
3630  */
3631
3632
3633 /*
3634  * Interrupt processing.
3635  *
3636  * Find a free slot in the per-cpu array of PC samples and write the
3637  * current (PMC,PID,PC) triple to it.  If an event was successfully
3638  * added, a bit is set in mask 'pmc_cpumask' denoting that the
3639  * DO_SAMPLES hook needs to be invoked from the clock handler.
3640  *
3641  * This function is meant to be called from an NMI handler.  It cannot
3642  * use any of the locking primitives supplied by the OS.
3643  */
3644
3645 int
3646 pmc_process_interrupt(int cpu, struct pmc *pm, uintfptr_t pc, int usermode)
3647 {
3648         int error, ri;
3649         struct thread *td;
3650         struct pmc_sample *ps;
3651         struct pmc_samplebuffer *psb;
3652
3653         error = 0;
3654         ri = PMC_TO_ROWINDEX(pm);
3655
3656         psb = pmc_pcpu[cpu]->pc_sb;
3657
3658         ps = psb->ps_write;
3659         if (ps->ps_pc) {        /* in use, reader hasn't caught up */
3660                 pm->pm_stalled = 1;
3661                 atomic_add_int(&pmc_stats.pm_intr_bufferfull, 1);
3662                 PMCDBG(SAM,INT,1,"(spc) cpu=%d pm=%p pc=%jx um=%d wr=%d rd=%d",
3663                     cpu, pm, (uint64_t) pc, usermode,
3664                     (int) (psb->ps_write - psb->ps_samples),
3665                     (int) (psb->ps_read - psb->ps_samples));
3666                 error = ENOMEM;
3667                 goto done;
3668         }
3669
3670         /* fill in entry */
3671         PMCDBG(SAM,INT,1,"cpu=%d pm=%p pc=%jx um=%d wr=%d rd=%d", cpu, pm,
3672             (uint64_t) pc, usermode,
3673             (int) (psb->ps_write - psb->ps_samples),
3674             (int) (psb->ps_read - psb->ps_samples));
3675
3676         atomic_add_rel_32(&pm->pm_runcount, 1);         /* hold onto PMC */
3677         ps->ps_pmc = pm;
3678         if ((td = curthread) && td->td_proc)
3679                 ps->ps_pid = td->td_proc->p_pid;
3680         else
3681                 ps->ps_pid = -1;
3682         ps->ps_usermode = usermode;
3683         ps->ps_pc = pc;         /* mark entry as in use */
3684
3685         /* increment write pointer, modulo ring buffer size */
3686         ps++;
3687         if (ps == psb->ps_fence)
3688                 psb->ps_write = psb->ps_samples;
3689         else
3690                 psb->ps_write = ps;
3691
3692  done:
3693         /* mark CPU as needing processing */
3694         atomic_set_rel_int(&pmc_cpumask, (1 << cpu));
3695
3696         return error;
3697 }
3698
3699
3700 /*
3701  * Process saved PC samples.
3702  */
3703
3704 static void
3705 pmc_process_samples(int cpu)
3706 {
3707         int n, ri;
3708         struct pmc *pm;
3709         struct thread *td;
3710         struct pmc_owner *po;
3711         struct pmc_sample *ps;
3712         struct pmc_samplebuffer *psb;
3713
3714         KASSERT(PCPU_GET(cpuid) == cpu,
3715             ("[pmc,%d] not on the correct CPU pcpu=%d cpu=%d", __LINE__,
3716                 PCPU_GET(cpuid), cpu));
3717
3718         psb = pmc_pcpu[cpu]->pc_sb;
3719
3720         for (n = 0; n < pmc_nsamples; n++) { /* bound on #iterations */
3721
3722                 ps = psb->ps_read;
3723                 if (ps->ps_pc == (uintfptr_t) 0)        /* no data */
3724                         break;
3725
3726                 pm = ps->ps_pmc;
3727                 po = pm->pm_owner;
3728
3729                 KASSERT(PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)),
3730                     ("[pmc,%d] pmc=%p non-sampling mode=%d", __LINE__,
3731                         pm, PMC_TO_MODE(pm)));
3732
3733                 /* Ignore PMCs that have been switched off */
3734                 if (pm->pm_state != PMC_STATE_RUNNING)
3735                         goto entrydone;
3736
3737                 PMCDBG(SAM,OPS,1,"cpu=%d pm=%p pc=%jx um=%d wr=%d rd=%d", cpu,
3738                     pm, (uint64_t) ps->ps_pc, ps->ps_usermode,
3739                     (int) (psb->ps_write - psb->ps_samples),
3740                     (int) (psb->ps_read - psb->ps_samples));
3741
3742                 /*
3743                  * If this is a process-mode PMC that is attached to
3744                  * its owner, and if the PC is in user mode, update
3745                  * profiling statistics like timer-based profiling
3746                  * would have done.
3747                  */
3748                 if (pm->pm_flags & PMC_F_ATTACHED_TO_OWNER) {
3749                         if (ps->ps_usermode) {
3750                                 td = FIRST_THREAD_IN_PROC(po->po_owner);
3751                                 addupc_intr(td, ps->ps_pc, 1);
3752                         }
3753                         goto entrydone;
3754                 }
3755
3756                 /*
3757                  * Otherwise, this is either a sampling mode PMC that
3758                  * is attached to a different process than its owner,
3759                  * or a system-wide sampling PMC.  Dispatch a log
3760                  * entry to the PMC's owner process.
3761                  */
3762
3763                 pmclog_process_pcsample(pm, ps);
3764
3765         entrydone:
3766                 ps->ps_pc = (uintfptr_t) 0;     /* mark entry as free */
3767                 atomic_subtract_rel_32(&pm->pm_runcount, 1);
3768
3769                 /* increment read pointer, modulo sample size */
3770                 if (++ps == psb->ps_fence)
3771                         psb->ps_read = psb->ps_samples;
3772                 else
3773                         psb->ps_read = ps;
3774         }
3775
3776         atomic_add_int(&pmc_stats.pm_log_sweeps, 1);
3777
3778         /* Do not re-enable stalled PMCs if we failed to process any samples */
3779         if (n == 0)
3780                 return;
3781
3782         /*
3783          * Restart any stalled sampling PMCs on this CPU.
3784          *
3785          * If the NMI handler sets the pm_stalled field of a PMC after
3786          * the check below, we'll end up processing the stalled PMC at
3787          * the next hardclock tick.
3788          */
3789         for (n = 0; n < md->pmd_npmc; n++) {
3790                 (void) (*md->pmd_get_config)(cpu,n,&pm);
3791                 if (pm == NULL ||                        /* !cfg'ed */
3792                     pm->pm_state != PMC_STATE_RUNNING || /* !active */
3793                     !PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)) || /* !sampling */
3794                     pm->pm_stalled == 0) /* !stalled */
3795                         continue;
3796
3797                 pm->pm_stalled = 0;
3798                 ri = PMC_TO_ROWINDEX(pm);
3799                 (*md->pmd_start_pmc)(cpu, ri);
3800         }
3801 }
3802
3803 /*
3804  * Event handlers.
3805  */
3806
3807 /*
3808  * Handle a process exit.
3809  *
3810  * Remove this process from all hash tables.  If this process
3811  * owned any PMCs, turn off those PMCs and deallocate them,
3812  * removing any associations with target processes.
3813  *
3814  * This function will be called by the last 'thread' of a
3815  * process.
3816  *
3817  * XXX This eventhandler gets called early in the exit process.
3818  * Consider using a 'hook' invocation from thread_exit() or equivalent
3819  * spot.  Another negative is that kse_exit doesn't seem to call
3820  * exit1() [??].
3821  *
3822  */
3823
3824 static void
3825 pmc_process_exit(void *arg __unused, struct proc *p)
3826 {
3827         int is_using_hwpmcs;
3828         int cpu;
3829         unsigned int ri;
3830         struct pmc *pm;
3831         struct pmc_process *pp;
3832         struct pmc_owner *po;
3833         pmc_value_t newvalue, tmp;
3834
3835         PROC_LOCK(p);
3836         is_using_hwpmcs = p->p_flag & P_HWPMC;
3837         PROC_UNLOCK(p);
3838
3839         /*
3840          * Log a sysexit event to all SS PMC owners.
3841          */
3842         LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
3843             if (po->po_flags & PMC_PO_OWNS_LOGFILE)
3844                     pmclog_process_sysexit(po, p->p_pid);
3845
3846         if (!is_using_hwpmcs)
3847                 return;
3848
3849         PMC_GET_SX_XLOCK();
3850         PMCDBG(PRC,EXT,1,"process-exit proc=%p (%d, %s)", p, p->p_pid,
3851             p->p_comm);
3852
3853         /*
3854          * Since this code is invoked by the last thread in an exiting
3855          * process, we would have context switched IN at some prior
3856          * point.  However, with PREEMPTION, kernel mode context
3857          * switches may happen any time, so we want to disable a
3858          * context switch OUT till we get any PMCs targetting this
3859          * process off the hardware.
3860          *
3861          * We also need to atomically remove this process'
3862          * entry from our target process hash table, using
3863          * PMC_FLAG_REMOVE.
3864          */
3865         PMCDBG(PRC,EXT,1, "process-exit proc=%p (%d, %s)", p, p->p_pid,
3866             p->p_comm);
3867
3868         critical_enter(); /* no preemption */
3869
3870         cpu = curthread->td_oncpu;
3871
3872         if ((pp = pmc_find_process_descriptor(p,
3873                  PMC_FLAG_REMOVE)) != NULL) {
3874
3875                 PMCDBG(PRC,EXT,2,
3876                     "process-exit proc=%p pmc-process=%p", p, pp);
3877
3878                 /*
3879                  * The exiting process could the target of
3880                  * some PMCs which will be running on
3881                  * currently executing CPU.
3882                  *
3883                  * We need to turn these PMCs off like we
3884                  * would do at context switch OUT time.
3885                  */
3886                 for (ri = 0; ri < md->pmd_npmc; ri++) {
3887
3888                         /*
3889                          * Pick up the pmc pointer from hardware
3890                          * state similar to the CSW_OUT code.
3891                          */
3892                         pm = NULL;
3893                         (void) (*md->pmd_get_config)(cpu, ri, &pm);
3894
3895                         PMCDBG(PRC,EXT,2, "ri=%d pm=%p", ri, pm);
3896
3897                         if (pm == NULL ||
3898                             !PMC_IS_VIRTUAL_MODE(PMC_TO_MODE(pm)))
3899                                 continue;
3900
3901                         PMCDBG(PRC,EXT,2, "ppmcs[%d]=%p pm=%p "
3902                             "state=%d", ri, pp->pp_pmcs[ri].pp_pmc,
3903                             pm, pm->pm_state);
3904
3905                         KASSERT(PMC_TO_ROWINDEX(pm) == ri,
3906                             ("[pmc,%d] ri mismatch pmc(%d) ri(%d)",
3907                                 __LINE__, PMC_TO_ROWINDEX(pm), ri));
3908
3909                         KASSERT(pm == pp->pp_pmcs[ri].pp_pmc,
3910                             ("[pmc,%d] pm %p != pp_pmcs[%d] %p",
3911                                 __LINE__, pm, ri, pp->pp_pmcs[ri].pp_pmc));
3912
3913                         (void) md->pmd_stop_pmc(cpu, ri);
3914
3915                         KASSERT(pm->pm_runcount > 0,
3916                             ("[pmc,%d] bad runcount ri %d rc %d",
3917                                 __LINE__, ri, pm->pm_runcount));
3918
3919                         /* Stop hardware only if it is actually running */
3920                         if (pm->pm_state == PMC_STATE_RUNNING &&
3921                             pm->pm_stalled == 0) {
3922                                 md->pmd_read_pmc(cpu, ri, &newvalue);
3923                                 tmp = newvalue -
3924                                     PMC_PCPU_SAVED(cpu,ri);
3925
3926                                 mtx_pool_lock_spin(pmc_mtxpool, pm);
3927                                 pm->pm_gv.pm_savedvalue += tmp;
3928                                 pp->pp_pmcs[ri].pp_pmcval += tmp;
3929                                 mtx_pool_unlock_spin(pmc_mtxpool, pm);
3930                         }
3931
3932                         atomic_subtract_rel_32(&pm->pm_runcount,1);
3933
3934                         KASSERT((int) pm->pm_runcount >= 0,
3935                             ("[pmc,%d] runcount is %d", __LINE__, ri));
3936
3937                         (void) md->pmd_config_pmc(cpu, ri, NULL);
3938                 }
3939
3940                 /*
3941                  * Inform the MD layer of this pseudo "context switch
3942                  * out"
3943                  */
3944                 (void) md->pmd_switch_out(pmc_pcpu[cpu], pp);
3945
3946                 critical_exit(); /* ok to be pre-empted now */
3947
3948                 /*
3949                  * Unlink this process from the PMCs that are
3950                  * targetting it.  This will send a signal to
3951                  * all PMC owner's whose PMCs are orphaned.
3952                  *
3953                  * Log PMC value at exit time if requested.
3954                  */
3955                 for (ri = 0; ri < md->pmd_npmc; ri++)
3956                         if ((pm = pp->pp_pmcs[ri].pp_pmc) != NULL) {
3957                                 if (pm->pm_flags & PMC_F_NEEDS_LOGFILE &&
3958                                     PMC_IS_COUNTING_MODE(PMC_TO_MODE(pm)))
3959                                         pmclog_process_procexit(pm, pp);
3960                                 pmc_unlink_target_process(pm, pp);
3961                         }
3962                 FREE(pp, M_PMC);
3963
3964         } else
3965                 critical_exit(); /* pp == NULL */
3966
3967
3968         /*
3969          * If the process owned PMCs, free them up and free up
3970          * memory.
3971          */
3972         if ((po = pmc_find_owner_descriptor(p)) != NULL) {
3973                 pmc_remove_owner(po);
3974                 pmc_destroy_owner_descriptor(po);
3975         }
3976
3977         sx_xunlock(&pmc_sx);
3978 }
3979
3980 /*
3981  * Handle a process fork.
3982  *
3983  * If the parent process 'p1' is under HWPMC monitoring, then copy
3984  * over any attached PMCs that have 'do_descendants' semantics.
3985  */
3986
3987 static void
3988 pmc_process_fork(void *arg __unused, struct proc *p1, struct proc *newproc,
3989     int flags)
3990 {
3991         int is_using_hwpmcs;
3992         unsigned int ri;
3993         uint32_t do_descendants;
3994         struct pmc *pm;
3995         struct pmc_owner *po;
3996         struct pmc_process *ppnew, *ppold;
3997
3998         (void) flags;           /* unused parameter */
3999
4000         PROC_LOCK(p1);
4001         is_using_hwpmcs = p1->p_flag & P_HWPMC;
4002         PROC_UNLOCK(p1);
4003
4004         /*
4005          * If there are system-wide sampling PMCs active, we need to
4006          * log all fork events to their owner's logs.
4007          */
4008
4009         LIST_FOREACH(po, &pmc_ss_owners, po_ssnext)
4010             if (po->po_flags & PMC_PO_OWNS_LOGFILE)
4011                     pmclog_process_procfork(po, p1->p_pid, newproc->p_pid);
4012
4013         if (!is_using_hwpmcs)
4014                 return;
4015
4016         PMC_GET_SX_XLOCK();
4017         PMCDBG(PMC,FRK,1, "process-fork proc=%p (%d, %s) -> %p", p1,
4018             p1->p_pid, p1->p_comm, newproc);
4019
4020         /*
4021          * If the parent process (curthread->td_proc) is a
4022          * target of any PMCs, look for PMCs that are to be
4023          * inherited, and link these into the new process
4024          * descriptor.
4025          */
4026         if ((ppold = pmc_find_process_descriptor(curthread->td_proc,
4027                  PMC_FLAG_NONE)) == NULL)
4028                 goto done;              /* nothing to do */
4029
4030         do_descendants = 0;
4031         for (ri = 0; ri < md->pmd_npmc; ri++)
4032                 if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL)
4033                         do_descendants |= pm->pm_flags & PMC_F_DESCENDANTS;
4034         if (do_descendants == 0) /* nothing to do */
4035                 goto done;
4036
4037         /* allocate a descriptor for the new process  */
4038         if ((ppnew = pmc_find_process_descriptor(newproc,
4039                  PMC_FLAG_ALLOCATE)) == NULL)
4040                 goto done;
4041
4042         /*
4043          * Run through all PMCs that were targeting the old process
4044          * and which specified F_DESCENDANTS and attach them to the
4045          * new process.
4046          *
4047          * Log the fork event to all owners of PMCs attached to this
4048          * process, if not already logged.
4049          */
4050         for (ri = 0; ri < md->pmd_npmc; ri++)
4051                 if ((pm = ppold->pp_pmcs[ri].pp_pmc) != NULL &&
4052                     (pm->pm_flags & PMC_F_DESCENDANTS)) {
4053                         pmc_link_target_process(pm, ppnew);
4054                         po = pm->pm_owner;
4055                         if (po->po_sscount == 0 &&
4056                             po->po_flags & PMC_PO_OWNS_LOGFILE)
4057                                 pmclog_process_procfork(po, p1->p_pid,
4058                                     newproc->p_pid);
4059                 }
4060
4061         /*
4062          * Now mark the new process as being tracked by this driver.
4063          */
4064         PROC_LOCK(newproc);
4065         newproc->p_flag |= P_HWPMC;
4066         PROC_UNLOCK(newproc);
4067
4068  done:
4069         sx_xunlock(&pmc_sx);
4070 }
4071
4072
4073 /*
4074  * initialization
4075  */
4076
4077 static const char *pmc_name_of_pmcclass[] = {
4078 #undef  __PMC_CLASS
4079 #define __PMC_CLASS(N) #N ,
4080         __PMC_CLASSES()
4081 };
4082
4083 static int
4084 pmc_initialize(void)
4085 {
4086         int cpu, error, n;
4087         struct pmc_binding pb;
4088         struct pmc_samplebuffer *sb;
4089
4090         md = NULL;
4091         error = 0;
4092
4093 #ifdef  DEBUG
4094         /* parse debug flags first */
4095         if (TUNABLE_STR_FETCH(PMC_SYSCTL_NAME_PREFIX "debugflags",
4096                 pmc_debugstr, sizeof(pmc_debugstr)))
4097                 pmc_debugflags_parse(pmc_debugstr,
4098                     pmc_debugstr+strlen(pmc_debugstr));
4099 #endif
4100
4101         PMCDBG(MOD,INI,0, "PMC Initialize (version %x)", PMC_VERSION);
4102
4103         /* check kernel version */
4104         if (pmc_kernel_version != PMC_VERSION) {
4105                 if (pmc_kernel_version == 0)
4106                         printf("hwpmc: this kernel has not been compiled with "
4107                             "'options HWPMC_HOOKS'.\n");
4108                 else
4109                         printf("hwpmc: kernel version (0x%x) does not match "
4110                             "module version (0x%x).\n", pmc_kernel_version,
4111                             PMC_VERSION);
4112                 return EPROGMISMATCH;
4113         }
4114
4115         /*
4116          * check sysctl parameters
4117          */
4118
4119         if (pmc_hashsize <= 0) {
4120                 (void) printf("hwpmc: tunable hashsize=%d must be greater "
4121                     "than zero.\n", pmc_hashsize);
4122                 pmc_hashsize = PMC_HASH_SIZE;
4123         }
4124
4125         if (pmc_nsamples <= 0 || pmc_nsamples > 65535) {
4126                 (void) printf("hwpmc: tunable nsamples=%d out of range.\n",
4127                     pmc_nsamples);
4128                 pmc_nsamples = PMC_NSAMPLES;
4129         }
4130
4131         md = pmc_md_initialize();
4132
4133         if (md == NULL || md->pmd_init == NULL)
4134                 return ENOSYS;
4135
4136         /* allocate space for the per-cpu array */
4137         MALLOC(pmc_pcpu, struct pmc_cpu **, mp_ncpus * sizeof(struct pmc_cpu *),
4138             M_PMC, M_WAITOK|M_ZERO);
4139
4140         /* per-cpu 'saved values' for managing process-mode PMCs */
4141         MALLOC(pmc_pcpu_saved, pmc_value_t *,
4142             sizeof(pmc_value_t) * mp_ncpus * md->pmd_npmc, M_PMC, M_WAITOK);
4143
4144         /* perform cpu dependent initialization */
4145         pmc_save_cpu_binding(&pb);
4146         for (cpu = 0; cpu < mp_ncpus; cpu++) {
4147                 if (pmc_cpu_is_disabled(cpu))
4148                         continue;
4149                 pmc_select_cpu(cpu);
4150                 if ((error = md->pmd_init(cpu)) != 0)
4151                         break;
4152         }
4153         pmc_restore_cpu_binding(&pb);
4154
4155         if (error != 0)
4156                 return error;
4157
4158         /* allocate space for the sample array */
4159         for (cpu = 0; cpu < mp_ncpus; cpu++) {
4160                 if (pmc_cpu_is_disabled(cpu))
4161                         continue;
4162                 MALLOC(sb, struct pmc_samplebuffer *,
4163                     sizeof(struct pmc_samplebuffer) +
4164                     pmc_nsamples * sizeof(struct pmc_sample), M_PMC,
4165                     M_WAITOK|M_ZERO);
4166
4167                 sb->ps_read = sb->ps_write = sb->ps_samples;
4168                 sb->ps_fence = sb->ps_samples + pmc_nsamples;
4169                 KASSERT(pmc_pcpu[cpu] != NULL,
4170                     ("[pmc,%d] cpu=%d Null per-cpu data", __LINE__, cpu));
4171
4172                 pmc_pcpu[cpu]->pc_sb = sb;
4173         }
4174
4175         /* allocate space for the row disposition array */
4176         pmc_pmcdisp = malloc(sizeof(enum pmc_mode) * md->pmd_npmc,
4177             M_PMC, M_WAITOK|M_ZERO);
4178
4179         KASSERT(pmc_pmcdisp != NULL,
4180             ("[pmc,%d] pmcdisp allocation returned NULL", __LINE__));
4181
4182         /* mark all PMCs as available */
4183         for (n = 0; n < (int) md->pmd_npmc; n++)
4184                 PMC_MARK_ROW_FREE(n);
4185
4186         /* allocate thread hash tables */
4187         pmc_ownerhash = hashinit(pmc_hashsize, M_PMC,
4188             &pmc_ownerhashmask);
4189
4190         pmc_processhash = hashinit(pmc_hashsize, M_PMC,
4191             &pmc_processhashmask);
4192         mtx_init(&pmc_processhash_mtx, "pmc-process-hash", "pmc-leaf",
4193             MTX_SPIN);
4194
4195         LIST_INIT(&pmc_ss_owners);
4196         pmc_ss_count = 0;
4197
4198         /* allocate a pool of spin mutexes */
4199         pmc_mtxpool = mtx_pool_create("pmc-leaf", pmc_mtxpool_size,
4200             MTX_SPIN);
4201
4202         PMCDBG(MOD,INI,1, "pmc_ownerhash=%p, mask=0x%lx "
4203             "targethash=%p mask=0x%lx", pmc_ownerhash, pmc_ownerhashmask,
4204             pmc_processhash, pmc_processhashmask);
4205
4206         /* register process {exit,fork,exec} handlers */
4207         pmc_exit_tag = EVENTHANDLER_REGISTER(process_exit,
4208             pmc_process_exit, NULL, EVENTHANDLER_PRI_ANY);
4209         pmc_fork_tag = EVENTHANDLER_REGISTER(process_fork,
4210             pmc_process_fork, NULL, EVENTHANDLER_PRI_ANY);
4211
4212         /* initialize logging */
4213         pmclog_initialize();
4214
4215         /* set hook functions */
4216         pmc_intr = md->pmd_intr;
4217         pmc_hook = pmc_hook_handler;
4218
4219         if (error == 0) {
4220                 printf(PMC_MODULE_NAME ":");
4221                 for (n = 0; n < (int) md->pmd_nclass; n++) {
4222                         printf(" %s/%d/0x%b",
4223                             pmc_name_of_pmcclass[md->pmd_classes[n].pm_class],
4224                             md->pmd_nclasspmcs[n],
4225                             md->pmd_classes[n].pm_caps,
4226                             "\20"
4227                             "\1INT\2USR\3SYS\4EDG\5THR"
4228                             "\6REA\7WRI\10INV\11QUA\12PRC"
4229                             "\13TAG\14CSC");
4230                 }
4231                 printf("\n");
4232         }
4233
4234         return error;
4235 }
4236
4237 /* prepare to be unloaded */
4238 static void
4239 pmc_cleanup(void)
4240 {
4241         int cpu;
4242         struct pmc_ownerhash *ph;
4243         struct pmc_owner *po, *tmp;
4244         struct pmc_binding pb;
4245 #ifdef  DEBUG
4246         struct pmc_processhash *prh;
4247 #endif
4248
4249         PMCDBG(MOD,INI,0, "%s", "cleanup");
4250
4251         /* switch off sampling */
4252         atomic_store_rel_int(&pmc_cpumask, 0);
4253         pmc_intr = NULL;
4254
4255         sx_xlock(&pmc_sx);
4256         if (pmc_hook == NULL) { /* being unloaded already */
4257                 sx_xunlock(&pmc_sx);
4258                 return;
4259         }
4260
4261         pmc_hook = NULL; /* prevent new threads from entering module */
4262
4263         /* deregister event handlers */
4264         EVENTHANDLER_DEREGISTER(process_fork, pmc_fork_tag);
4265         EVENTHANDLER_DEREGISTER(process_exit, pmc_exit_tag);
4266
4267         /* send SIGBUS to all owner threads, free up allocations */
4268         if (pmc_ownerhash)
4269                 for (ph = pmc_ownerhash;
4270                      ph <= &pmc_ownerhash[pmc_ownerhashmask];
4271                      ph++) {
4272                         LIST_FOREACH_SAFE(po, ph, po_next, tmp) {
4273                                 pmc_remove_owner(po);
4274
4275                                 /* send SIGBUS to owner processes */
4276                                 PMCDBG(MOD,INI,2, "cleanup signal proc=%p "
4277                                     "(%d, %s)", po->po_owner,
4278                                     po->po_owner->p_pid,
4279                                     po->po_owner->p_comm);
4280
4281                                 PROC_LOCK(po->po_owner);
4282                                 psignal(po->po_owner, SIGBUS);
4283                                 PROC_UNLOCK(po->po_owner);
4284
4285                                 pmc_destroy_owner_descriptor(po);
4286                         }
4287                 }
4288
4289         /* reclaim allocated data structures */
4290         if (pmc_mtxpool)
4291                 mtx_pool_destroy(&pmc_mtxpool);
4292
4293         mtx_destroy(&pmc_processhash_mtx);
4294         if (pmc_processhash) {
4295 #ifdef  DEBUG
4296                 struct pmc_process *pp;
4297
4298                 PMCDBG(MOD,INI,3, "%s", "destroy process hash");
4299                 for (prh = pmc_processhash;
4300                      prh <= &pmc_processhash[pmc_processhashmask];
4301                      prh++)
4302                         LIST_FOREACH(pp, prh, pp_next)
4303                             PMCDBG(MOD,INI,3, "pid=%d", pp->pp_proc->p_pid);
4304 #endif
4305
4306                 hashdestroy(pmc_processhash, M_PMC, pmc_processhashmask);
4307                 pmc_processhash = NULL;
4308         }
4309
4310         if (pmc_ownerhash) {
4311                 PMCDBG(MOD,INI,3, "%s", "destroy owner hash");
4312                 hashdestroy(pmc_ownerhash, M_PMC, pmc_ownerhashmask);
4313                 pmc_ownerhash = NULL;
4314         }
4315
4316         KASSERT(LIST_EMPTY(&pmc_ss_owners),
4317             ("[pmc,%d] Global SS owner list not empty", __LINE__));
4318         KASSERT(pmc_ss_count == 0,
4319             ("[pmc,%d] Global SS count not empty", __LINE__));
4320
4321         /* free the per-cpu sample buffers */
4322         for (cpu = 0; cpu < mp_ncpus; cpu++) {
4323                 if (pmc_cpu_is_disabled(cpu))
4324                         continue;
4325                 KASSERT(pmc_pcpu[cpu]->pc_sb != NULL,
4326                     ("[pmc,%d] Null cpu sample buffer cpu=%d", __LINE__,
4327                         cpu));
4328                 FREE(pmc_pcpu[cpu]->pc_sb, M_PMC);
4329                 pmc_pcpu[cpu]->pc_sb = NULL;
4330         }
4331
4332         /* do processor dependent cleanup */
4333         PMCDBG(MOD,INI,3, "%s", "md cleanup");
4334         if (md) {
4335                 pmc_save_cpu_binding(&pb);
4336                 for (cpu = 0; cpu < mp_ncpus; cpu++) {
4337                         PMCDBG(MOD,INI,1,"pmc-cleanup cpu=%d pcs=%p",
4338                             cpu, pmc_pcpu[cpu]);
4339                         if (pmc_cpu_is_disabled(cpu))
4340                                 continue;
4341                         pmc_select_cpu(cpu);
4342                         if (pmc_pcpu[cpu])
4343                                 (void) md->pmd_cleanup(cpu);
4344                 }
4345                 FREE(md, M_PMC);
4346                 md = NULL;
4347                 pmc_restore_cpu_binding(&pb);
4348         }
4349
4350         /* deallocate per-cpu structures */
4351         FREE(pmc_pcpu, M_PMC);
4352         pmc_pcpu = NULL;
4353
4354         FREE(pmc_pcpu_saved, M_PMC);
4355         pmc_pcpu_saved = NULL;
4356
4357         if (pmc_pmcdisp) {
4358                 FREE(pmc_pmcdisp, M_PMC);
4359                 pmc_pmcdisp = NULL;
4360         }
4361
4362         pmclog_shutdown();
4363
4364         sx_xunlock(&pmc_sx);    /* we are done */
4365 }
4366
4367 /*
4368  * The function called at load/unload.
4369  */
4370
4371 static int
4372 load (struct module *module __unused, int cmd, void *arg __unused)
4373 {
4374         int error;
4375
4376         error = 0;
4377
4378         switch (cmd) {
4379         case MOD_LOAD :
4380                 /* initialize the subsystem */
4381                 error = pmc_initialize();
4382                 if (error != 0)
4383                         break;
4384                 PMCDBG(MOD,INI,1, "syscall=%d ncpus=%d",
4385                     pmc_syscall_num, mp_ncpus);
4386                 break;
4387
4388
4389         case MOD_UNLOAD :
4390         case MOD_SHUTDOWN:
4391                 pmc_cleanup();
4392                 PMCDBG(MOD,INI,1, "%s", "unloaded");
4393                 break;
4394
4395         default :
4396                 error = EINVAL; /* XXX should panic(9) */
4397                 break;
4398         }
4399
4400         return error;
4401 }
4402
4403 /* memory pool */
4404 MALLOC_DEFINE(M_PMC, "pmc", "Memory space for the PMC module");