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