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