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