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