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