xref: /freebsd/sys/dev/hwpmc/hwpmc_logging.c (revision 9f855fb282de1e5fa854b737dec66fb11aaf51e2)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2005-2007 Joseph Koshy
5  * Copyright (c) 2007 The FreeBSD Foundation
6  * Copyright (c) 2018 Matthew Macy
7  * All rights reserved.
8  *
9  * Portions of this software were developed by A. Joseph Koshy under
10  * sponsorship from the FreeBSD Foundation and Google, Inc.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  */
34 
35 /*
36  * Logging code for hwpmc(4)
37  */
38 
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD$");
41 
42 #include <sys/param.h>
43 #include <sys/capsicum.h>
44 #include <sys/file.h>
45 #include <sys/kernel.h>
46 #include <sys/kthread.h>
47 #include <sys/lock.h>
48 #include <sys/module.h>
49 #include <sys/mutex.h>
50 #include <sys/pmc.h>
51 #include <sys/pmckern.h>
52 #include <sys/pmclog.h>
53 #include <sys/proc.h>
54 #include <sys/sched.h>
55 #include <sys/signalvar.h>
56 #include <sys/smp.h>
57 #include <sys/syscallsubr.h>
58 #include <sys/sysctl.h>
59 #include <sys/systm.h>
60 #include <sys/uio.h>
61 #include <sys/unistd.h>
62 #include <sys/vnode.h>
63 
64 #ifdef NUMA
65 #define NDOMAINS vm_ndomains
66 #define curdomain PCPU_GET(domain)
67 #else
68 #define NDOMAINS 1
69 #define curdomain 0
70 #define malloc_domain(size, type, domain, flags) malloc((size), (type), (flags))
71 #define free_domain(addr, type) free(addr, type)
72 #endif
73 
74 /*
75  * Sysctl tunables
76  */
77 
78 SYSCTL_DECL(_kern_hwpmc);
79 
80 /*
81  * kern.hwpmc.logbuffersize -- size of the per-cpu owner buffers.
82  */
83 
84 static int pmclog_buffer_size = PMC_LOG_BUFFER_SIZE;
85 #if (__FreeBSD_version < 1100000)
86 TUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "logbuffersize", &pmclog_buffer_size);
87 #endif
88 SYSCTL_INT(_kern_hwpmc, OID_AUTO, logbuffersize, CTLFLAG_RDTUN,
89     &pmclog_buffer_size, 0, "size of log buffers in kilobytes");
90 
91 /*
92  * kern.hwpmc.nbuffer -- number of global log buffers
93  */
94 
95 static int pmc_nlogbuffers_pcpu = PMC_NLOGBUFFERS_PCPU;
96 #if (__FreeBSD_version < 1100000)
97 TUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "nbuffers", &pmc_nlogbuffers_pcpu);
98 #endif
99 SYSCTL_INT(_kern_hwpmc, OID_AUTO, nbuffers_pcpu, CTLFLAG_RDTUN,
100     &pmc_nlogbuffers_pcpu, 0, "number of log buffers per cpu");
101 
102 /*
103  * Global log buffer list and associated spin lock.
104  */
105 
106 static struct mtx pmc_kthread_mtx;	/* sleep lock */
107 
108 #define	PMCLOG_INIT_BUFFER_DESCRIPTOR(D, buf, domain) do {						\
109 		(D)->plb_fence = ((char *) (buf)) +	1024*pmclog_buffer_size;			\
110 		(D)->plb_base  = (D)->plb_ptr = ((char *) (buf));				\
111 		(D)->plb_domain = domain; \
112 	} while (0)
113 
114 #define	PMCLOG_RESET_BUFFER_DESCRIPTOR(D) do {			\
115 		(D)->plb_ptr  = (D)->plb_base; \
116 	} while (0)
117 
118 /*
119  * Log file record constructors.
120  */
121 #define	_PMCLOG_TO_HEADER(T,L)						\
122 	((PMCLOG_HEADER_MAGIC << 24) |					\
123 	 (PMCLOG_TYPE_ ## T << 16)   |					\
124 	 ((L) & 0xFFFF))
125 
126 /* reserve LEN bytes of space and initialize the entry header */
127 #define	_PMCLOG_RESERVE_SAFE(PO,TYPE,LEN,ACTION) do {			\
128 		uint32_t *_le;						\
129 		int _len = roundup((LEN), sizeof(uint32_t));	\
130 		if ((_le = pmclog_reserve((PO), _len)) == NULL) {	\
131 			ACTION;						\
132 		}							\
133 		*_le = _PMCLOG_TO_HEADER(TYPE,_len);			\
134 		_le += 3	/* skip over timestamp */
135 
136 /* reserve LEN bytes of space and initialize the entry header */
137 #define	_PMCLOG_RESERVE(PO,TYPE,LEN,ACTION) do {			\
138 		uint32_t *_le;						\
139 		int _len = roundup((LEN), sizeof(uint32_t));		\
140 		spinlock_enter();									\
141 		if ((_le = pmclog_reserve((PO), _len)) == NULL) {	\
142 			spinlock_exit();								\
143 			ACTION;											\
144 		}												\
145 		*_le = _PMCLOG_TO_HEADER(TYPE,_len);			\
146 		_le += 3	/* skip over timestamp */
147 
148 
149 #define	PMCLOG_RESERVE_SAFE(P,T,L)		_PMCLOG_RESERVE_SAFE(P,T,L,return)
150 #define	PMCLOG_RESERVE(P,T,L)		_PMCLOG_RESERVE(P,T,L,return)
151 #define	PMCLOG_RESERVE_WITH_ERROR(P,T,L) _PMCLOG_RESERVE(P,T,L,		\
152 	error=ENOMEM;goto error)
153 
154 #define	PMCLOG_EMIT32(V)	do { *_le++ = (V); } while (0)
155 #define	PMCLOG_EMIT64(V)	do { 					\
156 		*_le++ = (uint32_t) ((V) & 0xFFFFFFFF);			\
157 		*_le++ = (uint32_t) (((V) >> 32) & 0xFFFFFFFF);		\
158 	} while (0)
159 
160 
161 /* Emit a string.  Caution: does NOT update _le, so needs to be last */
162 #define	PMCLOG_EMITSTRING(S,L)	do { bcopy((S), _le, (L)); } while (0)
163 #define	PMCLOG_EMITNULLSTRING(L) do { bzero(_le, (L)); } while (0)
164 
165 #define	PMCLOG_DESPATCH_SAFE(PO)						\
166 	    pmclog_release((PO));						\
167 	} while (0)
168 
169 #define	PMCLOG_DESPATCH_SCHED_LOCK(PO)						\
170 	     pmclog_release_flags((PO), 0);							\
171 	} while (0)
172 
173 #define	PMCLOG_DESPATCH(PO)							\
174 	    pmclog_release((PO));						\
175 		spinlock_exit();							\
176 	} while (0)
177 
178 #define	PMCLOG_DESPATCH_SYNC(PO)						\
179 	    pmclog_schedule_io((PO), 1);						\
180 		spinlock_exit();								\
181 		} while (0)
182 
183 
184 /*
185  * Assertions about the log file format.
186  */
187 
188 CTASSERT(sizeof(struct pmclog_callchain) == 8*4 +
189     PMC_CALLCHAIN_DEPTH_MAX*sizeof(uintfptr_t));
190 CTASSERT(sizeof(struct pmclog_closelog) == 4*4);
191 CTASSERT(sizeof(struct pmclog_dropnotify) == 4*4);
192 CTASSERT(sizeof(struct pmclog_map_in) == PATH_MAX +
193     4*4 + sizeof(uintfptr_t));
194 CTASSERT(offsetof(struct pmclog_map_in,pl_pathname) ==
195     4*4 + sizeof(uintfptr_t));
196 CTASSERT(sizeof(struct pmclog_map_out) == 4*4 + 2*sizeof(uintfptr_t));
197 CTASSERT(sizeof(struct pmclog_pmcallocate) == 6*4);
198 CTASSERT(sizeof(struct pmclog_pmcattach) == 6*4 + PATH_MAX);
199 CTASSERT(offsetof(struct pmclog_pmcattach,pl_pathname) == 6*4);
200 CTASSERT(sizeof(struct pmclog_pmcdetach) == 6*4);
201 CTASSERT(sizeof(struct pmclog_proccsw) == 6*4 + 8);
202 CTASSERT(sizeof(struct pmclog_procexec) == 6*4 + PATH_MAX +
203     sizeof(uintfptr_t));
204 CTASSERT(offsetof(struct pmclog_procexec,pl_pathname) == 6*4 +
205     sizeof(uintfptr_t));
206 CTASSERT(sizeof(struct pmclog_procexit) == 6*4 + 8);
207 CTASSERT(sizeof(struct pmclog_procfork) == 6*4);
208 CTASSERT(sizeof(struct pmclog_sysexit) == 4*4);
209 CTASSERT(sizeof(struct pmclog_userdata) == 4*4);
210 
211 /*
212  * Log buffer structure
213  */
214 
215 struct pmclog_buffer {
216 	TAILQ_ENTRY(pmclog_buffer) plb_next;
217 	char 		*plb_base;
218 	char		*plb_ptr;
219 	char 		*plb_fence;
220 	uint16_t	 plb_domain;
221 } __aligned(CACHE_LINE_SIZE);
222 
223 /*
224  * Prototypes
225  */
226 
227 static int pmclog_get_buffer(struct pmc_owner *po);
228 static void pmclog_loop(void *arg);
229 static void pmclog_release(struct pmc_owner *po);
230 static uint32_t *pmclog_reserve(struct pmc_owner *po, int length);
231 static void pmclog_schedule_io(struct pmc_owner *po, int wakeup);
232 static void pmclog_schedule_all(struct pmc_owner *po, int force);
233 static void pmclog_stop_kthread(struct pmc_owner *po);
234 
235 /*
236  * Helper functions
237  */
238 
239 static inline void
240 pmc_plb_rele_unlocked(struct pmclog_buffer *plb)
241 {
242 	TAILQ_INSERT_HEAD(&pmc_dom_hdrs[plb->plb_domain]->pdbh_head, plb, plb_next);
243 }
244 
245 static inline void
246 pmc_plb_rele(struct pmclog_buffer *plb)
247 {
248 	mtx_lock_spin(&pmc_dom_hdrs[plb->plb_domain]->pdbh_mtx);
249 	pmc_plb_rele_unlocked(plb);
250 	mtx_unlock_spin(&pmc_dom_hdrs[plb->plb_domain]->pdbh_mtx);
251 }
252 
253 /*
254  * Get a log buffer
255  */
256 static int
257 pmclog_get_buffer(struct pmc_owner *po)
258 {
259 	struct pmclog_buffer *plb;
260 	int domain;
261 
262 	KASSERT(po->po_curbuf[curcpu] == NULL,
263 	    ("[pmclog,%d] po=%p current buffer still valid", __LINE__, po));
264 
265 	domain = curdomain;
266 	MPASS(pmc_dom_hdrs[domain]);
267 	mtx_lock_spin(&pmc_dom_hdrs[domain]->pdbh_mtx);
268 	if ((plb = TAILQ_FIRST(&pmc_dom_hdrs[domain]->pdbh_head)) != NULL)
269 		TAILQ_REMOVE(&pmc_dom_hdrs[domain]->pdbh_head, plb, plb_next);
270 	mtx_unlock_spin(&pmc_dom_hdrs[domain]->pdbh_mtx);
271 
272 	PMCDBG2(LOG,GTB,1, "po=%p plb=%p", po, plb);
273 
274 #ifdef	HWPMC_DEBUG
275 	if (plb)
276 		KASSERT(plb->plb_ptr == plb->plb_base &&
277 		    plb->plb_base < plb->plb_fence,
278 		    ("[pmclog,%d] po=%p buffer invariants: ptr=%p "
279 		    "base=%p fence=%p", __LINE__, po, plb->plb_ptr,
280 		    plb->plb_base, plb->plb_fence));
281 #endif
282 
283 	po->po_curbuf[curcpu] = plb;
284 
285 	/* update stats */
286 	counter_u64_add(pmc_stats.pm_buffer_requests, 1);
287 	if (plb == NULL)
288 		counter_u64_add(pmc_stats.pm_buffer_requests_failed, 1);
289 
290 	return (plb ? 0 : ENOMEM);
291 }
292 
293 struct pmclog_proc_init_args {
294 	struct proc *kthr;
295 	struct pmc_owner *po;
296 	bool exit;
297 	bool acted;
298 };
299 
300 int
301 pmclog_proc_create(struct thread *td, void **handlep)
302 {
303 	struct pmclog_proc_init_args *ia;
304 	int error;
305 
306 	ia = malloc(sizeof(*ia), M_TEMP, M_WAITOK | M_ZERO);
307 	error = kproc_create(pmclog_loop, ia, &ia->kthr,
308 	    RFHIGHPID, 0, "hwpmc: proc(%d)", td->td_proc->p_pid);
309 	if (error == 0)
310 		*handlep = ia;
311 	return (error);
312 }
313 
314 void
315 pmclog_proc_ignite(void *handle, struct pmc_owner *po)
316 {
317 	struct pmclog_proc_init_args *ia;
318 
319 	ia = handle;
320 	mtx_lock(&pmc_kthread_mtx);
321 	MPASS(!ia->acted);
322 	MPASS(ia->po == NULL);
323 	MPASS(!ia->exit);
324 	MPASS(ia->kthr != NULL);
325 	if (po == NULL) {
326 		ia->exit = true;
327 	} else {
328 		ia->po = po;
329 		KASSERT(po->po_kthread == NULL,
330 		    ("[pmclog,%d] po=%p kthread (%p) already present",
331 		    __LINE__, po, po->po_kthread));
332 		po->po_kthread = ia->kthr;
333 	}
334 	wakeup(ia);
335 	while (!ia->acted)
336 		msleep(ia, &pmc_kthread_mtx, PWAIT, "pmclogw", 0);
337 	mtx_unlock(&pmc_kthread_mtx);
338 	free(ia, M_TEMP);
339 }
340 
341 /*
342  * Log handler loop.
343  *
344  * This function is executed by each pmc owner's helper thread.
345  */
346 static void
347 pmclog_loop(void *arg)
348 {
349 	struct pmclog_proc_init_args *ia;
350 	struct pmc_owner *po;
351 	struct pmclog_buffer *lb;
352 	struct proc *p;
353 	struct ucred *ownercred;
354 	struct ucred *mycred;
355 	struct thread *td;
356 	sigset_t unb;
357 	struct uio auio;
358 	struct iovec aiov;
359 	size_t nbytes;
360 	int error;
361 
362 	td = curthread;
363 
364 	SIGEMPTYSET(unb);
365 	SIGADDSET(unb, SIGHUP);
366 	(void)kern_sigprocmask(td, SIG_UNBLOCK, &unb, NULL, 0);
367 
368 	ia = arg;
369 	MPASS(ia->kthr == curproc);
370 	MPASS(!ia->acted);
371 	mtx_lock(&pmc_kthread_mtx);
372 	while (ia->po == NULL && !ia->exit)
373 		msleep(ia, &pmc_kthread_mtx, PWAIT, "pmclogi", 0);
374 	if (ia->exit) {
375 		ia->acted = true;
376 		wakeup(ia);
377 		mtx_unlock(&pmc_kthread_mtx);
378 		kproc_exit(0);
379 	}
380 	MPASS(ia->po != NULL);
381 	po = ia->po;
382 	ia->acted = true;
383 	wakeup(ia);
384 	mtx_unlock(&pmc_kthread_mtx);
385 	ia = NULL;
386 
387 	p = po->po_owner;
388 	mycred = td->td_ucred;
389 
390 	PROC_LOCK(p);
391 	ownercred = crhold(p->p_ucred);
392 	PROC_UNLOCK(p);
393 
394 	PMCDBG2(LOG,INI,1, "po=%p kt=%p", po, po->po_kthread);
395 	KASSERT(po->po_kthread == curthread->td_proc,
396 	    ("[pmclog,%d] proc mismatch po=%p po/kt=%p curproc=%p", __LINE__,
397 		po, po->po_kthread, curthread->td_proc));
398 
399 	lb = NULL;
400 
401 
402 	/*
403 	 * Loop waiting for I/O requests to be added to the owner
404 	 * struct's queue.  The loop is exited when the log file
405 	 * is deconfigured.
406 	 */
407 
408 	mtx_lock(&pmc_kthread_mtx);
409 
410 	for (;;) {
411 
412 		/* check if we've been asked to exit */
413 		if ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)
414 			break;
415 
416 		if (lb == NULL) { /* look for a fresh buffer to write */
417 			mtx_lock_spin(&po->po_mtx);
418 			if ((lb = TAILQ_FIRST(&po->po_logbuffers)) == NULL) {
419 				mtx_unlock_spin(&po->po_mtx);
420 
421 				/* No more buffers and shutdown required. */
422 				if (po->po_flags & PMC_PO_SHUTDOWN)
423 					break;
424 
425 				(void) msleep(po, &pmc_kthread_mtx, PWAIT,
426 				    "pmcloop", 250);
427 				continue;
428 			}
429 
430 			TAILQ_REMOVE(&po->po_logbuffers, lb, plb_next);
431 			mtx_unlock_spin(&po->po_mtx);
432 		}
433 
434 		mtx_unlock(&pmc_kthread_mtx);
435 
436 		/* process the request */
437 		PMCDBG3(LOG,WRI,2, "po=%p base=%p ptr=%p", po,
438 		    lb->plb_base, lb->plb_ptr);
439 		/* change our thread's credentials before issuing the I/O */
440 
441 		aiov.iov_base = lb->plb_base;
442 		aiov.iov_len  = nbytes = lb->plb_ptr - lb->plb_base;
443 
444 		auio.uio_iov    = &aiov;
445 		auio.uio_iovcnt = 1;
446 		auio.uio_offset = -1;
447 		auio.uio_resid  = nbytes;
448 		auio.uio_rw     = UIO_WRITE;
449 		auio.uio_segflg = UIO_SYSSPACE;
450 		auio.uio_td     = td;
451 
452 		/* switch thread credentials -- see kern_ktrace.c */
453 		td->td_ucred = ownercred;
454 		error = fo_write(po->po_file, &auio, ownercred, 0, td);
455 		td->td_ucred = mycred;
456 
457 		if (error) {
458 			/* XXX some errors are recoverable */
459 			/* send a SIGIO to the owner and exit */
460 			PROC_LOCK(p);
461 			kern_psignal(p, SIGIO);
462 			PROC_UNLOCK(p);
463 
464 			mtx_lock(&pmc_kthread_mtx);
465 
466 			po->po_error = error; /* save for flush log */
467 
468 			PMCDBG2(LOG,WRI,2, "po=%p error=%d", po, error);
469 
470 			break;
471 		}
472 
473 		mtx_lock(&pmc_kthread_mtx);
474 
475 		/* put the used buffer back into the global pool */
476 		PMCLOG_RESET_BUFFER_DESCRIPTOR(lb);
477 
478 		pmc_plb_rele(lb);
479 		lb = NULL;
480 	}
481 
482 	wakeup_one(po->po_kthread);
483 	po->po_kthread = NULL;
484 
485 	mtx_unlock(&pmc_kthread_mtx);
486 
487 	/* return the current I/O buffer to the global pool */
488 	if (lb) {
489 		PMCLOG_RESET_BUFFER_DESCRIPTOR(lb);
490 
491 		pmc_plb_rele(lb);
492 	}
493 
494 	/*
495 	 * Exit this thread, signalling the waiter
496 	 */
497 
498 	crfree(ownercred);
499 
500 	kproc_exit(0);
501 }
502 
503 /*
504  * Release and log entry and schedule an I/O if needed.
505  */
506 
507 static void
508 pmclog_release_flags(struct pmc_owner *po, int wakeup)
509 {
510 	struct pmclog_buffer *plb;
511 
512 	plb = po->po_curbuf[curcpu];
513 	KASSERT(plb->plb_ptr >= plb->plb_base,
514 	    ("[pmclog,%d] buffer invariants po=%p ptr=%p base=%p", __LINE__,
515 		po, plb->plb_ptr, plb->plb_base));
516 	KASSERT(plb->plb_ptr <= plb->plb_fence,
517 	    ("[pmclog,%d] buffer invariants po=%p ptr=%p fenc=%p", __LINE__,
518 		po, plb->plb_ptr, plb->plb_fence));
519 
520 	/* schedule an I/O if we've filled a buffer */
521 	if (plb->plb_ptr >= plb->plb_fence)
522 		pmclog_schedule_io(po, wakeup);
523 
524 	PMCDBG1(LOG,REL,1, "po=%p", po);
525 }
526 
527 static void
528 pmclog_release(struct pmc_owner *po)
529 {
530 
531 	pmclog_release_flags(po, 1);
532 }
533 
534 
535 /*
536  * Attempt to reserve 'length' bytes of space in an owner's log
537  * buffer.  The function returns a pointer to 'length' bytes of space
538  * if there was enough space or returns NULL if no space was
539  * available.  Non-null returns do so with the po mutex locked.  The
540  * caller must invoke pmclog_release() on the pmc owner structure
541  * when done.
542  */
543 
544 static uint32_t *
545 pmclog_reserve(struct pmc_owner *po, int length)
546 {
547 	uintptr_t newptr, oldptr;
548 	uint32_t *lh;
549 	struct timespec ts;
550 	struct pmclog_buffer *plb, **pplb;
551 
552 	PMCDBG2(LOG,ALL,1, "po=%p len=%d", po, length);
553 
554 	KASSERT(length % sizeof(uint32_t) == 0,
555 	    ("[pmclog,%d] length not a multiple of word size", __LINE__));
556 
557 	/* No more data when shutdown in progress. */
558 	if (po->po_flags & PMC_PO_SHUTDOWN)
559 		return (NULL);
560 
561 	pplb = &po->po_curbuf[curcpu];
562 	if (*pplb == NULL && pmclog_get_buffer(po) != 0)
563 		goto fail;
564 
565 	KASSERT(*pplb != NULL,
566 	    ("[pmclog,%d] po=%p no current buffer", __LINE__, po));
567 
568 	plb = *pplb;
569 	KASSERT(plb->plb_ptr >= plb->plb_base &&
570 	    plb->plb_ptr <= plb->plb_fence,
571 	    ("[pmclog,%d] po=%p buffer invariants: ptr=%p base=%p fence=%p",
572 		__LINE__, po, plb->plb_ptr, plb->plb_base,
573 		plb->plb_fence));
574 
575 	oldptr = (uintptr_t) plb->plb_ptr;
576 	newptr = oldptr + length;
577 
578 	KASSERT(oldptr != (uintptr_t) NULL,
579 	    ("[pmclog,%d] po=%p Null log buffer pointer", __LINE__, po));
580 
581 	/*
582 	 * If we have space in the current buffer, return a pointer to
583 	 * available space with the PO structure locked.
584 	 */
585 	if (newptr <= (uintptr_t) plb->plb_fence) {
586 		plb->plb_ptr = (char *) newptr;
587 		goto done;
588 	}
589 
590 	/*
591 	 * Otherwise, schedule the current buffer for output and get a
592 	 * fresh buffer.
593 	 */
594 	pmclog_schedule_io(po, 0);
595 
596 	if (pmclog_get_buffer(po) != 0)
597 		goto fail;
598 
599 	plb = *pplb;
600 	KASSERT(plb != NULL,
601 	    ("[pmclog,%d] po=%p no current buffer", __LINE__, po));
602 
603 	KASSERT(plb->plb_ptr != NULL,
604 	    ("[pmclog,%d] null return from pmc_get_log_buffer", __LINE__));
605 
606 	KASSERT(plb->plb_ptr == plb->plb_base &&
607 	    plb->plb_ptr <= plb->plb_fence,
608 	    ("[pmclog,%d] po=%p buffer invariants: ptr=%p base=%p fence=%p",
609 		__LINE__, po, plb->plb_ptr, plb->plb_base,
610 		plb->plb_fence));
611 
612 	oldptr = (uintptr_t) plb->plb_ptr;
613 
614  done:
615 	lh = (uint32_t *) oldptr;
616 	lh++;				/* skip header */
617 	getnanotime(&ts);		/* fill in the timestamp */
618 	*lh++ = ts.tv_sec & 0xFFFFFFFF;
619 	*lh++ = ts.tv_nsec & 0xFFFFFFF;
620 	return ((uint32_t *) oldptr);
621  fail:
622 	return (NULL);
623 }
624 
625 /*
626  * Schedule an I/O.
627  *
628  * Transfer the current buffer to the helper kthread.
629  */
630 
631 static void
632 pmclog_schedule_io(struct pmc_owner *po, int wakeup)
633 {
634 	struct pmclog_buffer *plb;
635 
636 	plb = po->po_curbuf[curcpu];
637 	po->po_curbuf[curcpu] = NULL;
638 	KASSERT(plb != NULL,
639 	    ("[pmclog,%d] schedule_io with null buffer po=%p", __LINE__, po));
640 	KASSERT(plb->plb_ptr >= plb->plb_base,
641 	    ("[pmclog,%d] buffer invariants po=%p ptr=%p base=%p", __LINE__,
642 		po, plb->plb_ptr, plb->plb_base));
643 	KASSERT(plb->plb_ptr <= plb->plb_fence,
644 	    ("[pmclog,%d] buffer invariants po=%p ptr=%p fenc=%p", __LINE__,
645 		po, plb->plb_ptr, plb->plb_fence));
646 
647 	PMCDBG1(LOG,SIO, 1, "po=%p", po);
648 
649 	/*
650 	 * Add the current buffer to the tail of the buffer list and
651 	 * wakeup the helper.
652 	 */
653 	mtx_lock_spin(&po->po_mtx);
654 	TAILQ_INSERT_TAIL(&po->po_logbuffers, plb, plb_next);
655 	mtx_unlock_spin(&po->po_mtx);
656 	if (wakeup)
657 		wakeup_one(po);
658 }
659 
660 /*
661  * Stop the helper kthread.
662  */
663 
664 static void
665 pmclog_stop_kthread(struct pmc_owner *po)
666 {
667 
668 	mtx_lock(&pmc_kthread_mtx);
669 	po->po_flags &= ~PMC_PO_OWNS_LOGFILE;
670 	if (po->po_kthread != NULL) {
671 		PROC_LOCK(po->po_kthread);
672 		kern_psignal(po->po_kthread, SIGHUP);
673 		PROC_UNLOCK(po->po_kthread);
674 	}
675 	wakeup_one(po);
676 	while (po->po_kthread)
677 		msleep(po->po_kthread, &pmc_kthread_mtx, PPAUSE, "pmckstp", 0);
678 	mtx_unlock(&pmc_kthread_mtx);
679 }
680 
681 /*
682  * Public functions
683  */
684 
685 /*
686  * Configure a log file for pmc owner 'po'.
687  *
688  * Parameter 'logfd' is a file handle referencing an open file in the
689  * owner process.  This file needs to have been opened for writing.
690  */
691 
692 int
693 pmclog_configure_log(struct pmc_mdep *md, struct pmc_owner *po, int logfd)
694 {
695 	struct proc *p;
696 	int error;
697 
698 	sx_assert(&pmc_sx, SA_XLOCKED);
699 	PMCDBG2(LOG,CFG,1, "config po=%p logfd=%d", po, logfd);
700 
701 	p = po->po_owner;
702 
703 	/* return EBUSY if a log file was already present */
704 	if (po->po_flags & PMC_PO_OWNS_LOGFILE)
705 		return (EBUSY);
706 
707 	KASSERT(po->po_file == NULL,
708 	    ("[pmclog,%d] po=%p file (%p) already present", __LINE__, po,
709 		po->po_file));
710 
711 	/* get a reference to the file state */
712 	error = fget_write(curthread, logfd, &cap_write_rights, &po->po_file);
713 	if (error)
714 		goto error;
715 
716 	/* mark process as owning a log file */
717 	po->po_flags |= PMC_PO_OWNS_LOGFILE;
718 
719 	/* mark process as using HWPMCs */
720 	PROC_LOCK(p);
721 	p->p_flag |= P_HWPMC;
722 	PROC_UNLOCK(p);
723 
724 	/* create a log initialization entry */
725 	PMCLOG_RESERVE_WITH_ERROR(po, INITIALIZE,
726 	    sizeof(struct pmclog_initialize));
727 	PMCLOG_EMIT32(PMC_VERSION);
728 	PMCLOG_EMIT32(md->pmd_cputype);
729 	PMCLOG_EMITSTRING(pmc_cpuid, PMC_CPUID_LEN);
730 	PMCLOG_DESPATCH_SYNC(po);
731 
732 	return (0);
733 
734  error:
735 	KASSERT(po->po_kthread == NULL, ("[pmclog,%d] po=%p kthread not "
736 	    "stopped", __LINE__, po));
737 
738 	if (po->po_file)
739 		(void) fdrop(po->po_file, curthread);
740 	po->po_file  = NULL;	/* clear file and error state */
741 	po->po_error = 0;
742 	po->po_flags &= ~PMC_PO_OWNS_LOGFILE;
743 
744 	return (error);
745 }
746 
747 
748 /*
749  * De-configure a log file.  This will throw away any buffers queued
750  * for this owner process.
751  */
752 
753 int
754 pmclog_deconfigure_log(struct pmc_owner *po)
755 {
756 	int error;
757 	struct pmclog_buffer *lb;
758 
759 	PMCDBG1(LOG,CFG,1, "de-config po=%p", po);
760 
761 	if ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)
762 		return (EINVAL);
763 
764 	KASSERT(po->po_sscount == 0,
765 	    ("[pmclog,%d] po=%p still owning SS PMCs", __LINE__, po));
766 	KASSERT(po->po_file != NULL,
767 	    ("[pmclog,%d] po=%p no log file", __LINE__, po));
768 
769 	/* stop the kthread, this will reset the 'OWNS_LOGFILE' flag */
770 	pmclog_stop_kthread(po);
771 
772 	KASSERT(po->po_kthread == NULL,
773 	    ("[pmclog,%d] po=%p kthread not stopped", __LINE__, po));
774 
775 	/* return all queued log buffers to the global pool */
776 	while ((lb = TAILQ_FIRST(&po->po_logbuffers)) != NULL) {
777 		TAILQ_REMOVE(&po->po_logbuffers, lb, plb_next);
778 		PMCLOG_RESET_BUFFER_DESCRIPTOR(lb);
779 		pmc_plb_rele(lb);
780 	}
781 	for (int i = 0; i < mp_ncpus; i++) {
782 		thread_lock(curthread);
783 		sched_bind(curthread, i);
784 		thread_unlock(curthread);
785 		/* return the 'current' buffer to the global pool */
786 		if ((lb = po->po_curbuf[curcpu]) != NULL) {
787 			PMCLOG_RESET_BUFFER_DESCRIPTOR(lb);
788 			pmc_plb_rele(lb);
789 		}
790 	}
791 	thread_lock(curthread);
792 	sched_unbind(curthread);
793 	thread_unlock(curthread);
794 
795 	/* drop a reference to the fd */
796 	if (po->po_file != NULL) {
797 		error = fdrop(po->po_file, curthread);
798 		po->po_file = NULL;
799 	} else
800 		error = 0;
801 	po->po_error = 0;
802 
803 	return (error);
804 }
805 
806 /*
807  * Flush a process' log buffer.
808  */
809 
810 int
811 pmclog_flush(struct pmc_owner *po, int force)
812 {
813 	int error;
814 
815 	PMCDBG1(LOG,FLS,1, "po=%p", po);
816 
817 	/*
818 	 * If there is a pending error recorded by the logger thread,
819 	 * return that.
820 	 */
821 	if (po->po_error)
822 		return (po->po_error);
823 
824 	error = 0;
825 
826 	/*
827 	 * Check that we do have an active log file.
828 	 */
829 	mtx_lock(&pmc_kthread_mtx);
830 	if ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0) {
831 		error = EINVAL;
832 		goto error;
833 	}
834 
835 	pmclog_schedule_all(po, force);
836  error:
837 	mtx_unlock(&pmc_kthread_mtx);
838 
839 	return (error);
840 }
841 
842 static void
843 pmclog_schedule_one_cond(struct pmc_owner *po, int force)
844 {
845 	struct pmclog_buffer *plb;
846 	int cpu;
847 
848 	spinlock_enter();
849 	cpu = curcpu;
850 	/* tell hardclock not to run again */
851 	if (PMC_CPU_HAS_SAMPLES(cpu))
852 		PMC_CALL_HOOK_UNLOCKED(curthread, PMC_FN_DO_SAMPLES, NULL);
853 	if (force)
854 		pmc_flush_samples(cpu);
855 	plb = po->po_curbuf[cpu];
856 	if (plb && plb->plb_ptr != plb->plb_base)
857 		pmclog_schedule_io(po, 1);
858 	spinlock_exit();
859 }
860 
861 static void
862 pmclog_schedule_all(struct pmc_owner *po, int force)
863 {
864 	/*
865 	 * Schedule the current buffer if any and not empty.
866 	 */
867 	for (int i = 0; i < mp_ncpus; i++) {
868 		thread_lock(curthread);
869 		sched_bind(curthread, i);
870 		thread_unlock(curthread);
871 		pmclog_schedule_one_cond(po, force);
872 	}
873 	thread_lock(curthread);
874 	sched_unbind(curthread);
875 	thread_unlock(curthread);
876 }
877 
878 int
879 pmclog_close(struct pmc_owner *po)
880 {
881 
882 	PMCDBG1(LOG,CLO,1, "po=%p", po);
883 
884 	pmclog_process_closelog(po);
885 
886 	mtx_lock(&pmc_kthread_mtx);
887 	/*
888 	 * Initiate shutdown: no new data queued,
889 	 * thread will close file on last block.
890 	 */
891 	po->po_flags |= PMC_PO_SHUTDOWN;
892 	/* give time for all to see */
893 	DELAY(50);
894 
895 	/*
896 	 * Schedule the current buffer.
897 	 */
898 	pmclog_schedule_all(po, 0);
899 	wakeup_one(po);
900 
901 	mtx_unlock(&pmc_kthread_mtx);
902 
903 	return (0);
904 }
905 
906 void
907 pmclog_process_callchain(struct pmc *pm, struct pmc_sample *ps)
908 {
909 	int n, recordlen;
910 	uint32_t flags;
911 	struct pmc_owner *po;
912 
913 	PMCDBG3(LOG,SAM,1,"pm=%p pid=%d n=%d", pm, ps->ps_pid,
914 	    ps->ps_nsamples);
915 
916 	recordlen = offsetof(struct pmclog_callchain, pl_pc) +
917 	    ps->ps_nsamples * sizeof(uintfptr_t);
918 	po = pm->pm_owner;
919 	flags = PMC_CALLCHAIN_TO_CPUFLAGS(ps->ps_cpu,ps->ps_flags);
920 	PMCLOG_RESERVE_SAFE(po, CALLCHAIN, recordlen);
921 	PMCLOG_EMIT32(ps->ps_pid);
922 	PMCLOG_EMIT32(ps->ps_tid);
923 	PMCLOG_EMIT32(pm->pm_id);
924 	PMCLOG_EMIT32(flags);
925 	/* unused for now */
926 	PMCLOG_EMIT32(0);
927 	for (n = 0; n < ps->ps_nsamples; n++)
928 		PMCLOG_EMITADDR(ps->ps_pc[n]);
929 	PMCLOG_DESPATCH_SAFE(po);
930 }
931 
932 void
933 pmclog_process_closelog(struct pmc_owner *po)
934 {
935 	PMCLOG_RESERVE(po,CLOSELOG,sizeof(struct pmclog_closelog));
936 	PMCLOG_DESPATCH_SYNC(po);
937 }
938 
939 void
940 pmclog_process_dropnotify(struct pmc_owner *po)
941 {
942 	PMCLOG_RESERVE(po,DROPNOTIFY,sizeof(struct pmclog_dropnotify));
943 	PMCLOG_DESPATCH(po);
944 }
945 
946 void
947 pmclog_process_map_in(struct pmc_owner *po, pid_t pid, uintfptr_t start,
948     const char *path)
949 {
950 	int pathlen, recordlen;
951 
952 	KASSERT(path != NULL, ("[pmclog,%d] map-in, null path", __LINE__));
953 
954 	pathlen = strlen(path) + 1;	/* #bytes for path name */
955 	recordlen = offsetof(struct pmclog_map_in, pl_pathname) +
956 	    pathlen;
957 
958 	PMCLOG_RESERVE(po, MAP_IN, recordlen);
959 	PMCLOG_EMIT32(pid);
960 	PMCLOG_EMITADDR(start);
961 	PMCLOG_EMITSTRING(path,pathlen);
962 	PMCLOG_DESPATCH_SYNC(po);
963 }
964 
965 void
966 pmclog_process_map_out(struct pmc_owner *po, pid_t pid, uintfptr_t start,
967     uintfptr_t end)
968 {
969 	KASSERT(start <= end, ("[pmclog,%d] start > end", __LINE__));
970 
971 	PMCLOG_RESERVE(po, MAP_OUT, sizeof(struct pmclog_map_out));
972 	PMCLOG_EMIT32(pid);
973 	PMCLOG_EMITADDR(start);
974 	PMCLOG_EMITADDR(end);
975 	PMCLOG_DESPATCH(po);
976 }
977 
978 void
979 pmclog_process_pmcallocate(struct pmc *pm)
980 {
981 	struct pmc_owner *po;
982 	struct pmc_soft *ps;
983 
984 	po = pm->pm_owner;
985 
986 	PMCDBG1(LOG,ALL,1, "pm=%p", pm);
987 
988 	if (PMC_TO_CLASS(pm) == PMC_CLASS_SOFT) {
989 		PMCLOG_RESERVE(po, PMCALLOCATEDYN,
990 		    sizeof(struct pmclog_pmcallocatedyn));
991 		PMCLOG_EMIT32(pm->pm_id);
992 		PMCLOG_EMIT32(pm->pm_event);
993 		PMCLOG_EMIT32(pm->pm_flags);
994 		ps = pmc_soft_ev_acquire(pm->pm_event);
995 		if (ps != NULL)
996 			PMCLOG_EMITSTRING(ps->ps_ev.pm_ev_name,PMC_NAME_MAX);
997 		else
998 			PMCLOG_EMITNULLSTRING(PMC_NAME_MAX);
999 		pmc_soft_ev_release(ps);
1000 		PMCLOG_DESPATCH_SYNC(po);
1001 	} else {
1002 		PMCLOG_RESERVE(po, PMCALLOCATE,
1003 		    sizeof(struct pmclog_pmcallocate));
1004 		PMCLOG_EMIT32(pm->pm_id);
1005 		PMCLOG_EMIT32(pm->pm_event);
1006 		PMCLOG_EMIT32(pm->pm_flags);
1007 		PMCLOG_DESPATCH_SYNC(po);
1008 	}
1009 }
1010 
1011 void
1012 pmclog_process_pmcattach(struct pmc *pm, pid_t pid, char *path)
1013 {
1014 	int pathlen, recordlen;
1015 	struct pmc_owner *po;
1016 
1017 	PMCDBG2(LOG,ATT,1,"pm=%p pid=%d", pm, pid);
1018 
1019 	po = pm->pm_owner;
1020 
1021 	pathlen = strlen(path) + 1;	/* #bytes for the string */
1022 	recordlen = offsetof(struct pmclog_pmcattach, pl_pathname) + pathlen;
1023 
1024 	PMCLOG_RESERVE(po, PMCATTACH, recordlen);
1025 	PMCLOG_EMIT32(pm->pm_id);
1026 	PMCLOG_EMIT32(pid);
1027 	PMCLOG_EMIT32(0);
1028 	PMCLOG_EMITSTRING(path, pathlen);
1029 	PMCLOG_DESPATCH_SYNC(po);
1030 }
1031 
1032 void
1033 pmclog_process_pmcdetach(struct pmc *pm, pid_t pid)
1034 {
1035 	struct pmc_owner *po;
1036 
1037 	PMCDBG2(LOG,ATT,1,"!pm=%p pid=%d", pm, pid);
1038 
1039 	po = pm->pm_owner;
1040 
1041 	PMCLOG_RESERVE(po, PMCDETACH, sizeof(struct pmclog_pmcdetach));
1042 	PMCLOG_EMIT32(pm->pm_id);
1043 	PMCLOG_EMIT32(pid);
1044 	PMCLOG_DESPATCH_SYNC(po);
1045 }
1046 
1047 void
1048 pmclog_process_proccreate(struct pmc_owner *po, struct proc *p, int sync)
1049 {
1050 	if (sync) {
1051 		PMCLOG_RESERVE(po, PROC_CREATE, sizeof(struct pmclog_proccreate));
1052 		PMCLOG_EMIT32(p->p_pid);
1053 		PMCLOG_EMITSTRING(p->p_comm, MAXCOMLEN+1);
1054 		PMCLOG_DESPATCH_SYNC(po);
1055 	} else {
1056 		PMCLOG_RESERVE(po, PROC_CREATE, sizeof(struct pmclog_proccreate));
1057 		PMCLOG_EMIT32(p->p_pid);
1058 		PMCLOG_EMITSTRING(p->p_comm, MAXCOMLEN+1);
1059 		PMCLOG_DESPATCH(po);
1060 	}
1061 }
1062 
1063 /*
1064  * Log a context switch event to the log file.
1065  */
1066 
1067 void
1068 pmclog_process_proccsw(struct pmc *pm, struct pmc_process *pp, pmc_value_t v, struct thread *td)
1069 {
1070 	struct pmc_owner *po;
1071 
1072 	KASSERT(pm->pm_flags & PMC_F_LOG_PROCCSW,
1073 	    ("[pmclog,%d] log-process-csw called gratuitously", __LINE__));
1074 
1075 	PMCDBG3(LOG,SWO,1,"pm=%p pid=%d v=%jx", pm, pp->pp_proc->p_pid,
1076 	    v);
1077 
1078 	po = pm->pm_owner;
1079 
1080 	PMCLOG_RESERVE_SAFE(po, PROCCSW, sizeof(struct pmclog_proccsw));
1081 	PMCLOG_EMIT32(pm->pm_id);
1082 	PMCLOG_EMIT64(v);
1083 	PMCLOG_EMIT32(pp->pp_proc->p_pid);
1084 	PMCLOG_EMIT32(td->td_tid);
1085 	PMCLOG_DESPATCH_SCHED_LOCK(po);
1086 }
1087 
1088 void
1089 pmclog_process_procexec(struct pmc_owner *po, pmc_id_t pmid, pid_t pid,
1090     uintfptr_t startaddr, char *path)
1091 {
1092 	int pathlen, recordlen;
1093 
1094 	PMCDBG3(LOG,EXC,1,"po=%p pid=%d path=\"%s\"", po, pid, path);
1095 
1096 	pathlen   = strlen(path) + 1;	/* #bytes for the path */
1097 	recordlen = offsetof(struct pmclog_procexec, pl_pathname) + pathlen;
1098 	PMCLOG_RESERVE(po, PROCEXEC, recordlen);
1099 	PMCLOG_EMIT32(pid);
1100 	PMCLOG_EMIT32(pmid);
1101 	PMCLOG_EMIT32(0);
1102 	PMCLOG_EMITADDR(startaddr);
1103 	PMCLOG_EMITSTRING(path,pathlen);
1104 	PMCLOG_DESPATCH_SYNC(po);
1105 }
1106 
1107 /*
1108  * Log a process exit event (and accumulated pmc value) to the log file.
1109  */
1110 
1111 void
1112 pmclog_process_procexit(struct pmc *pm, struct pmc_process *pp)
1113 {
1114 	int ri;
1115 	struct pmc_owner *po;
1116 
1117 	ri = PMC_TO_ROWINDEX(pm);
1118 	PMCDBG3(LOG,EXT,1,"pm=%p pid=%d v=%jx", pm, pp->pp_proc->p_pid,
1119 	    pp->pp_pmcs[ri].pp_pmcval);
1120 
1121 	po = pm->pm_owner;
1122 
1123 	PMCLOG_RESERVE(po, PROCEXIT, sizeof(struct pmclog_procexit));
1124 	PMCLOG_EMIT32(pm->pm_id);
1125 	PMCLOG_EMIT32(pp->pp_proc->p_pid);
1126 	PMCLOG_EMIT32(0);
1127 	PMCLOG_EMIT64(pp->pp_pmcs[ri].pp_pmcval);
1128 	PMCLOG_DESPATCH(po);
1129 }
1130 
1131 /*
1132  * Log a fork event.
1133  */
1134 
1135 void
1136 pmclog_process_procfork(struct pmc_owner *po, pid_t oldpid, pid_t newpid)
1137 {
1138 	PMCLOG_RESERVE(po, PROCFORK, sizeof(struct pmclog_procfork));
1139 	PMCLOG_EMIT32(oldpid);
1140 	PMCLOG_EMIT32(newpid);
1141 	PMCLOG_DESPATCH(po);
1142 }
1143 
1144 /*
1145  * Log a process exit event of the form suitable for system-wide PMCs.
1146  */
1147 
1148 void
1149 pmclog_process_sysexit(struct pmc_owner *po, pid_t pid)
1150 {
1151 	PMCLOG_RESERVE(po, SYSEXIT, sizeof(struct pmclog_sysexit));
1152 	PMCLOG_EMIT32(pid);
1153 	PMCLOG_DESPATCH(po);
1154 }
1155 
1156 void
1157 pmclog_process_threadcreate(struct pmc_owner *po, struct thread *td, int sync)
1158 {
1159 	struct proc *p;
1160 
1161 	p = td->td_proc;
1162 	if (sync) {
1163 		PMCLOG_RESERVE(po, THR_CREATE, sizeof(struct pmclog_threadcreate));
1164 		PMCLOG_EMIT32(td->td_tid);
1165 		PMCLOG_EMIT32(p->p_pid);
1166 		PMCLOG_EMIT32(0);
1167 		PMCLOG_EMITSTRING(td->td_name, MAXCOMLEN+1);
1168 		PMCLOG_DESPATCH_SYNC(po);
1169 	} else {
1170 		PMCLOG_RESERVE(po, THR_CREATE, sizeof(struct pmclog_threadcreate));
1171 		PMCLOG_EMIT32(td->td_tid);
1172 		PMCLOG_EMIT32(p->p_pid);
1173 		PMCLOG_EMIT32(0);
1174 		PMCLOG_EMITSTRING(td->td_name, MAXCOMLEN+1);
1175 		PMCLOG_DESPATCH(po);
1176 	}
1177 }
1178 
1179 void
1180 pmclog_process_threadexit(struct pmc_owner *po, struct thread *td)
1181 {
1182 
1183 	PMCLOG_RESERVE(po, THR_EXIT, sizeof(struct pmclog_threadexit));
1184 	PMCLOG_EMIT32(td->td_tid);
1185 	PMCLOG_DESPATCH(po);
1186 }
1187 
1188 /*
1189  * Write a user log entry.
1190  */
1191 
1192 int
1193 pmclog_process_userlog(struct pmc_owner *po, struct pmc_op_writelog *wl)
1194 {
1195 	int error;
1196 
1197 	PMCDBG2(LOG,WRI,1, "writelog po=%p ud=0x%x", po, wl->pm_userdata);
1198 
1199 	error = 0;
1200 
1201 	PMCLOG_RESERVE_WITH_ERROR(po, USERDATA,
1202 	    sizeof(struct pmclog_userdata));
1203 	PMCLOG_EMIT32(wl->pm_userdata);
1204 	PMCLOG_DESPATCH(po);
1205 
1206  error:
1207 	return (error);
1208 }
1209 
1210 /*
1211  * Initialization.
1212  *
1213  * Create a pool of log buffers and initialize mutexes.
1214  */
1215 
1216 void
1217 pmclog_initialize()
1218 {
1219 	int domain;
1220 	struct pmclog_buffer *plb;
1221 
1222 	if (pmclog_buffer_size <= 0 || pmclog_buffer_size > 16*1024) {
1223 		(void) printf("hwpmc: tunable logbuffersize=%d must be "
1224 					  "greater than zero and less than or equal to 16MB.\n",
1225 					  pmclog_buffer_size);
1226 		pmclog_buffer_size = PMC_LOG_BUFFER_SIZE;
1227 	}
1228 
1229 	if (pmc_nlogbuffers_pcpu <= 0) {
1230 		(void) printf("hwpmc: tunable nlogbuffers=%d must be greater "
1231 					  "than zero.\n", pmc_nlogbuffers_pcpu);
1232 		pmc_nlogbuffers_pcpu = PMC_NLOGBUFFERS_PCPU;
1233 	}
1234 	if (pmc_nlogbuffers_pcpu*pmclog_buffer_size > 32*1024) {
1235 		(void) printf("hwpmc: memory allocated pcpu must be less than 32MB (is %dK).\n",
1236 					  pmc_nlogbuffers_pcpu*pmclog_buffer_size);
1237 		pmc_nlogbuffers_pcpu = PMC_NLOGBUFFERS_PCPU;
1238 		pmclog_buffer_size = PMC_LOG_BUFFER_SIZE;
1239 	}
1240 	for (domain = 0; domain < NDOMAINS; domain++) {
1241 		int ncpus = pmc_dom_hdrs[domain]->pdbh_ncpus;
1242 		int total = ncpus*pmc_nlogbuffers_pcpu;
1243 
1244 		plb = malloc_domain(sizeof(struct pmclog_buffer)*total, M_PMC, domain, M_WAITOK|M_ZERO);
1245 		pmc_dom_hdrs[domain]->pdbh_plbs = plb;
1246 		for (int i = 0; i < total; i++, plb++) {
1247 			void *buf;
1248 
1249 			buf = malloc_domain(1024 * pmclog_buffer_size, M_PMC, domain,
1250 								M_WAITOK|M_ZERO);
1251 			PMCLOG_INIT_BUFFER_DESCRIPTOR(plb, buf, domain);
1252 			pmc_plb_rele_unlocked(plb);
1253 		}
1254 	}
1255 	mtx_init(&pmc_kthread_mtx, "pmc-kthread", "pmc-sleep", MTX_DEF);
1256 }
1257 
1258 /*
1259  * Shutdown logging.
1260  *
1261  * Destroy mutexes and release memory back the to free pool.
1262  */
1263 
1264 void
1265 pmclog_shutdown()
1266 {
1267 	struct pmclog_buffer *plb;
1268 	int domain;
1269 
1270 	mtx_destroy(&pmc_kthread_mtx);
1271 
1272 	for (domain = 0; domain < NDOMAINS; domain++) {
1273 		while ((plb = TAILQ_FIRST(&pmc_dom_hdrs[domain]->pdbh_head)) != NULL) {
1274 			TAILQ_REMOVE(&pmc_dom_hdrs[domain]->pdbh_head, plb, plb_next);
1275 			free(plb->plb_base, M_PMC);
1276 		}
1277 		free(pmc_dom_hdrs[domain]->pdbh_plbs, M_PMC);
1278 	}
1279 }
1280