Home | History | Annotate | Line # | Download | only in kern
kern_ktrace.c revision 1.119.2.4
      1 /*	$NetBSD: kern_ktrace.c,v 1.119.2.4 2007/04/10 12:07:13 ad Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1989, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. Neither the name of the University nor the names of its contributors
     16  *    may be used to endorse or promote products derived from this software
     17  *    without specific prior written permission.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     29  * SUCH DAMAGE.
     30  *
     31  *	@(#)kern_ktrace.c	8.5 (Berkeley) 5/14/95
     32  */
     33 
     34 #include <sys/cdefs.h>
     35 __KERNEL_RCSID(0, "$NetBSD: kern_ktrace.c,v 1.119.2.4 2007/04/10 12:07:13 ad Exp $");
     36 
     37 #include "opt_ktrace.h"
     38 #include "opt_compat_mach.h"
     39 
     40 #include <sys/param.h>
     41 #include <sys/systm.h>
     42 #include <sys/proc.h>
     43 #include <sys/file.h>
     44 #include <sys/namei.h>
     45 #include <sys/vnode.h>
     46 #include <sys/kernel.h>
     47 #include <sys/kthread.h>
     48 #include <sys/ktrace.h>
     49 #include <sys/kmem.h>
     50 #include <sys/syslog.h>
     51 #include <sys/filedesc.h>
     52 #include <sys/ioctl.h>
     53 #include <sys/callout.h>
     54 #include <sys/kauth.h>
     55 
     56 #include <sys/mount.h>
     57 #include <sys/syscallargs.h>
     58 
     59 #ifdef KTRACE
     60 
     61 /*
     62  * TODO:
     63  *	- need better error reporting?
     64  *	- userland utility to sort ktrace.out by timestamp.
     65  *	- keep minimum information in ktrace_entry when rest of alloc failed.
     66  *	- per trace control of configurable parameters.
     67  */
     68 
     69 struct ktrace_entry {
     70 	TAILQ_ENTRY(ktrace_entry) kte_list;
     71 	struct	ktr_header kte_kth;
     72 	void	*kte_buf;
     73 	size_t	kte_bufsz;
     74 #define	KTE_SPACE		32
     75 	uint8_t kte_space[KTE_SPACE];
     76 };
     77 
     78 struct ktr_desc {
     79 	TAILQ_ENTRY(ktr_desc) ktd_list;
     80 	int ktd_flags;
     81 #define	KTDF_WAIT		0x0001
     82 #define	KTDF_DONE		0x0002
     83 #define	KTDF_BLOCKING		0x0004
     84 #define	KTDF_INTERACTIVE	0x0008
     85 	int ktd_error;
     86 #define	KTDE_ENOMEM		0x0001
     87 #define	KTDE_ENOSPC		0x0002
     88 	int ktd_errcnt;
     89 	int ktd_ref;			/* # of reference */
     90 	int ktd_qcount;			/* # of entry in the queue */
     91 
     92 	/*
     93 	 * Params to control behaviour.
     94 	 */
     95 	int ktd_delayqcnt;		/* # of entry allowed to delay */
     96 	int ktd_wakedelay;		/* delay of wakeup in *tick* */
     97 	int ktd_intrwakdl;		/* ditto, but when interactive */
     98 
     99 	struct file *ktd_fp;		/* trace output file */
    100 	struct lwp *ktd_lwp;		/* our kernel thread */
    101 	TAILQ_HEAD(, ktrace_entry) ktd_queue;
    102 	struct callout ktd_wakch;	/* delayed wakeup */
    103 	kcondvar_t ktd_sync_cv;
    104 	kcondvar_t ktd_cv;
    105 };
    106 
    107 static int	ktealloc(struct ktrace_entry **, void **, struct lwp *, int,
    108 			 size_t);
    109 static void	ktrwrite(struct ktr_desc *, struct ktrace_entry *);
    110 static int	ktrace_common(struct lwp *, int, int, int, struct file *);
    111 static int	ktrops(struct lwp *, struct proc *, int, int,
    112 		    struct ktr_desc *);
    113 static int	ktrsetchildren(struct lwp *, struct proc *, int, int,
    114 		    struct ktr_desc *);
    115 static int	ktrcanset(struct lwp *, struct proc *);
    116 static int	ktrsamefile(struct file *, struct file *);
    117 
    118 static struct ktr_desc *
    119 		ktd_lookup(struct file *);
    120 static void	ktdrel(struct ktr_desc *);
    121 static void	ktdref(struct ktr_desc *);
    122 static void	ktraddentry(struct lwp *, struct ktrace_entry *, int);
    123 /* Flags for ktraddentry (3rd arg) */
    124 #define	KTA_NOWAIT		0x0000
    125 #define	KTA_WAITOK		0x0001
    126 #define	KTA_LARGE		0x0002
    127 static void	ktefree(struct ktrace_entry *);
    128 static void	ktd_logerrl(struct ktr_desc *, int);
    129 static void	ktrace_thread(void *);
    130 static int	ktrderefall(struct ktr_desc *, int);
    131 
    132 /*
    133  * Default vaules.
    134  */
    135 #define	KTD_MAXENTRY		1000	/* XXX: tune */
    136 #define	KTD_TIMEOUT		5	/* XXX: tune */
    137 #define	KTD_DELAYQCNT		100	/* XXX: tune */
    138 #define	KTD_WAKEDELAY		5000	/* XXX: tune */
    139 #define	KTD_INTRWAKDL		100	/* XXX: tune */
    140 
    141 /*
    142  * Patchable variables.
    143  */
    144 int ktd_maxentry = KTD_MAXENTRY;	/* max # of entry in the queue */
    145 int ktd_timeout = KTD_TIMEOUT;		/* timeout in seconds */
    146 int ktd_delayqcnt = KTD_DELAYQCNT;	/* # of entry allowed to delay */
    147 int ktd_wakedelay = KTD_WAKEDELAY;	/* delay of wakeup in *ms* */
    148 int ktd_intrwakdl = KTD_INTRWAKDL;	/* ditto, but when interactive */
    149 
    150 kmutex_t ktrace_mutex;
    151 static TAILQ_HEAD(, ktr_desc) ktdq = TAILQ_HEAD_INITIALIZER(ktdq);
    152 
    153 MALLOC_DEFINE(M_KTRACE, "ktrace", "ktrace data buffer");
    154 POOL_INIT(kte_pool, sizeof(struct ktrace_entry), 0, 0, 0,
    155     "ktepl", &pool_allocator_nointr, IPL_NONE);
    156 
    157 static inline void
    158 ktd_wakeup(struct ktr_desc *ktd)
    159 {
    160 
    161 	callout_stop(&ktd->ktd_wakch);
    162 	cv_wakeup(&ktd->ktd_cv);		/* XXXSMP */
    163 }
    164 
    165 static void
    166 ktd_logerrl(struct ktr_desc *ktd, int error)
    167 {
    168 
    169 	ktd->ktd_error |= error;
    170 	ktd->ktd_errcnt++;
    171 }
    172 
    173 #if 0
    174 static void
    175 ktd_logerr(struct proc *p, int error)
    176 {
    177 	struct ktr_desc *ktd;
    178 
    179 	KASSERT(mutex_owned(&ktrace_mutex));
    180 
    181 	ktd = p->p_tracep;
    182 	if (ktd == NULL)
    183 		return;
    184 
    185 	ktd_logerrl(ktd, error);
    186 }
    187 #endif
    188 
    189 static inline int
    190 ktrenter(struct lwp *l)
    191 {
    192 
    193 	if ((l->l_pflag & LP_KTRACTIVE) != 0)
    194 		return 1;
    195 	l->l_pflag |= LP_KTRACTIVE;
    196 	return 0;
    197 }
    198 
    199 static inline void
    200 ktrexit(struct lwp *l)
    201 {
    202 
    203 	l->l_pflag &= ~LP_KTRACTIVE;
    204 }
    205 
    206 /*
    207  * Initialise the ktrace system.
    208  */
    209 void
    210 ktrinit(void)
    211 {
    212 
    213 	mutex_init(&ktrace_mutex, MUTEX_DEFAULT, IPL_NONE);
    214 }
    215 
    216 /*
    217  * Release a reference.  Called with ktrace_mutex held.
    218  */
    219 void
    220 ktdrel(struct ktr_desc *ktd)
    221 {
    222 
    223 	KASSERT(mutex_owned(&ktrace_mutex));
    224 
    225 	KDASSERT(ktd->ktd_ref != 0);
    226 	KASSERT(ktd->ktd_ref > 0);
    227 	if (--ktd->ktd_ref <= 0) {
    228 		ktd->ktd_flags |= KTDF_DONE;
    229 		cv_broadcast(&ktd->ktd_cv);
    230 	}
    231 }
    232 
    233 void
    234 ktdref(struct ktr_desc *ktd)
    235 {
    236 
    237 	KASSERT(mutex_owned(&ktrace_mutex));
    238 
    239 	ktd->ktd_ref++;
    240 }
    241 
    242 struct ktr_desc *
    243 ktd_lookup(struct file *fp)
    244 {
    245 	struct ktr_desc *ktd;
    246 
    247 	KASSERT(mutex_owned(&ktrace_mutex));
    248 
    249 	for (ktd = TAILQ_FIRST(&ktdq); ktd != NULL;
    250 	    ktd = TAILQ_NEXT(ktd, ktd_list)) {
    251 		if (ktrsamefile(ktd->ktd_fp, fp)) {
    252 			ktd->ktd_ref++;
    253 			break;
    254 		}
    255 	}
    256 
    257 	return (ktd);
    258 }
    259 
    260 void
    261 ktraddentry(struct lwp *l, struct ktrace_entry *kte, int flags)
    262 {
    263 	struct proc *p = l->l_proc;
    264 	struct ktr_desc *ktd;
    265 #ifdef DEBUG
    266 	struct timeval t1, t2;
    267 #endif
    268 
    269 	mutex_enter(&ktrace_mutex);
    270 
    271 	if (p->p_traceflag & KTRFAC_TRC_EMUL) {
    272 		/* Add emulation trace before first entry for this process */
    273 		p->p_traceflag &= ~KTRFAC_TRC_EMUL;
    274 		mutex_exit(&ktrace_mutex);
    275 		ktrexit(l);
    276 		ktremul(l);
    277 		(void)ktrenter(l);
    278 		mutex_enter(&ktrace_mutex);
    279 	}
    280 
    281 	/*
    282 	 * Tracing may be canceled while we were sleeping waiting for
    283 	 * memory.
    284 	 */
    285 	ktd = p->p_tracep;
    286 	if (ktd == NULL)
    287 		goto freekte;
    288 
    289 	/*
    290 	 * Bump reference count so that the object will remain while
    291 	 * we are here.  Note that the trace is controlled by other
    292 	 * process.
    293 	 */
    294 	ktdref(ktd);
    295 
    296 	if (ktd->ktd_flags & KTDF_DONE)
    297 		goto relktd;
    298 
    299 	if (ktd->ktd_qcount > ktd_maxentry) {
    300 		ktd_logerrl(ktd, KTDE_ENOSPC);
    301 		goto relktd;
    302 	}
    303 	TAILQ_INSERT_TAIL(&ktd->ktd_queue, kte, kte_list);
    304 	ktd->ktd_qcount++;
    305 	if (ktd->ktd_flags & KTDF_BLOCKING)
    306 		goto skip_sync;
    307 
    308 	if (flags & KTA_WAITOK &&
    309 	    (/* flags & KTA_LARGE */0 || ktd->ktd_flags & KTDF_WAIT ||
    310 	    ktd->ktd_qcount > ktd_maxentry >> 1))
    311 		/*
    312 		 * Sync with writer thread since we're requesting rather
    313 		 * big one or many requests are pending.
    314 		 */
    315 		do {
    316 			ktd->ktd_flags |= KTDF_WAIT;
    317 			ktd_wakeup(ktd);
    318 #ifdef DEBUG
    319 			getmicrouptime(&t1);
    320 #endif
    321 			if (cv_timedwait(&ktd->ktd_sync_cv, &ktrace_mutex,
    322 			    ktd_timeout * hz) != 0) {
    323 				ktd->ktd_flags |= KTDF_BLOCKING;
    324 				/*
    325 				 * Maybe the writer thread is blocking
    326 				 * completely for some reason, but
    327 				 * don't stop target process forever.
    328 				 */
    329 				log(LOG_NOTICE, "ktrace timeout\n");
    330 				break;
    331 			}
    332 #ifdef DEBUG
    333 			getmicrouptime(&t2);
    334 			timersub(&t2, &t1, &t2);
    335 			if (t2.tv_sec > 0)
    336 				log(LOG_NOTICE,
    337 				    "ktrace long wait: %ld.%06ld\n",
    338 				    t2.tv_sec, t2.tv_usec);
    339 #endif
    340 		} while (p->p_tracep == ktd &&
    341 		    (ktd->ktd_flags & (KTDF_WAIT | KTDF_DONE)) == KTDF_WAIT);
    342 	else {
    343 		/* Schedule delayed wakeup */
    344 		if (ktd->ktd_qcount > ktd->ktd_delayqcnt)
    345 			ktd_wakeup(ktd);	/* Wakeup now */
    346 		else if (!callout_pending(&ktd->ktd_wakch))
    347 			callout_reset(&ktd->ktd_wakch,
    348 			    ktd->ktd_flags & KTDF_INTERACTIVE ?
    349 			    ktd->ktd_intrwakdl : ktd->ktd_wakedelay,
    350 			    (void (*)(void *))ktd_wakeup, ktd);
    351 	}
    352 
    353 skip_sync:
    354 	ktdrel(ktd);
    355 	mutex_exit(&ktrace_mutex);
    356 	ktrexit(l);
    357 	return;
    358 
    359 relktd:
    360 	ktdrel(ktd);
    361 
    362 freekte:
    363 	mutex_exit(&ktrace_mutex);
    364 	ktefree(kte);
    365 	ktrexit(l);
    366 }
    367 
    368 void
    369 ktefree(struct ktrace_entry *kte)
    370 {
    371 
    372 	if (kte->kte_buf != kte->kte_space)
    373 		kmem_free(kte->kte_buf, kte->kte_bufsz);
    374 	pool_put(&kte_pool, kte);
    375 }
    376 
    377 /*
    378  * "deep" compare of two files for the purposes of clearing a trace.
    379  * Returns true if they're the same open file, or if they point at the
    380  * same underlying vnode/socket.
    381  */
    382 
    383 int
    384 ktrsamefile(struct file *f1, struct file *f2)
    385 {
    386 
    387 	return ((f1 == f2) ||
    388 	    ((f1 != NULL) && (f2 != NULL) &&
    389 		(f1->f_type == f2->f_type) &&
    390 		(f1->f_data == f2->f_data)));
    391 }
    392 
    393 void
    394 ktrderef(struct proc *p)
    395 {
    396 	struct ktr_desc *ktd = p->p_tracep;
    397 
    398 	KASSERT(mutex_owned(&ktrace_mutex));
    399 
    400 	p->p_traceflag = 0;
    401 	if (ktd == NULL)
    402 		return;
    403 	p->p_tracep = NULL;
    404 
    405 	cv_broadcast(&ktd->ktd_sync_cv);
    406 	ktdrel(ktd);
    407 }
    408 
    409 void
    410 ktradref(struct proc *p)
    411 {
    412 	struct ktr_desc *ktd = p->p_tracep;
    413 
    414 	KASSERT(mutex_owned(&ktrace_mutex));
    415 
    416 	ktdref(ktd);
    417 }
    418 
    419 int
    420 ktrderefall(struct ktr_desc *ktd, int auth)
    421 {
    422 	struct lwp *curl = curlwp;
    423 	struct proc *p;
    424 	int error = 0;
    425 
    426 	mutex_enter(&proclist_lock);
    427 	PROCLIST_FOREACH(p, &allproc) {
    428 		if (p->p_tracep != ktd)
    429 			continue;
    430 		mutex_enter(&p->p_mutex);
    431 		mutex_enter(&ktrace_mutex);
    432 		if (p->p_tracep == ktd) {
    433 			if (!auth || ktrcanset(curl, p))
    434 				ktrderef(p);
    435 			else
    436 				error = EPERM;
    437 		}
    438 		mutex_exit(&ktrace_mutex);
    439 		mutex_exit(&p->p_mutex);
    440 	}
    441 	mutex_exit(&proclist_lock);
    442 
    443 	return error;
    444 }
    445 
    446 int
    447 ktealloc(struct ktrace_entry **ktep, void **bufp, struct lwp *l, int type,
    448 	 size_t sz)
    449 {
    450 	struct proc *p = l->l_proc;
    451 	struct ktrace_entry *kte;
    452 	struct ktr_header *kth;
    453 	void *buf;
    454 
    455 	if (ktrenter(l))
    456 		return EAGAIN;
    457 
    458 	kte = pool_get(&kte_pool, PR_WAITOK);
    459 	if (sz > sizeof(kte->kte_space)) {
    460 		if ((buf = kmem_alloc(sz, KM_SLEEP)) == NULL) {
    461 			pool_put(&kte_pool, kte);
    462 			ktrexit(l);
    463 			return ENOMEM;
    464 		}
    465 	} else
    466 		buf = kte->kte_space;
    467 
    468 	kte->kte_bufsz = sz;
    469 	kte->kte_buf = buf;
    470 
    471 	kth = &kte->kte_kth;
    472 	(void)memset(kth, 0, sizeof(*kth));
    473 	kth->ktr_len = sz;
    474 	kth->ktr_type = type;
    475 	kth->ktr_pid = p->p_pid;
    476 	memcpy(kth->ktr_comm, p->p_comm, MAXCOMLEN);
    477 	kth->ktr_version = KTRFAC_VERSION(p->p_traceflag);
    478 
    479 	switch (KTRFAC_VERSION(p->p_traceflag)) {
    480 	case 0:
    481 		/* This is the original format */
    482 		microtime(&kth->ktr_tv);
    483 		break;
    484 	case 1:
    485 		kth->ktr_lid = l->l_lid;
    486 		nanotime(&kth->ktr_time);
    487 		break;
    488 	default:
    489 		break;
    490 	}
    491 
    492 	*ktep = kte;
    493 	*bufp = buf;
    494 
    495 	return 0;
    496 }
    497 
    498 void
    499 ktrsyscall(struct lwp *l, register_t code, register_t realcode,
    500     const struct sysent *callp, register_t args[])
    501 {
    502 	struct proc *p = l->l_proc;
    503 	struct ktrace_entry *kte;
    504 	struct ktr_syscall *ktp;
    505 	register_t *argp;
    506 	int argsize;
    507 	size_t len;
    508 	u_int i;
    509 
    510 	if (callp == NULL)
    511 		callp = p->p_emul->e_sysent;
    512 
    513 	argsize = callp[code].sy_argsize;
    514 #ifdef _LP64
    515 	if (p->p_flag & PK_32)
    516 		argsize = argsize << 1;
    517 #endif
    518 	len = sizeof(struct ktr_syscall) + argsize;
    519 
    520 	if (ktealloc(&kte, (void *)&ktp, l, KTR_SYSCALL, len))
    521 		return;
    522 
    523 	ktp->ktr_code = realcode;
    524 	ktp->ktr_argsize = argsize;
    525 	argp = (register_t *)(ktp + 1);
    526 	for (i = 0; i < (argsize / sizeof(*argp)); i++)
    527 		*argp++ = args[i];
    528 
    529 	ktraddentry(l, kte, KTA_WAITOK);
    530 }
    531 
    532 void
    533 ktrsysret(struct lwp *l, register_t code, int error, register_t *retval)
    534 {
    535 	struct ktrace_entry *kte;
    536 	struct ktr_sysret *ktp;
    537 
    538 	if (ktealloc(&kte, (void *)&ktp, l, KTR_SYSRET,
    539 	    sizeof(struct ktr_sysret)))
    540 		return;
    541 
    542 	ktp->ktr_code = code;
    543 	ktp->ktr_eosys = 0;			/* XXX unused */
    544 	ktp->ktr_error = error;
    545 	ktp->ktr_retval = retval ? retval[0] : 0;
    546 	ktp->ktr_retval_1 = retval ? retval[1] : 0;
    547 
    548 	ktraddentry(l, kte, KTA_WAITOK);
    549 }
    550 
    551 /*
    552  * XXX: ndp->ni_pathlen should be passed.
    553  */
    554 void
    555 ktrnamei(struct lwp *l, char *path)
    556 {
    557 
    558 	ktrkmem(l, KTR_NAMEI, path, strlen(path));
    559 }
    560 
    561 void
    562 ktremul(struct lwp *l)
    563 {
    564 	const char *emul = l->l_proc->p_emul->e_name;
    565 
    566 	ktrkmem(l, KTR_EMUL, emul, strlen(emul));
    567 }
    568 
    569 void
    570 ktrkmem(struct lwp *l, int type, const void *bf, size_t len)
    571 {
    572 	struct ktrace_entry *kte;
    573 	void *buf;
    574 
    575 	if (ktealloc(&kte, &buf, l, type, len))
    576 		return;
    577 	memcpy(buf, bf, len);
    578 	ktraddentry(l, kte, KTA_WAITOK);
    579 }
    580 
    581 void
    582 ktrgenio(struct lwp *l, int fd, enum uio_rw rw, struct iovec *iov,
    583 	 int len, int error)
    584 {
    585 	struct ktrace_entry *kte;
    586 	struct ktr_genio *ktp;
    587 	int resid = len, cnt;
    588 	void *cp;
    589 	int buflen;
    590 
    591 	if (error)
    592 		return;
    593 
    594  next:
    595 	buflen = min(PAGE_SIZE, resid + sizeof(struct ktr_genio));
    596 
    597 	if (ktealloc(&kte, (void *)&ktp, l, KTR_GENIO, buflen))
    598 		return;
    599 
    600 	ktp->ktr_fd = fd;
    601 	ktp->ktr_rw = rw;
    602 
    603 	cp = (void *)(ktp + 1);
    604 	buflen -= sizeof(struct ktr_genio);
    605 	kte->kte_kth.ktr_len = sizeof(struct ktr_genio);
    606 
    607 	while (buflen > 0) {
    608 		cnt = min(iov->iov_len, buflen);
    609 		if (copyin(iov->iov_base, cp, cnt) != 0)
    610 			goto out;
    611 		kte->kte_kth.ktr_len += cnt;
    612 		buflen -= cnt;
    613 		resid -= cnt;
    614 		iov->iov_len -= cnt;
    615 		if (iov->iov_len == 0)
    616 			iov++;
    617 		else
    618 			iov->iov_base = (char *)iov->iov_base + cnt;
    619 	}
    620 
    621 	/*
    622 	 * Don't push so many entry at once.  It will cause kmem map
    623 	 * shortage.
    624 	 */
    625 	ktraddentry(l, kte, KTA_WAITOK | KTA_LARGE);
    626 	if (resid > 0) {
    627 		if (curcpu()->ci_schedstate.spc_flags & SPCF_SHOULDYIELD) {
    628 			(void)ktrenter(l);
    629 			preempt();
    630 			ktrexit(l);
    631 		}
    632 
    633 		goto next;
    634 	}
    635 
    636 	return;
    637 
    638 out:
    639 	ktefree(kte);
    640 	ktrexit(l);
    641 }
    642 
    643 void
    644 ktrpsig(struct lwp *l, int sig, sig_t action, const sigset_t *mask,
    645     const ksiginfo_t *ksi)
    646 {
    647 	struct ktrace_entry *kte;
    648 	struct {
    649 		struct ktr_psig	kp;
    650 		siginfo_t	si;
    651 	} *kbuf;
    652 
    653 	if (ktealloc(&kte, (void *)&kbuf, l, KTR_PSIG, sizeof(*kbuf)))
    654 		return;
    655 
    656 	kbuf->kp.signo = (char)sig;
    657 	kbuf->kp.action = action;
    658 	kbuf->kp.mask = *mask;
    659 
    660 	if (ksi) {
    661 		kbuf->kp.code = KSI_TRAPCODE(ksi);
    662 		(void)memset(&kbuf->si, 0, sizeof(kbuf->si));
    663 		kbuf->si._info = ksi->ksi_info;
    664 		kte->kte_kth.ktr_len = sizeof(*kbuf);
    665 	} else {
    666 		kbuf->kp.code = 0;
    667 		kte->kte_kth.ktr_len = sizeof(struct ktr_psig);
    668 	}
    669 
    670 	ktraddentry(l, kte, KTA_WAITOK);
    671 }
    672 
    673 void
    674 ktrcsw(struct lwp *l, int out, int user)
    675 {
    676 	struct proc *p = l->l_proc;
    677 	struct ktrace_entry *kte;
    678 	struct ktr_csw *kc;
    679 
    680 	/*
    681 	 * Don't record context switches resulting from blocking on
    682 	 * locks; it's too easy to get duff results.
    683 	 */
    684 	if (l->l_syncobj == &mutex_syncobj || l->l_syncobj == &rw_syncobj)
    685 		return;
    686 
    687 	/*
    688 	 * We can't sleep if we're already going to sleep (if original
    689 	 * condition is met during sleep, we hang up).
    690 	 *
    691 	 * XXX This is not ideal: it would be better to maintain a pool
    692 	 * of ktes and actually push this to the kthread when context
    693 	 * switch happens, however given the points where we are called
    694 	 * from that is difficult to do.
    695 	 */
    696 	if (out) {
    697 		if (ktrenter(l))
    698 			return;
    699 
    700 		switch (KTRFAC_VERSION(p->p_traceflag)) {
    701 		case 0:
    702 			/* This is the original format */
    703 			microtime(&l->l_ktrcsw.tv);
    704 			l->l_pflag |= LP_KTRCSW;
    705 			break;
    706 		case 1:
    707 			nanotime(&l->l_ktrcsw.ts);
    708 			l->l_pflag |= LP_KTRCSW;
    709 			break;
    710 		default:
    711 			break;
    712 		}
    713 
    714 		if (user)
    715 			l->l_pflag |= LP_KTRCSWUSER;
    716 		else
    717 			l->l_pflag &= ~LP_KTRCSWUSER;
    718 
    719 		ktrexit(l);
    720 		return;
    721 	}
    722 
    723 	/*
    724 	 * On the way back in, we need to record twice: once for entry, and
    725 	 * once for exit.
    726 	 */
    727 	if ((l->l_pflag & LP_KTRCSW) != 0) {
    728 		l->l_pflag &= ~LP_KTRCSW;
    729 
    730 		if (ktealloc(&kte, (void *)&kc, l, KTR_CSW, sizeof(*kc)))
    731 			return;
    732 
    733 		kc->out = 1;
    734 		kc->user = ((l->l_pflag & LP_KTRCSWUSER) != 0);
    735 
    736 		switch (KTRFAC_VERSION(p->p_traceflag)) {
    737 		case 0:
    738 			/* This is the original format */
    739 			memcpy(&kte->kte_kth.ktr_tv, &l->l_ktrcsw.tv,
    740 			    sizeof(kte->kte_kth.ktr_tv));
    741 			break;
    742 		case 1:
    743 			memcpy(&kte->kte_kth.ktr_time, &l->l_ktrcsw.ts,
    744 			    sizeof(kte->kte_kth.ktr_time));
    745 			break;
    746 		default:
    747 			break;
    748 		}
    749 
    750 		ktraddentry(l, kte, KTA_WAITOK);
    751 	}
    752 
    753 	if (ktealloc(&kte, (void *)&kc, l, KTR_CSW, sizeof(*kc)))
    754 		return;
    755 
    756 	kc->out = 0;
    757 	kc->user = user;
    758 
    759 	ktraddentry(l, kte, KTA_WAITOK);
    760 }
    761 
    762 int
    763 ktruser(struct lwp *l, const char *id, void *addr, size_t len, int ustr)
    764 {
    765 	struct ktrace_entry *kte;
    766 	struct ktr_user *ktp;
    767 	void *user_dta;
    768 	int error;
    769 
    770 	if (len > KTR_USER_MAXLEN)
    771 		return ENOSPC;
    772 
    773 	error = ktealloc(&kte, (void *)&ktp, l, KTR_USER, sizeof(*ktp) + len);
    774 	if (error != 0)
    775 		return error;
    776 
    777 	if (ustr) {
    778 		if (copyinstr(id, ktp->ktr_id, KTR_USER_MAXIDLEN, NULL) != 0)
    779 			ktp->ktr_id[0] = '\0';
    780 	} else
    781 		strncpy(ktp->ktr_id, id, KTR_USER_MAXIDLEN);
    782 	ktp->ktr_id[KTR_USER_MAXIDLEN-1] = '\0';
    783 
    784 	user_dta = (void *)(ktp + 1);
    785 	if ((error = copyin(addr, (void *)user_dta, len)) != 0)
    786 		len = 0;
    787 
    788 	ktraddentry(l, kte, KTA_WAITOK);
    789 	return error;
    790 }
    791 
    792 void
    793 ktrmmsg(struct lwp *l, const void *msgh, size_t size)
    794 {
    795 	ktrkmem(l, KTR_MMSG, msgh, size);
    796 }
    797 
    798 void
    799 ktrmool(struct lwp *l, const void *kaddr, size_t size, const void *uaddr)
    800 {
    801 	struct ktrace_entry *kte;
    802 	struct ktr_mool *kp;
    803 	struct ktr_mool *bf;
    804 
    805 	if (ktealloc(&kte, (void *)&kp, l, KTR_MOOL, size + sizeof(*kp)))
    806 		return;
    807 
    808 	kp->uaddr = uaddr;
    809 	kp->size = size;
    810 	bf = kp + 1; /* Skip uaddr and size */
    811 	(void)memcpy(bf, kaddr, size);
    812 
    813 	ktraddentry(l, kte, KTA_WAITOK);
    814 }
    815 
    816 void
    817 ktrmib(struct lwp *l, const int *name, u_int namelen)
    818 {
    819 	struct ktrace_entry *kte;
    820 	int *namep;
    821 	size_t size;
    822 
    823 	size = namelen * sizeof(*name);
    824 
    825 	if (ktealloc(&kte, (void *)&namep, l, KTR_MIB, size))
    826 		return;
    827 
    828 	(void)memcpy(namep, name, namelen * sizeof(*name));
    829 
    830 	ktraddentry(l, kte, KTA_WAITOK);
    831 }
    832 
    833 /* Interface and common routines */
    834 
    835 int
    836 ktrace_common(struct lwp *curl, int ops, int facs, int pid, struct file *fp)
    837 {
    838 	struct proc *curp;
    839 	struct proc *p;
    840 	struct pgrp *pg;
    841 	struct ktr_desc *ktd = NULL;
    842 	int ret = 0;
    843 	int error = 0;
    844 	int descend;
    845 
    846 	curp = curl->l_proc;
    847 	descend = ops & KTRFLAG_DESCEND;
    848 	facs = facs & ~((unsigned) KTRFAC_ROOT);
    849 
    850 	(void)ktrenter(curl);
    851 
    852 	switch (KTROP(ops)) {
    853 
    854 	case KTROP_CLEARFILE:
    855 		/*
    856 		 * Clear all uses of the tracefile
    857 		 */
    858 		mutex_enter(&ktrace_mutex);
    859 		ktd = ktd_lookup(fp);
    860 		mutex_exit(&ktrace_mutex);
    861 		if (ktd == NULL)
    862 			goto done;
    863 		error = ktrderefall(ktd, 1);
    864 		goto done;
    865 
    866 	case KTROP_SET:
    867 		mutex_enter(&ktrace_mutex);
    868 		ktd = ktd_lookup(fp);
    869 		mutex_exit(&ktrace_mutex);
    870 		if (ktd == NULL) {
    871 			ktd = kmem_alloc(sizeof(*ktd), KM_SLEEP);
    872 			TAILQ_INIT(&ktd->ktd_queue);
    873 			callout_init(&ktd->ktd_wakch);
    874 			cv_init(&ktd->ktd_cv, "ktrwait");
    875 			cv_init(&ktd->ktd_sync_cv, "ktrsync");
    876 			ktd->ktd_flags = ktd->ktd_qcount =
    877 			    ktd->ktd_error = ktd->ktd_errcnt = 0;
    878 			ktd->ktd_ref = 1;
    879 			ktd->ktd_delayqcnt = ktd_delayqcnt;
    880 			ktd->ktd_wakedelay = mstohz(ktd_wakedelay);
    881 			ktd->ktd_intrwakdl = mstohz(ktd_intrwakdl);
    882 			/*
    883 			 * XXX: not correct.  needs an way to detect
    884 			 * whether ktruss or ktrace.
    885 			 */
    886 			if (fp->f_type == DTYPE_PIPE)
    887 				ktd->ktd_flags |= KTDF_INTERACTIVE;
    888 
    889 			error = kthread_create(PRI_NONE, true, ktrace_thread,
    890 			    ktd, &ktd->ktd_lwp, "ktrace");
    891 			if (error != 0) {
    892 				kmem_free(ktd, sizeof(*ktd));
    893 				goto done;
    894 			}
    895 
    896 			mutex_enter(&fp->f_lock);
    897 			fp->f_count++;
    898 			mutex_exit(&fp->f_lock);
    899 			ktd->ktd_fp = fp;
    900 
    901 			mutex_enter(&ktrace_mutex);
    902 			if (ktd_lookup(fp) != NULL) {
    903 				ktdrel(ktd);
    904 				ktd = NULL;
    905 			} else
    906 				TAILQ_INSERT_TAIL(&ktdq, ktd, ktd_list);
    907 			if (ktd == NULL)
    908 				cv_wait(&lbolt, &ktrace_mutex);
    909 			mutex_exit(&ktrace_mutex);
    910 			if (ktd == NULL)
    911 				goto done;
    912 		}
    913 		break;
    914 
    915 	case KTROP_CLEAR:
    916 		break;
    917 	}
    918 
    919 	/*
    920 	 * need something to (un)trace (XXX - why is this here?)
    921 	 */
    922 	if (!facs) {
    923 		error = EINVAL;
    924 		goto done;
    925 	}
    926 
    927 	/*
    928 	 * do it
    929 	 */
    930 	mutex_enter(&proclist_lock);
    931 	if (pid < 0) {
    932 		/*
    933 		 * by process group
    934 		 */
    935 		pg = pg_find(-pid, PFIND_LOCKED);
    936 		if (pg == NULL)
    937 			error = ESRCH;
    938 		else {
    939 			LIST_FOREACH(p, &pg->pg_members, p_pglist) {
    940 				if (descend)
    941 					ret |= ktrsetchildren(curl, p, ops,
    942 					    facs, ktd);
    943 				else
    944 					ret |= ktrops(curl, p, ops, facs,
    945 					    ktd);
    946 			}
    947 		}
    948 
    949 	} else {
    950 		/*
    951 		 * by pid
    952 		 */
    953 		p = p_find(pid, PFIND_LOCKED);
    954 		if (p == NULL)
    955 			error = ESRCH;
    956 		else if (descend)
    957 			ret |= ktrsetchildren(curl, p, ops, facs, ktd);
    958 		else
    959 			ret |= ktrops(curl, p, ops, facs, ktd);
    960 	}
    961 	mutex_exit(&proclist_lock);	/* taken by p{g}_find */
    962 	if (error == 0 && !ret)
    963 		error = EPERM;
    964 done:
    965 	if (ktd != NULL) {
    966 		if (error != 0) {
    967 			/*
    968 			 * Wakeup the thread so that it can be die if we
    969 			 * can't trace any process.
    970 			 */
    971 			ktd_wakeup(ktd);
    972 		}
    973 		if (KTROP(ops) == KTROP_SET || KTROP(ops) == KTROP_CLEARFILE) {
    974 			mutex_enter(&ktrace_mutex);
    975 			ktdrel(ktd);
    976 			mutex_exit(&ktrace_mutex);
    977 		}
    978 	}
    979 	ktrexit(curl);
    980 	return (error);
    981 }
    982 
    983 /*
    984  * fktrace system call
    985  */
    986 /* ARGSUSED */
    987 int
    988 sys_fktrace(struct lwp *l, void *v, register_t *retval)
    989 {
    990 	struct sys_fktrace_args /* {
    991 		syscallarg(int) fd;
    992 		syscallarg(int) ops;
    993 		syscallarg(int) facs;
    994 		syscallarg(int) pid;
    995 	} */ *uap = v;
    996 	struct file *fp = NULL;
    997 	struct filedesc *fdp = l->l_proc->p_fd;
    998 	int error;
    999 
   1000 	fdp = l->l_proc->p_fd;
   1001 	if ((fp = fd_getfile(fdp, SCARG(uap, fd))) == NULL)
   1002 		return (EBADF);
   1003 
   1004 	FILE_USE(fp);
   1005 
   1006 	if ((fp->f_flag & FWRITE) == 0)
   1007 		error = EBADF;
   1008 	else
   1009 		error = ktrace_common(l, SCARG(uap, ops),
   1010 		    SCARG(uap, facs), SCARG(uap, pid), fp);
   1011 
   1012 	FILE_UNUSE(fp, l);
   1013 
   1014 	return error;
   1015 }
   1016 
   1017 /*
   1018  * ktrace system call
   1019  */
   1020 /* ARGSUSED */
   1021 int
   1022 sys_ktrace(struct lwp *l, void *v, register_t *retval)
   1023 {
   1024 	struct sys_ktrace_args /* {
   1025 		syscallarg(const char *) fname;
   1026 		syscallarg(int) ops;
   1027 		syscallarg(int) facs;
   1028 		syscallarg(int) pid;
   1029 	} */ *uap = v;
   1030 	struct vnode *vp = NULL;
   1031 	struct file *fp = NULL;
   1032 	struct nameidata nd;
   1033 	int error = 0;
   1034 	int fd;
   1035 
   1036 	if (ktrenter(l))
   1037 		return EAGAIN;
   1038 
   1039 	if (KTROP(SCARG(uap, ops)) != KTROP_CLEAR) {
   1040 		/*
   1041 		 * an operation which requires a file argument.
   1042 		 */
   1043 		NDINIT(&nd, LOOKUP, FOLLOW, UIO_USERSPACE, SCARG(uap, fname),
   1044 		    l);
   1045 		if ((error = vn_open(&nd, FREAD|FWRITE, 0)) != 0) {
   1046 			ktrexit(l);
   1047 			return (error);
   1048 		}
   1049 		vp = nd.ni_vp;
   1050 		VOP_UNLOCK(vp, 0);
   1051 		if (vp->v_type != VREG) {
   1052 			(void) vn_close(vp, FREAD|FWRITE, l->l_cred, l);
   1053 			ktrexit(l);
   1054 			return (EACCES);
   1055 		}
   1056 		/*
   1057 		 * XXX This uses up a file descriptor slot in the
   1058 		 * tracing process for the duration of this syscall.
   1059 		 * This is not expected to be a problem.  If
   1060 		 * falloc(NULL, ...) DTRT we could skip that part, but
   1061 		 * that would require changing its interface to allow
   1062 		 * the caller to pass in a ucred..
   1063 		 *
   1064 		 * This will FILE_USE the fp it returns, if any.
   1065 		 * Keep it in use until we return.
   1066 		 */
   1067 		if ((error = falloc(l, &fp, &fd)) != 0)
   1068 			goto done;
   1069 
   1070 		fp->f_flag = FWRITE;
   1071 		fp->f_type = DTYPE_VNODE;
   1072 		fp->f_ops = &vnops;
   1073 		fp->f_data = (void *)vp;
   1074 		FILE_SET_MATURE(fp);
   1075 		vp = NULL;
   1076 	}
   1077 	error = ktrace_common(l, SCARG(uap, ops), SCARG(uap, facs),
   1078 	    SCARG(uap, pid), fp);
   1079 done:
   1080 	if (vp != NULL)
   1081 		(void) vn_close(vp, FWRITE, l->l_cred, l);
   1082 	if (fp != NULL) {
   1083 		FILE_UNUSE(fp, l);	/* release file */
   1084 		fdrelease(l, fd); 	/* release fd table slot */
   1085 	}
   1086 	return (error);
   1087 }
   1088 
   1089 int
   1090 ktrops(struct lwp *curl, struct proc *p, int ops, int facs,
   1091     struct ktr_desc *ktd)
   1092 {
   1093 	int vers = ops & KTRFAC_VER_MASK;
   1094 	int error = 0;
   1095 
   1096 	mutex_enter(&p->p_mutex);
   1097 	mutex_enter(&ktrace_mutex);
   1098 
   1099 	if (!ktrcanset(curl, p))
   1100 		goto out;
   1101 
   1102 	switch (vers) {
   1103 	case KTRFACv0:
   1104 	case KTRFACv1:
   1105 		break;
   1106 	default:
   1107 		error = EINVAL;
   1108 		goto out;
   1109 	}
   1110 
   1111 	if (KTROP(ops) == KTROP_SET) {
   1112 		if (p->p_tracep != ktd) {
   1113 			/*
   1114 			 * if trace file already in use, relinquish
   1115 			 */
   1116 			ktrderef(p);
   1117 			p->p_tracep = ktd;
   1118 			ktradref(p);
   1119 		}
   1120 		p->p_traceflag |= facs;
   1121 		if (kauth_authorize_generic(curl->l_cred,
   1122 		    KAUTH_GENERIC_ISSUSER, NULL) == 0)
   1123 			p->p_traceflag |= KTRFAC_ROOT;
   1124 	} else {
   1125 		/* KTROP_CLEAR */
   1126 		if (((p->p_traceflag &= ~facs) & KTRFAC_MASK) == 0) {
   1127 			/* no more tracing */
   1128 			ktrderef(p);
   1129 		}
   1130 	}
   1131 
   1132 	if (p->p_traceflag)
   1133 		p->p_traceflag |= vers;
   1134 	/*
   1135 	 * Emit an emulation record, every time there is a ktrace
   1136 	 * change/attach request.
   1137 	 */
   1138 	if (KTRPOINT(p, KTR_EMUL))
   1139 		p->p_traceflag |= KTRFAC_TRC_EMUL;
   1140 #ifdef __HAVE_SYSCALL_INTERN
   1141 	(*p->p_emul->e_syscall_intern)(p);
   1142 #endif
   1143 
   1144  out:
   1145  	mutex_exit(&ktrace_mutex);
   1146  	mutex_exit(&p->p_mutex);
   1147 
   1148 	return (1);
   1149 }
   1150 
   1151 int
   1152 ktrsetchildren(struct lwp *curl, struct proc *top, int ops, int facs,
   1153     struct ktr_desc *ktd)
   1154 {
   1155 	struct proc *p;
   1156 	int ret = 0;
   1157 
   1158 	KASSERT(mutex_owned(&proclist_lock));
   1159 
   1160 	p = top;
   1161 	for (;;) {
   1162 		ret |= ktrops(curl, p, ops, facs, ktd);
   1163 		/*
   1164 		 * If this process has children, descend to them next,
   1165 		 * otherwise do any siblings, and if done with this level,
   1166 		 * follow back up the tree (but not past top).
   1167 		 */
   1168 		if (LIST_FIRST(&p->p_children) != NULL) {
   1169 			p = LIST_FIRST(&p->p_children);
   1170 			continue;
   1171 		}
   1172 		for (;;) {
   1173 			if (p == top)
   1174 				return (ret);
   1175 			if (LIST_NEXT(p, p_sibling) != NULL) {
   1176 				p = LIST_NEXT(p, p_sibling);
   1177 				break;
   1178 			}
   1179 			p = p->p_pptr;
   1180 		}
   1181 	}
   1182 	/*NOTREACHED*/
   1183 }
   1184 
   1185 void
   1186 ktrwrite(struct ktr_desc *ktd, struct ktrace_entry *kte)
   1187 {
   1188 	struct uio auio;
   1189 	struct iovec aiov[64], *iov;
   1190 	struct ktrace_entry *top = kte;
   1191 	struct ktr_header *kth;
   1192 	struct file *fp = ktd->ktd_fp;
   1193 	int error;
   1194 next:
   1195 	auio.uio_iov = iov = &aiov[0];
   1196 	auio.uio_offset = 0;
   1197 	auio.uio_rw = UIO_WRITE;
   1198 	auio.uio_resid = 0;
   1199 	auio.uio_iovcnt = 0;
   1200 	UIO_SETUP_SYSSPACE(&auio);
   1201 	do {
   1202 		kth = &kte->kte_kth;
   1203 
   1204 		if (kth->ktr_version == 0) {
   1205 			/*
   1206 			 * Convert back to the old format fields
   1207 			 */
   1208 			TIMESPEC_TO_TIMEVAL(&kth->ktr_tv, &kth->ktr_time);
   1209 			kth->ktr_unused = NULL;
   1210 		}
   1211 		iov->iov_base = (void *)kth;
   1212 		iov++->iov_len = sizeof(struct ktr_header);
   1213 		auio.uio_resid += sizeof(struct ktr_header);
   1214 		auio.uio_iovcnt++;
   1215 		if (kth->ktr_len > 0) {
   1216 			iov->iov_base = kte->kte_buf;
   1217 			iov++->iov_len = kth->ktr_len;
   1218 			auio.uio_resid += kth->ktr_len;
   1219 			auio.uio_iovcnt++;
   1220 		}
   1221 	} while ((kte = TAILQ_NEXT(kte, kte_list)) != NULL &&
   1222 	    auio.uio_iovcnt < sizeof(aiov) / sizeof(aiov[0]) - 1);
   1223 
   1224 again:
   1225 	mutex_enter(&fp->f_lock);
   1226 	FILE_USE(fp);
   1227 	error = (*fp->f_ops->fo_write)(fp, &fp->f_offset, &auio,
   1228 	    fp->f_cred, FOF_UPDATE_OFFSET);
   1229 	FILE_UNUSE(fp, NULL);
   1230 	switch (error) {
   1231 
   1232 	case 0:
   1233 		if (auio.uio_resid > 0)
   1234 			goto again;
   1235 		if (kte != NULL)
   1236 			goto next;
   1237 		break;
   1238 
   1239 	case EWOULDBLOCK:
   1240 		kpause("ktrzzz", false, 1, NULL);
   1241 		goto again;
   1242 
   1243 	default:
   1244 		/*
   1245 		 * If error encountered, give up tracing on this
   1246 		 * vnode.  Don't report EPIPE as this can easily
   1247 		 * happen with fktrace()/ktruss.
   1248 		 */
   1249 #ifndef DEBUG
   1250 		if (error != EPIPE)
   1251 #endif
   1252 			log(LOG_NOTICE,
   1253 			    "ktrace write failed, errno %d, tracing stopped\n",
   1254 			    error);
   1255 		(void)ktrderefall(ktd, 0);
   1256 	}
   1257 
   1258 	while ((kte = top) != NULL) {
   1259 		top = TAILQ_NEXT(top, kte_list);
   1260 		ktefree(kte);
   1261 	}
   1262 }
   1263 
   1264 void
   1265 ktrace_thread(void *arg)
   1266 {
   1267 	struct ktr_desc *ktd = arg;
   1268 	struct file *fp = ktd->ktd_fp;
   1269 	struct ktrace_entry *kte;
   1270 	int ktrerr, errcnt;
   1271 
   1272 	mutex_enter(&ktrace_mutex);
   1273 	for (;;) {
   1274 		kte = TAILQ_FIRST(&ktd->ktd_queue);
   1275 		if (kte == NULL) {
   1276 			if (ktd->ktd_flags & KTDF_WAIT) {
   1277 				ktd->ktd_flags &= ~(KTDF_WAIT | KTDF_BLOCKING);
   1278 				cv_broadcast(&ktd->ktd_sync_cv);
   1279 			}
   1280 			if (ktd->ktd_ref == 0)
   1281 				break;
   1282 			cv_wait(&ktd->ktd_cv, &ktrace_mutex);
   1283 			continue;
   1284 		}
   1285 		TAILQ_INIT(&ktd->ktd_queue);
   1286 		ktd->ktd_qcount = 0;
   1287 		ktrerr = ktd->ktd_error;
   1288 		errcnt = ktd->ktd_errcnt;
   1289 		ktd->ktd_error = ktd->ktd_errcnt = 0;
   1290 		mutex_exit(&ktrace_mutex);
   1291 
   1292 		if (ktrerr) {
   1293 			log(LOG_NOTICE,
   1294 			    "ktrace failed, fp %p, error 0x%x, total %d\n",
   1295 			    fp, ktrerr, errcnt);
   1296 		}
   1297 		ktrwrite(ktd, kte);
   1298 		mutex_enter(&ktrace_mutex);
   1299 	}
   1300 
   1301 	TAILQ_REMOVE(&ktdq, ktd, ktd_list);
   1302 	mutex_exit(&ktrace_mutex);
   1303 
   1304 	mutex_enter(&fp->f_lock);
   1305 	FILE_USE(fp);
   1306 
   1307 	/*
   1308 	 * ktrace file descriptor can't be watched (are not visible to
   1309 	 * userspace), so no kqueue stuff here
   1310 	 * XXX: The above comment is wrong, because the fktrace file
   1311 	 * descriptor is available in userland.
   1312 	 */
   1313 	closef(fp, NULL);
   1314 
   1315 	callout_stop(&ktd->ktd_wakch);
   1316 	kmem_free(ktd, sizeof(*ktd));
   1317 
   1318 	kthread_exit(0);
   1319 }
   1320 
   1321 /*
   1322  * Return true if caller has permission to set the ktracing state
   1323  * of target.  Essentially, the target can't possess any
   1324  * more permissions than the caller.  KTRFAC_ROOT signifies that
   1325  * root previously set the tracing status on the target process, and
   1326  * so, only root may further change it.
   1327  *
   1328  * TODO: check groups.  use caller effective gid.
   1329  */
   1330 int
   1331 ktrcanset(struct lwp *calll, struct proc *targetp)
   1332 {
   1333 	KASSERT(mutex_owned(&targetp->p_mutex));
   1334 	KASSERT(mutex_owned(&ktrace_mutex));
   1335 
   1336 	if (kauth_authorize_process(calll->l_cred, KAUTH_PROCESS_CANKTRACE,
   1337 	    targetp, NULL, NULL, NULL) == 0)
   1338 		return (1);
   1339 
   1340 	return (0);
   1341 }
   1342 #endif /* KTRACE */
   1343 
   1344 /*
   1345  * Put user defined entry to ktrace records.
   1346  */
   1347 int
   1348 sys_utrace(struct lwp *l, void *v, register_t *retval)
   1349 {
   1350 #ifdef KTRACE
   1351 	struct sys_utrace_args /* {
   1352 		syscallarg(const char *) label;
   1353 		syscallarg(void *) addr;
   1354 		syscallarg(size_t) len;
   1355 	} */ *uap = v;
   1356 	struct proc *p = l->l_proc;
   1357 
   1358 	if (!KTRPOINT(p, KTR_USER))
   1359 		return (0);
   1360 
   1361 	return ktruser(l, SCARG(uap, label), SCARG(uap, addr),
   1362 	    SCARG(uap, len), 1);
   1363 #else /* !KTRACE */
   1364 	return ENOSYS;
   1365 #endif /* KTRACE */
   1366 }
   1367