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