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
34 #include <sys/cdefs.h>
35 #include "opt_ktrace.h"
37 #include <sys/param.h>
38 #include <sys/capsicum.h>
39 #include <sys/systm.h>
40 #include <sys/fcntl.h>
41 #include <sys/kernel.h>
42 #include <sys/kthread.h>
44 #include <sys/mutex.h>
45 #include <sys/malloc.h>
46 #include <sys/mount.h>
47 #include <sys/namei.h>
50 #include <sys/resourcevar.h>
51 #include <sys/unistd.h>
52 #include <sys/vnode.h>
53 #include <sys/socket.h>
55 #include <sys/ktrace.h>
57 #include <sys/sysctl.h>
58 #include <sys/sysent.h>
59 #include <sys/syslog.h>
60 #include <sys/sysproto.h>
62 #include <security/mac/mac_framework.h>
65 * The ktrace facility allows the tracing of certain key events in user space
66 * processes, such as system calls, signal delivery, context switches, and
67 * user generated events using utrace(2). It works by streaming event
68 * records and data to a vnode associated with the process using the
69 * ktrace(2) system call. In general, records can be written directly from
70 * the context that generates the event. One important exception to this is
71 * during a context switch, where sleeping is not permitted. To handle this
72 * case, trace events are generated using in-kernel ktr_request records, and
73 * then delivered to disk at a convenient moment -- either immediately, the
74 * next traceable event, at system call return, or at process exit.
76 * When dealing with multiple threads or processes writing to the same event
77 * log, ordering guarantees are weak: specifically, if an event has multiple
78 * records (i.e., system call enter and return), they may be interlaced with
79 * records from another event. Process and thread ID information is provided
80 * in the record, and user applications can de-interlace events if required.
83 static MALLOC_DEFINE(M_KTRACE, "KTRACE", "KTRACE");
87 FEATURE(ktrace, "Kernel support for system-call tracing");
89 #ifndef KTRACE_REQUEST_POOL
90 #define KTRACE_REQUEST_POOL 100
94 struct ktr_header ktr_header;
97 struct ktr_proc_ctor ktr_proc_ctor;
98 struct ktr_cap_fail ktr_cap_fail;
99 struct ktr_syscall ktr_syscall;
100 struct ktr_sysret ktr_sysret;
101 struct ktr_genio ktr_genio;
102 struct ktr_psig ktr_psig;
103 struct ktr_csw ktr_csw;
104 struct ktr_fault ktr_fault;
105 struct ktr_faultend ktr_faultend;
106 struct ktr_struct_array ktr_struct_array;
108 STAILQ_ENTRY(ktr_request) ktr_list;
111 static const int data_lengths[] = {
112 [KTR_SYSCALL] = offsetof(struct ktr_syscall, ktr_args),
113 [KTR_SYSRET] = sizeof(struct ktr_sysret),
115 [KTR_GENIO] = sizeof(struct ktr_genio),
116 [KTR_PSIG] = sizeof(struct ktr_psig),
117 [KTR_CSW] = sizeof(struct ktr_csw),
121 [KTR_PROCCTOR] = sizeof(struct ktr_proc_ctor),
123 [KTR_CAPFAIL] = sizeof(struct ktr_cap_fail),
124 [KTR_FAULT] = sizeof(struct ktr_fault),
125 [KTR_FAULTEND] = sizeof(struct ktr_faultend),
126 [KTR_STRUCT_ARRAY] = sizeof(struct ktr_struct_array),
129 static STAILQ_HEAD(, ktr_request) ktr_free;
131 static SYSCTL_NODE(_kern, OID_AUTO, ktrace, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
134 static u_int ktr_requestpool = KTRACE_REQUEST_POOL;
135 TUNABLE_INT("kern.ktrace.request_pool", &ktr_requestpool);
137 u_int ktr_geniosize = PAGE_SIZE;
138 SYSCTL_UINT(_kern_ktrace, OID_AUTO, genio_size, CTLFLAG_RWTUN, &ktr_geniosize,
139 0, "Maximum size of genio event payload");
142 * Allow to not to send signal to traced process, in which context the
143 * ktr record is written. The limit is applied from the process that
144 * set up ktrace, so killing the traced process is not completely fair.
146 int ktr_filesize_limit_signal = 0;
147 SYSCTL_INT(_kern_ktrace, OID_AUTO, filesize_limit_signal, CTLFLAG_RWTUN,
148 &ktr_filesize_limit_signal, 0,
149 "Send SIGXFSZ to the traced process when the log size limit is exceeded");
151 static int print_message = 1;
152 static struct mtx ktrace_mtx;
153 static struct sx ktrace_sx;
155 struct ktr_io_params {
162 static void ktrace_init(void *dummy);
163 static int sysctl_kern_ktrace_request_pool(SYSCTL_HANDLER_ARGS);
164 static u_int ktrace_resize_pool(u_int oldsize, u_int newsize);
165 static struct ktr_request *ktr_getrequest_entered(struct thread *td, int type);
166 static struct ktr_request *ktr_getrequest(int type);
167 static void ktr_submitrequest(struct thread *td, struct ktr_request *req);
168 static struct ktr_io_params *ktr_freeproc(struct proc *p);
169 static void ktr_freerequest(struct ktr_request *req);
170 static void ktr_freerequest_locked(struct ktr_request *req);
171 static void ktr_writerequest(struct thread *td, struct ktr_request *req);
172 static int ktrcanset(struct thread *,struct proc *);
173 static int ktrsetchildren(struct thread *, struct proc *, int, int,
174 struct ktr_io_params *);
175 static int ktrops(struct thread *, struct proc *, int, int,
176 struct ktr_io_params *);
177 static void ktrprocctor_entered(struct thread *, struct proc *);
180 * ktrace itself generates events, such as context switches, which we do not
181 * wish to trace. Maintain a flag, TDP_INKTRACE, on each thread to determine
182 * whether or not it is in a region where tracing of events should be
186 ktrace_enter(struct thread *td)
189 KASSERT(!(td->td_pflags & TDP_INKTRACE), ("ktrace_enter: flag set"));
190 td->td_pflags |= TDP_INKTRACE;
194 ktrace_exit(struct thread *td)
197 KASSERT(td->td_pflags & TDP_INKTRACE, ("ktrace_exit: flag not set"));
198 td->td_pflags &= ~TDP_INKTRACE;
202 ktrace_assert(struct thread *td)
205 KASSERT(td->td_pflags & TDP_INKTRACE, ("ktrace_assert: flag not set"));
209 ast_ktrace(struct thread *td, int tda __unused)
215 ktrace_init(void *dummy)
217 struct ktr_request *req;
220 mtx_init(&ktrace_mtx, "ktrace", NULL, MTX_DEF | MTX_QUIET);
221 sx_init(&ktrace_sx, "ktrace_sx");
222 STAILQ_INIT(&ktr_free);
223 for (i = 0; i < ktr_requestpool; i++) {
224 req = malloc(sizeof(struct ktr_request), M_KTRACE, M_WAITOK |
226 STAILQ_INSERT_HEAD(&ktr_free, req, ktr_list);
228 ast_register(TDA_KTRACE, ASTR_ASTF_REQUIRED, 0, ast_ktrace);
230 SYSINIT(ktrace_init, SI_SUB_KTRACE, SI_ORDER_ANY, ktrace_init, NULL);
233 sysctl_kern_ktrace_request_pool(SYSCTL_HANDLER_ARGS)
236 u_int newsize, oldsize, wantsize;
239 /* Handle easy read-only case first to avoid warnings from GCC. */
241 oldsize = ktr_requestpool;
242 return (SYSCTL_OUT(req, &oldsize, sizeof(u_int)));
245 error = SYSCTL_IN(req, &wantsize, sizeof(u_int));
250 oldsize = ktr_requestpool;
251 newsize = ktrace_resize_pool(oldsize, wantsize);
253 error = SYSCTL_OUT(req, &oldsize, sizeof(u_int));
256 if (wantsize > oldsize && newsize < wantsize)
260 SYSCTL_PROC(_kern_ktrace, OID_AUTO, request_pool,
261 CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_NEEDGIANT, &ktr_requestpool, 0,
262 sysctl_kern_ktrace_request_pool, "IU",
263 "Pool buffer size for ktrace(1)");
266 ktrace_resize_pool(u_int oldsize, u_int newsize)
268 STAILQ_HEAD(, ktr_request) ktr_new;
269 struct ktr_request *req;
273 bound = newsize - oldsize;
275 return (ktr_requestpool);
277 mtx_lock(&ktrace_mtx);
278 /* Shrink pool down to newsize if possible. */
279 while (bound++ < 0) {
280 req = STAILQ_FIRST(&ktr_free);
283 STAILQ_REMOVE_HEAD(&ktr_free, ktr_list);
288 /* Grow pool up to newsize. */
289 STAILQ_INIT(&ktr_new);
290 while (bound-- > 0) {
291 req = malloc(sizeof(struct ktr_request), M_KTRACE,
293 STAILQ_INSERT_HEAD(&ktr_new, req, ktr_list);
295 mtx_lock(&ktrace_mtx);
296 STAILQ_CONCAT(&ktr_free, &ktr_new);
297 ktr_requestpool += (newsize - oldsize);
299 mtx_unlock(&ktrace_mtx);
300 return (ktr_requestpool);
303 /* ktr_getrequest() assumes that ktr_comm[] is the same size as td_name[]. */
304 CTASSERT(sizeof(((struct ktr_header *)NULL)->ktr_comm) ==
305 (sizeof((struct thread *)NULL)->td_name));
307 static struct ktr_request *
308 ktr_getrequest_entered(struct thread *td, int type)
310 struct ktr_request *req;
311 struct proc *p = td->td_proc;
314 mtx_lock(&ktrace_mtx);
315 if (!KTRCHECK(td, type)) {
316 mtx_unlock(&ktrace_mtx);
319 req = STAILQ_FIRST(&ktr_free);
321 STAILQ_REMOVE_HEAD(&ktr_free, ktr_list);
322 req->ktr_header.ktr_type = type;
323 if (p->p_traceflag & KTRFAC_DROP) {
324 req->ktr_header.ktr_type |= KTR_DROP;
325 p->p_traceflag &= ~KTRFAC_DROP;
327 mtx_unlock(&ktrace_mtx);
328 nanotime(&req->ktr_header.ktr_time);
329 req->ktr_header.ktr_type |= KTR_VERSIONED;
330 req->ktr_header.ktr_pid = p->p_pid;
331 req->ktr_header.ktr_tid = td->td_tid;
332 req->ktr_header.ktr_cpu = PCPU_GET(cpuid);
333 req->ktr_header.ktr_version = KTR_VERSION1;
334 bcopy(td->td_name, req->ktr_header.ktr_comm,
335 sizeof(req->ktr_header.ktr_comm));
336 req->ktr_buffer = NULL;
337 req->ktr_header.ktr_len = 0;
339 p->p_traceflag |= KTRFAC_DROP;
342 mtx_unlock(&ktrace_mtx);
344 printf("Out of ktrace request objects.\n");
349 static struct ktr_request *
350 ktr_getrequest(int type)
352 struct thread *td = curthread;
353 struct ktr_request *req;
356 req = ktr_getrequest_entered(td, type);
364 * Some trace generation environments don't permit direct access to VFS,
365 * such as during a context switch where sleeping is not allowed. Under these
366 * circumstances, queue a request to the thread to be written asynchronously
370 ktr_enqueuerequest(struct thread *td, struct ktr_request *req)
373 mtx_lock(&ktrace_mtx);
374 STAILQ_INSERT_TAIL(&td->td_proc->p_ktr, req, ktr_list);
375 mtx_unlock(&ktrace_mtx);
376 ast_sched(td, TDA_KTRACE);
380 * Drain any pending ktrace records from the per-thread queue to disk. This
381 * is used both internally before committing other records, and also on
382 * system call return. We drain all the ones we can find at the time when
383 * drain is requested, but don't keep draining after that as those events
384 * may be approximately "after" the current event.
387 ktr_drain(struct thread *td)
389 struct ktr_request *queued_req;
390 STAILQ_HEAD(, ktr_request) local_queue;
393 sx_assert(&ktrace_sx, SX_XLOCKED);
395 STAILQ_INIT(&local_queue);
397 if (!STAILQ_EMPTY(&td->td_proc->p_ktr)) {
398 mtx_lock(&ktrace_mtx);
399 STAILQ_CONCAT(&local_queue, &td->td_proc->p_ktr);
400 mtx_unlock(&ktrace_mtx);
402 while ((queued_req = STAILQ_FIRST(&local_queue))) {
403 STAILQ_REMOVE_HEAD(&local_queue, ktr_list);
404 ktr_writerequest(td, queued_req);
405 ktr_freerequest(queued_req);
411 * Submit a trace record for immediate commit to disk -- to be used only
412 * where entering VFS is OK. First drain any pending records that may have
413 * been cached in the thread.
416 ktr_submitrequest(struct thread *td, struct ktr_request *req)
421 sx_xlock(&ktrace_sx);
423 ktr_writerequest(td, req);
424 ktr_freerequest(req);
425 sx_xunlock(&ktrace_sx);
430 ktr_freerequest(struct ktr_request *req)
433 mtx_lock(&ktrace_mtx);
434 ktr_freerequest_locked(req);
435 mtx_unlock(&ktrace_mtx);
439 ktr_freerequest_locked(struct ktr_request *req)
442 mtx_assert(&ktrace_mtx, MA_OWNED);
443 if (req->ktr_buffer != NULL)
444 free(req->ktr_buffer, M_KTRACE);
445 STAILQ_INSERT_HEAD(&ktr_free, req, ktr_list);
449 ktr_io_params_ref(struct ktr_io_params *kiop)
451 mtx_assert(&ktrace_mtx, MA_OWNED);
455 static struct ktr_io_params *
456 ktr_io_params_rele(struct ktr_io_params *kiop)
458 mtx_assert(&ktrace_mtx, MA_OWNED);
461 KASSERT(kiop->refs > 0, ("kiop ref == 0 %p", kiop));
462 return (--(kiop->refs) == 0 ? kiop : NULL);
466 ktr_io_params_free(struct ktr_io_params *kiop)
471 MPASS(kiop->refs == 0);
472 vn_close(kiop->vp, FWRITE, kiop->cr, curthread);
474 free(kiop, M_KTRACE);
477 static struct ktr_io_params *
478 ktr_io_params_alloc(struct thread *td, struct vnode *vp)
480 struct ktr_io_params *res;
482 res = malloc(sizeof(struct ktr_io_params), M_KTRACE, M_WAITOK);
484 res->cr = crhold(td->td_ucred);
485 res->lim = lim_cur(td, RLIMIT_FSIZE);
491 * Disable tracing for a process and release all associated resources.
492 * The caller is responsible for releasing a reference on the returned
493 * vnode and credentials.
495 static struct ktr_io_params *
496 ktr_freeproc(struct proc *p)
498 struct ktr_io_params *kiop;
499 struct ktr_request *req;
501 PROC_LOCK_ASSERT(p, MA_OWNED);
502 mtx_assert(&ktrace_mtx, MA_OWNED);
503 kiop = ktr_io_params_rele(p->p_ktrioparms);
504 p->p_ktrioparms = NULL;
506 while ((req = STAILQ_FIRST(&p->p_ktr)) != NULL) {
507 STAILQ_REMOVE_HEAD(&p->p_ktr, ktr_list);
508 ktr_freerequest_locked(req);
514 ktr_get_tracevp(struct proc *p, bool ref)
518 PROC_LOCK_ASSERT(p, MA_OWNED);
520 if (p->p_ktrioparms != NULL) {
521 vp = p->p_ktrioparms->vp;
531 ktrsyscall(int code, int narg, syscallarg_t args[])
533 struct ktr_request *req;
534 struct ktr_syscall *ktp;
538 if (__predict_false(curthread->td_pflags & TDP_INKTRACE))
541 buflen = sizeof(register_t) * narg;
543 buf = malloc(buflen, M_KTRACE, M_WAITOK);
544 bcopy(args, buf, buflen);
546 req = ktr_getrequest(KTR_SYSCALL);
552 ktp = &req->ktr_data.ktr_syscall;
553 ktp->ktr_code = code;
554 ktp->ktr_narg = narg;
556 req->ktr_header.ktr_len = buflen;
557 req->ktr_buffer = buf;
559 ktr_submitrequest(curthread, req);
563 ktrsysret(int code, int error, register_t retval)
565 struct ktr_request *req;
566 struct ktr_sysret *ktp;
568 if (__predict_false(curthread->td_pflags & TDP_INKTRACE))
571 req = ktr_getrequest(KTR_SYSRET);
574 ktp = &req->ktr_data.ktr_sysret;
575 ktp->ktr_code = code;
576 ktp->ktr_error = error;
577 ktp->ktr_retval = ((error == 0) ? retval: 0); /* what about val2 ? */
578 ktr_submitrequest(curthread, req);
582 * When a setuid process execs, disable tracing.
584 * XXX: We toss any pending asynchronous records.
586 struct ktr_io_params *
587 ktrprocexec(struct proc *p)
589 struct ktr_io_params *kiop;
591 PROC_LOCK_ASSERT(p, MA_OWNED);
593 kiop = p->p_ktrioparms;
594 if (kiop == NULL || priv_check_cred(kiop->cr, PRIV_DEBUG_DIFFCRED))
597 mtx_lock(&ktrace_mtx);
598 kiop = ktr_freeproc(p);
599 mtx_unlock(&ktrace_mtx);
604 * When a process exits, drain per-process asynchronous trace records
605 * and disable tracing.
608 ktrprocexit(struct thread *td)
610 struct ktr_request *req;
612 struct ktr_io_params *kiop;
615 if (p->p_traceflag == 0)
619 req = ktr_getrequest_entered(td, KTR_PROCDTOR);
621 ktr_enqueuerequest(td, req);
622 sx_xlock(&ktrace_sx);
624 sx_xunlock(&ktrace_sx);
626 mtx_lock(&ktrace_mtx);
627 kiop = ktr_freeproc(p);
628 mtx_unlock(&ktrace_mtx);
630 ktr_io_params_free(kiop);
635 ktrprocctor_entered(struct thread *td, struct proc *p)
637 struct ktr_proc_ctor *ktp;
638 struct ktr_request *req;
642 td2 = FIRST_THREAD_IN_PROC(p);
643 req = ktr_getrequest_entered(td2, KTR_PROCCTOR);
646 ktp = &req->ktr_data.ktr_proc_ctor;
647 ktp->sv_flags = p->p_sysent->sv_flags;
648 ktr_enqueuerequest(td2, req);
652 ktrprocctor(struct proc *p)
654 struct thread *td = curthread;
656 if ((p->p_traceflag & KTRFAC_MASK) == 0)
660 ktrprocctor_entered(td, p);
665 * When a process forks, enable tracing in the new process if needed.
668 ktrprocfork(struct proc *p1, struct proc *p2)
671 MPASS(p2->p_ktrioparms == NULL);
672 MPASS(p2->p_traceflag == 0);
674 if (p1->p_traceflag == 0)
678 mtx_lock(&ktrace_mtx);
679 if (p1->p_traceflag & KTRFAC_INHERIT) {
680 p2->p_traceflag = p1->p_traceflag;
681 if ((p2->p_ktrioparms = p1->p_ktrioparms) != NULL)
682 p1->p_ktrioparms->refs++;
684 mtx_unlock(&ktrace_mtx);
691 * When a thread returns, drain any asynchronous records generated by the
695 ktruserret(struct thread *td)
699 sx_xlock(&ktrace_sx);
701 sx_xunlock(&ktrace_sx);
706 ktrnamei(const char *path)
708 struct ktr_request *req;
712 namelen = strlen(path);
714 buf = malloc(namelen, M_KTRACE, M_WAITOK);
715 bcopy(path, buf, namelen);
717 req = ktr_getrequest(KTR_NAMEI);
724 req->ktr_header.ktr_len = namelen;
725 req->ktr_buffer = buf;
727 ktr_submitrequest(curthread, req);
731 ktrsysctl(int *name, u_int namelen)
733 struct ktr_request *req;
734 u_int mib[CTL_MAXNAME + 2];
739 /* Lookup name of mib. */
740 KASSERT(namelen <= CTL_MAXNAME, ("sysctl MIB too long"));
743 bcopy(name, mib + 2, namelen * sizeof(*name));
745 mibname = malloc(mibnamelen, M_KTRACE, M_WAITOK);
746 error = kernel_sysctl(curthread, mib, namelen + 2, mibname, &mibnamelen,
747 NULL, 0, &mibnamelen, 0);
749 free(mibname, M_KTRACE);
752 req = ktr_getrequest(KTR_SYSCTL);
754 free(mibname, M_KTRACE);
757 req->ktr_header.ktr_len = mibnamelen;
758 req->ktr_buffer = mibname;
759 ktr_submitrequest(curthread, req);
763 ktrgenio(int fd, enum uio_rw rw, struct uio *uio, int error)
765 struct ktr_request *req;
766 struct ktr_genio *ktg;
770 if (error != 0 && (rw == UIO_READ || error == EFAULT)) {
775 uio->uio_rw = UIO_WRITE;
776 datalen = MIN(uio->uio_resid, ktr_geniosize);
777 buf = malloc(datalen, M_KTRACE, M_WAITOK);
778 error = uiomove(buf, datalen, uio);
784 req = ktr_getrequest(KTR_GENIO);
789 ktg = &req->ktr_data.ktr_genio;
792 req->ktr_header.ktr_len = datalen;
793 req->ktr_buffer = buf;
794 ktr_submitrequest(curthread, req);
798 ktrpsig(int sig, sig_t action, sigset_t *mask, int code)
800 struct thread *td = curthread;
801 struct ktr_request *req;
804 req = ktr_getrequest(KTR_PSIG);
807 kp = &req->ktr_data.ktr_psig;
808 kp->signo = (char)sig;
812 ktr_enqueuerequest(td, req);
817 ktrcsw(int out, int user, const char *wmesg)
819 struct thread *td = curthread;
820 struct ktr_request *req;
823 if (__predict_false(curthread->td_pflags & TDP_INKTRACE))
826 req = ktr_getrequest(KTR_CSW);
829 kc = &req->ktr_data.ktr_csw;
833 strlcpy(kc->wmesg, wmesg, sizeof(kc->wmesg));
835 bzero(kc->wmesg, sizeof(kc->wmesg));
836 ktr_enqueuerequest(td, req);
841 ktrstruct(const char *name, const void *data, size_t datalen)
843 struct ktr_request *req;
845 size_t buflen, namelen;
847 if (__predict_false(curthread->td_pflags & TDP_INKTRACE))
852 namelen = strlen(name) + 1;
853 buflen = namelen + datalen;
854 buf = malloc(buflen, M_KTRACE, M_WAITOK);
856 bcopy(data, buf + namelen, datalen);
857 if ((req = ktr_getrequest(KTR_STRUCT)) == NULL) {
861 req->ktr_buffer = buf;
862 req->ktr_header.ktr_len = buflen;
863 ktr_submitrequest(curthread, req);
867 ktrstruct_error(const char *name, const void *data, size_t datalen, int error)
871 ktrstruct(name, data, datalen);
875 ktrstructarray(const char *name, enum uio_seg seg, const void *data,
876 int num_items, size_t struct_size)
878 struct ktr_request *req;
879 struct ktr_struct_array *ksa;
881 size_t buflen, datalen, namelen;
884 if (__predict_false(curthread->td_pflags & TDP_INKTRACE))
889 /* Trim array length to genio size. */
890 max_items = ktr_geniosize / struct_size;
891 if (num_items > max_items) {
895 num_items = max_items;
897 datalen = num_items * struct_size;
902 namelen = strlen(name) + 1;
903 buflen = namelen + datalen;
904 buf = malloc(buflen, M_KTRACE, M_WAITOK);
906 if (seg == UIO_SYSSPACE)
907 bcopy(data, buf + namelen, datalen);
909 if (copyin(data, buf + namelen, datalen) != 0) {
914 if ((req = ktr_getrequest(KTR_STRUCT_ARRAY)) == NULL) {
918 ksa = &req->ktr_data.ktr_struct_array;
919 ksa->struct_size = struct_size;
920 req->ktr_buffer = buf;
921 req->ktr_header.ktr_len = buflen;
922 ktr_submitrequest(curthread, req);
926 ktrcapfail(enum ktr_cap_fail_type type, const cap_rights_t *needed,
927 const cap_rights_t *held)
929 struct thread *td = curthread;
930 struct ktr_request *req;
931 struct ktr_cap_fail *kcf;
933 if (__predict_false(curthread->td_pflags & TDP_INKTRACE))
936 req = ktr_getrequest(KTR_CAPFAIL);
939 kcf = &req->ktr_data.ktr_cap_fail;
940 kcf->cap_type = type;
942 kcf->cap_needed = *needed;
944 cap_rights_init(&kcf->cap_needed);
946 kcf->cap_held = *held;
948 cap_rights_init(&kcf->cap_held);
949 ktr_enqueuerequest(td, req);
954 ktrfault(vm_offset_t vaddr, int type)
956 struct thread *td = curthread;
957 struct ktr_request *req;
958 struct ktr_fault *kf;
960 if (__predict_false(curthread->td_pflags & TDP_INKTRACE))
963 req = ktr_getrequest(KTR_FAULT);
966 kf = &req->ktr_data.ktr_fault;
969 ktr_enqueuerequest(td, req);
974 ktrfaultend(int result)
976 struct thread *td = curthread;
977 struct ktr_request *req;
978 struct ktr_faultend *kf;
980 if (__predict_false(curthread->td_pflags & TDP_INKTRACE))
983 req = ktr_getrequest(KTR_FAULTEND);
986 kf = &req->ktr_data.ktr_faultend;
988 ktr_enqueuerequest(td, req);
993 /* Interface and common routines */
995 #ifndef _SYS_SYSPROTO_H_
1005 sys_ktrace(struct thread *td, struct ktrace_args *uap)
1008 struct vnode *vp = NULL;
1011 int facs = uap->facs & ~KTRFAC_ROOT;
1012 int ops = KTROP(uap->ops);
1013 int descend = uap->ops & KTRFLAG_DESCEND;
1015 int flags, error = 0;
1016 struct nameidata nd;
1017 struct ktr_io_params *kiop, *old_kiop;
1020 * Need something to (un)trace.
1022 if (ops != KTROP_CLEARFILE && facs == 0)
1026 if (ops != KTROP_CLEAR) {
1028 * an operation which requires a file argument.
1030 NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_USERSPACE, uap->fname);
1031 flags = FREAD | FWRITE | O_NOFOLLOW;
1032 error = vn_open(&nd, &flags, 0, NULL);
1038 if (vp->v_type != VREG) {
1039 (void)vn_close(vp, FREAD|FWRITE, td->td_ucred, td);
1042 kiop = ktr_io_params_alloc(td, vp);
1046 * Clear all uses of the tracefile.
1049 if (ops == KTROP_CLEARFILE) {
1051 sx_slock(&allproc_lock);
1052 FOREACH_PROC_IN_SYSTEM(p) {
1055 if (p->p_ktrioparms != NULL &&
1056 p->p_ktrioparms->vp == vp) {
1057 if (ktrcanset(td, p)) {
1058 mtx_lock(&ktrace_mtx);
1059 old_kiop = ktr_freeproc(p);
1060 mtx_unlock(&ktrace_mtx);
1065 if (old_kiop != NULL) {
1066 sx_sunlock(&allproc_lock);
1067 ktr_io_params_free(old_kiop);
1071 sx_sunlock(&allproc_lock);
1077 sx_slock(&proctree_lock);
1082 pg = pgfind(-uap->pid);
1084 sx_sunlock(&proctree_lock);
1090 * ktrops() may call vrele(). Lock pg_members
1091 * by the proctree_lock rather than pg_mtx.
1094 if (LIST_EMPTY(&pg->pg_members)) {
1095 sx_sunlock(&proctree_lock);
1099 LIST_FOREACH(p, &pg->pg_members, p_pglist) {
1102 ret |= ktrsetchildren(td, p, ops, facs, kiop);
1104 ret |= ktrops(td, p, ops, facs, kiop);
1110 p = pfind(uap->pid);
1113 sx_sunlock(&proctree_lock);
1117 ret |= ktrsetchildren(td, p, ops, facs, kiop);
1119 ret |= ktrops(td, p, ops, facs, kiop);
1121 sx_sunlock(&proctree_lock);
1126 mtx_lock(&ktrace_mtx);
1127 kiop = ktr_io_params_rele(kiop);
1128 mtx_unlock(&ktrace_mtx);
1129 ktr_io_params_free(kiop);
1140 sys_utrace(struct thread *td, struct utrace_args *uap)
1144 struct ktr_request *req;
1148 if (!KTRPOINT(td, KTR_USER))
1150 if (uap->len > KTR_USER_MAXLEN)
1152 cp = malloc(uap->len, M_KTRACE, M_WAITOK);
1153 error = copyin(uap->addr, cp, uap->len);
1158 req = ktr_getrequest(KTR_USER);
1163 req->ktr_buffer = cp;
1164 req->ktr_header.ktr_len = uap->len;
1165 ktr_submitrequest(td, req);
1174 ktrops(struct thread *td, struct proc *p, int ops, int facs,
1175 struct ktr_io_params *new_kiop)
1177 struct ktr_io_params *old_kiop;
1179 PROC_LOCK_ASSERT(p, MA_OWNED);
1180 if (!ktrcanset(td, p)) {
1184 if ((ops == KTROP_SET && p->p_state == PRS_NEW) ||
1185 p_cansee(td, p) != 0) {
1187 * Disallow setting trace points if the process is being born.
1188 * This avoids races with trace point inheritance in
1194 if ((p->p_flag & P_WEXIT) != 0) {
1196 * There's nothing to do if the process is exiting, but avoid
1197 * signaling an error.
1203 mtx_lock(&ktrace_mtx);
1204 if (ops == KTROP_SET) {
1205 if (p->p_ktrioparms != NULL &&
1206 p->p_ktrioparms->vp != new_kiop->vp) {
1207 /* if trace file already in use, relinquish below */
1208 old_kiop = ktr_io_params_rele(p->p_ktrioparms);
1209 p->p_ktrioparms = NULL;
1211 if (p->p_ktrioparms == NULL) {
1212 p->p_ktrioparms = new_kiop;
1213 ktr_io_params_ref(new_kiop);
1215 p->p_traceflag |= facs;
1216 if (priv_check(td, PRIV_KTRACE) == 0)
1217 p->p_traceflag |= KTRFAC_ROOT;
1220 if (((p->p_traceflag &= ~facs) & KTRFAC_MASK) == 0)
1221 /* no more tracing */
1222 old_kiop = ktr_freeproc(p);
1224 mtx_unlock(&ktrace_mtx);
1225 if ((p->p_traceflag & KTRFAC_MASK) != 0)
1226 ktrprocctor_entered(td, p);
1228 ktr_io_params_free(old_kiop);
1234 ktrsetchildren(struct thread *td, struct proc *top, int ops, int facs,
1235 struct ktr_io_params *new_kiop)
1241 PROC_LOCK_ASSERT(p, MA_OWNED);
1242 sx_assert(&proctree_lock, SX_LOCKED);
1244 ret |= ktrops(td, p, ops, facs, new_kiop);
1246 * If this process has children, descend to them next,
1247 * otherwise do any siblings, and if done with this level,
1248 * follow back up the tree (but not past top).
1250 if (!LIST_EMPTY(&p->p_children))
1251 p = LIST_FIRST(&p->p_children);
1255 if (LIST_NEXT(p, p_sibling)) {
1256 p = LIST_NEXT(p, p_sibling);
1267 ktr_writerequest(struct thread *td, struct ktr_request *req)
1269 struct ktr_io_params *kiop, *kiop1;
1270 struct ktr_header *kth;
1275 struct iovec aiov[3];
1278 int datalen, buflen;
1284 * We reference the kiop for use in I/O in case ktrace is
1285 * disabled on the process as we write out the request.
1287 mtx_lock(&ktrace_mtx);
1288 kiop = p->p_ktrioparms;
1291 * If kiop is NULL, it has been cleared out from under this
1292 * request, so just drop it.
1295 mtx_unlock(&ktrace_mtx);
1299 ktr_io_params_ref(kiop);
1304 KASSERT(cred != NULL, ("ktr_writerequest: cred == NULL"));
1305 mtx_unlock(&ktrace_mtx);
1307 kth = &req->ktr_header;
1308 KASSERT(((u_short)kth->ktr_type & ~KTR_TYPE) < nitems(data_lengths),
1309 ("data_lengths array overflow"));
1310 datalen = data_lengths[(u_short)kth->ktr_type & ~KTR_TYPE];
1311 buflen = kth->ktr_len;
1312 auio.uio_iov = &aiov[0];
1313 auio.uio_offset = 0;
1314 auio.uio_segflg = UIO_SYSSPACE;
1315 auio.uio_rw = UIO_WRITE;
1316 aiov[0].iov_base = (caddr_t)kth;
1317 aiov[0].iov_len = sizeof(struct ktr_header);
1318 auio.uio_resid = sizeof(struct ktr_header);
1319 auio.uio_iovcnt = 1;
1322 aiov[1].iov_base = (caddr_t)&req->ktr_data;
1323 aiov[1].iov_len = datalen;
1324 auio.uio_resid += datalen;
1326 kth->ktr_len += datalen;
1329 KASSERT(req->ktr_buffer != NULL, ("ktrace: nothing to write"));
1330 aiov[auio.uio_iovcnt].iov_base = req->ktr_buffer;
1331 aiov[auio.uio_iovcnt].iov_len = buflen;
1332 auio.uio_resid += buflen;
1336 vn_start_write(vp, &mp, V_WAIT);
1337 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1338 td->td_ktr_io_lim = lim;
1340 error = mac_vnode_check_write(cred, NOCRED, vp);
1343 error = VOP_WRITE(vp, &auio, IO_UNIT | IO_APPEND, cred);
1345 vn_finished_write(mp);
1347 mtx_lock(&ktrace_mtx);
1348 kiop = ktr_io_params_rele(kiop);
1349 mtx_unlock(&ktrace_mtx);
1350 ktr_io_params_free(kiop);
1355 * If error encountered, give up tracing on this vnode on this
1356 * process. Other processes might still be suitable for
1357 * writes to this vnode.
1360 "ktrace write failed, errno %d, tracing stopped for pid %d\n",
1365 mtx_lock(&ktrace_mtx);
1366 if (p->p_ktrioparms != NULL && p->p_ktrioparms->vp == vp)
1367 kiop1 = ktr_freeproc(p);
1368 kiop = ktr_io_params_rele(kiop);
1369 mtx_unlock(&ktrace_mtx);
1371 ktr_io_params_free(kiop1);
1372 ktr_io_params_free(kiop);
1376 * Return true if caller has permission to set the ktracing state
1377 * of target. Essentially, the target can't possess any
1378 * more permissions than the caller. KTRFAC_ROOT signifies that
1379 * root previously set the tracing status on the target process, and
1380 * so, only root may further change it.
1383 ktrcanset(struct thread *td, struct proc *targetp)
1386 PROC_LOCK_ASSERT(targetp, MA_OWNED);
1387 if (targetp->p_traceflag & KTRFAC_ROOT &&
1388 priv_check(td, PRIV_KTRACE))
1391 if (p_candebug(td, targetp) != 0)