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