]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/kern_ktrace.c
Move vnode-to-file-handle translation from vfs_vptofh to vop_vptofh method.
[FreeBSD/FreeBSD.git] / sys / kern / kern_ktrace.c
1 /*-
2  * Copyright (c) 1989, 1993
3  *      The Regents of the University of California.
4  * Copyright (c) 2005 Robert N. M. Watson
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 4. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *      @(#)kern_ktrace.c       8.2 (Berkeley) 9/23/93
32  */
33
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36
37 #include "opt_ktrace.h"
38 #include "opt_mac.h"
39
40 #include <sys/param.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/ktrace.h>
55 #include <sys/sx.h>
56 #include <sys/sysctl.h>
57 #include <sys/syslog.h>
58 #include <sys/sysproto.h>
59
60 #include <security/mac/mac_framework.h>
61
62 /*
63  * The ktrace facility allows the tracing of certain key events in user space
64  * processes, such as system calls, signal delivery, context switches, and
65  * user generated events using utrace(2).  It works by streaming event
66  * records and data to a vnode associated with the process using the
67  * ktrace(2) system call.  In general, records can be written directly from
68  * the context that generates the event.  One important exception to this is
69  * during a context switch, where sleeping is not permitted.  To handle this
70  * case, trace events are generated using in-kernel ktr_request records, and
71  * then delivered to disk at a convenient moment -- either immediately, the
72  * next traceable event, at system call return, or at process exit.
73  *
74  * When dealing with multiple threads or processes writing to the same event
75  * log, ordering guarantees are weak: specifically, if an event has multiple
76  * records (i.e., system call enter and return), they may be interlaced with
77  * records from another event.  Process and thread ID information is provided
78  * in the record, and user applications can de-interlace events if required.
79  */
80
81 static MALLOC_DEFINE(M_KTRACE, "KTRACE", "KTRACE");
82
83 #ifdef KTRACE
84
85 #ifndef KTRACE_REQUEST_POOL
86 #define KTRACE_REQUEST_POOL     100
87 #endif
88
89 struct ktr_request {
90         struct  ktr_header ktr_header;
91         void    *ktr_buffer;
92         union {
93                 struct  ktr_syscall ktr_syscall;
94                 struct  ktr_sysret ktr_sysret;
95                 struct  ktr_genio ktr_genio;
96                 struct  ktr_psig ktr_psig;
97                 struct  ktr_csw ktr_csw;
98         } ktr_data;
99         STAILQ_ENTRY(ktr_request) ktr_list;
100 };
101
102 static int data_lengths[] = {
103         0,                                      /* none */
104         offsetof(struct ktr_syscall, ktr_args), /* KTR_SYSCALL */
105         sizeof(struct ktr_sysret),              /* KTR_SYSRET */
106         0,                                      /* KTR_NAMEI */
107         sizeof(struct ktr_genio),               /* KTR_GENIO */
108         sizeof(struct ktr_psig),                /* KTR_PSIG */
109         sizeof(struct ktr_csw),                 /* KTR_CSW */
110         0                                       /* KTR_USER */
111 };
112
113 static STAILQ_HEAD(, ktr_request) ktr_free;
114
115 static SYSCTL_NODE(_kern, OID_AUTO, ktrace, CTLFLAG_RD, 0, "KTRACE options");
116
117 static u_int ktr_requestpool = KTRACE_REQUEST_POOL;
118 TUNABLE_INT("kern.ktrace.request_pool", &ktr_requestpool);
119
120 static u_int ktr_geniosize = PAGE_SIZE;
121 TUNABLE_INT("kern.ktrace.genio_size", &ktr_geniosize);
122 SYSCTL_UINT(_kern_ktrace, OID_AUTO, genio_size, CTLFLAG_RW, &ktr_geniosize,
123     0, "Maximum size of genio event payload");
124
125 static int print_message = 1;
126 struct mtx ktrace_mtx;
127 static struct sx ktrace_sx;
128
129 static void ktrace_init(void *dummy);
130 static int sysctl_kern_ktrace_request_pool(SYSCTL_HANDLER_ARGS);
131 static u_int ktrace_resize_pool(u_int newsize);
132 static struct ktr_request *ktr_getrequest(int type);
133 static void ktr_submitrequest(struct thread *td, struct ktr_request *req);
134 static void ktr_freerequest(struct ktr_request *req);
135 static void ktr_writerequest(struct thread *td, struct ktr_request *req);
136 static int ktrcanset(struct thread *,struct proc *);
137 static int ktrsetchildren(struct thread *,struct proc *,int,int,struct vnode *);
138 static int ktrops(struct thread *,struct proc *,int,int,struct vnode *);
139
140 /*
141  * ktrace itself generates events, such as context switches, which we do not
142  * wish to trace.  Maintain a flag, TDP_INKTRACE, on each thread to determine
143  * whether or not it is in a region where tracing of events should be
144  * suppressed.
145  */
146 static void
147 ktrace_enter(struct thread *td)
148 {
149
150         KASSERT(!(td->td_pflags & TDP_INKTRACE), ("ktrace_enter: flag set"));
151         td->td_pflags |= TDP_INKTRACE;
152 }
153
154 static void
155 ktrace_exit(struct thread *td)
156 {
157
158         KASSERT(td->td_pflags & TDP_INKTRACE, ("ktrace_exit: flag not set"));
159         td->td_pflags &= ~TDP_INKTRACE;
160 }
161
162 static void
163 ktrace_assert(struct thread *td)
164 {
165
166         KASSERT(td->td_pflags & TDP_INKTRACE, ("ktrace_assert: flag not set"));
167 }
168
169 static void
170 ktrace_init(void *dummy)
171 {
172         struct ktr_request *req;
173         int i;
174
175         mtx_init(&ktrace_mtx, "ktrace", NULL, MTX_DEF | MTX_QUIET);
176         sx_init(&ktrace_sx, "ktrace_sx");
177         STAILQ_INIT(&ktr_free);
178         for (i = 0; i < ktr_requestpool; i++) {
179                 req = malloc(sizeof(struct ktr_request), M_KTRACE, M_WAITOK);
180                 STAILQ_INSERT_HEAD(&ktr_free, req, ktr_list);
181         }
182 }
183 SYSINIT(ktrace_init, SI_SUB_KTRACE, SI_ORDER_ANY, ktrace_init, NULL);
184
185 static int
186 sysctl_kern_ktrace_request_pool(SYSCTL_HANDLER_ARGS)
187 {
188         struct thread *td;
189         u_int newsize, oldsize, wantsize;
190         int error;
191
192         /* Handle easy read-only case first to avoid warnings from GCC. */
193         if (!req->newptr) {
194                 mtx_lock(&ktrace_mtx);
195                 oldsize = ktr_requestpool;
196                 mtx_unlock(&ktrace_mtx);
197                 return (SYSCTL_OUT(req, &oldsize, sizeof(u_int)));
198         }
199
200         error = SYSCTL_IN(req, &wantsize, sizeof(u_int));
201         if (error)
202                 return (error);
203         td = curthread;
204         ktrace_enter(td);
205         mtx_lock(&ktrace_mtx);
206         oldsize = ktr_requestpool;
207         newsize = ktrace_resize_pool(wantsize);
208         mtx_unlock(&ktrace_mtx);
209         ktrace_exit(td);
210         error = SYSCTL_OUT(req, &oldsize, sizeof(u_int));
211         if (error)
212                 return (error);
213         if (wantsize > oldsize && newsize < wantsize)
214                 return (ENOSPC);
215         return (0);
216 }
217 SYSCTL_PROC(_kern_ktrace, OID_AUTO, request_pool, CTLTYPE_UINT|CTLFLAG_RW,
218     &ktr_requestpool, 0, sysctl_kern_ktrace_request_pool, "IU", "");
219
220 static u_int
221 ktrace_resize_pool(u_int newsize)
222 {
223         struct ktr_request *req;
224         int bound;
225
226         mtx_assert(&ktrace_mtx, MA_OWNED);
227         print_message = 1;
228         bound = newsize - ktr_requestpool;
229         if (bound == 0)
230                 return (ktr_requestpool);
231         if (bound < 0)
232                 /* Shrink pool down to newsize if possible. */
233                 while (bound++ < 0) {
234                         req = STAILQ_FIRST(&ktr_free);
235                         if (req == NULL)
236                                 return (ktr_requestpool);
237                         STAILQ_REMOVE_HEAD(&ktr_free, ktr_list);
238                         ktr_requestpool--;
239                         mtx_unlock(&ktrace_mtx);
240                         free(req, M_KTRACE);
241                         mtx_lock(&ktrace_mtx);
242                 }
243         else
244                 /* Grow pool up to newsize. */
245                 while (bound-- > 0) {
246                         mtx_unlock(&ktrace_mtx);
247                         req = malloc(sizeof(struct ktr_request), M_KTRACE,
248                             M_WAITOK);
249                         mtx_lock(&ktrace_mtx);
250                         STAILQ_INSERT_HEAD(&ktr_free, req, ktr_list);
251                         ktr_requestpool++;
252                 }
253         return (ktr_requestpool);
254 }
255
256 static struct ktr_request *
257 ktr_getrequest(int type)
258 {
259         struct ktr_request *req;
260         struct thread *td = curthread;
261         struct proc *p = td->td_proc;
262         int pm;
263
264         ktrace_enter(td);       /* XXX: In caller instead? */
265         mtx_lock(&ktrace_mtx);
266         if (!KTRCHECK(td, type)) {
267                 mtx_unlock(&ktrace_mtx);
268                 ktrace_exit(td);
269                 return (NULL);
270         }
271         req = STAILQ_FIRST(&ktr_free);
272         if (req != NULL) {
273                 STAILQ_REMOVE_HEAD(&ktr_free, ktr_list);
274                 req->ktr_header.ktr_type = type;
275                 if (p->p_traceflag & KTRFAC_DROP) {
276                         req->ktr_header.ktr_type |= KTR_DROP;
277                         p->p_traceflag &= ~KTRFAC_DROP;
278                 }
279                 mtx_unlock(&ktrace_mtx);
280                 microtime(&req->ktr_header.ktr_time);
281                 req->ktr_header.ktr_pid = p->p_pid;
282                 req->ktr_header.ktr_tid = td->td_tid;
283                 bcopy(p->p_comm, req->ktr_header.ktr_comm, MAXCOMLEN + 1);
284                 req->ktr_buffer = NULL;
285                 req->ktr_header.ktr_len = 0;
286         } else {
287                 p->p_traceflag |= KTRFAC_DROP;
288                 pm = print_message;
289                 print_message = 0;
290                 mtx_unlock(&ktrace_mtx);
291                 if (pm)
292                         printf("Out of ktrace request objects.\n");
293                 ktrace_exit(td);
294         }
295         return (req);
296 }
297
298 /*
299  * Some trace generation environments don't permit direct access to VFS,
300  * such as during a context switch where sleeping is not allowed.  Under these
301  * circumstances, queue a request to the thread to be written asynchronously
302  * later.
303  */
304 static void
305 ktr_enqueuerequest(struct thread *td, struct ktr_request *req)
306 {
307
308         mtx_lock(&ktrace_mtx);
309         STAILQ_INSERT_TAIL(&td->td_proc->p_ktr, req, ktr_list);
310         mtx_unlock(&ktrace_mtx);
311         ktrace_exit(td);
312 }
313
314 /*
315  * Drain any pending ktrace records from the per-thread queue to disk.  This
316  * is used both internally before committing other records, and also on
317  * system call return.  We drain all the ones we can find at the time when
318  * drain is requested, but don't keep draining after that as those events
319  * may me approximately "after" the current event.
320  */
321 static void
322 ktr_drain(struct thread *td)
323 {
324         struct ktr_request *queued_req;
325         STAILQ_HEAD(, ktr_request) local_queue;
326
327         ktrace_assert(td);
328         sx_assert(&ktrace_sx, SX_XLOCKED);
329
330         STAILQ_INIT(&local_queue);      /* XXXRW: needed? */
331
332         if (!STAILQ_EMPTY(&td->td_proc->p_ktr)) {
333                 mtx_lock(&ktrace_mtx);
334                 STAILQ_CONCAT(&local_queue, &td->td_proc->p_ktr);
335                 mtx_unlock(&ktrace_mtx);
336
337                 while ((queued_req = STAILQ_FIRST(&local_queue))) {
338                         STAILQ_REMOVE_HEAD(&local_queue, ktr_list);
339                         ktr_writerequest(td, queued_req);
340                         ktr_freerequest(queued_req);
341                 }
342         }
343 }
344
345 /*
346  * Submit a trace record for immediate commit to disk -- to be used only
347  * where entering VFS is OK.  First drain any pending records that may have
348  * been cached in the thread.
349  */
350 static void
351 ktr_submitrequest(struct thread *td, struct ktr_request *req)
352 {
353
354         ktrace_assert(td);
355
356         sx_xlock(&ktrace_sx);
357         ktr_drain(td);
358         ktr_writerequest(td, req);
359         ktr_freerequest(req);
360         sx_xunlock(&ktrace_sx);
361
362         ktrace_exit(td);
363 }
364
365 static void
366 ktr_freerequest(struct ktr_request *req)
367 {
368
369         if (req->ktr_buffer != NULL)
370                 free(req->ktr_buffer, M_KTRACE);
371         mtx_lock(&ktrace_mtx);
372         STAILQ_INSERT_HEAD(&ktr_free, req, ktr_list);
373         mtx_unlock(&ktrace_mtx);
374 }
375
376 /*
377  * MPSAFE
378  */
379 void
380 ktrsyscall(code, narg, args)
381         int code, narg;
382         register_t args[];
383 {
384         struct ktr_request *req;
385         struct ktr_syscall *ktp;
386         size_t buflen;
387         char *buf = NULL;
388
389         buflen = sizeof(register_t) * narg;
390         if (buflen > 0) {
391                 buf = malloc(buflen, M_KTRACE, M_WAITOK);
392                 bcopy(args, buf, buflen);
393         }
394         req = ktr_getrequest(KTR_SYSCALL);
395         if (req == NULL) {
396                 if (buf != NULL)
397                         free(buf, M_KTRACE);
398                 return;
399         }
400         ktp = &req->ktr_data.ktr_syscall;
401         ktp->ktr_code = code;
402         ktp->ktr_narg = narg;
403         if (buflen > 0) {
404                 req->ktr_header.ktr_len = buflen;
405                 req->ktr_buffer = buf;
406         }
407         ktr_submitrequest(curthread, req);
408 }
409
410 /*
411  * MPSAFE
412  */
413 void
414 ktrsysret(code, error, retval)
415         int code, error;
416         register_t retval;
417 {
418         struct ktr_request *req;
419         struct ktr_sysret *ktp;
420
421         req = ktr_getrequest(KTR_SYSRET);
422         if (req == NULL)
423                 return;
424         ktp = &req->ktr_data.ktr_sysret;
425         ktp->ktr_code = code;
426         ktp->ktr_error = error;
427         ktp->ktr_retval = retval;               /* what about val2 ? */
428         ktr_submitrequest(curthread, req);
429 }
430
431 /*
432  * When a process exits, drain per-process asynchronous trace records.
433  */
434 void
435 ktrprocexit(struct thread *td)
436 {
437
438         ktrace_enter(td);
439         sx_xlock(&ktrace_sx);
440         ktr_drain(td);
441         sx_xunlock(&ktrace_sx);
442         ktrace_exit(td);
443 }
444
445 /*
446  * When a thread returns, drain any asynchronous records generated by the
447  * system call.
448  */
449 void
450 ktruserret(struct thread *td)
451 {
452
453         ktrace_enter(td);
454         sx_xlock(&ktrace_sx);
455         ktr_drain(td);
456         sx_xunlock(&ktrace_sx);
457         ktrace_exit(td);
458 }
459
460 void
461 ktrnamei(path)
462         char *path;
463 {
464         struct ktr_request *req;
465         int namelen;
466         char *buf = NULL;
467
468         namelen = strlen(path);
469         if (namelen > 0) {
470                 buf = malloc(namelen, M_KTRACE, M_WAITOK);
471                 bcopy(path, buf, namelen);
472         }
473         req = ktr_getrequest(KTR_NAMEI);
474         if (req == NULL) {
475                 if (buf != NULL)
476                         free(buf, M_KTRACE);
477                 return;
478         }
479         if (namelen > 0) {
480                 req->ktr_header.ktr_len = namelen;
481                 req->ktr_buffer = buf;
482         }
483         ktr_submitrequest(curthread, req);
484 }
485
486 void
487 ktrgenio(fd, rw, uio, error)
488         int fd;
489         enum uio_rw rw;
490         struct uio *uio;
491         int error;
492 {
493         struct ktr_request *req;
494         struct ktr_genio *ktg;
495         int datalen;
496         char *buf;
497
498         if (error) {
499                 free(uio, M_IOV);
500                 return;
501         }
502         uio->uio_offset = 0;
503         uio->uio_rw = UIO_WRITE;
504         datalen = imin(uio->uio_resid, ktr_geniosize);
505         buf = malloc(datalen, M_KTRACE, M_WAITOK);
506         error = uiomove(buf, datalen, uio);
507         free(uio, M_IOV);
508         if (error) {
509                 free(buf, M_KTRACE);
510                 return;
511         }
512         req = ktr_getrequest(KTR_GENIO);
513         if (req == NULL) {
514                 free(buf, M_KTRACE);
515                 return;
516         }
517         ktg = &req->ktr_data.ktr_genio;
518         ktg->ktr_fd = fd;
519         ktg->ktr_rw = rw;
520         req->ktr_header.ktr_len = datalen;
521         req->ktr_buffer = buf;
522         ktr_submitrequest(curthread, req);
523 }
524
525 void
526 ktrpsig(sig, action, mask, code)
527         int sig;
528         sig_t action;
529         sigset_t *mask;
530         int code;
531 {
532         struct ktr_request *req;
533         struct ktr_psig *kp;
534
535         req = ktr_getrequest(KTR_PSIG);
536         if (req == NULL)
537                 return;
538         kp = &req->ktr_data.ktr_psig;
539         kp->signo = (char)sig;
540         kp->action = action;
541         kp->mask = *mask;
542         kp->code = code;
543         ktr_enqueuerequest(curthread, req);
544 }
545
546 void
547 ktrcsw(out, user)
548         int out, user;
549 {
550         struct ktr_request *req;
551         struct ktr_csw *kc;
552
553         req = ktr_getrequest(KTR_CSW);
554         if (req == NULL)
555                 return;
556         kc = &req->ktr_data.ktr_csw;
557         kc->out = out;
558         kc->user = user;
559         ktr_enqueuerequest(curthread, req);
560 }
561 #endif /* KTRACE */
562
563 /* Interface and common routines */
564
565 /*
566  * ktrace system call
567  *
568  * MPSAFE
569  */
570 #ifndef _SYS_SYSPROTO_H_
571 struct ktrace_args {
572         char    *fname;
573         int     ops;
574         int     facs;
575         int     pid;
576 };
577 #endif
578 /* ARGSUSED */
579 int
580 ktrace(td, uap)
581         struct thread *td;
582         register struct ktrace_args *uap;
583 {
584 #ifdef KTRACE
585         register struct vnode *vp = NULL;
586         register struct proc *p;
587         struct pgrp *pg;
588         int facs = uap->facs & ~KTRFAC_ROOT;
589         int ops = KTROP(uap->ops);
590         int descend = uap->ops & KTRFLAG_DESCEND;
591         int nfound, ret = 0;
592         int flags, error = 0, vfslocked;
593         struct nameidata nd;
594         struct ucred *cred;
595
596         /*
597          * Need something to (un)trace.
598          */
599         if (ops != KTROP_CLEARFILE && facs == 0)
600                 return (EINVAL);
601
602         ktrace_enter(td);
603         if (ops != KTROP_CLEAR) {
604                 /*
605                  * an operation which requires a file argument.
606                  */
607                 NDINIT(&nd, LOOKUP, NOFOLLOW | MPSAFE, UIO_USERSPACE,
608                     uap->fname, td);
609                 flags = FREAD | FWRITE | O_NOFOLLOW;
610                 error = vn_open(&nd, &flags, 0, -1);
611                 if (error) {
612                         ktrace_exit(td);
613                         return (error);
614                 }
615                 vfslocked = NDHASGIANT(&nd);
616                 NDFREE(&nd, NDF_ONLY_PNBUF);
617                 vp = nd.ni_vp;
618                 VOP_UNLOCK(vp, 0, td);
619                 if (vp->v_type != VREG) {
620                         (void) vn_close(vp, FREAD|FWRITE, td->td_ucred, td);
621                         VFS_UNLOCK_GIANT(vfslocked);
622                         ktrace_exit(td);
623                         return (EACCES);
624                 }
625                 VFS_UNLOCK_GIANT(vfslocked);
626         }
627         /*
628          * Clear all uses of the tracefile.
629          */
630         if (ops == KTROP_CLEARFILE) {
631                 int vrele_count;
632
633                 vrele_count = 0;
634                 sx_slock(&allproc_lock);
635                 FOREACH_PROC_IN_SYSTEM(p) {
636                         PROC_LOCK(p);
637                         if (p->p_tracevp == vp) {
638                                 if (ktrcanset(td, p)) {
639                                         mtx_lock(&ktrace_mtx);
640                                         cred = p->p_tracecred;
641                                         p->p_tracecred = NULL;
642                                         p->p_tracevp = NULL;
643                                         p->p_traceflag = 0;
644                                         mtx_unlock(&ktrace_mtx);
645                                         vrele_count++;
646                                         crfree(cred);
647                                 } else
648                                         error = EPERM;
649                         }
650                         PROC_UNLOCK(p);
651                 }
652                 sx_sunlock(&allproc_lock);
653                 if (vrele_count > 0) {
654                         vfslocked = VFS_LOCK_GIANT(vp->v_mount);
655                         while (vrele_count-- > 0)
656                                 vrele(vp);
657                         VFS_UNLOCK_GIANT(vfslocked);
658                 }
659                 goto done;
660         }
661         /*
662          * do it
663          */
664         sx_slock(&proctree_lock);
665         if (uap->pid < 0) {
666                 /*
667                  * by process group
668                  */
669                 pg = pgfind(-uap->pid);
670                 if (pg == NULL) {
671                         sx_sunlock(&proctree_lock);
672                         error = ESRCH;
673                         goto done;
674                 }
675                 /*
676                  * ktrops() may call vrele(). Lock pg_members
677                  * by the proctree_lock rather than pg_mtx.
678                  */
679                 PGRP_UNLOCK(pg);
680                 nfound = 0;
681                 LIST_FOREACH(p, &pg->pg_members, p_pglist) {
682                         PROC_LOCK(p);
683                         if (p_cansee(td, p) != 0) {
684                                 PROC_UNLOCK(p); 
685                                 continue;
686                         }
687                         PROC_UNLOCK(p); 
688                         nfound++;
689                         if (descend)
690                                 ret |= ktrsetchildren(td, p, ops, facs, vp);
691                         else
692                                 ret |= ktrops(td, p, ops, facs, vp);
693                 }
694                 if (nfound == 0) {
695                         sx_sunlock(&proctree_lock);
696                         error = ESRCH;
697                         goto done;
698                 }
699         } else {
700                 /*
701                  * by pid
702                  */
703                 p = pfind(uap->pid);
704                 if (p == NULL) {
705                         sx_sunlock(&proctree_lock);
706                         error = ESRCH;
707                         goto done;
708                 }
709                 error = p_cansee(td, p);
710                 /*
711                  * The slock of the proctree lock will keep this process
712                  * from going away, so unlocking the proc here is ok.
713                  */
714                 PROC_UNLOCK(p);
715                 if (error) {
716                         sx_sunlock(&proctree_lock);
717                         goto done;
718                 }
719                 if (descend)
720                         ret |= ktrsetchildren(td, p, ops, facs, vp);
721                 else
722                         ret |= ktrops(td, p, ops, facs, vp);
723         }
724         sx_sunlock(&proctree_lock);
725         if (!ret)
726                 error = EPERM;
727 done:
728         if (vp != NULL) {
729                 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
730                 (void) vn_close(vp, FWRITE, td->td_ucred, td);
731                 VFS_UNLOCK_GIANT(vfslocked);
732         }
733         ktrace_exit(td);
734         return (error);
735 #else /* !KTRACE */
736         return (ENOSYS);
737 #endif /* KTRACE */
738 }
739
740 /*
741  * utrace system call
742  *
743  * MPSAFE
744  */
745 /* ARGSUSED */
746 int
747 utrace(td, uap)
748         struct thread *td;
749         register struct utrace_args *uap;
750 {
751
752 #ifdef KTRACE
753         struct ktr_request *req;
754         void *cp;
755         int error;
756
757         if (!KTRPOINT(td, KTR_USER))
758                 return (0);
759         if (uap->len > KTR_USER_MAXLEN)
760                 return (EINVAL);
761         cp = malloc(uap->len, M_KTRACE, M_WAITOK);
762         error = copyin(uap->addr, cp, uap->len);
763         if (error) {
764                 free(cp, M_KTRACE);
765                 return (error);
766         }
767         req = ktr_getrequest(KTR_USER);
768         if (req == NULL) {
769                 free(cp, M_KTRACE);
770                 return (ENOMEM);
771         }
772         req->ktr_buffer = cp;
773         req->ktr_header.ktr_len = uap->len;
774         ktr_submitrequest(td, req);
775         return (0);
776 #else /* !KTRACE */
777         return (ENOSYS);
778 #endif /* KTRACE */
779 }
780
781 #ifdef KTRACE
782 static int
783 ktrops(td, p, ops, facs, vp)
784         struct thread *td;
785         struct proc *p;
786         int ops, facs;
787         struct vnode *vp;
788 {
789         struct vnode *tracevp = NULL;
790         struct ucred *tracecred = NULL;
791
792         PROC_LOCK(p);
793         if (!ktrcanset(td, p)) {
794                 PROC_UNLOCK(p);
795                 return (0);
796         }
797         mtx_lock(&ktrace_mtx);
798         if (ops == KTROP_SET) {
799                 if (p->p_tracevp != vp) {
800                         /*
801                          * if trace file already in use, relinquish below
802                          */
803                         tracevp = p->p_tracevp;
804                         VREF(vp);
805                         p->p_tracevp = vp;
806                 }
807                 if (p->p_tracecred != td->td_ucred) {
808                         tracecred = p->p_tracecred;
809                         p->p_tracecred = crhold(td->td_ucred);
810                 }
811                 p->p_traceflag |= facs;
812                 if (priv_check_cred(td->td_ucred, PRIV_KTRACE,
813                     SUSER_ALLOWJAIL) == 0)
814                         p->p_traceflag |= KTRFAC_ROOT;
815         } else {
816                 /* KTROP_CLEAR */
817                 if (((p->p_traceflag &= ~facs) & KTRFAC_MASK) == 0) {
818                         /* no more tracing */
819                         p->p_traceflag = 0;
820                         tracevp = p->p_tracevp;
821                         p->p_tracevp = NULL;
822                         tracecred = p->p_tracecred;
823                         p->p_tracecred = NULL;
824                 }
825         }
826         mtx_unlock(&ktrace_mtx);
827         PROC_UNLOCK(p);
828         if (tracevp != NULL) {
829                 int vfslocked;
830
831                 vfslocked = VFS_LOCK_GIANT(tracevp->v_mount);
832                 vrele(tracevp);
833                 VFS_UNLOCK_GIANT(vfslocked);
834         }
835         if (tracecred != NULL)
836                 crfree(tracecred);
837
838         return (1);
839 }
840
841 static int
842 ktrsetchildren(td, top, ops, facs, vp)
843         struct thread *td;
844         struct proc *top;
845         int ops, facs;
846         struct vnode *vp;
847 {
848         register struct proc *p;
849         register int ret = 0;
850
851         p = top;
852         sx_assert(&proctree_lock, SX_LOCKED);
853         for (;;) {
854                 ret |= ktrops(td, p, ops, facs, vp);
855                 /*
856                  * If this process has children, descend to them next,
857                  * otherwise do any siblings, and if done with this level,
858                  * follow back up the tree (but not past top).
859                  */
860                 if (!LIST_EMPTY(&p->p_children))
861                         p = LIST_FIRST(&p->p_children);
862                 else for (;;) {
863                         if (p == top)
864                                 return (ret);
865                         if (LIST_NEXT(p, p_sibling)) {
866                                 p = LIST_NEXT(p, p_sibling);
867                                 break;
868                         }
869                         p = p->p_pptr;
870                 }
871         }
872         /*NOTREACHED*/
873 }
874
875 static void
876 ktr_writerequest(struct thread *td, struct ktr_request *req)
877 {
878         struct ktr_header *kth;
879         struct vnode *vp;
880         struct proc *p;
881         struct ucred *cred;
882         struct uio auio;
883         struct iovec aiov[3];
884         struct mount *mp;
885         int datalen, buflen, vrele_count;
886         int error, vfslocked;
887
888         /*
889          * We hold the vnode and credential for use in I/O in case ktrace is
890          * disabled on the process as we write out the request.
891          *
892          * XXXRW: This is not ideal: we could end up performing a write after
893          * the vnode has been closed.
894          */
895         mtx_lock(&ktrace_mtx);
896         vp = td->td_proc->p_tracevp;
897         if (vp != NULL)
898                 VREF(vp);
899         cred = td->td_proc->p_tracecred;
900         if (cred != NULL)
901                 crhold(cred);
902         mtx_unlock(&ktrace_mtx);
903
904         /*
905          * If vp is NULL, the vp has been cleared out from under this
906          * request, so just drop it.  Make sure the credential and vnode are
907          * in sync: we should have both or neither.
908          */
909         if (vp == NULL) {
910                 KASSERT(cred == NULL, ("ktr_writerequest: cred != NULL"));
911                 return;
912         }
913         KASSERT(cred != NULL, ("ktr_writerequest: cred == NULL"));
914
915         kth = &req->ktr_header;
916         datalen = data_lengths[(u_short)kth->ktr_type & ~KTR_DROP];
917         buflen = kth->ktr_len;
918         auio.uio_iov = &aiov[0];
919         auio.uio_offset = 0;
920         auio.uio_segflg = UIO_SYSSPACE;
921         auio.uio_rw = UIO_WRITE;
922         aiov[0].iov_base = (caddr_t)kth;
923         aiov[0].iov_len = sizeof(struct ktr_header);
924         auio.uio_resid = sizeof(struct ktr_header);
925         auio.uio_iovcnt = 1;
926         auio.uio_td = td;
927         if (datalen != 0) {
928                 aiov[1].iov_base = (caddr_t)&req->ktr_data;
929                 aiov[1].iov_len = datalen;
930                 auio.uio_resid += datalen;
931                 auio.uio_iovcnt++;
932                 kth->ktr_len += datalen;
933         }
934         if (buflen != 0) {
935                 KASSERT(req->ktr_buffer != NULL, ("ktrace: nothing to write"));
936                 aiov[auio.uio_iovcnt].iov_base = req->ktr_buffer;
937                 aiov[auio.uio_iovcnt].iov_len = buflen;
938                 auio.uio_resid += buflen;
939                 auio.uio_iovcnt++;
940         }
941
942         vfslocked = VFS_LOCK_GIANT(vp->v_mount);
943         vn_start_write(vp, &mp, V_WAIT);
944         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, td);
945         (void)VOP_LEASE(vp, td, cred, LEASE_WRITE);
946 #ifdef MAC
947         error = mac_check_vnode_write(cred, NOCRED, vp);
948         if (error == 0)
949 #endif
950                 error = VOP_WRITE(vp, &auio, IO_UNIT | IO_APPEND, cred);
951         VOP_UNLOCK(vp, 0, td);
952         vn_finished_write(mp);
953         vrele(vp);
954         VFS_UNLOCK_GIANT(vfslocked);
955         if (!error)
956                 return;
957         /*
958          * If error encountered, give up tracing on this vnode.  We defer
959          * all the vrele()'s on the vnode until after we are finished walking
960          * the various lists to avoid needlessly holding locks.
961          */
962         log(LOG_NOTICE, "ktrace write failed, errno %d, tracing stopped\n",
963             error);
964         vrele_count = 0;
965         /*
966          * First, clear this vnode from being used by any processes in the
967          * system.
968          * XXX - If one process gets an EPERM writing to the vnode, should
969          * we really do this?  Other processes might have suitable
970          * credentials for the operation.
971          */
972         cred = NULL;
973         sx_slock(&allproc_lock);
974         FOREACH_PROC_IN_SYSTEM(p) {
975                 PROC_LOCK(p);
976                 if (p->p_tracevp == vp) {
977                         mtx_lock(&ktrace_mtx);
978                         p->p_tracevp = NULL;
979                         p->p_traceflag = 0;
980                         cred = p->p_tracecred;
981                         p->p_tracecred = NULL;
982                         mtx_unlock(&ktrace_mtx);
983                         vrele_count++;
984                 }
985                 PROC_UNLOCK(p);
986                 if (cred != NULL) {
987                         crfree(cred);
988                         cred = NULL;
989                 }
990         }
991         sx_sunlock(&allproc_lock);
992
993         /*
994          * We can't clear any pending requests in threads that have cached
995          * them but not yet committed them, as those are per-thread.  The
996          * thread will have to clear it itself on system call return.
997          */
998         vfslocked = VFS_LOCK_GIANT(vp->v_mount);
999         while (vrele_count-- > 0)
1000                 vrele(vp);
1001         VFS_UNLOCK_GIANT(vfslocked);
1002 }
1003
1004 /*
1005  * Return true if caller has permission to set the ktracing state
1006  * of target.  Essentially, the target can't possess any
1007  * more permissions than the caller.  KTRFAC_ROOT signifies that
1008  * root previously set the tracing status on the target process, and
1009  * so, only root may further change it.
1010  */
1011 static int
1012 ktrcanset(td, targetp)
1013         struct thread *td;
1014         struct proc *targetp;
1015 {
1016
1017         PROC_LOCK_ASSERT(targetp, MA_OWNED);
1018         if (targetp->p_traceflag & KTRFAC_ROOT &&
1019             priv_check_cred(td->td_ucred, PRIV_KTRACE, SUSER_ALLOWJAIL))
1020                 return (0);
1021
1022         if (p_candebug(td, targetp) != 0)
1023                 return (0);
1024
1025         return (1);
1026 }
1027
1028 #endif /* KTRACE */