2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1989, 1993
5 * The Regents of the University of California.
6 * Copyright (c) 2005 Robert N. M. Watson
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
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.
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
33 * @(#)kern_ktrace.c 8.2 (Berkeley) 9/23/93
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
39 #include "opt_ktrace.h"
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>
48 #include <sys/mutex.h>
49 #include <sys/malloc.h>
50 #include <sys/mount.h>
51 #include <sys/namei.h>
54 #include <sys/unistd.h>
55 #include <sys/vnode.h>
56 #include <sys/socket.h>
58 #include <sys/ktrace.h>
60 #include <sys/sysctl.h>
61 #include <sys/sysent.h>
62 #include <sys/syslog.h>
63 #include <sys/sysproto.h>
65 #include <security/mac/mac_framework.h>
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.
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.
86 static MALLOC_DEFINE(M_KTRACE, "KTRACE", "KTRACE");
90 FEATURE(ktrace, "Kernel support for system-call tracing");
92 #ifndef KTRACE_REQUEST_POOL
93 #define KTRACE_REQUEST_POOL 100
97 struct ktr_header ktr_header;
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;
111 STAILQ_ENTRY(ktr_request) ktr_list;
114 static int data_lengths[] = {
115 [KTR_SYSCALL] = offsetof(struct ktr_syscall, ktr_args),
116 [KTR_SYSRET] = sizeof(struct ktr_sysret),
118 [KTR_GENIO] = sizeof(struct ktr_genio),
119 [KTR_PSIG] = sizeof(struct ktr_psig),
120 [KTR_CSW] = sizeof(struct ktr_csw),
124 [KTR_PROCCTOR] = sizeof(struct ktr_proc_ctor),
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),
132 static STAILQ_HEAD(, ktr_request) ktr_free;
134 static SYSCTL_NODE(_kern, OID_AUTO, ktrace, CTLFLAG_RD, 0, "KTRACE options");
136 static u_int ktr_requestpool = KTRACE_REQUEST_POOL;
137 TUNABLE_INT("kern.ktrace.request_pool", &ktr_requestpool);
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");
143 static int print_message = 1;
144 static struct mtx ktrace_mtx;
145 static struct sx ktrace_sx;
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,
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 *);
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
170 ktrace_enter(struct thread *td)
173 KASSERT(!(td->td_pflags & TDP_INKTRACE), ("ktrace_enter: flag set"));
174 td->td_pflags |= TDP_INKTRACE;
178 ktrace_exit(struct thread *td)
181 KASSERT(td->td_pflags & TDP_INKTRACE, ("ktrace_exit: flag not set"));
182 td->td_pflags &= ~TDP_INKTRACE;
186 ktrace_assert(struct thread *td)
189 KASSERT(td->td_pflags & TDP_INKTRACE, ("ktrace_assert: flag not set"));
193 ktrace_init(void *dummy)
195 struct ktr_request *req;
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);
206 SYSINIT(ktrace_init, SI_SUB_KTRACE, SI_ORDER_ANY, ktrace_init, NULL);
209 sysctl_kern_ktrace_request_pool(SYSCTL_HANDLER_ARGS)
212 u_int newsize, oldsize, wantsize;
215 /* Handle easy read-only case first to avoid warnings from GCC. */
217 oldsize = ktr_requestpool;
218 return (SYSCTL_OUT(req, &oldsize, sizeof(u_int)));
221 error = SYSCTL_IN(req, &wantsize, sizeof(u_int));
226 oldsize = ktr_requestpool;
227 newsize = ktrace_resize_pool(oldsize, wantsize);
229 error = SYSCTL_OUT(req, &oldsize, sizeof(u_int));
232 if (wantsize > oldsize && newsize < wantsize)
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)");
241 ktrace_resize_pool(u_int oldsize, u_int newsize)
243 STAILQ_HEAD(, ktr_request) ktr_new;
244 struct ktr_request *req;
248 bound = newsize - oldsize;
250 return (ktr_requestpool);
252 mtx_lock(&ktrace_mtx);
253 /* Shrink pool down to newsize if possible. */
254 while (bound++ < 0) {
255 req = STAILQ_FIRST(&ktr_free);
258 STAILQ_REMOVE_HEAD(&ktr_free, ktr_list);
263 /* Grow pool up to newsize. */
264 STAILQ_INIT(&ktr_new);
265 while (bound-- > 0) {
266 req = malloc(sizeof(struct ktr_request), M_KTRACE,
268 STAILQ_INSERT_HEAD(&ktr_new, req, ktr_list);
270 mtx_lock(&ktrace_mtx);
271 STAILQ_CONCAT(&ktr_free, &ktr_new);
272 ktr_requestpool += (newsize - oldsize);
274 mtx_unlock(&ktrace_mtx);
275 return (ktr_requestpool);
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));
282 static struct ktr_request *
283 ktr_getrequest_entered(struct thread *td, int type)
285 struct ktr_request *req;
286 struct proc *p = td->td_proc;
289 mtx_lock(&ktrace_mtx);
290 if (!KTRCHECK(td, type)) {
291 mtx_unlock(&ktrace_mtx);
294 req = STAILQ_FIRST(&ktr_free);
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;
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;
311 p->p_traceflag |= KTRFAC_DROP;
314 mtx_unlock(&ktrace_mtx);
316 printf("Out of ktrace request objects.\n");
321 static struct ktr_request *
322 ktr_getrequest(int type)
324 struct thread *td = curthread;
325 struct ktr_request *req;
328 req = ktr_getrequest_entered(td, type);
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
342 ktr_enqueuerequest(struct thread *td, struct ktr_request *req)
345 mtx_lock(&ktrace_mtx);
346 STAILQ_INSERT_TAIL(&td->td_proc->p_ktr, req, ktr_list);
347 mtx_unlock(&ktrace_mtx);
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.
358 ktr_drain(struct thread *td)
360 struct ktr_request *queued_req;
361 STAILQ_HEAD(, ktr_request) local_queue;
364 sx_assert(&ktrace_sx, SX_XLOCKED);
366 STAILQ_INIT(&local_queue);
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);
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);
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.
387 ktr_submitrequest(struct thread *td, struct ktr_request *req)
392 sx_xlock(&ktrace_sx);
394 ktr_writerequest(td, req);
395 ktr_freerequest(req);
396 sx_xunlock(&ktrace_sx);
401 ktr_freerequest(struct ktr_request *req)
404 mtx_lock(&ktrace_mtx);
405 ktr_freerequest_locked(req);
406 mtx_unlock(&ktrace_mtx);
410 ktr_freerequest_locked(struct ktr_request *req)
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);
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.
425 ktr_freeproc(struct proc *p, struct ucred **uc, struct vnode **vp)
427 struct ktr_request *req;
429 PROC_LOCK_ASSERT(p, MA_OWNED);
430 mtx_assert(&ktrace_mtx, MA_OWNED);
431 *uc = p->p_tracecred;
432 p->p_tracecred = NULL;
437 while ((req = STAILQ_FIRST(&p->p_ktr)) != NULL) {
438 STAILQ_REMOVE_HEAD(&p->p_ktr, ktr_list);
439 ktr_freerequest_locked(req);
444 ktrsyscall(int code, int narg, register_t args[])
446 struct ktr_request *req;
447 struct ktr_syscall *ktp;
451 buflen = sizeof(register_t) * narg;
453 buf = malloc(buflen, M_KTRACE, M_WAITOK);
454 bcopy(args, buf, buflen);
456 req = ktr_getrequest(KTR_SYSCALL);
462 ktp = &req->ktr_data.ktr_syscall;
463 ktp->ktr_code = code;
464 ktp->ktr_narg = narg;
466 req->ktr_header.ktr_len = buflen;
467 req->ktr_buffer = buf;
469 ktr_submitrequest(curthread, req);
473 ktrsysret(int code, int error, register_t retval)
475 struct ktr_request *req;
476 struct ktr_sysret *ktp;
478 req = ktr_getrequest(KTR_SYSRET);
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);
489 * When a setuid process execs, disable tracing.
491 * XXX: We toss any pending asynchronous records.
494 ktrprocexec(struct proc *p, struct ucred **uc, struct vnode **vp)
497 PROC_LOCK_ASSERT(p, MA_OWNED);
498 mtx_lock(&ktrace_mtx);
499 ktr_freeproc(p, uc, vp);
500 mtx_unlock(&ktrace_mtx);
504 * When a process exits, drain per-process asynchronous trace records
505 * and disable tracing.
508 ktrprocexit(struct thread *td)
510 struct ktr_request *req;
516 if (p->p_traceflag == 0)
520 req = ktr_getrequest_entered(td, KTR_PROCDTOR);
522 ktr_enqueuerequest(td, req);
523 sx_xlock(&ktrace_sx);
525 sx_xunlock(&ktrace_sx);
527 mtx_lock(&ktrace_mtx);
528 ktr_freeproc(p, &cred, &vp);
529 mtx_unlock(&ktrace_mtx);
539 ktrprocctor_entered(struct thread *td, struct proc *p)
541 struct ktr_proc_ctor *ktp;
542 struct ktr_request *req;
546 td2 = FIRST_THREAD_IN_PROC(p);
547 req = ktr_getrequest_entered(td2, KTR_PROCCTOR);
550 ktp = &req->ktr_data.ktr_proc_ctor;
551 ktp->sv_flags = p->p_sysent->sv_flags;
552 ktr_enqueuerequest(td2, req);
556 ktrprocctor(struct proc *p)
558 struct thread *td = curthread;
560 if ((p->p_traceflag & KTRFAC_MASK) == 0)
564 ktrprocctor_entered(td, p);
569 * When a process forks, enable tracing in the new process if needed.
572 ktrprocfork(struct proc *p1, struct proc *p2)
575 MPASS(p2->p_tracevp == NULL);
576 MPASS(p2->p_traceflag == 0);
578 if (p1->p_traceflag == 0)
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) {
587 KASSERT(p1->p_tracecred != NULL,
588 ("ktrace vnode with no cred"));
589 p2->p_tracecred = crhold(p1->p_tracecred);
592 mtx_unlock(&ktrace_mtx);
599 * When a thread returns, drain any asynchronous records generated by the
603 ktruserret(struct thread *td)
607 sx_xlock(&ktrace_sx);
609 sx_xunlock(&ktrace_sx);
617 struct ktr_request *req;
621 namelen = strlen(path);
623 buf = malloc(namelen, M_KTRACE, M_WAITOK);
624 bcopy(path, buf, namelen);
626 req = ktr_getrequest(KTR_NAMEI);
633 req->ktr_header.ktr_len = namelen;
634 req->ktr_buffer = buf;
636 ktr_submitrequest(curthread, req);
640 ktrsysctl(int *name, u_int namelen)
642 struct ktr_request *req;
643 u_int mib[CTL_MAXNAME + 2];
648 /* Lookup name of mib. */
649 KASSERT(namelen <= CTL_MAXNAME, ("sysctl MIB too long"));
652 bcopy(name, mib + 2, namelen * sizeof(*name));
654 mibname = malloc(mibnamelen, M_KTRACE, M_WAITOK);
655 error = kernel_sysctl(curthread, mib, namelen + 2, mibname, &mibnamelen,
656 NULL, 0, &mibnamelen, 0);
658 free(mibname, M_KTRACE);
661 req = ktr_getrequest(KTR_SYSCTL);
663 free(mibname, M_KTRACE);
666 req->ktr_header.ktr_len = mibnamelen;
667 req->ktr_buffer = mibname;
668 ktr_submitrequest(curthread, req);
672 ktrgenio(int fd, enum uio_rw rw, struct uio *uio, int error)
674 struct ktr_request *req;
675 struct ktr_genio *ktg;
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);
693 req = ktr_getrequest(KTR_GENIO);
698 ktg = &req->ktr_data.ktr_genio;
701 req->ktr_header.ktr_len = datalen;
702 req->ktr_buffer = buf;
703 ktr_submitrequest(curthread, req);
707 ktrpsig(int sig, sig_t action, sigset_t *mask, int code)
709 struct thread *td = curthread;
710 struct ktr_request *req;
713 req = ktr_getrequest(KTR_PSIG);
716 kp = &req->ktr_data.ktr_psig;
717 kp->signo = (char)sig;
721 ktr_enqueuerequest(td, req);
726 ktrcsw(int out, int user, const char *wmesg)
728 struct thread *td = curthread;
729 struct ktr_request *req;
732 req = ktr_getrequest(KTR_CSW);
735 kc = &req->ktr_data.ktr_csw;
739 strlcpy(kc->wmesg, wmesg, sizeof(kc->wmesg));
741 bzero(kc->wmesg, sizeof(kc->wmesg));
742 ktr_enqueuerequest(td, req);
747 ktrstruct(const char *name, const void *data, size_t datalen)
749 struct ktr_request *req;
751 size_t buflen, namelen;
755 namelen = strlen(name) + 1;
756 buflen = namelen + datalen;
757 buf = malloc(buflen, M_KTRACE, M_WAITOK);
759 bcopy(data, buf + namelen, datalen);
760 if ((req = ktr_getrequest(KTR_STRUCT)) == NULL) {
764 req->ktr_buffer = buf;
765 req->ktr_header.ktr_len = buflen;
766 ktr_submitrequest(curthread, req);
770 ktrstructarray(const char *name, enum uio_seg seg, const void *data,
771 int num_items, size_t struct_size)
773 struct ktr_request *req;
774 struct ktr_struct_array *ksa;
776 size_t buflen, datalen, namelen;
779 /* Trim array length to genio size. */
780 max_items = ktr_geniosize / struct_size;
781 if (num_items > max_items) {
785 num_items = max_items;
787 datalen = num_items * struct_size;
792 namelen = strlen(name) + 1;
793 buflen = namelen + datalen;
794 buf = malloc(buflen, M_KTRACE, M_WAITOK);
796 if (seg == UIO_SYSSPACE)
797 bcopy(data, buf + namelen, datalen);
799 if (copyin(data, buf + namelen, datalen) != 0) {
804 if ((req = ktr_getrequest(KTR_STRUCT_ARRAY)) == NULL) {
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);
816 ktrcapfail(enum ktr_cap_fail_type type, const cap_rights_t *needed,
817 const cap_rights_t *held)
819 struct thread *td = curthread;
820 struct ktr_request *req;
821 struct ktr_cap_fail *kcf;
823 req = ktr_getrequest(KTR_CAPFAIL);
826 kcf = &req->ktr_data.ktr_cap_fail;
827 kcf->cap_type = type;
829 kcf->cap_needed = *needed;
831 cap_rights_init(&kcf->cap_needed);
833 kcf->cap_held = *held;
835 cap_rights_init(&kcf->cap_held);
836 ktr_enqueuerequest(td, req);
841 ktrfault(vm_offset_t vaddr, int type)
843 struct thread *td = curthread;
844 struct ktr_request *req;
845 struct ktr_fault *kf;
847 req = ktr_getrequest(KTR_FAULT);
850 kf = &req->ktr_data.ktr_fault;
853 ktr_enqueuerequest(td, req);
858 ktrfaultend(int result)
860 struct thread *td = curthread;
861 struct ktr_request *req;
862 struct ktr_faultend *kf;
864 req = ktr_getrequest(KTR_FAULTEND);
867 kf = &req->ktr_data.ktr_faultend;
869 ktr_enqueuerequest(td, req);
874 /* Interface and common routines */
876 #ifndef _SYS_SYSPROTO_H_
886 sys_ktrace(struct thread *td, struct ktrace_args *uap)
889 struct vnode *vp = NULL;
892 int facs = uap->facs & ~KTRFAC_ROOT;
893 int ops = KTROP(uap->ops);
894 int descend = uap->ops & KTRFLAG_DESCEND;
896 int flags, error = 0;
901 * Need something to (un)trace.
903 if (ops != KTROP_CLEARFILE && facs == 0)
907 if (ops != KTROP_CLEAR) {
909 * an operation which requires a file argument.
911 NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_USERSPACE, uap->fname, td);
912 flags = FREAD | FWRITE | O_NOFOLLOW;
913 error = vn_open(&nd, &flags, 0, NULL);
918 NDFREE(&nd, NDF_ONLY_PNBUF);
921 if (vp->v_type != VREG) {
922 (void) vn_close(vp, FREAD|FWRITE, td->td_ucred, td);
928 * Clear all uses of the tracefile.
930 if (ops == KTROP_CLEARFILE) {
934 sx_slock(&allproc_lock);
935 FOREACH_PROC_IN_SYSTEM(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);
949 sx_sunlock(&allproc_lock);
950 if (vrele_count > 0) {
951 while (vrele_count-- > 0)
959 sx_slock(&proctree_lock);
964 pg = pgfind(-uap->pid);
966 sx_sunlock(&proctree_lock);
971 * ktrops() may call vrele(). Lock pg_members
972 * by the proctree_lock rather than pg_mtx.
976 LIST_FOREACH(p, &pg->pg_members, p_pglist) {
978 if (p->p_state == PRS_NEW ||
979 p_cansee(td, p) != 0) {
985 ret |= ktrsetchildren(td, p, ops, facs, vp);
987 ret |= ktrops(td, p, ops, facs, vp);
990 sx_sunlock(&proctree_lock);
1002 error = p_cansee(td, p);
1006 sx_sunlock(&proctree_lock);
1010 ret |= ktrsetchildren(td, p, ops, facs, vp);
1012 ret |= ktrops(td, p, ops, facs, vp);
1014 sx_sunlock(&proctree_lock);
1019 (void) vn_close(vp, FWRITE, td->td_ucred, td);
1029 sys_utrace(struct thread *td, struct utrace_args *uap)
1033 struct ktr_request *req;
1037 if (!KTRPOINT(td, KTR_USER))
1039 if (uap->len > KTR_USER_MAXLEN)
1041 cp = malloc(uap->len, M_KTRACE, M_WAITOK);
1042 error = copyin(uap->addr, cp, uap->len);
1047 req = ktr_getrequest(KTR_USER);
1052 req->ktr_buffer = cp;
1053 req->ktr_header.ktr_len = uap->len;
1054 ktr_submitrequest(td, req);
1063 ktrops(struct thread *td, struct proc *p, int ops, int facs, struct vnode *vp)
1065 struct vnode *tracevp = NULL;
1066 struct ucred *tracecred = NULL;
1068 PROC_LOCK_ASSERT(p, MA_OWNED);
1069 if (!ktrcanset(td, p)) {
1073 if (p->p_flag & P_WEXIT) {
1074 /* If the process is exiting, just ignore it. */
1078 mtx_lock(&ktrace_mtx);
1079 if (ops == KTROP_SET) {
1080 if (p->p_tracevp != vp) {
1082 * if trace file already in use, relinquish below
1084 tracevp = p->p_tracevp;
1088 if (p->p_tracecred != td->td_ucred) {
1089 tracecred = p->p_tracecred;
1090 p->p_tracecred = crhold(td->td_ucred);
1092 p->p_traceflag |= facs;
1093 if (priv_check(td, PRIV_KTRACE) == 0)
1094 p->p_traceflag |= KTRFAC_ROOT;
1097 if (((p->p_traceflag &= ~facs) & KTRFAC_MASK) == 0)
1098 /* no more tracing */
1099 ktr_freeproc(p, &tracecred, &tracevp);
1101 mtx_unlock(&ktrace_mtx);
1102 if ((p->p_traceflag & KTRFAC_MASK) != 0)
1103 ktrprocctor_entered(td, p);
1105 if (tracevp != NULL)
1107 if (tracecred != NULL)
1114 ktrsetchildren(struct thread *td, struct proc *top, int ops, int facs,
1121 PROC_LOCK_ASSERT(p, MA_OWNED);
1122 sx_assert(&proctree_lock, SX_LOCKED);
1124 ret |= ktrops(td, p, ops, facs, vp);
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).
1130 if (!LIST_EMPTY(&p->p_children))
1131 p = LIST_FIRST(&p->p_children);
1135 if (LIST_NEXT(p, p_sibling)) {
1136 p = LIST_NEXT(p, p_sibling);
1147 ktr_writerequest(struct thread *td, struct ktr_request *req)
1149 struct ktr_header *kth;
1154 struct iovec aiov[3];
1156 int datalen, buflen, vrele_count;
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.
1163 * XXXRW: This is not ideal: we could end up performing a write after
1164 * the vnode has been closed.
1166 mtx_lock(&ktrace_mtx);
1167 vp = td->td_proc->p_tracevp;
1168 cred = td->td_proc->p_tracecred;
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.
1176 KASSERT(cred == NULL, ("ktr_writerequest: cred != NULL"));
1177 mtx_unlock(&ktrace_mtx);
1181 KASSERT(cred != NULL, ("ktr_writerequest: cred == NULL"));
1183 mtx_unlock(&ktrace_mtx);
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;
1200 aiov[1].iov_base = (caddr_t)&req->ktr_data;
1201 aiov[1].iov_len = datalen;
1202 auio.uio_resid += datalen;
1204 kth->ktr_len += datalen;
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;
1214 vn_start_write(vp, &mp, V_WAIT);
1215 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1217 error = mac_vnode_check_write(cred, NOCRED, vp);
1220 error = VOP_WRITE(vp, &auio, IO_UNIT | IO_APPEND, cred);
1222 vn_finished_write(mp);
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.
1238 log(LOG_NOTICE, "ktrace write failed, errno %d, tracing stopped\n",
1242 * First, clear this vnode from being used by any processes in the
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.
1249 sx_slock(&allproc_lock);
1250 FOREACH_PROC_IN_SYSTEM(p) {
1252 if (p->p_tracevp == vp) {
1253 mtx_lock(&ktrace_mtx);
1254 ktr_freeproc(p, &cred, NULL);
1255 mtx_unlock(&ktrace_mtx);
1264 sx_sunlock(&allproc_lock);
1266 while (vrele_count-- > 0)
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.
1278 ktrcanset(struct thread *td, struct proc *targetp)
1281 PROC_LOCK_ASSERT(targetp, MA_OWNED);
1282 if (targetp->p_traceflag & KTRFAC_ROOT &&
1283 priv_check(td, PRIV_KTRACE))
1286 if (p_candebug(td, targetp) != 0)