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