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