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