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