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