xref: /freebsd/sys/kern/kern_ktrace.c (revision eb69d1f144a6fcc765d1b9d44a5ae8082353e70b)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1989, 1993
5  *	The Regents of the University of California.
6  * Copyright (c) 2005 Robert N. M. Watson
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *	@(#)kern_ktrace.c	8.2 (Berkeley) 9/23/93
34  */
35 
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
38 
39 #include "opt_ktrace.h"
40 
41 #include <sys/param.h>
42 #include <sys/capsicum.h>
43 #include <sys/systm.h>
44 #include <sys/fcntl.h>
45 #include <sys/kernel.h>
46 #include <sys/kthread.h>
47 #include <sys/lock.h>
48 #include <sys/mutex.h>
49 #include <sys/malloc.h>
50 #include <sys/mount.h>
51 #include <sys/namei.h>
52 #include <sys/priv.h>
53 #include <sys/proc.h>
54 #include <sys/unistd.h>
55 #include <sys/vnode.h>
56 #include <sys/socket.h>
57 #include <sys/stat.h>
58 #include <sys/ktrace.h>
59 #include <sys/sx.h>
60 #include <sys/sysctl.h>
61 #include <sys/sysent.h>
62 #include <sys/syslog.h>
63 #include <sys/sysproto.h>
64 
65 #include <security/mac/mac_framework.h>
66 
67 /*
68  * The ktrace facility allows the tracing of certain key events in user space
69  * processes, such as system calls, signal delivery, context switches, and
70  * user generated events using utrace(2).  It works by streaming event
71  * records and data to a vnode associated with the process using the
72  * ktrace(2) system call.  In general, records can be written directly from
73  * the context that generates the event.  One important exception to this is
74  * during a context switch, where sleeping is not permitted.  To handle this
75  * case, trace events are generated using in-kernel ktr_request records, and
76  * then delivered to disk at a convenient moment -- either immediately, the
77  * next traceable event, at system call return, or at process exit.
78  *
79  * When dealing with multiple threads or processes writing to the same event
80  * log, ordering guarantees are weak: specifically, if an event has multiple
81  * records (i.e., system call enter and return), they may be interlaced with
82  * records from another event.  Process and thread ID information is provided
83  * in the record, and user applications can de-interlace events if required.
84  */
85 
86 static MALLOC_DEFINE(M_KTRACE, "KTRACE", "KTRACE");
87 
88 #ifdef KTRACE
89 
90 FEATURE(ktrace, "Kernel support for system-call tracing");
91 
92 #ifndef KTRACE_REQUEST_POOL
93 #define	KTRACE_REQUEST_POOL	100
94 #endif
95 
96 struct ktr_request {
97 	struct	ktr_header ktr_header;
98 	void	*ktr_buffer;
99 	union {
100 		struct	ktr_proc_ctor ktr_proc_ctor;
101 		struct	ktr_cap_fail ktr_cap_fail;
102 		struct	ktr_syscall ktr_syscall;
103 		struct	ktr_sysret ktr_sysret;
104 		struct	ktr_genio ktr_genio;
105 		struct	ktr_psig ktr_psig;
106 		struct	ktr_csw ktr_csw;
107 		struct	ktr_fault ktr_fault;
108 		struct	ktr_faultend ktr_faultend;
109 		struct  ktr_struct_array ktr_struct_array;
110 	} ktr_data;
111 	STAILQ_ENTRY(ktr_request) ktr_list;
112 };
113 
114 static int data_lengths[] = {
115 	[KTR_SYSCALL] = offsetof(struct ktr_syscall, ktr_args),
116 	[KTR_SYSRET] = sizeof(struct ktr_sysret),
117 	[KTR_NAMEI] = 0,
118 	[KTR_GENIO] = sizeof(struct ktr_genio),
119 	[KTR_PSIG] = sizeof(struct ktr_psig),
120 	[KTR_CSW] = sizeof(struct ktr_csw),
121 	[KTR_USER] = 0,
122 	[KTR_STRUCT] = 0,
123 	[KTR_SYSCTL] = 0,
124 	[KTR_PROCCTOR] = sizeof(struct ktr_proc_ctor),
125 	[KTR_PROCDTOR] = 0,
126 	[KTR_CAPFAIL] = sizeof(struct ktr_cap_fail),
127 	[KTR_FAULT] = sizeof(struct ktr_fault),
128 	[KTR_FAULTEND] = sizeof(struct ktr_faultend),
129 	[KTR_STRUCT_ARRAY] = sizeof(struct ktr_struct_array),
130 };
131 
132 static STAILQ_HEAD(, ktr_request) ktr_free;
133 
134 static SYSCTL_NODE(_kern, OID_AUTO, ktrace, CTLFLAG_RD, 0, "KTRACE options");
135 
136 static u_int ktr_requestpool = KTRACE_REQUEST_POOL;
137 TUNABLE_INT("kern.ktrace.request_pool", &ktr_requestpool);
138 
139 u_int ktr_geniosize = PAGE_SIZE;
140 SYSCTL_UINT(_kern_ktrace, OID_AUTO, genio_size, CTLFLAG_RWTUN, &ktr_geniosize,
141     0, "Maximum size of genio event payload");
142 
143 static int print_message = 1;
144 static struct mtx ktrace_mtx;
145 static struct sx ktrace_sx;
146 
147 static void ktrace_init(void *dummy);
148 static int sysctl_kern_ktrace_request_pool(SYSCTL_HANDLER_ARGS);
149 static u_int ktrace_resize_pool(u_int oldsize, u_int newsize);
150 static struct ktr_request *ktr_getrequest_entered(struct thread *td, int type);
151 static struct ktr_request *ktr_getrequest(int type);
152 static void ktr_submitrequest(struct thread *td, struct ktr_request *req);
153 static void ktr_freeproc(struct proc *p, struct ucred **uc,
154     struct vnode **vp);
155 static void ktr_freerequest(struct ktr_request *req);
156 static void ktr_freerequest_locked(struct ktr_request *req);
157 static void ktr_writerequest(struct thread *td, struct ktr_request *req);
158 static int ktrcanset(struct thread *,struct proc *);
159 static int ktrsetchildren(struct thread *,struct proc *,int,int,struct vnode *);
160 static int ktrops(struct thread *,struct proc *,int,int,struct vnode *);
161 static void ktrprocctor_entered(struct thread *, struct proc *);
162 
163 /*
164  * ktrace itself generates events, such as context switches, which we do not
165  * wish to trace.  Maintain a flag, TDP_INKTRACE, on each thread to determine
166  * whether or not it is in a region where tracing of events should be
167  * suppressed.
168  */
169 static void
170 ktrace_enter(struct thread *td)
171 {
172 
173 	KASSERT(!(td->td_pflags & TDP_INKTRACE), ("ktrace_enter: flag set"));
174 	td->td_pflags |= TDP_INKTRACE;
175 }
176 
177 static void
178 ktrace_exit(struct thread *td)
179 {
180 
181 	KASSERT(td->td_pflags & TDP_INKTRACE, ("ktrace_exit: flag not set"));
182 	td->td_pflags &= ~TDP_INKTRACE;
183 }
184 
185 static void
186 ktrace_assert(struct thread *td)
187 {
188 
189 	KASSERT(td->td_pflags & TDP_INKTRACE, ("ktrace_assert: flag not set"));
190 }
191 
192 static void
193 ktrace_init(void *dummy)
194 {
195 	struct ktr_request *req;
196 	int i;
197 
198 	mtx_init(&ktrace_mtx, "ktrace", NULL, MTX_DEF | MTX_QUIET);
199 	sx_init(&ktrace_sx, "ktrace_sx");
200 	STAILQ_INIT(&ktr_free);
201 	for (i = 0; i < ktr_requestpool; i++) {
202 		req = malloc(sizeof(struct ktr_request), M_KTRACE, M_WAITOK);
203 		STAILQ_INSERT_HEAD(&ktr_free, req, ktr_list);
204 	}
205 }
206 SYSINIT(ktrace_init, SI_SUB_KTRACE, SI_ORDER_ANY, ktrace_init, NULL);
207 
208 static int
209 sysctl_kern_ktrace_request_pool(SYSCTL_HANDLER_ARGS)
210 {
211 	struct thread *td;
212 	u_int newsize, oldsize, wantsize;
213 	int error;
214 
215 	/* Handle easy read-only case first to avoid warnings from GCC. */
216 	if (!req->newptr) {
217 		oldsize = ktr_requestpool;
218 		return (SYSCTL_OUT(req, &oldsize, sizeof(u_int)));
219 	}
220 
221 	error = SYSCTL_IN(req, &wantsize, sizeof(u_int));
222 	if (error)
223 		return (error);
224 	td = curthread;
225 	ktrace_enter(td);
226 	oldsize = ktr_requestpool;
227 	newsize = ktrace_resize_pool(oldsize, wantsize);
228 	ktrace_exit(td);
229 	error = SYSCTL_OUT(req, &oldsize, sizeof(u_int));
230 	if (error)
231 		return (error);
232 	if (wantsize > oldsize && newsize < wantsize)
233 		return (ENOSPC);
234 	return (0);
235 }
236 SYSCTL_PROC(_kern_ktrace, OID_AUTO, request_pool, CTLTYPE_UINT|CTLFLAG_RW,
237     &ktr_requestpool, 0, sysctl_kern_ktrace_request_pool, "IU",
238     "Pool buffer size for ktrace(1)");
239 
240 static u_int
241 ktrace_resize_pool(u_int oldsize, u_int newsize)
242 {
243 	STAILQ_HEAD(, ktr_request) ktr_new;
244 	struct ktr_request *req;
245 	int bound;
246 
247 	print_message = 1;
248 	bound = newsize - oldsize;
249 	if (bound == 0)
250 		return (ktr_requestpool);
251 	if (bound < 0) {
252 		mtx_lock(&ktrace_mtx);
253 		/* Shrink pool down to newsize if possible. */
254 		while (bound++ < 0) {
255 			req = STAILQ_FIRST(&ktr_free);
256 			if (req == NULL)
257 				break;
258 			STAILQ_REMOVE_HEAD(&ktr_free, ktr_list);
259 			ktr_requestpool--;
260 			free(req, M_KTRACE);
261 		}
262 	} else {
263 		/* Grow pool up to newsize. */
264 		STAILQ_INIT(&ktr_new);
265 		while (bound-- > 0) {
266 			req = malloc(sizeof(struct ktr_request), M_KTRACE,
267 			    M_WAITOK);
268 			STAILQ_INSERT_HEAD(&ktr_new, req, ktr_list);
269 		}
270 		mtx_lock(&ktrace_mtx);
271 		STAILQ_CONCAT(&ktr_free, &ktr_new);
272 		ktr_requestpool += (newsize - oldsize);
273 	}
274 	mtx_unlock(&ktrace_mtx);
275 	return (ktr_requestpool);
276 }
277 
278 /* ktr_getrequest() assumes that ktr_comm[] is the same size as td_name[]. */
279 CTASSERT(sizeof(((struct ktr_header *)NULL)->ktr_comm) ==
280     (sizeof((struct thread *)NULL)->td_name));
281 
282 static struct ktr_request *
283 ktr_getrequest_entered(struct thread *td, int type)
284 {
285 	struct ktr_request *req;
286 	struct proc *p = td->td_proc;
287 	int pm;
288 
289 	mtx_lock(&ktrace_mtx);
290 	if (!KTRCHECK(td, type)) {
291 		mtx_unlock(&ktrace_mtx);
292 		return (NULL);
293 	}
294 	req = STAILQ_FIRST(&ktr_free);
295 	if (req != NULL) {
296 		STAILQ_REMOVE_HEAD(&ktr_free, ktr_list);
297 		req->ktr_header.ktr_type = type;
298 		if (p->p_traceflag & KTRFAC_DROP) {
299 			req->ktr_header.ktr_type |= KTR_DROP;
300 			p->p_traceflag &= ~KTRFAC_DROP;
301 		}
302 		mtx_unlock(&ktrace_mtx);
303 		microtime(&req->ktr_header.ktr_time);
304 		req->ktr_header.ktr_pid = p->p_pid;
305 		req->ktr_header.ktr_tid = td->td_tid;
306 		bcopy(td->td_name, req->ktr_header.ktr_comm,
307 		    sizeof(req->ktr_header.ktr_comm));
308 		req->ktr_buffer = NULL;
309 		req->ktr_header.ktr_len = 0;
310 	} else {
311 		p->p_traceflag |= KTRFAC_DROP;
312 		pm = print_message;
313 		print_message = 0;
314 		mtx_unlock(&ktrace_mtx);
315 		if (pm)
316 			printf("Out of ktrace request objects.\n");
317 	}
318 	return (req);
319 }
320 
321 static struct ktr_request *
322 ktr_getrequest(int type)
323 {
324 	struct thread *td = curthread;
325 	struct ktr_request *req;
326 
327 	ktrace_enter(td);
328 	req = ktr_getrequest_entered(td, type);
329 	if (req == NULL)
330 		ktrace_exit(td);
331 
332 	return (req);
333 }
334 
335 /*
336  * Some trace generation environments don't permit direct access to VFS,
337  * such as during a context switch where sleeping is not allowed.  Under these
338  * circumstances, queue a request to the thread to be written asynchronously
339  * later.
340  */
341 static void
342 ktr_enqueuerequest(struct thread *td, struct ktr_request *req)
343 {
344 
345 	mtx_lock(&ktrace_mtx);
346 	STAILQ_INSERT_TAIL(&td->td_proc->p_ktr, req, ktr_list);
347 	mtx_unlock(&ktrace_mtx);
348 }
349 
350 /*
351  * Drain any pending ktrace records from the per-thread queue to disk.  This
352  * is used both internally before committing other records, and also on
353  * system call return.  We drain all the ones we can find at the time when
354  * drain is requested, but don't keep draining after that as those events
355  * may be approximately "after" the current event.
356  */
357 static void
358 ktr_drain(struct thread *td)
359 {
360 	struct ktr_request *queued_req;
361 	STAILQ_HEAD(, ktr_request) local_queue;
362 
363 	ktrace_assert(td);
364 	sx_assert(&ktrace_sx, SX_XLOCKED);
365 
366 	STAILQ_INIT(&local_queue);
367 
368 	if (!STAILQ_EMPTY(&td->td_proc->p_ktr)) {
369 		mtx_lock(&ktrace_mtx);
370 		STAILQ_CONCAT(&local_queue, &td->td_proc->p_ktr);
371 		mtx_unlock(&ktrace_mtx);
372 
373 		while ((queued_req = STAILQ_FIRST(&local_queue))) {
374 			STAILQ_REMOVE_HEAD(&local_queue, ktr_list);
375 			ktr_writerequest(td, queued_req);
376 			ktr_freerequest(queued_req);
377 		}
378 	}
379 }
380 
381 /*
382  * Submit a trace record for immediate commit to disk -- to be used only
383  * where entering VFS is OK.  First drain any pending records that may have
384  * been cached in the thread.
385  */
386 static void
387 ktr_submitrequest(struct thread *td, struct ktr_request *req)
388 {
389 
390 	ktrace_assert(td);
391 
392 	sx_xlock(&ktrace_sx);
393 	ktr_drain(td);
394 	ktr_writerequest(td, req);
395 	ktr_freerequest(req);
396 	sx_xunlock(&ktrace_sx);
397 	ktrace_exit(td);
398 }
399 
400 static void
401 ktr_freerequest(struct ktr_request *req)
402 {
403 
404 	mtx_lock(&ktrace_mtx);
405 	ktr_freerequest_locked(req);
406 	mtx_unlock(&ktrace_mtx);
407 }
408 
409 static void
410 ktr_freerequest_locked(struct ktr_request *req)
411 {
412 
413 	mtx_assert(&ktrace_mtx, MA_OWNED);
414 	if (req->ktr_buffer != NULL)
415 		free(req->ktr_buffer, M_KTRACE);
416 	STAILQ_INSERT_HEAD(&ktr_free, req, ktr_list);
417 }
418 
419 /*
420  * Disable tracing for a process and release all associated resources.
421  * The caller is responsible for releasing a reference on the returned
422  * vnode and credentials.
423  */
424 static void
425 ktr_freeproc(struct proc *p, struct ucred **uc, struct vnode **vp)
426 {
427 	struct ktr_request *req;
428 
429 	PROC_LOCK_ASSERT(p, MA_OWNED);
430 	mtx_assert(&ktrace_mtx, MA_OWNED);
431 	*uc = p->p_tracecred;
432 	p->p_tracecred = NULL;
433 	if (vp != NULL)
434 		*vp = p->p_tracevp;
435 	p->p_tracevp = NULL;
436 	p->p_traceflag = 0;
437 	while ((req = STAILQ_FIRST(&p->p_ktr)) != NULL) {
438 		STAILQ_REMOVE_HEAD(&p->p_ktr, ktr_list);
439 		ktr_freerequest_locked(req);
440 	}
441 }
442 
443 void
444 ktrsyscall(int code, int narg, register_t args[])
445 {
446 	struct ktr_request *req;
447 	struct ktr_syscall *ktp;
448 	size_t buflen;
449 	char *buf = NULL;
450 
451 	buflen = sizeof(register_t) * narg;
452 	if (buflen > 0) {
453 		buf = malloc(buflen, M_KTRACE, M_WAITOK);
454 		bcopy(args, buf, buflen);
455 	}
456 	req = ktr_getrequest(KTR_SYSCALL);
457 	if (req == NULL) {
458 		if (buf != NULL)
459 			free(buf, M_KTRACE);
460 		return;
461 	}
462 	ktp = &req->ktr_data.ktr_syscall;
463 	ktp->ktr_code = code;
464 	ktp->ktr_narg = narg;
465 	if (buflen > 0) {
466 		req->ktr_header.ktr_len = buflen;
467 		req->ktr_buffer = buf;
468 	}
469 	ktr_submitrequest(curthread, req);
470 }
471 
472 void
473 ktrsysret(int code, int error, register_t retval)
474 {
475 	struct ktr_request *req;
476 	struct ktr_sysret *ktp;
477 
478 	req = ktr_getrequest(KTR_SYSRET);
479 	if (req == NULL)
480 		return;
481 	ktp = &req->ktr_data.ktr_sysret;
482 	ktp->ktr_code = code;
483 	ktp->ktr_error = error;
484 	ktp->ktr_retval = ((error == 0) ? retval: 0);		/* what about val2 ? */
485 	ktr_submitrequest(curthread, req);
486 }
487 
488 /*
489  * When a setuid process execs, disable tracing.
490  *
491  * XXX: We toss any pending asynchronous records.
492  */
493 void
494 ktrprocexec(struct proc *p, struct ucred **uc, struct vnode **vp)
495 {
496 
497 	PROC_LOCK_ASSERT(p, MA_OWNED);
498 	mtx_lock(&ktrace_mtx);
499 	ktr_freeproc(p, uc, vp);
500 	mtx_unlock(&ktrace_mtx);
501 }
502 
503 /*
504  * When a process exits, drain per-process asynchronous trace records
505  * and disable tracing.
506  */
507 void
508 ktrprocexit(struct thread *td)
509 {
510 	struct ktr_request *req;
511 	struct proc *p;
512 	struct ucred *cred;
513 	struct vnode *vp;
514 
515 	p = td->td_proc;
516 	if (p->p_traceflag == 0)
517 		return;
518 
519 	ktrace_enter(td);
520 	req = ktr_getrequest_entered(td, KTR_PROCDTOR);
521 	if (req != NULL)
522 		ktr_enqueuerequest(td, req);
523 	sx_xlock(&ktrace_sx);
524 	ktr_drain(td);
525 	sx_xunlock(&ktrace_sx);
526 	PROC_LOCK(p);
527 	mtx_lock(&ktrace_mtx);
528 	ktr_freeproc(p, &cred, &vp);
529 	mtx_unlock(&ktrace_mtx);
530 	PROC_UNLOCK(p);
531 	if (vp != NULL)
532 		vrele(vp);
533 	if (cred != NULL)
534 		crfree(cred);
535 	ktrace_exit(td);
536 }
537 
538 static void
539 ktrprocctor_entered(struct thread *td, struct proc *p)
540 {
541 	struct ktr_proc_ctor *ktp;
542 	struct ktr_request *req;
543 	struct thread *td2;
544 
545 	ktrace_assert(td);
546 	td2 = FIRST_THREAD_IN_PROC(p);
547 	req = ktr_getrequest_entered(td2, KTR_PROCCTOR);
548 	if (req == NULL)
549 		return;
550 	ktp = &req->ktr_data.ktr_proc_ctor;
551 	ktp->sv_flags = p->p_sysent->sv_flags;
552 	ktr_enqueuerequest(td2, req);
553 }
554 
555 void
556 ktrprocctor(struct proc *p)
557 {
558 	struct thread *td = curthread;
559 
560 	if ((p->p_traceflag & KTRFAC_MASK) == 0)
561 		return;
562 
563 	ktrace_enter(td);
564 	ktrprocctor_entered(td, p);
565 	ktrace_exit(td);
566 }
567 
568 /*
569  * When a process forks, enable tracing in the new process if needed.
570  */
571 void
572 ktrprocfork(struct proc *p1, struct proc *p2)
573 {
574 
575 	MPASS(p2->p_tracevp == NULL);
576 	MPASS(p2->p_traceflag == 0);
577 
578 	if (p1->p_traceflag == 0)
579 		return;
580 
581 	PROC_LOCK(p1);
582 	mtx_lock(&ktrace_mtx);
583 	if (p1->p_traceflag & KTRFAC_INHERIT) {
584 		p2->p_traceflag = p1->p_traceflag;
585 		if ((p2->p_tracevp = p1->p_tracevp) != NULL) {
586 			VREF(p2->p_tracevp);
587 			KASSERT(p1->p_tracecred != NULL,
588 			    ("ktrace vnode with no cred"));
589 			p2->p_tracecred = crhold(p1->p_tracecred);
590 		}
591 	}
592 	mtx_unlock(&ktrace_mtx);
593 	PROC_UNLOCK(p1);
594 
595 	ktrprocctor(p2);
596 }
597 
598 /*
599  * When a thread returns, drain any asynchronous records generated by the
600  * system call.
601  */
602 void
603 ktruserret(struct thread *td)
604 {
605 
606 	ktrace_enter(td);
607 	sx_xlock(&ktrace_sx);
608 	ktr_drain(td);
609 	sx_xunlock(&ktrace_sx);
610 	ktrace_exit(td);
611 }
612 
613 void
614 ktrnamei(path)
615 	char *path;
616 {
617 	struct ktr_request *req;
618 	int namelen;
619 	char *buf = NULL;
620 
621 	namelen = strlen(path);
622 	if (namelen > 0) {
623 		buf = malloc(namelen, M_KTRACE, M_WAITOK);
624 		bcopy(path, buf, namelen);
625 	}
626 	req = ktr_getrequest(KTR_NAMEI);
627 	if (req == NULL) {
628 		if (buf != NULL)
629 			free(buf, M_KTRACE);
630 		return;
631 	}
632 	if (namelen > 0) {
633 		req->ktr_header.ktr_len = namelen;
634 		req->ktr_buffer = buf;
635 	}
636 	ktr_submitrequest(curthread, req);
637 }
638 
639 void
640 ktrsysctl(int *name, u_int namelen)
641 {
642 	struct ktr_request *req;
643 	u_int mib[CTL_MAXNAME + 2];
644 	char *mibname;
645 	size_t mibnamelen;
646 	int error;
647 
648 	/* Lookup name of mib. */
649 	KASSERT(namelen <= CTL_MAXNAME, ("sysctl MIB too long"));
650 	mib[0] = 0;
651 	mib[1] = 1;
652 	bcopy(name, mib + 2, namelen * sizeof(*name));
653 	mibnamelen = 128;
654 	mibname = malloc(mibnamelen, M_KTRACE, M_WAITOK);
655 	error = kernel_sysctl(curthread, mib, namelen + 2, mibname, &mibnamelen,
656 	    NULL, 0, &mibnamelen, 0);
657 	if (error) {
658 		free(mibname, M_KTRACE);
659 		return;
660 	}
661 	req = ktr_getrequest(KTR_SYSCTL);
662 	if (req == NULL) {
663 		free(mibname, M_KTRACE);
664 		return;
665 	}
666 	req->ktr_header.ktr_len = mibnamelen;
667 	req->ktr_buffer = mibname;
668 	ktr_submitrequest(curthread, req);
669 }
670 
671 void
672 ktrgenio(int fd, enum uio_rw rw, struct uio *uio, int error)
673 {
674 	struct ktr_request *req;
675 	struct ktr_genio *ktg;
676 	int datalen;
677 	char *buf;
678 
679 	if (error) {
680 		free(uio, M_IOV);
681 		return;
682 	}
683 	uio->uio_offset = 0;
684 	uio->uio_rw = UIO_WRITE;
685 	datalen = MIN(uio->uio_resid, ktr_geniosize);
686 	buf = malloc(datalen, M_KTRACE, M_WAITOK);
687 	error = uiomove(buf, datalen, uio);
688 	free(uio, M_IOV);
689 	if (error) {
690 		free(buf, M_KTRACE);
691 		return;
692 	}
693 	req = ktr_getrequest(KTR_GENIO);
694 	if (req == NULL) {
695 		free(buf, M_KTRACE);
696 		return;
697 	}
698 	ktg = &req->ktr_data.ktr_genio;
699 	ktg->ktr_fd = fd;
700 	ktg->ktr_rw = rw;
701 	req->ktr_header.ktr_len = datalen;
702 	req->ktr_buffer = buf;
703 	ktr_submitrequest(curthread, req);
704 }
705 
706 void
707 ktrpsig(int sig, sig_t action, sigset_t *mask, int code)
708 {
709 	struct thread *td = curthread;
710 	struct ktr_request *req;
711 	struct ktr_psig	*kp;
712 
713 	req = ktr_getrequest(KTR_PSIG);
714 	if (req == NULL)
715 		return;
716 	kp = &req->ktr_data.ktr_psig;
717 	kp->signo = (char)sig;
718 	kp->action = action;
719 	kp->mask = *mask;
720 	kp->code = code;
721 	ktr_enqueuerequest(td, req);
722 	ktrace_exit(td);
723 }
724 
725 void
726 ktrcsw(int out, int user, const char *wmesg)
727 {
728 	struct thread *td = curthread;
729 	struct ktr_request *req;
730 	struct ktr_csw *kc;
731 
732 	req = ktr_getrequest(KTR_CSW);
733 	if (req == NULL)
734 		return;
735 	kc = &req->ktr_data.ktr_csw;
736 	kc->out = out;
737 	kc->user = user;
738 	if (wmesg != NULL)
739 		strlcpy(kc->wmesg, wmesg, sizeof(kc->wmesg));
740 	else
741 		bzero(kc->wmesg, sizeof(kc->wmesg));
742 	ktr_enqueuerequest(td, req);
743 	ktrace_exit(td);
744 }
745 
746 void
747 ktrstruct(const char *name, const void *data, size_t datalen)
748 {
749 	struct ktr_request *req;
750 	char *buf;
751 	size_t buflen, namelen;
752 
753 	if (data == NULL)
754 		datalen = 0;
755 	namelen = strlen(name) + 1;
756 	buflen = namelen + datalen;
757 	buf = malloc(buflen, M_KTRACE, M_WAITOK);
758 	strcpy(buf, name);
759 	bcopy(data, buf + namelen, datalen);
760 	if ((req = ktr_getrequest(KTR_STRUCT)) == NULL) {
761 		free(buf, M_KTRACE);
762 		return;
763 	}
764 	req->ktr_buffer = buf;
765 	req->ktr_header.ktr_len = buflen;
766 	ktr_submitrequest(curthread, req);
767 }
768 
769 void
770 ktrstructarray(const char *name, enum uio_seg seg, const void *data,
771     int num_items, size_t struct_size)
772 {
773 	struct ktr_request *req;
774 	struct ktr_struct_array *ksa;
775 	char *buf;
776 	size_t buflen, datalen, namelen;
777 	int max_items;
778 
779 	/* Trim array length to genio size. */
780 	max_items = ktr_geniosize / struct_size;
781 	if (num_items > max_items) {
782 		if (max_items == 0)
783 			num_items = 1;
784 		else
785 			num_items = max_items;
786 	}
787 	datalen = num_items * struct_size;
788 
789 	if (data == NULL)
790 		datalen = 0;
791 
792 	namelen = strlen(name) + 1;
793 	buflen = namelen + datalen;
794 	buf = malloc(buflen, M_KTRACE, M_WAITOK);
795 	strcpy(buf, name);
796 	if (seg == UIO_SYSSPACE)
797 		bcopy(data, buf + namelen, datalen);
798 	else {
799 		if (copyin(data, buf + namelen, datalen) != 0) {
800 			free(buf, M_KTRACE);
801 			return;
802 		}
803 	}
804 	if ((req = ktr_getrequest(KTR_STRUCT_ARRAY)) == NULL) {
805 		free(buf, M_KTRACE);
806 		return;
807 	}
808 	ksa = &req->ktr_data.ktr_struct_array;
809 	ksa->struct_size = struct_size;
810 	req->ktr_buffer = buf;
811 	req->ktr_header.ktr_len = buflen;
812 	ktr_submitrequest(curthread, req);
813 }
814 
815 void
816 ktrcapfail(enum ktr_cap_fail_type type, const cap_rights_t *needed,
817     const cap_rights_t *held)
818 {
819 	struct thread *td = curthread;
820 	struct ktr_request *req;
821 	struct ktr_cap_fail *kcf;
822 
823 	req = ktr_getrequest(KTR_CAPFAIL);
824 	if (req == NULL)
825 		return;
826 	kcf = &req->ktr_data.ktr_cap_fail;
827 	kcf->cap_type = type;
828 	if (needed != NULL)
829 		kcf->cap_needed = *needed;
830 	else
831 		cap_rights_init(&kcf->cap_needed);
832 	if (held != NULL)
833 		kcf->cap_held = *held;
834 	else
835 		cap_rights_init(&kcf->cap_held);
836 	ktr_enqueuerequest(td, req);
837 	ktrace_exit(td);
838 }
839 
840 void
841 ktrfault(vm_offset_t vaddr, int type)
842 {
843 	struct thread *td = curthread;
844 	struct ktr_request *req;
845 	struct ktr_fault *kf;
846 
847 	req = ktr_getrequest(KTR_FAULT);
848 	if (req == NULL)
849 		return;
850 	kf = &req->ktr_data.ktr_fault;
851 	kf->vaddr = vaddr;
852 	kf->type = type;
853 	ktr_enqueuerequest(td, req);
854 	ktrace_exit(td);
855 }
856 
857 void
858 ktrfaultend(int result)
859 {
860 	struct thread *td = curthread;
861 	struct ktr_request *req;
862 	struct ktr_faultend *kf;
863 
864 	req = ktr_getrequest(KTR_FAULTEND);
865 	if (req == NULL)
866 		return;
867 	kf = &req->ktr_data.ktr_faultend;
868 	kf->result = result;
869 	ktr_enqueuerequest(td, req);
870 	ktrace_exit(td);
871 }
872 #endif /* KTRACE */
873 
874 /* Interface and common routines */
875 
876 #ifndef _SYS_SYSPROTO_H_
877 struct ktrace_args {
878 	char	*fname;
879 	int	ops;
880 	int	facs;
881 	int	pid;
882 };
883 #endif
884 /* ARGSUSED */
885 int
886 sys_ktrace(struct thread *td, struct ktrace_args *uap)
887 {
888 #ifdef KTRACE
889 	struct vnode *vp = NULL;
890 	struct proc *p;
891 	struct pgrp *pg;
892 	int facs = uap->facs & ~KTRFAC_ROOT;
893 	int ops = KTROP(uap->ops);
894 	int descend = uap->ops & KTRFLAG_DESCEND;
895 	int nfound, ret = 0;
896 	int flags, error = 0;
897 	struct nameidata nd;
898 	struct ucred *cred;
899 
900 	/*
901 	 * Need something to (un)trace.
902 	 */
903 	if (ops != KTROP_CLEARFILE && facs == 0)
904 		return (EINVAL);
905 
906 	ktrace_enter(td);
907 	if (ops != KTROP_CLEAR) {
908 		/*
909 		 * an operation which requires a file argument.
910 		 */
911 		NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_USERSPACE, uap->fname, td);
912 		flags = FREAD | FWRITE | O_NOFOLLOW;
913 		error = vn_open(&nd, &flags, 0, NULL);
914 		if (error) {
915 			ktrace_exit(td);
916 			return (error);
917 		}
918 		NDFREE(&nd, NDF_ONLY_PNBUF);
919 		vp = nd.ni_vp;
920 		VOP_UNLOCK(vp, 0);
921 		if (vp->v_type != VREG) {
922 			(void) vn_close(vp, FREAD|FWRITE, td->td_ucred, td);
923 			ktrace_exit(td);
924 			return (EACCES);
925 		}
926 	}
927 	/*
928 	 * Clear all uses of the tracefile.
929 	 */
930 	if (ops == KTROP_CLEARFILE) {
931 		int vrele_count;
932 
933 		vrele_count = 0;
934 		sx_slock(&allproc_lock);
935 		FOREACH_PROC_IN_SYSTEM(p) {
936 			PROC_LOCK(p);
937 			if (p->p_tracevp == vp) {
938 				if (ktrcanset(td, p)) {
939 					mtx_lock(&ktrace_mtx);
940 					ktr_freeproc(p, &cred, NULL);
941 					mtx_unlock(&ktrace_mtx);
942 					vrele_count++;
943 					crfree(cred);
944 				} else
945 					error = EPERM;
946 			}
947 			PROC_UNLOCK(p);
948 		}
949 		sx_sunlock(&allproc_lock);
950 		if (vrele_count > 0) {
951 			while (vrele_count-- > 0)
952 				vrele(vp);
953 		}
954 		goto done;
955 	}
956 	/*
957 	 * do it
958 	 */
959 	sx_slock(&proctree_lock);
960 	if (uap->pid < 0) {
961 		/*
962 		 * by process group
963 		 */
964 		pg = pgfind(-uap->pid);
965 		if (pg == NULL) {
966 			sx_sunlock(&proctree_lock);
967 			error = ESRCH;
968 			goto done;
969 		}
970 		/*
971 		 * ktrops() may call vrele(). Lock pg_members
972 		 * by the proctree_lock rather than pg_mtx.
973 		 */
974 		PGRP_UNLOCK(pg);
975 		nfound = 0;
976 		LIST_FOREACH(p, &pg->pg_members, p_pglist) {
977 			PROC_LOCK(p);
978 			if (p->p_state == PRS_NEW ||
979 			    p_cansee(td, p) != 0) {
980 				PROC_UNLOCK(p);
981 				continue;
982 			}
983 			nfound++;
984 			if (descend)
985 				ret |= ktrsetchildren(td, p, ops, facs, vp);
986 			else
987 				ret |= ktrops(td, p, ops, facs, vp);
988 		}
989 		if (nfound == 0) {
990 			sx_sunlock(&proctree_lock);
991 			error = ESRCH;
992 			goto done;
993 		}
994 	} else {
995 		/*
996 		 * by pid
997 		 */
998 		p = pfind(uap->pid);
999 		if (p == NULL)
1000 			error = ESRCH;
1001 		else
1002 			error = p_cansee(td, p);
1003 		if (error) {
1004 			if (p != NULL)
1005 				PROC_UNLOCK(p);
1006 			sx_sunlock(&proctree_lock);
1007 			goto done;
1008 		}
1009 		if (descend)
1010 			ret |= ktrsetchildren(td, p, ops, facs, vp);
1011 		else
1012 			ret |= ktrops(td, p, ops, facs, vp);
1013 	}
1014 	sx_sunlock(&proctree_lock);
1015 	if (!ret)
1016 		error = EPERM;
1017 done:
1018 	if (vp != NULL)
1019 		(void) vn_close(vp, FWRITE, td->td_ucred, td);
1020 	ktrace_exit(td);
1021 	return (error);
1022 #else /* !KTRACE */
1023 	return (ENOSYS);
1024 #endif /* KTRACE */
1025 }
1026 
1027 /* ARGSUSED */
1028 int
1029 sys_utrace(struct thread *td, struct utrace_args *uap)
1030 {
1031 
1032 #ifdef KTRACE
1033 	struct ktr_request *req;
1034 	void *cp;
1035 	int error;
1036 
1037 	if (!KTRPOINT(td, KTR_USER))
1038 		return (0);
1039 	if (uap->len > KTR_USER_MAXLEN)
1040 		return (EINVAL);
1041 	cp = malloc(uap->len, M_KTRACE, M_WAITOK);
1042 	error = copyin(uap->addr, cp, uap->len);
1043 	if (error) {
1044 		free(cp, M_KTRACE);
1045 		return (error);
1046 	}
1047 	req = ktr_getrequest(KTR_USER);
1048 	if (req == NULL) {
1049 		free(cp, M_KTRACE);
1050 		return (ENOMEM);
1051 	}
1052 	req->ktr_buffer = cp;
1053 	req->ktr_header.ktr_len = uap->len;
1054 	ktr_submitrequest(td, req);
1055 	return (0);
1056 #else /* !KTRACE */
1057 	return (ENOSYS);
1058 #endif /* KTRACE */
1059 }
1060 
1061 #ifdef KTRACE
1062 static int
1063 ktrops(struct thread *td, struct proc *p, int ops, int facs, struct vnode *vp)
1064 {
1065 	struct vnode *tracevp = NULL;
1066 	struct ucred *tracecred = NULL;
1067 
1068 	PROC_LOCK_ASSERT(p, MA_OWNED);
1069 	if (!ktrcanset(td, p)) {
1070 		PROC_UNLOCK(p);
1071 		return (0);
1072 	}
1073 	if (p->p_flag & P_WEXIT) {
1074 		/* If the process is exiting, just ignore it. */
1075 		PROC_UNLOCK(p);
1076 		return (1);
1077 	}
1078 	mtx_lock(&ktrace_mtx);
1079 	if (ops == KTROP_SET) {
1080 		if (p->p_tracevp != vp) {
1081 			/*
1082 			 * if trace file already in use, relinquish below
1083 			 */
1084 			tracevp = p->p_tracevp;
1085 			VREF(vp);
1086 			p->p_tracevp = vp;
1087 		}
1088 		if (p->p_tracecred != td->td_ucred) {
1089 			tracecred = p->p_tracecred;
1090 			p->p_tracecred = crhold(td->td_ucred);
1091 		}
1092 		p->p_traceflag |= facs;
1093 		if (priv_check(td, PRIV_KTRACE) == 0)
1094 			p->p_traceflag |= KTRFAC_ROOT;
1095 	} else {
1096 		/* KTROP_CLEAR */
1097 		if (((p->p_traceflag &= ~facs) & KTRFAC_MASK) == 0)
1098 			/* no more tracing */
1099 			ktr_freeproc(p, &tracecred, &tracevp);
1100 	}
1101 	mtx_unlock(&ktrace_mtx);
1102 	if ((p->p_traceflag & KTRFAC_MASK) != 0)
1103 		ktrprocctor_entered(td, p);
1104 	PROC_UNLOCK(p);
1105 	if (tracevp != NULL)
1106 		vrele(tracevp);
1107 	if (tracecred != NULL)
1108 		crfree(tracecred);
1109 
1110 	return (1);
1111 }
1112 
1113 static int
1114 ktrsetchildren(struct thread *td, struct proc *top, int ops, int facs,
1115     struct vnode *vp)
1116 {
1117 	struct proc *p;
1118 	int ret = 0;
1119 
1120 	p = top;
1121 	PROC_LOCK_ASSERT(p, MA_OWNED);
1122 	sx_assert(&proctree_lock, SX_LOCKED);
1123 	for (;;) {
1124 		ret |= ktrops(td, p, ops, facs, vp);
1125 		/*
1126 		 * If this process has children, descend to them next,
1127 		 * otherwise do any siblings, and if done with this level,
1128 		 * follow back up the tree (but not past top).
1129 		 */
1130 		if (!LIST_EMPTY(&p->p_children))
1131 			p = LIST_FIRST(&p->p_children);
1132 		else for (;;) {
1133 			if (p == top)
1134 				return (ret);
1135 			if (LIST_NEXT(p, p_sibling)) {
1136 				p = LIST_NEXT(p, p_sibling);
1137 				break;
1138 			}
1139 			p = p->p_pptr;
1140 		}
1141 		PROC_LOCK(p);
1142 	}
1143 	/*NOTREACHED*/
1144 }
1145 
1146 static void
1147 ktr_writerequest(struct thread *td, struct ktr_request *req)
1148 {
1149 	struct ktr_header *kth;
1150 	struct vnode *vp;
1151 	struct proc *p;
1152 	struct ucred *cred;
1153 	struct uio auio;
1154 	struct iovec aiov[3];
1155 	struct mount *mp;
1156 	int datalen, buflen, vrele_count;
1157 	int error;
1158 
1159 	/*
1160 	 * We hold the vnode and credential for use in I/O in case ktrace is
1161 	 * disabled on the process as we write out the request.
1162 	 *
1163 	 * XXXRW: This is not ideal: we could end up performing a write after
1164 	 * the vnode has been closed.
1165 	 */
1166 	mtx_lock(&ktrace_mtx);
1167 	vp = td->td_proc->p_tracevp;
1168 	cred = td->td_proc->p_tracecred;
1169 
1170 	/*
1171 	 * If vp is NULL, the vp has been cleared out from under this
1172 	 * request, so just drop it.  Make sure the credential and vnode are
1173 	 * in sync: we should have both or neither.
1174 	 */
1175 	if (vp == NULL) {
1176 		KASSERT(cred == NULL, ("ktr_writerequest: cred != NULL"));
1177 		mtx_unlock(&ktrace_mtx);
1178 		return;
1179 	}
1180 	VREF(vp);
1181 	KASSERT(cred != NULL, ("ktr_writerequest: cred == NULL"));
1182 	crhold(cred);
1183 	mtx_unlock(&ktrace_mtx);
1184 
1185 	kth = &req->ktr_header;
1186 	KASSERT(((u_short)kth->ktr_type & ~KTR_DROP) < nitems(data_lengths),
1187 	    ("data_lengths array overflow"));
1188 	datalen = data_lengths[(u_short)kth->ktr_type & ~KTR_DROP];
1189 	buflen = kth->ktr_len;
1190 	auio.uio_iov = &aiov[0];
1191 	auio.uio_offset = 0;
1192 	auio.uio_segflg = UIO_SYSSPACE;
1193 	auio.uio_rw = UIO_WRITE;
1194 	aiov[0].iov_base = (caddr_t)kth;
1195 	aiov[0].iov_len = sizeof(struct ktr_header);
1196 	auio.uio_resid = sizeof(struct ktr_header);
1197 	auio.uio_iovcnt = 1;
1198 	auio.uio_td = td;
1199 	if (datalen != 0) {
1200 		aiov[1].iov_base = (caddr_t)&req->ktr_data;
1201 		aiov[1].iov_len = datalen;
1202 		auio.uio_resid += datalen;
1203 		auio.uio_iovcnt++;
1204 		kth->ktr_len += datalen;
1205 	}
1206 	if (buflen != 0) {
1207 		KASSERT(req->ktr_buffer != NULL, ("ktrace: nothing to write"));
1208 		aiov[auio.uio_iovcnt].iov_base = req->ktr_buffer;
1209 		aiov[auio.uio_iovcnt].iov_len = buflen;
1210 		auio.uio_resid += buflen;
1211 		auio.uio_iovcnt++;
1212 	}
1213 
1214 	vn_start_write(vp, &mp, V_WAIT);
1215 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1216 #ifdef MAC
1217 	error = mac_vnode_check_write(cred, NOCRED, vp);
1218 	if (error == 0)
1219 #endif
1220 		error = VOP_WRITE(vp, &auio, IO_UNIT | IO_APPEND, cred);
1221 	VOP_UNLOCK(vp, 0);
1222 	vn_finished_write(mp);
1223 	crfree(cred);
1224 	if (!error) {
1225 		vrele(vp);
1226 		return;
1227 	}
1228 
1229 	/*
1230 	 * If error encountered, give up tracing on this vnode.  We defer
1231 	 * all the vrele()'s on the vnode until after we are finished walking
1232 	 * the various lists to avoid needlessly holding locks.
1233 	 * NB: at this point we still hold the vnode reference that must
1234 	 * not go away as we need the valid vnode to compare with. Thus let
1235 	 * vrele_count start at 1 and the reference will be freed
1236 	 * by the loop at the end after our last use of vp.
1237 	 */
1238 	log(LOG_NOTICE, "ktrace write failed, errno %d, tracing stopped\n",
1239 	    error);
1240 	vrele_count = 1;
1241 	/*
1242 	 * First, clear this vnode from being used by any processes in the
1243 	 * system.
1244 	 * XXX - If one process gets an EPERM writing to the vnode, should
1245 	 * we really do this?  Other processes might have suitable
1246 	 * credentials for the operation.
1247 	 */
1248 	cred = NULL;
1249 	sx_slock(&allproc_lock);
1250 	FOREACH_PROC_IN_SYSTEM(p) {
1251 		PROC_LOCK(p);
1252 		if (p->p_tracevp == vp) {
1253 			mtx_lock(&ktrace_mtx);
1254 			ktr_freeproc(p, &cred, NULL);
1255 			mtx_unlock(&ktrace_mtx);
1256 			vrele_count++;
1257 		}
1258 		PROC_UNLOCK(p);
1259 		if (cred != NULL) {
1260 			crfree(cred);
1261 			cred = NULL;
1262 		}
1263 	}
1264 	sx_sunlock(&allproc_lock);
1265 
1266 	while (vrele_count-- > 0)
1267 		vrele(vp);
1268 }
1269 
1270 /*
1271  * Return true if caller has permission to set the ktracing state
1272  * of target.  Essentially, the target can't possess any
1273  * more permissions than the caller.  KTRFAC_ROOT signifies that
1274  * root previously set the tracing status on the target process, and
1275  * so, only root may further change it.
1276  */
1277 static int
1278 ktrcanset(struct thread *td, struct proc *targetp)
1279 {
1280 
1281 	PROC_LOCK_ASSERT(targetp, MA_OWNED);
1282 	if (targetp->p_traceflag & KTRFAC_ROOT &&
1283 	    priv_check(td, PRIV_KTRACE))
1284 		return (0);
1285 
1286 	if (p_candebug(td, targetp) != 0)
1287 		return (0);
1288 
1289 	return (1);
1290 }
1291 
1292 #endif /* KTRACE */
1293