xref: /netbsd-src/sys/kern/kern_ktrace.c (revision 267197ec1eebfcb9810ea27a89625b6ddf68e3e7)
1 /*	$NetBSD: kern_ktrace.c,v 1.138 2008/02/06 22:12:41 dsl 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.138 2008/02/06 22:12:41 dsl 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, const register_t args[], int narg)
543 {
544 	lwp_t *l = curlwp;
545 	struct proc *p = l->l_proc;
546 	struct ktrace_entry *kte;
547 	struct ktr_syscall *ktp;
548 	register_t *argp;
549 	size_t len;
550 	u_int i;
551 
552 	if (!KTRPOINT(p, KTR_SYSCALL))
553 		return;
554 
555 	len = sizeof(struct ktr_syscall) + narg * sizeof argp[0];
556 
557 	if (ktealloc(&kte, (void *)&ktp, l, KTR_SYSCALL, len))
558 		return;
559 
560 	ktp->ktr_code = code;
561 	ktp->ktr_argsize = narg * sizeof argp[0];
562 	argp = (register_t *)(ktp + 1);
563 	for (i = 0; i < narg; i++)
564 		*argp++ = args[i];
565 
566 	ktraddentry(l, kte, KTA_WAITOK);
567 }
568 
569 void
570 ktr_sysret(register_t code, int error, register_t *retval)
571 {
572 	lwp_t *l = curlwp;
573 	struct ktrace_entry *kte;
574 	struct ktr_sysret *ktp;
575 
576 	if (!KTRPOINT(l->l_proc, KTR_SYSRET))
577 		return;
578 
579 	if (ktealloc(&kte, (void *)&ktp, l, KTR_SYSRET,
580 	    sizeof(struct ktr_sysret)))
581 		return;
582 
583 	ktp->ktr_code = code;
584 	ktp->ktr_eosys = 0;			/* XXX unused */
585 	ktp->ktr_error = error;
586 	ktp->ktr_retval = retval ? retval[0] : 0;
587 	ktp->ktr_retval_1 = retval ? retval[1] : 0;
588 
589 	ktraddentry(l, kte, KTA_WAITOK);
590 }
591 
592 void
593 ktr_namei(const char *path, size_t pathlen)
594 {
595 	lwp_t *l = curlwp;
596 
597 	if (!KTRPOINT(l->l_proc, KTR_NAMEI))
598 		return;
599 
600 	ktr_kmem(l, KTR_NAMEI, path, pathlen);
601 }
602 
603 void
604 ktr_namei2(const char *eroot, size_t erootlen,
605 	  const char *path, size_t pathlen)
606 {
607 	lwp_t *l = curlwp;
608 	struct ktrace_entry *kte;
609 	void *buf;
610 
611 	if (!KTRPOINT(l->l_proc, KTR_NAMEI))
612 		return;
613 
614 	if (ktealloc(&kte, &buf, l, KTR_NAMEI, erootlen + pathlen))
615 		return;
616 	memcpy(buf, eroot, erootlen);
617 	buf = (char *)buf + erootlen;
618 	memcpy(buf, path, pathlen);
619 	ktraddentry(l, kte, KTA_WAITOK);
620 }
621 
622 void
623 ktr_emul(void)
624 {
625 	lwp_t *l = curlwp;
626 	const char *emul = l->l_proc->p_emul->e_name;
627 
628 	if (!KTRPOINT(l->l_proc, KTR_EMUL))
629 		return;
630 
631 	ktr_kmem(l, KTR_EMUL, emul, strlen(emul));
632 }
633 
634 void
635 ktr_execarg(const void *bf, size_t len)
636 {
637 	lwp_t *l = curlwp;
638 
639 	if (!KTRPOINT(l->l_proc, KTR_EXEC_ARG))
640 		return;
641 
642 	ktr_kmem(l, KTR_EXEC_ARG, bf, len);
643 }
644 
645 void
646 ktr_execenv(const void *bf, size_t len)
647 {
648 	lwp_t *l = curlwp;
649 
650 	if (!KTRPOINT(l->l_proc, KTR_EXEC_ENV))
651 		return;
652 
653 	ktr_kmem(l, KTR_EXEC_ENV, bf, len);
654 }
655 
656 static void
657 ktr_kmem(lwp_t *l, int type, const void *bf, size_t len)
658 {
659 	struct ktrace_entry *kte;
660 	void *buf;
661 
662 	if (ktealloc(&kte, &buf, l, type, len))
663 		return;
664 	memcpy(buf, bf, len);
665 	ktraddentry(l, kte, KTA_WAITOK);
666 }
667 
668 static void
669 ktr_io(lwp_t *l, int fd, enum uio_rw rw, struct iovec *iov, size_t len)
670 {
671 	struct ktrace_entry *kte;
672 	struct ktr_genio *ktp;
673 	size_t resid = len, cnt, buflen;
674 	void *cp;
675 
676  next:
677 	buflen = min(PAGE_SIZE, resid + sizeof(struct ktr_genio));
678 
679 	if (ktealloc(&kte, (void *)&ktp, l, KTR_GENIO, buflen))
680 		return;
681 
682 	ktp->ktr_fd = fd;
683 	ktp->ktr_rw = rw;
684 
685 	cp = (void *)(ktp + 1);
686 	buflen -= sizeof(struct ktr_genio);
687 	kte->kte_kth.ktr_len = sizeof(struct ktr_genio);
688 
689 	while (buflen > 0) {
690 		cnt = min(iov->iov_len, buflen);
691 		if (copyin(iov->iov_base, cp, cnt) != 0)
692 			goto out;
693 		kte->kte_kth.ktr_len += cnt;
694 		buflen -= cnt;
695 		resid -= cnt;
696 		iov->iov_len -= cnt;
697 		if (iov->iov_len == 0)
698 			iov++;
699 		else
700 			iov->iov_base = (char *)iov->iov_base + cnt;
701 	}
702 
703 	/*
704 	 * Don't push so many entry at once.  It will cause kmem map
705 	 * shortage.
706 	 */
707 	ktraddentry(l, kte, KTA_WAITOK | KTA_LARGE);
708 	if (resid > 0) {
709 		if (curcpu()->ci_schedstate.spc_flags & SPCF_SHOULDYIELD) {
710 			(void)ktrenter(l);
711 			preempt();
712 			ktrexit(l);
713 		}
714 
715 		goto next;
716 	}
717 
718 	return;
719 
720 out:
721 	ktefree(kte);
722 	ktrexit(l);
723 }
724 
725 void
726 ktr_genio(int fd, enum uio_rw rw, const void *addr, size_t len, int error)
727 {
728 	lwp_t *l = curlwp;
729 	struct iovec iov;
730 
731 	if (!KTRPOINT(l->l_proc, KTR_GENIO) || error != 0)
732 		return;
733 	iov.iov_base = __UNCONST(addr);
734 	iov.iov_len = len;
735 	ktr_io(l, fd, rw, &iov, len);
736 }
737 
738 void
739 ktr_geniov(int fd, enum uio_rw rw, struct iovec *iov, size_t len, int error)
740 {
741 	lwp_t *l = curlwp;
742 
743 	if (!KTRPOINT(l->l_proc, KTR_GENIO) || error != 0)
744 		return;
745 	ktr_io(l, fd, rw, iov, len);
746 }
747 
748 void
749 ktr_mibio(int fd, enum uio_rw rw, const void *addr, size_t len, int error)
750 {
751 	lwp_t *l = curlwp;
752 	struct iovec iov;
753 
754 	if (!KTRPOINT(l->l_proc, KTR_MIB) || error != 0)
755 		return;
756 	iov.iov_base = __UNCONST(addr);
757 	iov.iov_len = len;
758 	ktr_io(l, fd, rw, &iov, len);
759 }
760 
761 void
762 ktr_psig(int sig, sig_t action, const sigset_t *mask,
763 	 const ksiginfo_t *ksi)
764 {
765 	struct ktrace_entry *kte;
766 	lwp_t *l = curlwp;
767 	struct {
768 		struct ktr_psig	kp;
769 		siginfo_t	si;
770 	} *kbuf;
771 
772 	if (!KTRPOINT(l->l_proc, KTR_PSIG))
773 		return;
774 
775 	if (ktealloc(&kte, (void *)&kbuf, l, KTR_PSIG, sizeof(*kbuf)))
776 		return;
777 
778 	kbuf->kp.signo = (char)sig;
779 	kbuf->kp.action = action;
780 	kbuf->kp.mask = *mask;
781 
782 	if (ksi) {
783 		kbuf->kp.code = KSI_TRAPCODE(ksi);
784 		(void)memset(&kbuf->si, 0, sizeof(kbuf->si));
785 		kbuf->si._info = ksi->ksi_info;
786 		kte->kte_kth.ktr_len = sizeof(*kbuf);
787 	} else {
788 		kbuf->kp.code = 0;
789 		kte->kte_kth.ktr_len = sizeof(struct ktr_psig);
790 	}
791 
792 	ktraddentry(l, kte, KTA_WAITOK);
793 }
794 
795 void
796 ktr_csw(int out, int user)
797 {
798 	lwp_t *l = curlwp;
799 	struct proc *p = l->l_proc;
800 	struct ktrace_entry *kte;
801 	struct ktr_csw *kc;
802 
803 	if (!KTRPOINT(p, KTR_CSW))
804 		return;
805 
806 	/*
807 	 * Don't record context switches resulting from blocking on
808 	 * locks; it's too easy to get duff results.
809 	 */
810 	if (l->l_syncobj == &mutex_syncobj || l->l_syncobj == &rw_syncobj)
811 		return;
812 
813 	/*
814 	 * We can't sleep if we're already going to sleep (if original
815 	 * condition is met during sleep, we hang up).
816 	 *
817 	 * XXX This is not ideal: it would be better to maintain a pool
818 	 * of ktes and actually push this to the kthread when context
819 	 * switch happens, however given the points where we are called
820 	 * from that is difficult to do.
821 	 */
822 	if (out) {
823 		if (ktrenter(l))
824 			return;
825 
826 		switch (KTRFAC_VERSION(p->p_traceflag)) {
827 		case 0:
828 			/* This is the original format */
829 			microtime(&l->l_ktrcsw.tv);
830 			l->l_pflag |= LP_KTRCSW;
831 			break;
832 		case 1:
833 			nanotime(&l->l_ktrcsw.ts);
834 			l->l_pflag |= LP_KTRCSW;
835 			break;
836 		default:
837 			break;
838 		}
839 
840 		if (user)
841 			l->l_pflag |= LP_KTRCSWUSER;
842 		else
843 			l->l_pflag &= ~LP_KTRCSWUSER;
844 
845 		ktrexit(l);
846 		return;
847 	}
848 
849 	/*
850 	 * On the way back in, we need to record twice: once for entry, and
851 	 * once for exit.
852 	 */
853 	if ((l->l_pflag & LP_KTRCSW) != 0) {
854 		l->l_pflag &= ~LP_KTRCSW;
855 
856 		if (ktealloc(&kte, (void *)&kc, l, KTR_CSW, sizeof(*kc)))
857 			return;
858 
859 		kc->out = 1;
860 		kc->user = ((l->l_pflag & LP_KTRCSWUSER) != 0);
861 
862 		switch (KTRFAC_VERSION(p->p_traceflag)) {
863 		case 0:
864 			/* This is the original format */
865 			memcpy(&kte->kte_kth.ktr_tv, &l->l_ktrcsw.tv,
866 			    sizeof(kte->kte_kth.ktr_tv));
867 			break;
868 		case 1:
869 			memcpy(&kte->kte_kth.ktr_time, &l->l_ktrcsw.ts,
870 			    sizeof(kte->kte_kth.ktr_time));
871 			break;
872 		default:
873 			break;
874 		}
875 
876 		ktraddentry(l, kte, KTA_WAITOK);
877 	}
878 
879 	if (ktealloc(&kte, (void *)&kc, l, KTR_CSW, sizeof(*kc)))
880 		return;
881 
882 	kc->out = 0;
883 	kc->user = user;
884 
885 	ktraddentry(l, kte, KTA_WAITOK);
886 }
887 
888 bool
889 ktr_point(int fac_bit)
890 {
891 	return curlwp->l_proc->p_traceflag & fac_bit;
892 }
893 
894 int
895 ktruser(const char *id, void *addr, size_t len, int ustr)
896 {
897 	struct ktrace_entry *kte;
898 	struct ktr_user *ktp;
899 	lwp_t *l = curlwp;
900 	void *user_dta;
901 	int error;
902 
903 	if (!KTRPOINT(l->l_proc, KTR_USER))
904 		return 0;
905 
906 	if (len > KTR_USER_MAXLEN)
907 		return ENOSPC;
908 
909 	error = ktealloc(&kte, (void *)&ktp, l, KTR_USER, sizeof(*ktp) + len);
910 	if (error != 0)
911 		return error;
912 
913 	if (ustr) {
914 		if (copyinstr(id, ktp->ktr_id, KTR_USER_MAXIDLEN, NULL) != 0)
915 			ktp->ktr_id[0] = '\0';
916 	} else
917 		strncpy(ktp->ktr_id, id, KTR_USER_MAXIDLEN);
918 	ktp->ktr_id[KTR_USER_MAXIDLEN-1] = '\0';
919 
920 	user_dta = (void *)(ktp + 1);
921 	if ((error = copyin(addr, (void *)user_dta, len)) != 0)
922 		len = 0;
923 
924 	ktraddentry(l, kte, KTA_WAITOK);
925 	return error;
926 }
927 
928 void
929 ktr_kuser(const char *id, void *addr, size_t len)
930 {
931 	struct ktrace_entry *kte;
932 	struct ktr_user *ktp;
933 	lwp_t *l = curlwp;
934 	int error;
935 
936 	if (!KTRPOINT(l->l_proc, KTR_USER))
937 		return;
938 
939 	if (len > KTR_USER_MAXLEN)
940 		return;
941 
942 	error = ktealloc(&kte, (void *)&ktp, l, KTR_USER, sizeof(*ktp) + len);
943 	if (error != 0)
944 		return;
945 
946 	strlcpy(ktp->ktr_id, id, KTR_USER_MAXIDLEN);
947 
948 	memcpy(ktp + 1, addr, len);
949 
950 	ktraddentry(l, kte, KTA_WAITOK);
951 }
952 
953 void
954 ktr_mmsg(const void *msgh, size_t size)
955 {
956 	lwp_t *l = curlwp;
957 
958 	if (!KTRPOINT(l->l_proc, KTR_MMSG))
959 		return;
960 
961 	ktr_kmem(l, KTR_MMSG, msgh, size);
962 }
963 
964 void
965 ktr_mool(const void *kaddr, size_t size, const void *uaddr)
966 {
967 	struct ktrace_entry *kte;
968 	struct ktr_mool *kp;
969 	struct ktr_mool *bf;
970 	lwp_t *l = curlwp;
971 
972 	if (!KTRPOINT(l->l_proc, KTR_MOOL))
973 		return;
974 
975 	if (ktealloc(&kte, (void *)&kp, l, KTR_MOOL, size + sizeof(*kp)))
976 		return;
977 
978 	kp->uaddr = uaddr;
979 	kp->size = size;
980 	bf = kp + 1; /* Skip uaddr and size */
981 	(void)memcpy(bf, kaddr, size);
982 
983 	ktraddentry(l, kte, KTA_WAITOK);
984 }
985 
986 void
987 ktr_mib(const int *name, u_int namelen)
988 {
989 	struct ktrace_entry *kte;
990 	int *namep;
991 	size_t size;
992 	lwp_t *l = curlwp;
993 
994 	if (!KTRPOINT(l->l_proc, KTR_MIB))
995 		return;
996 
997 	size = namelen * sizeof(*name);
998 
999 	if (ktealloc(&kte, (void *)&namep, l, KTR_MIB, size))
1000 		return;
1001 
1002 	(void)memcpy(namep, name, namelen * sizeof(*name));
1003 
1004 	ktraddentry(l, kte, KTA_WAITOK);
1005 }
1006 
1007 /* Interface and common routines */
1008 
1009 int
1010 ktrace_common(lwp_t *curl, int ops, int facs, int pid, struct file *fp)
1011 {
1012 	struct proc *curp;
1013 	struct proc *p;
1014 	struct pgrp *pg;
1015 	struct ktr_desc *ktd = NULL;
1016 	int ret = 0;
1017 	int error = 0;
1018 	int descend;
1019 
1020 	curp = curl->l_proc;
1021 	descend = ops & KTRFLAG_DESCEND;
1022 	facs = facs & ~((unsigned) KTRFAC_PERSISTENT);
1023 
1024 	(void)ktrenter(curl);
1025 
1026 	switch (KTROP(ops)) {
1027 
1028 	case KTROP_CLEARFILE:
1029 		/*
1030 		 * Clear all uses of the tracefile
1031 		 */
1032 		mutex_enter(&ktrace_lock);
1033 		ktd = ktd_lookup(fp);
1034 		mutex_exit(&ktrace_lock);
1035 		if (ktd == NULL)
1036 			goto done;
1037 		error = ktrderefall(ktd, 1);
1038 		goto done;
1039 
1040 	case KTROP_SET:
1041 		mutex_enter(&ktrace_lock);
1042 		ktd = ktd_lookup(fp);
1043 		mutex_exit(&ktrace_lock);
1044 		if (ktd == NULL) {
1045 			ktd = kmem_alloc(sizeof(*ktd), KM_SLEEP);
1046 			TAILQ_INIT(&ktd->ktd_queue);
1047 			callout_init(&ktd->ktd_wakch, CALLOUT_MPSAFE);
1048 			cv_init(&ktd->ktd_cv, "ktrwait");
1049 			cv_init(&ktd->ktd_sync_cv, "ktrsync");
1050 			ktd->ktd_flags = 0;
1051 			ktd->ktd_qcount = 0;
1052 			ktd->ktd_error = 0;
1053 			ktd->ktd_errcnt = 0;
1054 			ktd->ktd_delayqcnt = ktd_delayqcnt;
1055 			ktd->ktd_wakedelay = mstohz(ktd_wakedelay);
1056 			ktd->ktd_intrwakdl = mstohz(ktd_intrwakdl);
1057 			ktd->ktd_ref = 0;
1058 			mutex_enter(&ktrace_lock);
1059 			ktdref(ktd);
1060 			mutex_exit(&ktrace_lock);
1061 
1062 			/*
1063 			 * XXX: not correct.  needs an way to detect
1064 			 * whether ktruss or ktrace.
1065 			 */
1066 			if (fp->f_type == DTYPE_PIPE)
1067 				ktd->ktd_flags |= KTDF_INTERACTIVE;
1068 
1069 			error = kthread_create(PRI_NONE, KTHREAD_MPSAFE, NULL,
1070 			    ktrace_thread, ktd, &ktd->ktd_lwp, "ktrace");
1071 			if (error != 0) {
1072 				kmem_free(ktd, sizeof(*ktd));
1073 				goto done;
1074 			}
1075 
1076 			FILE_LOCK(fp);
1077 			fp->f_count++;
1078 			FILE_UNLOCK(fp);
1079 			ktd->ktd_fp = fp;
1080 
1081 			mutex_enter(&ktrace_lock);
1082 			if (ktd_lookup(fp) != NULL) {
1083 				ktdrel(ktd);
1084 				ktd = NULL;
1085 			} else
1086 				TAILQ_INSERT_TAIL(&ktdq, ktd, ktd_list);
1087 			if (ktd == NULL)
1088 				cv_wait(&lbolt, &ktrace_lock);
1089 			mutex_exit(&ktrace_lock);
1090 			if (ktd == NULL)
1091 				goto done;
1092 		}
1093 		break;
1094 
1095 	case KTROP_CLEAR:
1096 		break;
1097 	}
1098 
1099 	/*
1100 	 * need something to (un)trace (XXX - why is this here?)
1101 	 */
1102 	if (!facs) {
1103 		error = EINVAL;
1104 		goto done;
1105 	}
1106 
1107 	/*
1108 	 * do it
1109 	 */
1110 	mutex_enter(&proclist_lock);
1111 	if (pid < 0) {
1112 		/*
1113 		 * by process group
1114 		 */
1115 		pg = pg_find(-pid, PFIND_LOCKED);
1116 		if (pg == NULL)
1117 			error = ESRCH;
1118 		else {
1119 			LIST_FOREACH(p, &pg->pg_members, p_pglist) {
1120 				if (descend)
1121 					ret |= ktrsetchildren(curl, p, ops,
1122 					    facs, ktd);
1123 				else
1124 					ret |= ktrops(curl, p, ops, facs,
1125 					    ktd);
1126 			}
1127 		}
1128 
1129 	} else {
1130 		/*
1131 		 * by pid
1132 		 */
1133 		p = p_find(pid, PFIND_LOCKED);
1134 		if (p == NULL)
1135 			error = ESRCH;
1136 		else if (descend)
1137 			ret |= ktrsetchildren(curl, p, ops, facs, ktd);
1138 		else
1139 			ret |= ktrops(curl, p, ops, facs, ktd);
1140 	}
1141 	mutex_exit(&proclist_lock);
1142 	if (error == 0 && !ret)
1143 		error = EPERM;
1144 done:
1145 	if (ktd != NULL) {
1146 		mutex_enter(&ktrace_lock);
1147 		if (error != 0) {
1148 			/*
1149 			 * Wakeup the thread so that it can be die if we
1150 			 * can't trace any process.
1151 			 */
1152 			ktd_wakeup(ktd);
1153 		}
1154 		if (KTROP(ops) == KTROP_SET || KTROP(ops) == KTROP_CLEARFILE)
1155 			ktdrel(ktd);
1156 		mutex_exit(&ktrace_lock);
1157 	}
1158 	ktrexit(curl);
1159 	return (error);
1160 }
1161 
1162 /*
1163  * fktrace system call
1164  */
1165 /* ARGSUSED */
1166 int
1167 sys_fktrace(struct lwp *l, const struct sys_fktrace_args *uap, register_t *retval)
1168 {
1169 	/* {
1170 		syscallarg(int) fd;
1171 		syscallarg(int) ops;
1172 		syscallarg(int) facs;
1173 		syscallarg(int) pid;
1174 	} */
1175 	struct file *fp = NULL;
1176 	struct filedesc *fdp = l->l_proc->p_fd;
1177 	int error;
1178 
1179 	fdp = l->l_proc->p_fd;
1180 	if ((fp = fd_getfile(fdp, SCARG(uap, fd))) == NULL)
1181 		return (EBADF);
1182 
1183 	FILE_USE(fp);
1184 
1185 	if ((fp->f_flag & FWRITE) == 0)
1186 		error = EBADF;
1187 	else
1188 		error = ktrace_common(l, SCARG(uap, ops),
1189 		    SCARG(uap, facs), SCARG(uap, pid), fp);
1190 
1191 	FILE_UNUSE(fp, l);
1192 
1193 	return error;
1194 }
1195 
1196 /*
1197  * ktrace system call
1198  */
1199 /* ARGSUSED */
1200 int
1201 sys_ktrace(struct lwp *l, const struct sys_ktrace_args *uap, register_t *retval)
1202 {
1203 	/* {
1204 		syscallarg(const char *) fname;
1205 		syscallarg(int) ops;
1206 		syscallarg(int) facs;
1207 		syscallarg(int) pid;
1208 	} */
1209 	struct vnode *vp = NULL;
1210 	struct file *fp = NULL;
1211 	struct nameidata nd;
1212 	int error = 0;
1213 	int fd;
1214 
1215 	if (ktrenter(l))
1216 		return EAGAIN;
1217 
1218 	if (KTROP(SCARG(uap, ops)) != KTROP_CLEAR) {
1219 		/*
1220 		 * an operation which requires a file argument.
1221 		 */
1222 		NDINIT(&nd, LOOKUP, FOLLOW, UIO_USERSPACE, SCARG(uap, fname));
1223 		if ((error = vn_open(&nd, FREAD|FWRITE, 0)) != 0) {
1224 			ktrexit(l);
1225 			return (error);
1226 		}
1227 		vp = nd.ni_vp;
1228 		VOP_UNLOCK(vp, 0);
1229 		if (vp->v_type != VREG) {
1230 			(void) vn_close(vp, FREAD|FWRITE, l->l_cred, l);
1231 			ktrexit(l);
1232 			return (EACCES);
1233 		}
1234 		/*
1235 		 * XXX This uses up a file descriptor slot in the
1236 		 * tracing process for the duration of this syscall.
1237 		 * This is not expected to be a problem.  If
1238 		 * falloc(NULL, ...) DTRT we could skip that part, but
1239 		 * that would require changing its interface to allow
1240 		 * the caller to pass in a ucred..
1241 		 *
1242 		 * This will FILE_USE the fp it returns, if any.
1243 		 * Keep it in use until we return.
1244 		 */
1245 		if ((error = falloc(l, &fp, &fd)) != 0)
1246 			goto done;
1247 
1248 		fp->f_flag = FWRITE;
1249 		fp->f_type = DTYPE_VNODE;
1250 		fp->f_ops = &vnops;
1251 		fp->f_data = (void *)vp;
1252 		FILE_SET_MATURE(fp);
1253 		vp = NULL;
1254 	}
1255 	error = ktrace_common(l, SCARG(uap, ops), SCARG(uap, facs),
1256 	    SCARG(uap, pid), fp);
1257 done:
1258 	if (vp != NULL)
1259 		(void) vn_close(vp, FWRITE, l->l_cred, l);
1260 	if (fp != NULL) {
1261 		FILE_UNUSE(fp, l);	/* release file */
1262 		fdrelease(l, fd); 	/* release fd table slot */
1263 	}
1264 	return (error);
1265 }
1266 
1267 int
1268 ktrops(lwp_t *curl, struct proc *p, int ops, int facs,
1269     struct ktr_desc *ktd)
1270 {
1271 	int vers = ops & KTRFAC_VER_MASK;
1272 	int error = 0;
1273 
1274 	mutex_enter(&p->p_mutex);
1275 	mutex_enter(&ktrace_lock);
1276 
1277 	if (!ktrcanset(curl, p))
1278 		goto out;
1279 
1280 	switch (vers) {
1281 	case KTRFACv0:
1282 	case KTRFACv1:
1283 		break;
1284 	default:
1285 		error = EINVAL;
1286 		goto out;
1287 	}
1288 
1289 	if (KTROP(ops) == KTROP_SET) {
1290 		if (p->p_tracep != ktd) {
1291 			/*
1292 			 * if trace file already in use, relinquish
1293 			 */
1294 			ktrderef(p);
1295 			p->p_tracep = ktd;
1296 			ktradref(p);
1297 		}
1298 		p->p_traceflag |= facs;
1299 		if (kauth_authorize_process(curl->l_cred, KAUTH_PROCESS_KTRACE,
1300 		    p, KAUTH_ARG(KAUTH_REQ_PROCESS_KTRACE_PERSISTENT), NULL,
1301 		    NULL) == 0)
1302 			p->p_traceflag |= KTRFAC_PERSISTENT;
1303 	} else {
1304 		/* KTROP_CLEAR */
1305 		if (((p->p_traceflag &= ~facs) & KTRFAC_MASK) == 0) {
1306 			/* no more tracing */
1307 			ktrderef(p);
1308 		}
1309 	}
1310 
1311 	if (p->p_traceflag)
1312 		p->p_traceflag |= vers;
1313 	/*
1314 	 * Emit an emulation record, every time there is a ktrace
1315 	 * change/attach request.
1316 	 */
1317 	if (KTRPOINT(p, KTR_EMUL))
1318 		p->p_traceflag |= KTRFAC_TRC_EMUL;
1319 #ifdef __HAVE_SYSCALL_INTERN
1320 	(*p->p_emul->e_syscall_intern)(p);
1321 #endif
1322 
1323  out:
1324  	mutex_exit(&ktrace_lock);
1325  	mutex_exit(&p->p_mutex);
1326 
1327 	return (1);
1328 }
1329 
1330 int
1331 ktrsetchildren(lwp_t *curl, struct proc *top, int ops, int facs,
1332     struct ktr_desc *ktd)
1333 {
1334 	struct proc *p;
1335 	int ret = 0;
1336 
1337 	KASSERT(mutex_owned(&proclist_lock));
1338 
1339 	p = top;
1340 	for (;;) {
1341 		ret |= ktrops(curl, p, ops, facs, ktd);
1342 		/*
1343 		 * If this process has children, descend to them next,
1344 		 * otherwise do any siblings, and if done with this level,
1345 		 * follow back up the tree (but not past top).
1346 		 */
1347 		if (LIST_FIRST(&p->p_children) != NULL) {
1348 			p = LIST_FIRST(&p->p_children);
1349 			continue;
1350 		}
1351 		for (;;) {
1352 			if (p == top)
1353 				return (ret);
1354 			if (LIST_NEXT(p, p_sibling) != NULL) {
1355 				p = LIST_NEXT(p, p_sibling);
1356 				break;
1357 			}
1358 			p = p->p_pptr;
1359 		}
1360 	}
1361 	/*NOTREACHED*/
1362 }
1363 
1364 void
1365 ktrwrite(struct ktr_desc *ktd, struct ktrace_entry *kte)
1366 {
1367 	struct uio auio;
1368 	struct iovec aiov[64], *iov;
1369 	struct ktrace_entry *top = kte;
1370 	struct ktr_header *kth;
1371 	struct file *fp = ktd->ktd_fp;
1372 	int error;
1373 next:
1374 	auio.uio_iov = iov = &aiov[0];
1375 	auio.uio_offset = 0;
1376 	auio.uio_rw = UIO_WRITE;
1377 	auio.uio_resid = 0;
1378 	auio.uio_iovcnt = 0;
1379 	UIO_SETUP_SYSSPACE(&auio);
1380 	do {
1381 		kth = &kte->kte_kth;
1382 
1383 		if (kth->ktr_version == 0) {
1384 			/*
1385 			 * Convert back to the old format fields
1386 			 */
1387 			TIMESPEC_TO_TIMEVAL(&kth->ktr_tv, &kth->ktr_time);
1388 			kth->ktr_unused = NULL;
1389 		}
1390 		iov->iov_base = (void *)kth;
1391 		iov++->iov_len = sizeof(struct ktr_header);
1392 		auio.uio_resid += sizeof(struct ktr_header);
1393 		auio.uio_iovcnt++;
1394 		if (kth->ktr_len > 0) {
1395 			iov->iov_base = kte->kte_buf;
1396 			iov++->iov_len = kth->ktr_len;
1397 			auio.uio_resid += kth->ktr_len;
1398 			auio.uio_iovcnt++;
1399 		}
1400 	} while ((kte = TAILQ_NEXT(kte, kte_list)) != NULL &&
1401 	    auio.uio_iovcnt < sizeof(aiov) / sizeof(aiov[0]) - 1);
1402 
1403 again:
1404 	FILE_LOCK(fp);
1405 	FILE_USE(fp);
1406 	error = (*fp->f_ops->fo_write)(fp, &fp->f_offset, &auio,
1407 	    fp->f_cred, FOF_UPDATE_OFFSET);
1408 	FILE_UNUSE(fp, NULL);
1409 	switch (error) {
1410 
1411 	case 0:
1412 		if (auio.uio_resid > 0)
1413 			goto again;
1414 		if (kte != NULL)
1415 			goto next;
1416 		break;
1417 
1418 	case EWOULDBLOCK:
1419 		kpause("ktrzzz", false, 1, NULL);
1420 		goto again;
1421 
1422 	default:
1423 		/*
1424 		 * If error encountered, give up tracing on this
1425 		 * vnode.  Don't report EPIPE as this can easily
1426 		 * happen with fktrace()/ktruss.
1427 		 */
1428 #ifndef DEBUG
1429 		if (error != EPIPE)
1430 #endif
1431 			log(LOG_NOTICE,
1432 			    "ktrace write failed, errno %d, tracing stopped\n",
1433 			    error);
1434 		(void)ktrderefall(ktd, 0);
1435 	}
1436 
1437 	while ((kte = top) != NULL) {
1438 		top = TAILQ_NEXT(top, kte_list);
1439 		ktefree(kte);
1440 	}
1441 }
1442 
1443 void
1444 ktrace_thread(void *arg)
1445 {
1446 	struct ktr_desc *ktd = arg;
1447 	struct file *fp = ktd->ktd_fp;
1448 	struct ktrace_entry *kte;
1449 	int ktrerr, errcnt;
1450 
1451 	mutex_enter(&ktrace_lock);
1452 	for (;;) {
1453 		kte = TAILQ_FIRST(&ktd->ktd_queue);
1454 		if (kte == NULL) {
1455 			if (ktd->ktd_flags & KTDF_WAIT) {
1456 				ktd->ktd_flags &= ~(KTDF_WAIT | KTDF_BLOCKING);
1457 				cv_broadcast(&ktd->ktd_sync_cv);
1458 			}
1459 			if (ktd->ktd_ref == 0)
1460 				break;
1461 			cv_wait(&ktd->ktd_cv, &ktrace_lock);
1462 			continue;
1463 		}
1464 		TAILQ_INIT(&ktd->ktd_queue);
1465 		ktd->ktd_qcount = 0;
1466 		ktrerr = ktd->ktd_error;
1467 		errcnt = ktd->ktd_errcnt;
1468 		ktd->ktd_error = ktd->ktd_errcnt = 0;
1469 		mutex_exit(&ktrace_lock);
1470 
1471 		if (ktrerr) {
1472 			log(LOG_NOTICE,
1473 			    "ktrace failed, fp %p, error 0x%x, total %d\n",
1474 			    fp, ktrerr, errcnt);
1475 		}
1476 		ktrwrite(ktd, kte);
1477 		mutex_enter(&ktrace_lock);
1478 	}
1479 
1480 	TAILQ_REMOVE(&ktdq, ktd, ktd_list);
1481 	mutex_exit(&ktrace_lock);
1482 
1483 	FILE_LOCK(fp);
1484 	FILE_USE(fp);
1485 
1486 	/*
1487 	 * ktrace file descriptor can't be watched (are not visible to
1488 	 * userspace), so no kqueue stuff here
1489 	 * XXX: The above comment is wrong, because the fktrace file
1490 	 * descriptor is available in userland.
1491 	 */
1492 	closef(fp, NULL);
1493 
1494 	callout_stop(&ktd->ktd_wakch);
1495 	callout_destroy(&ktd->ktd_wakch);
1496 	kmem_free(ktd, sizeof(*ktd));
1497 
1498 	kthread_exit(0);
1499 }
1500 
1501 /*
1502  * Return true if caller has permission to set the ktracing state
1503  * of target.  Essentially, the target can't possess any
1504  * more permissions than the caller.  KTRFAC_PERSISTENT signifies that
1505  * the tracing will persist on sugid processes during exec; it is only
1506  * settable by a process with appropriate credentials.
1507  *
1508  * TODO: check groups.  use caller effective gid.
1509  */
1510 int
1511 ktrcanset(lwp_t *calll, struct proc *targetp)
1512 {
1513 	KASSERT(mutex_owned(&targetp->p_mutex));
1514 	KASSERT(mutex_owned(&ktrace_lock));
1515 
1516 	if (kauth_authorize_process(calll->l_cred, KAUTH_PROCESS_KTRACE,
1517 	    targetp, NULL, NULL, NULL) == 0)
1518 		return (1);
1519 
1520 	return (0);
1521 }
1522 
1523 /*
1524  * Put user defined entry to ktrace records.
1525  */
1526 int
1527 sys_utrace(struct lwp *l, const struct sys_utrace_args *uap, register_t *retval)
1528 {
1529 	/* {
1530 		syscallarg(const char *) label;
1531 		syscallarg(void *) addr;
1532 		syscallarg(size_t) len;
1533 	} */
1534 
1535 	return ktruser(SCARG(uap, label), SCARG(uap, addr),
1536 	    SCARG(uap, len), 1);
1537 }
1538