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