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/resourcevar.h>
55 #include <sys/unistd.h>
56 #include <sys/vnode.h>
57 #include <sys/socket.h>
59 #include <sys/ktrace.h>
61 #include <sys/sysctl.h>
62 #include <sys/sysent.h>
63 #include <sys/syslog.h>
64 #include <sys/sysproto.h>
66 #include <security/mac/mac_framework.h>
69 * The ktrace facility allows the tracing of certain key events in user space
70 * processes, such as system calls, signal delivery, context switches, and
71 * user generated events using utrace(2). It works by streaming event
72 * records and data to a vnode associated with the process using the
73 * ktrace(2) system call. In general, records can be written directly from
74 * the context that generates the event. One important exception to this is
75 * during a context switch, where sleeping is not permitted. To handle this
76 * case, trace events are generated using in-kernel ktr_request records, and
77 * then delivered to disk at a convenient moment -- either immediately, the
78 * next traceable event, at system call return, or at process exit.
80 * When dealing with multiple threads or processes writing to the same event
81 * log, ordering guarantees are weak: specifically, if an event has multiple
82 * records (i.e., system call enter and return), they may be interlaced with
83 * records from another event. Process and thread ID information is provided
84 * in the record, and user applications can de-interlace events if required.
87 static MALLOC_DEFINE(M_KTRACE, "KTRACE", "KTRACE");
91 FEATURE(ktrace, "Kernel support for system-call tracing");
93 #ifndef KTRACE_REQUEST_POOL
94 #define KTRACE_REQUEST_POOL 100
98 struct ktr_header ktr_header;
101 struct ktr_proc_ctor ktr_proc_ctor;
102 struct ktr_cap_fail ktr_cap_fail;
103 struct ktr_syscall ktr_syscall;
104 struct ktr_sysret ktr_sysret;
105 struct ktr_genio ktr_genio;
106 struct ktr_psig ktr_psig;
107 struct ktr_csw ktr_csw;
108 struct ktr_fault ktr_fault;
109 struct ktr_faultend ktr_faultend;
110 struct ktr_struct_array ktr_struct_array;
112 STAILQ_ENTRY(ktr_request) ktr_list;
115 static int data_lengths[] = {
116 [KTR_SYSCALL] = offsetof(struct ktr_syscall, ktr_args),
117 [KTR_SYSRET] = sizeof(struct ktr_sysret),
119 [KTR_GENIO] = sizeof(struct ktr_genio),
120 [KTR_PSIG] = sizeof(struct ktr_psig),
121 [KTR_CSW] = sizeof(struct ktr_csw),
125 [KTR_PROCCTOR] = sizeof(struct ktr_proc_ctor),
127 [KTR_CAPFAIL] = sizeof(struct ktr_cap_fail),
128 [KTR_FAULT] = sizeof(struct ktr_fault),
129 [KTR_FAULTEND] = sizeof(struct ktr_faultend),
130 [KTR_STRUCT_ARRAY] = sizeof(struct ktr_struct_array),
133 static STAILQ_HEAD(, ktr_request) ktr_free;
135 static SYSCTL_NODE(_kern, OID_AUTO, ktrace, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
138 static u_int ktr_requestpool = KTRACE_REQUEST_POOL;
139 TUNABLE_INT("kern.ktrace.request_pool", &ktr_requestpool);
141 u_int ktr_geniosize = PAGE_SIZE;
142 SYSCTL_UINT(_kern_ktrace, OID_AUTO, genio_size, CTLFLAG_RWTUN, &ktr_geniosize,
143 0, "Maximum size of genio event payload");
146 * Allow to not to send signal to traced process, in which context the
147 * ktr record is written. The limit is applied from the process that
148 * set up ktrace, so killing the traced process is not completely fair.
150 int ktr_filesize_limit_signal = 0;
151 SYSCTL_INT(_kern_ktrace, OID_AUTO, filesize_limit_signal, CTLFLAG_RWTUN,
152 &ktr_filesize_limit_signal, 0,
153 "Send SIGXFSZ to the traced process when the log size limit is exceeded");
155 static int print_message = 1;
156 static struct mtx ktrace_mtx;
157 static struct sx ktrace_sx;
159 struct ktr_io_params {
166 static void ktrace_init(void *dummy);
167 static int sysctl_kern_ktrace_request_pool(SYSCTL_HANDLER_ARGS);
168 static u_int ktrace_resize_pool(u_int oldsize, u_int newsize);
169 static struct ktr_request *ktr_getrequest_entered(struct thread *td, int type);
170 static struct ktr_request *ktr_getrequest(int type);
171 static void ktr_submitrequest(struct thread *td, struct ktr_request *req);
172 static struct ktr_io_params *ktr_freeproc(struct proc *p);
173 static void ktr_freerequest(struct ktr_request *req);
174 static void ktr_freerequest_locked(struct ktr_request *req);
175 static void ktr_writerequest(struct thread *td, struct ktr_request *req);
176 static int ktrcanset(struct thread *,struct proc *);
177 static int ktrsetchildren(struct thread *, struct proc *, int, int,
178 struct ktr_io_params *);
179 static int ktrops(struct thread *, struct proc *, int, int,
180 struct ktr_io_params *);
181 static void ktrprocctor_entered(struct thread *, struct proc *);
184 * ktrace itself generates events, such as context switches, which we do not
185 * wish to trace. Maintain a flag, TDP_INKTRACE, on each thread to determine
186 * whether or not it is in a region where tracing of events should be
190 ktrace_enter(struct thread *td)
193 KASSERT(!(td->td_pflags & TDP_INKTRACE), ("ktrace_enter: flag set"));
194 td->td_pflags |= TDP_INKTRACE;
198 ktrace_exit(struct thread *td)
201 KASSERT(td->td_pflags & TDP_INKTRACE, ("ktrace_exit: flag not set"));
202 td->td_pflags &= ~TDP_INKTRACE;
206 ktrace_assert(struct thread *td)
209 KASSERT(td->td_pflags & TDP_INKTRACE, ("ktrace_assert: flag not set"));
213 ktrace_init(void *dummy)
215 struct ktr_request *req;
218 mtx_init(&ktrace_mtx, "ktrace", NULL, MTX_DEF | MTX_QUIET);
219 sx_init(&ktrace_sx, "ktrace_sx");
220 STAILQ_INIT(&ktr_free);
221 for (i = 0; i < ktr_requestpool; i++) {
222 req = malloc(sizeof(struct ktr_request), M_KTRACE, M_WAITOK);
223 STAILQ_INSERT_HEAD(&ktr_free, req, ktr_list);
226 SYSINIT(ktrace_init, SI_SUB_KTRACE, SI_ORDER_ANY, ktrace_init, NULL);
229 sysctl_kern_ktrace_request_pool(SYSCTL_HANDLER_ARGS)
232 u_int newsize, oldsize, wantsize;
235 /* Handle easy read-only case first to avoid warnings from GCC. */
237 oldsize = ktr_requestpool;
238 return (SYSCTL_OUT(req, &oldsize, sizeof(u_int)));
241 error = SYSCTL_IN(req, &wantsize, sizeof(u_int));
246 oldsize = ktr_requestpool;
247 newsize = ktrace_resize_pool(oldsize, wantsize);
249 error = SYSCTL_OUT(req, &oldsize, sizeof(u_int));
252 if (wantsize > oldsize && newsize < wantsize)
256 SYSCTL_PROC(_kern_ktrace, OID_AUTO, request_pool,
257 CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_NEEDGIANT, &ktr_requestpool, 0,
258 sysctl_kern_ktrace_request_pool, "IU",
259 "Pool buffer size for ktrace(1)");
262 ktrace_resize_pool(u_int oldsize, u_int newsize)
264 STAILQ_HEAD(, ktr_request) ktr_new;
265 struct ktr_request *req;
269 bound = newsize - oldsize;
271 return (ktr_requestpool);
273 mtx_lock(&ktrace_mtx);
274 /* Shrink pool down to newsize if possible. */
275 while (bound++ < 0) {
276 req = STAILQ_FIRST(&ktr_free);
279 STAILQ_REMOVE_HEAD(&ktr_free, ktr_list);
284 /* Grow pool up to newsize. */
285 STAILQ_INIT(&ktr_new);
286 while (bound-- > 0) {
287 req = malloc(sizeof(struct ktr_request), M_KTRACE,
289 STAILQ_INSERT_HEAD(&ktr_new, req, ktr_list);
291 mtx_lock(&ktrace_mtx);
292 STAILQ_CONCAT(&ktr_free, &ktr_new);
293 ktr_requestpool += (newsize - oldsize);
295 mtx_unlock(&ktrace_mtx);
296 return (ktr_requestpool);
299 /* ktr_getrequest() assumes that ktr_comm[] is the same size as td_name[]. */
300 CTASSERT(sizeof(((struct ktr_header *)NULL)->ktr_comm) ==
301 (sizeof((struct thread *)NULL)->td_name));
303 static struct ktr_request *
304 ktr_getrequest_entered(struct thread *td, int type)
306 struct ktr_request *req;
307 struct proc *p = td->td_proc;
310 mtx_lock(&ktrace_mtx);
311 if (!KTRCHECK(td, type)) {
312 mtx_unlock(&ktrace_mtx);
315 req = STAILQ_FIRST(&ktr_free);
317 STAILQ_REMOVE_HEAD(&ktr_free, ktr_list);
318 req->ktr_header.ktr_type = type;
319 if (p->p_traceflag & KTRFAC_DROP) {
320 req->ktr_header.ktr_type |= KTR_DROP;
321 p->p_traceflag &= ~KTRFAC_DROP;
323 mtx_unlock(&ktrace_mtx);
324 microtime(&req->ktr_header.ktr_time);
325 req->ktr_header.ktr_pid = p->p_pid;
326 req->ktr_header.ktr_tid = td->td_tid;
327 bcopy(td->td_name, req->ktr_header.ktr_comm,
328 sizeof(req->ktr_header.ktr_comm));
329 req->ktr_buffer = NULL;
330 req->ktr_header.ktr_len = 0;
332 p->p_traceflag |= KTRFAC_DROP;
335 mtx_unlock(&ktrace_mtx);
337 printf("Out of ktrace request objects.\n");
342 static struct ktr_request *
343 ktr_getrequest(int type)
345 struct thread *td = curthread;
346 struct ktr_request *req;
349 req = ktr_getrequest_entered(td, type);
357 * Some trace generation environments don't permit direct access to VFS,
358 * such as during a context switch where sleeping is not allowed. Under these
359 * circumstances, queue a request to the thread to be written asynchronously
363 ktr_enqueuerequest(struct thread *td, struct ktr_request *req)
366 mtx_lock(&ktrace_mtx);
367 STAILQ_INSERT_TAIL(&td->td_proc->p_ktr, req, ktr_list);
368 mtx_unlock(&ktrace_mtx);
370 td->td_flags |= TDF_ASTPENDING;
375 * Drain any pending ktrace records from the per-thread queue to disk. This
376 * is used both internally before committing other records, and also on
377 * system call return. We drain all the ones we can find at the time when
378 * drain is requested, but don't keep draining after that as those events
379 * may be approximately "after" the current event.
382 ktr_drain(struct thread *td)
384 struct ktr_request *queued_req;
385 STAILQ_HEAD(, ktr_request) local_queue;
388 sx_assert(&ktrace_sx, SX_XLOCKED);
390 STAILQ_INIT(&local_queue);
392 if (!STAILQ_EMPTY(&td->td_proc->p_ktr)) {
393 mtx_lock(&ktrace_mtx);
394 STAILQ_CONCAT(&local_queue, &td->td_proc->p_ktr);
395 mtx_unlock(&ktrace_mtx);
397 while ((queued_req = STAILQ_FIRST(&local_queue))) {
398 STAILQ_REMOVE_HEAD(&local_queue, ktr_list);
399 ktr_writerequest(td, queued_req);
400 ktr_freerequest(queued_req);
406 * Submit a trace record for immediate commit to disk -- to be used only
407 * where entering VFS is OK. First drain any pending records that may have
408 * been cached in the thread.
411 ktr_submitrequest(struct thread *td, struct ktr_request *req)
416 sx_xlock(&ktrace_sx);
418 ktr_writerequest(td, req);
419 ktr_freerequest(req);
420 sx_xunlock(&ktrace_sx);
425 ktr_freerequest(struct ktr_request *req)
428 mtx_lock(&ktrace_mtx);
429 ktr_freerequest_locked(req);
430 mtx_unlock(&ktrace_mtx);
434 ktr_freerequest_locked(struct ktr_request *req)
437 mtx_assert(&ktrace_mtx, MA_OWNED);
438 if (req->ktr_buffer != NULL)
439 free(req->ktr_buffer, M_KTRACE);
440 STAILQ_INSERT_HEAD(&ktr_free, req, ktr_list);
444 ktr_io_params_ref(struct ktr_io_params *kiop)
446 mtx_assert(&ktrace_mtx, MA_OWNED);
450 static struct ktr_io_params *
451 ktr_io_params_rele(struct ktr_io_params *kiop)
453 mtx_assert(&ktrace_mtx, MA_OWNED);
456 KASSERT(kiop->refs > 0, ("kiop ref == 0 %p", kiop));
457 return (--(kiop->refs) == 0 ? kiop : NULL);
461 ktr_io_params_free(struct ktr_io_params *kiop)
466 MPASS(kiop->refs == 0);
467 vn_close(kiop->vp, FWRITE, kiop->cr, curthread);
469 free(kiop, M_KTRACE);
472 static struct ktr_io_params *
473 ktr_io_params_alloc(struct thread *td, struct vnode *vp)
475 struct ktr_io_params *res;
477 res = malloc(sizeof(struct ktr_io_params), M_KTRACE, M_WAITOK);
479 res->cr = crhold(td->td_ucred);
480 res->lim = lim_cur(td, RLIMIT_FSIZE);
486 * Disable tracing for a process and release all associated resources.
487 * The caller is responsible for releasing a reference on the returned
488 * vnode and credentials.
490 static struct ktr_io_params *
491 ktr_freeproc(struct proc *p)
493 struct ktr_io_params *kiop;
494 struct ktr_request *req;
496 PROC_LOCK_ASSERT(p, MA_OWNED);
497 mtx_assert(&ktrace_mtx, MA_OWNED);
498 kiop = ktr_io_params_rele(p->p_ktrioparms);
499 p->p_ktrioparms = NULL;
501 while ((req = STAILQ_FIRST(&p->p_ktr)) != NULL) {
502 STAILQ_REMOVE_HEAD(&p->p_ktr, ktr_list);
503 ktr_freerequest_locked(req);
509 ktr_get_tracevp(struct proc *p, bool ref)
513 PROC_LOCK_ASSERT(p, MA_OWNED);
515 if (p->p_ktrioparms != NULL) {
516 vp = p->p_ktrioparms->vp;
526 ktrsyscall(int code, int narg, register_t args[])
528 struct ktr_request *req;
529 struct ktr_syscall *ktp;
533 if (__predict_false(curthread->td_pflags & TDP_INKTRACE))
536 buflen = sizeof(register_t) * narg;
538 buf = malloc(buflen, M_KTRACE, M_WAITOK);
539 bcopy(args, buf, buflen);
541 req = ktr_getrequest(KTR_SYSCALL);
547 ktp = &req->ktr_data.ktr_syscall;
548 ktp->ktr_code = code;
549 ktp->ktr_narg = narg;
551 req->ktr_header.ktr_len = buflen;
552 req->ktr_buffer = buf;
554 ktr_submitrequest(curthread, req);
558 ktrsysret(int code, int error, register_t retval)
560 struct ktr_request *req;
561 struct ktr_sysret *ktp;
563 if (__predict_false(curthread->td_pflags & TDP_INKTRACE))
566 req = ktr_getrequest(KTR_SYSRET);
569 ktp = &req->ktr_data.ktr_sysret;
570 ktp->ktr_code = code;
571 ktp->ktr_error = error;
572 ktp->ktr_retval = ((error == 0) ? retval: 0); /* what about val2 ? */
573 ktr_submitrequest(curthread, req);
577 * When a setuid process execs, disable tracing.
579 * XXX: We toss any pending asynchronous records.
581 struct ktr_io_params *
582 ktrprocexec(struct proc *p)
584 struct ktr_io_params *kiop;
586 PROC_LOCK_ASSERT(p, MA_OWNED);
588 kiop = p->p_ktrioparms;
589 if (kiop == NULL || priv_check_cred(kiop->cr, PRIV_DEBUG_DIFFCRED))
592 mtx_lock(&ktrace_mtx);
593 kiop = ktr_freeproc(p);
594 mtx_unlock(&ktrace_mtx);
599 * When a process exits, drain per-process asynchronous trace records
600 * and disable tracing.
603 ktrprocexit(struct thread *td)
605 struct ktr_request *req;
607 struct ktr_io_params *kiop;
610 if (p->p_traceflag == 0)
614 req = ktr_getrequest_entered(td, KTR_PROCDTOR);
616 ktr_enqueuerequest(td, req);
617 sx_xlock(&ktrace_sx);
619 sx_xunlock(&ktrace_sx);
621 mtx_lock(&ktrace_mtx);
622 kiop = ktr_freeproc(p);
623 mtx_unlock(&ktrace_mtx);
625 ktr_io_params_free(kiop);
630 ktrprocctor_entered(struct thread *td, struct proc *p)
632 struct ktr_proc_ctor *ktp;
633 struct ktr_request *req;
637 td2 = FIRST_THREAD_IN_PROC(p);
638 req = ktr_getrequest_entered(td2, KTR_PROCCTOR);
641 ktp = &req->ktr_data.ktr_proc_ctor;
642 ktp->sv_flags = p->p_sysent->sv_flags;
643 ktr_enqueuerequest(td2, req);
647 ktrprocctor(struct proc *p)
649 struct thread *td = curthread;
651 if ((p->p_traceflag & KTRFAC_MASK) == 0)
655 ktrprocctor_entered(td, p);
660 * When a process forks, enable tracing in the new process if needed.
663 ktrprocfork(struct proc *p1, struct proc *p2)
666 MPASS(p2->p_ktrioparms == NULL);
667 MPASS(p2->p_traceflag == 0);
669 if (p1->p_traceflag == 0)
673 mtx_lock(&ktrace_mtx);
674 if (p1->p_traceflag & KTRFAC_INHERIT) {
675 p2->p_traceflag = p1->p_traceflag;
676 if ((p2->p_ktrioparms = p1->p_ktrioparms) != NULL)
677 p1->p_ktrioparms->refs++;
679 mtx_unlock(&ktrace_mtx);
686 * When a thread returns, drain any asynchronous records generated by the
690 ktruserret(struct thread *td)
694 sx_xlock(&ktrace_sx);
696 sx_xunlock(&ktrace_sx);
704 struct ktr_request *req;
708 namelen = strlen(path);
710 buf = malloc(namelen, M_KTRACE, M_WAITOK);
711 bcopy(path, buf, namelen);
713 req = ktr_getrequest(KTR_NAMEI);
720 req->ktr_header.ktr_len = namelen;
721 req->ktr_buffer = buf;
723 ktr_submitrequest(curthread, req);
727 ktrsysctl(int *name, u_int namelen)
729 struct ktr_request *req;
730 u_int mib[CTL_MAXNAME + 2];
735 /* Lookup name of mib. */
736 KASSERT(namelen <= CTL_MAXNAME, ("sysctl MIB too long"));
739 bcopy(name, mib + 2, namelen * sizeof(*name));
741 mibname = malloc(mibnamelen, M_KTRACE, M_WAITOK);
742 error = kernel_sysctl(curthread, mib, namelen + 2, mibname, &mibnamelen,
743 NULL, 0, &mibnamelen, 0);
745 free(mibname, M_KTRACE);
748 req = ktr_getrequest(KTR_SYSCTL);
750 free(mibname, M_KTRACE);
753 req->ktr_header.ktr_len = mibnamelen;
754 req->ktr_buffer = mibname;
755 ktr_submitrequest(curthread, req);
759 ktrgenio(int fd, enum uio_rw rw, struct uio *uio, int error)
761 struct ktr_request *req;
762 struct ktr_genio *ktg;
771 uio->uio_rw = UIO_WRITE;
772 datalen = MIN(uio->uio_resid, ktr_geniosize);
773 buf = malloc(datalen, M_KTRACE, M_WAITOK);
774 error = uiomove(buf, datalen, uio);
780 req = ktr_getrequest(KTR_GENIO);
785 ktg = &req->ktr_data.ktr_genio;
788 req->ktr_header.ktr_len = datalen;
789 req->ktr_buffer = buf;
790 ktr_submitrequest(curthread, req);
794 ktrpsig(int sig, sig_t action, sigset_t *mask, int code)
796 struct thread *td = curthread;
797 struct ktr_request *req;
800 req = ktr_getrequest(KTR_PSIG);
803 kp = &req->ktr_data.ktr_psig;
804 kp->signo = (char)sig;
808 ktr_enqueuerequest(td, req);
813 ktrcsw(int out, int user, const char *wmesg)
815 struct thread *td = curthread;
816 struct ktr_request *req;
819 if (__predict_false(curthread->td_pflags & TDP_INKTRACE))
822 req = ktr_getrequest(KTR_CSW);
825 kc = &req->ktr_data.ktr_csw;
829 strlcpy(kc->wmesg, wmesg, sizeof(kc->wmesg));
831 bzero(kc->wmesg, sizeof(kc->wmesg));
832 ktr_enqueuerequest(td, req);
837 ktrstruct(const char *name, const void *data, size_t datalen)
839 struct ktr_request *req;
841 size_t buflen, namelen;
843 if (__predict_false(curthread->td_pflags & TDP_INKTRACE))
848 namelen = strlen(name) + 1;
849 buflen = namelen + datalen;
850 buf = malloc(buflen, M_KTRACE, M_WAITOK);
852 bcopy(data, buf + namelen, datalen);
853 if ((req = ktr_getrequest(KTR_STRUCT)) == NULL) {
857 req->ktr_buffer = buf;
858 req->ktr_header.ktr_len = buflen;
859 ktr_submitrequest(curthread, req);
863 ktrstruct_error(const char *name, const void *data, size_t datalen, int error)
867 ktrstruct(name, data, datalen);
871 ktrstructarray(const char *name, enum uio_seg seg, const void *data,
872 int num_items, size_t struct_size)
874 struct ktr_request *req;
875 struct ktr_struct_array *ksa;
877 size_t buflen, datalen, namelen;
880 if (__predict_false(curthread->td_pflags & TDP_INKTRACE))
885 /* Trim array length to genio size. */
886 max_items = ktr_geniosize / struct_size;
887 if (num_items > max_items) {
891 num_items = max_items;
893 datalen = num_items * struct_size;
898 namelen = strlen(name) + 1;
899 buflen = namelen + datalen;
900 buf = malloc(buflen, M_KTRACE, M_WAITOK);
902 if (seg == UIO_SYSSPACE)
903 bcopy(data, buf + namelen, datalen);
905 if (copyin(data, buf + namelen, datalen) != 0) {
910 if ((req = ktr_getrequest(KTR_STRUCT_ARRAY)) == NULL) {
914 ksa = &req->ktr_data.ktr_struct_array;
915 ksa->struct_size = struct_size;
916 req->ktr_buffer = buf;
917 req->ktr_header.ktr_len = buflen;
918 ktr_submitrequest(curthread, req);
922 ktrcapfail(enum ktr_cap_fail_type type, const cap_rights_t *needed,
923 const cap_rights_t *held)
925 struct thread *td = curthread;
926 struct ktr_request *req;
927 struct ktr_cap_fail *kcf;
929 if (__predict_false(curthread->td_pflags & TDP_INKTRACE))
932 req = ktr_getrequest(KTR_CAPFAIL);
935 kcf = &req->ktr_data.ktr_cap_fail;
936 kcf->cap_type = type;
938 kcf->cap_needed = *needed;
940 cap_rights_init(&kcf->cap_needed);
942 kcf->cap_held = *held;
944 cap_rights_init(&kcf->cap_held);
945 ktr_enqueuerequest(td, req);
950 ktrfault(vm_offset_t vaddr, int type)
952 struct thread *td = curthread;
953 struct ktr_request *req;
954 struct ktr_fault *kf;
956 if (__predict_false(curthread->td_pflags & TDP_INKTRACE))
959 req = ktr_getrequest(KTR_FAULT);
962 kf = &req->ktr_data.ktr_fault;
965 ktr_enqueuerequest(td, req);
970 ktrfaultend(int result)
972 struct thread *td = curthread;
973 struct ktr_request *req;
974 struct ktr_faultend *kf;
976 if (__predict_false(curthread->td_pflags & TDP_INKTRACE))
979 req = ktr_getrequest(KTR_FAULTEND);
982 kf = &req->ktr_data.ktr_faultend;
984 ktr_enqueuerequest(td, req);
989 /* Interface and common routines */
991 #ifndef _SYS_SYSPROTO_H_
1001 sys_ktrace(struct thread *td, struct ktrace_args *uap)
1004 struct vnode *vp = NULL;
1007 int facs = uap->facs & ~KTRFAC_ROOT;
1008 int ops = KTROP(uap->ops);
1009 int descend = uap->ops & KTRFLAG_DESCEND;
1010 int nfound, ret = 0;
1011 int flags, error = 0;
1012 struct nameidata nd;
1013 struct ktr_io_params *kiop, *old_kiop;
1016 * Need something to (un)trace.
1018 if (ops != KTROP_CLEARFILE && facs == 0)
1023 if (ops != KTROP_CLEAR) {
1025 * an operation which requires a file argument.
1027 NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_USERSPACE, uap->fname, td);
1028 flags = FREAD | FWRITE | O_NOFOLLOW;
1029 error = vn_open(&nd, &flags, 0, NULL);
1034 NDFREE(&nd, NDF_ONLY_PNBUF);
1037 if (vp->v_type != VREG) {
1038 (void) vn_close(vp, FREAD|FWRITE, td->td_ucred, td);
1042 kiop = ktr_io_params_alloc(td, vp);
1045 * Clear all uses of the tracefile.
1047 if (ops == KTROP_CLEARFILE) {
1049 sx_slock(&allproc_lock);
1050 FOREACH_PROC_IN_SYSTEM(p) {
1053 if (p->p_ktrioparms != NULL &&
1054 p->p_ktrioparms->vp == vp) {
1055 if (ktrcanset(td, p)) {
1056 mtx_lock(&ktrace_mtx);
1057 old_kiop = ktr_freeproc(p);
1058 mtx_unlock(&ktrace_mtx);
1063 if (old_kiop != NULL) {
1064 sx_sunlock(&allproc_lock);
1065 ktr_io_params_free(old_kiop);
1069 sx_sunlock(&allproc_lock);
1075 sx_slock(&proctree_lock);
1080 pg = pgfind(-uap->pid);
1082 sx_sunlock(&proctree_lock);
1087 * ktrops() may call vrele(). Lock pg_members
1088 * by the proctree_lock rather than pg_mtx.
1092 LIST_FOREACH(p, &pg->pg_members, p_pglist) {
1094 if (p->p_state == PRS_NEW ||
1095 p_cansee(td, p) != 0) {
1101 ret |= ktrsetchildren(td, p, ops, facs, kiop);
1103 ret |= ktrops(td, p, ops, facs, kiop);
1106 sx_sunlock(&proctree_lock);
1114 p = pfind(uap->pid);
1118 error = p_cansee(td, p);
1122 sx_sunlock(&proctree_lock);
1126 ret |= ktrsetchildren(td, p, ops, facs, kiop);
1128 ret |= ktrops(td, p, ops, facs, kiop);
1130 sx_sunlock(&proctree_lock);
1135 mtx_lock(&ktrace_mtx);
1136 kiop = ktr_io_params_rele(kiop);
1137 mtx_unlock(&ktrace_mtx);
1138 ktr_io_params_free(kiop);
1149 sys_utrace(struct thread *td, struct utrace_args *uap)
1153 struct ktr_request *req;
1157 if (!KTRPOINT(td, KTR_USER))
1159 if (uap->len > KTR_USER_MAXLEN)
1161 cp = malloc(uap->len, M_KTRACE, M_WAITOK);
1162 error = copyin(uap->addr, cp, uap->len);
1167 req = ktr_getrequest(KTR_USER);
1172 req->ktr_buffer = cp;
1173 req->ktr_header.ktr_len = uap->len;
1174 ktr_submitrequest(td, req);
1183 ktrops(struct thread *td, struct proc *p, int ops, int facs,
1184 struct ktr_io_params *new_kiop)
1186 struct ktr_io_params *old_kiop;
1188 PROC_LOCK_ASSERT(p, MA_OWNED);
1189 if (!ktrcanset(td, p)) {
1193 if (p->p_flag & P_WEXIT) {
1194 /* If the process is exiting, just ignore it. */
1199 mtx_lock(&ktrace_mtx);
1200 if (ops == KTROP_SET) {
1201 if (p->p_ktrioparms != NULL &&
1202 p->p_ktrioparms->vp != new_kiop->vp) {
1203 /* if trace file already in use, relinquish below */
1204 old_kiop = ktr_io_params_rele(p->p_ktrioparms);
1205 p->p_ktrioparms = NULL;
1207 if (p->p_ktrioparms == NULL) {
1208 p->p_ktrioparms = new_kiop;
1209 ktr_io_params_ref(new_kiop);
1211 p->p_traceflag |= facs;
1212 if (priv_check(td, PRIV_KTRACE) == 0)
1213 p->p_traceflag |= KTRFAC_ROOT;
1216 if (((p->p_traceflag &= ~facs) & KTRFAC_MASK) == 0)
1217 /* no more tracing */
1218 old_kiop = ktr_freeproc(p);
1220 mtx_unlock(&ktrace_mtx);
1221 if ((p->p_traceflag & KTRFAC_MASK) != 0)
1222 ktrprocctor_entered(td, p);
1224 ktr_io_params_free(old_kiop);
1230 ktrsetchildren(struct thread *td, struct proc *top, int ops, int facs,
1231 struct ktr_io_params *new_kiop)
1237 PROC_LOCK_ASSERT(p, MA_OWNED);
1238 sx_assert(&proctree_lock, SX_LOCKED);
1240 ret |= ktrops(td, p, ops, facs, new_kiop);
1242 * If this process has children, descend to them next,
1243 * otherwise do any siblings, and if done with this level,
1244 * follow back up the tree (but not past top).
1246 if (!LIST_EMPTY(&p->p_children))
1247 p = LIST_FIRST(&p->p_children);
1251 if (LIST_NEXT(p, p_sibling)) {
1252 p = LIST_NEXT(p, p_sibling);
1263 ktr_writerequest(struct thread *td, struct ktr_request *req)
1265 struct ktr_io_params *kiop, *kiop1;
1266 struct ktr_header *kth;
1271 struct iovec aiov[3];
1274 int datalen, buflen;
1280 * We reference the kiop for use in I/O in case ktrace is
1281 * disabled on the process as we write out the request.
1283 mtx_lock(&ktrace_mtx);
1284 kiop = p->p_ktrioparms;
1287 * If kiop is NULL, it has been cleared out from under this
1288 * request, so just drop it.
1291 mtx_unlock(&ktrace_mtx);
1295 ktr_io_params_ref(kiop);
1300 KASSERT(cred != NULL, ("ktr_writerequest: cred == NULL"));
1301 mtx_unlock(&ktrace_mtx);
1303 kth = &req->ktr_header;
1304 KASSERT(((u_short)kth->ktr_type & ~KTR_DROP) < nitems(data_lengths),
1305 ("data_lengths array overflow"));
1306 datalen = data_lengths[(u_short)kth->ktr_type & ~KTR_DROP];
1307 buflen = kth->ktr_len;
1308 auio.uio_iov = &aiov[0];
1309 auio.uio_offset = 0;
1310 auio.uio_segflg = UIO_SYSSPACE;
1311 auio.uio_rw = UIO_WRITE;
1312 aiov[0].iov_base = (caddr_t)kth;
1313 aiov[0].iov_len = sizeof(struct ktr_header);
1314 auio.uio_resid = sizeof(struct ktr_header);
1315 auio.uio_iovcnt = 1;
1318 aiov[1].iov_base = (caddr_t)&req->ktr_data;
1319 aiov[1].iov_len = datalen;
1320 auio.uio_resid += datalen;
1322 kth->ktr_len += datalen;
1325 KASSERT(req->ktr_buffer != NULL, ("ktrace: nothing to write"));
1326 aiov[auio.uio_iovcnt].iov_base = req->ktr_buffer;
1327 aiov[auio.uio_iovcnt].iov_len = buflen;
1328 auio.uio_resid += buflen;
1332 vn_start_write(vp, &mp, V_WAIT);
1333 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1334 td->td_ktr_io_lim = lim;
1336 error = mac_vnode_check_write(cred, NOCRED, vp);
1339 error = VOP_WRITE(vp, &auio, IO_UNIT | IO_APPEND, cred);
1341 vn_finished_write(mp);
1343 mtx_lock(&ktrace_mtx);
1344 kiop = ktr_io_params_rele(kiop);
1345 mtx_unlock(&ktrace_mtx);
1346 ktr_io_params_free(kiop);
1351 * If error encountered, give up tracing on this vnode on this
1352 * process. Other processes might still be suitable for
1353 * writes to this vnode.
1356 "ktrace write failed, errno %d, tracing stopped for pid %d\n",
1361 mtx_lock(&ktrace_mtx);
1362 if (p->p_ktrioparms != NULL && p->p_ktrioparms->vp == vp)
1363 kiop1 = ktr_freeproc(p);
1364 kiop = ktr_io_params_rele(kiop);
1365 mtx_unlock(&ktrace_mtx);
1367 ktr_io_params_free(kiop1);
1368 ktr_io_params_free(kiop);
1372 * Return true if caller has permission to set the ktracing state
1373 * of target. Essentially, the target can't possess any
1374 * more permissions than the caller. KTRFAC_ROOT signifies that
1375 * root previously set the tracing status on the target process, and
1376 * so, only root may further change it.
1379 ktrcanset(struct thread *td, struct proc *targetp)
1382 PROC_LOCK_ASSERT(targetp, MA_OWNED);
1383 if (targetp->p_traceflag & KTRFAC_ROOT &&
1384 priv_check(td, PRIV_KTRACE))
1387 if (p_candebug(td, targetp) != 0)