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