]> CyberLeo.Net >> Repos - FreeBSD/releng/9.2.git/blob - sys/kern/kern_ktrace.c
- Copy stable/9 to releng/9.2 as part of the 9.2-RELEASE cycle.
[FreeBSD/releng/9.2.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, wmesg)
735         int out, user;
736         const char *wmesg;
737 {
738         struct thread *td = curthread;
739         struct ktr_request *req;
740         struct ktr_csw *kc;
741
742         req = ktr_getrequest(KTR_CSW);
743         if (req == NULL)
744                 return;
745         kc = &req->ktr_data.ktr_csw;
746         kc->out = out;
747         kc->user = user;
748         if (wmesg != NULL)
749                 strlcpy(kc->wmesg, wmesg, sizeof(kc->wmesg));
750         else
751                 bzero(kc->wmesg, sizeof(kc->wmesg));
752         ktr_enqueuerequest(td, req);
753         ktrace_exit(td);
754 }
755
756 void
757 ktrstruct(name, data, datalen)
758         const char *name;
759         void *data;
760         size_t datalen;
761 {
762         struct ktr_request *req;
763         char *buf = NULL;
764         size_t buflen;
765
766         if (!data)
767                 datalen = 0;
768         buflen = strlen(name) + 1 + datalen;
769         buf = malloc(buflen, M_KTRACE, M_WAITOK);
770         strcpy(buf, name);
771         bcopy(data, buf + strlen(name) + 1, datalen);
772         if ((req = ktr_getrequest(KTR_STRUCT)) == NULL) {
773                 free(buf, M_KTRACE);
774                 return;
775         }
776         req->ktr_buffer = buf;
777         req->ktr_header.ktr_len = buflen;
778         ktr_submitrequest(curthread, req);
779 }
780
781 void
782 ktrfault(vaddr, type)
783         vm_offset_t vaddr;
784         int type;
785 {
786         struct thread *td = curthread;
787         struct ktr_request *req;
788         struct ktr_fault *kf;
789
790         req = ktr_getrequest(KTR_FAULT);
791         if (req == NULL)
792                 return;
793         kf = &req->ktr_data.ktr_fault;
794         kf->vaddr = vaddr;
795         kf->type = type;
796         ktr_enqueuerequest(td, req);
797         ktrace_exit(td);
798 }
799
800 void
801 ktrfaultend(result)
802         int result;
803 {
804         struct thread *td = curthread;
805         struct ktr_request *req;
806         struct ktr_faultend *kf;
807
808         req = ktr_getrequest(KTR_FAULTEND);
809         if (req == NULL)
810                 return;
811         kf = &req->ktr_data.ktr_faultend;
812         kf->result = result;
813         ktr_enqueuerequest(td, req);
814         ktrace_exit(td);
815 }
816 #endif /* KTRACE */
817
818 /* Interface and common routines */
819
820 #ifndef _SYS_SYSPROTO_H_
821 struct ktrace_args {
822         char    *fname;
823         int     ops;
824         int     facs;
825         int     pid;
826 };
827 #endif
828 /* ARGSUSED */
829 int
830 sys_ktrace(td, uap)
831         struct thread *td;
832         register struct ktrace_args *uap;
833 {
834 #ifdef KTRACE
835         register struct vnode *vp = NULL;
836         register struct proc *p;
837         struct pgrp *pg;
838         int facs = uap->facs & ~KTRFAC_ROOT;
839         int ops = KTROP(uap->ops);
840         int descend = uap->ops & KTRFLAG_DESCEND;
841         int nfound, ret = 0;
842         int flags, error = 0, vfslocked;
843         struct nameidata nd;
844         struct ucred *cred;
845
846         /*
847          * Need something to (un)trace.
848          */
849         if (ops != KTROP_CLEARFILE && facs == 0)
850                 return (EINVAL);
851
852         ktrace_enter(td);
853         if (ops != KTROP_CLEAR) {
854                 /*
855                  * an operation which requires a file argument.
856                  */
857                 NDINIT(&nd, LOOKUP, NOFOLLOW | MPSAFE, UIO_USERSPACE,
858                     uap->fname, td);
859                 flags = FREAD | FWRITE | O_NOFOLLOW;
860                 error = vn_open(&nd, &flags, 0, NULL);
861                 if (error) {
862                         ktrace_exit(td);
863                         return (error);
864                 }
865                 vfslocked = NDHASGIANT(&nd);
866                 NDFREE(&nd, NDF_ONLY_PNBUF);
867                 vp = nd.ni_vp;
868                 VOP_UNLOCK(vp, 0);
869                 if (vp->v_type != VREG) {
870                         (void) vn_close(vp, FREAD|FWRITE, td->td_ucred, td);
871                         VFS_UNLOCK_GIANT(vfslocked);
872                         ktrace_exit(td);
873                         return (EACCES);
874                 }
875                 VFS_UNLOCK_GIANT(vfslocked);
876         }
877         /*
878          * Clear all uses of the tracefile.
879          */
880         if (ops == KTROP_CLEARFILE) {
881                 int vrele_count;
882
883                 vrele_count = 0;
884                 sx_slock(&allproc_lock);
885                 FOREACH_PROC_IN_SYSTEM(p) {
886                         PROC_LOCK(p);
887                         if (p->p_tracevp == vp) {
888                                 if (ktrcanset(td, p)) {
889                                         mtx_lock(&ktrace_mtx);
890                                         ktr_freeproc(p, &cred, NULL);
891                                         mtx_unlock(&ktrace_mtx);
892                                         vrele_count++;
893                                         crfree(cred);
894                                 } else
895                                         error = EPERM;
896                         }
897                         PROC_UNLOCK(p);
898                 }
899                 sx_sunlock(&allproc_lock);
900                 if (vrele_count > 0) {
901                         vfslocked = VFS_LOCK_GIANT(vp->v_mount);
902                         while (vrele_count-- > 0)
903                                 vrele(vp);
904                         VFS_UNLOCK_GIANT(vfslocked);
905                 }
906                 goto done;
907         }
908         /*
909          * do it
910          */
911         sx_slock(&proctree_lock);
912         if (uap->pid < 0) {
913                 /*
914                  * by process group
915                  */
916                 pg = pgfind(-uap->pid);
917                 if (pg == NULL) {
918                         sx_sunlock(&proctree_lock);
919                         error = ESRCH;
920                         goto done;
921                 }
922                 /*
923                  * ktrops() may call vrele(). Lock pg_members
924                  * by the proctree_lock rather than pg_mtx.
925                  */
926                 PGRP_UNLOCK(pg);
927                 nfound = 0;
928                 LIST_FOREACH(p, &pg->pg_members, p_pglist) {
929                         PROC_LOCK(p);
930                         if (p->p_state == PRS_NEW ||
931                             p_cansee(td, p) != 0) {
932                                 PROC_UNLOCK(p); 
933                                 continue;
934                         }
935                         nfound++;
936                         if (descend)
937                                 ret |= ktrsetchildren(td, p, ops, facs, vp);
938                         else
939                                 ret |= ktrops(td, p, ops, facs, vp);
940                 }
941                 if (nfound == 0) {
942                         sx_sunlock(&proctree_lock);
943                         error = ESRCH;
944                         goto done;
945                 }
946         } else {
947                 /*
948                  * by pid
949                  */
950                 p = pfind(uap->pid);
951                 if (p == NULL)
952                         error = ESRCH;
953                 else
954                         error = p_cansee(td, p);
955                 if (error) {
956                         if (p != NULL)
957                                 PROC_UNLOCK(p);
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 sys_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_ASSERT(p, MA_OWNED);
1030         if (!ktrcanset(td, p)) {
1031                 PROC_UNLOCK(p);
1032                 return (0);
1033         }
1034         if (p->p_flag & P_WEXIT) {
1035                 /* If the process is exiting, just ignore it. */
1036                 PROC_UNLOCK(p);
1037                 return (1);
1038         }
1039         mtx_lock(&ktrace_mtx);
1040         if (ops == KTROP_SET) {
1041                 if (p->p_tracevp != vp) {
1042                         /*
1043                          * if trace file already in use, relinquish below
1044                          */
1045                         tracevp = p->p_tracevp;
1046                         VREF(vp);
1047                         p->p_tracevp = vp;
1048                 }
1049                 if (p->p_tracecred != td->td_ucred) {
1050                         tracecred = p->p_tracecred;
1051                         p->p_tracecred = crhold(td->td_ucred);
1052                 }
1053                 p->p_traceflag |= facs;
1054                 if (priv_check(td, PRIV_KTRACE) == 0)
1055                         p->p_traceflag |= KTRFAC_ROOT;
1056         } else {
1057                 /* KTROP_CLEAR */
1058                 if (((p->p_traceflag &= ~facs) & KTRFAC_MASK) == 0)
1059                         /* no more tracing */
1060                         ktr_freeproc(p, &tracecred, &tracevp);
1061         }
1062         mtx_unlock(&ktrace_mtx);
1063         if ((p->p_traceflag & KTRFAC_MASK) != 0)
1064                 ktrprocctor_entered(td, p);
1065         PROC_UNLOCK(p);
1066         if (tracevp != NULL) {
1067                 int vfslocked;
1068
1069                 vfslocked = VFS_LOCK_GIANT(tracevp->v_mount);
1070                 vrele(tracevp);
1071                 VFS_UNLOCK_GIANT(vfslocked);
1072         }
1073         if (tracecred != NULL)
1074                 crfree(tracecred);
1075
1076         return (1);
1077 }
1078
1079 static int
1080 ktrsetchildren(td, top, ops, facs, vp)
1081         struct thread *td;
1082         struct proc *top;
1083         int ops, facs;
1084         struct vnode *vp;
1085 {
1086         register struct proc *p;
1087         register int ret = 0;
1088
1089         p = top;
1090         PROC_LOCK_ASSERT(p, MA_OWNED);
1091         sx_assert(&proctree_lock, SX_LOCKED);
1092         for (;;) {
1093                 ret |= ktrops(td, p, ops, facs, vp);
1094                 /*
1095                  * If this process has children, descend to them next,
1096                  * otherwise do any siblings, and if done with this level,
1097                  * follow back up the tree (but not past top).
1098                  */
1099                 if (!LIST_EMPTY(&p->p_children))
1100                         p = LIST_FIRST(&p->p_children);
1101                 else for (;;) {
1102                         if (p == top)
1103                                 return (ret);
1104                         if (LIST_NEXT(p, p_sibling)) {
1105                                 p = LIST_NEXT(p, p_sibling);
1106                                 break;
1107                         }
1108                         p = p->p_pptr;
1109                 }
1110                 PROC_LOCK(p);
1111         }
1112         /*NOTREACHED*/
1113 }
1114
1115 static void
1116 ktr_writerequest(struct thread *td, struct ktr_request *req)
1117 {
1118         struct ktr_header *kth;
1119         struct vnode *vp;
1120         struct proc *p;
1121         struct ucred *cred;
1122         struct uio auio;
1123         struct iovec aiov[3];
1124         struct mount *mp;
1125         int datalen, buflen, vrele_count;
1126         int error, vfslocked;
1127
1128         /*
1129          * We hold the vnode and credential for use in I/O in case ktrace is
1130          * disabled on the process as we write out the request.
1131          *
1132          * XXXRW: This is not ideal: we could end up performing a write after
1133          * the vnode has been closed.
1134          */
1135         mtx_lock(&ktrace_mtx);
1136         vp = td->td_proc->p_tracevp;
1137         cred = td->td_proc->p_tracecred;
1138
1139         /*
1140          * If vp is NULL, the vp has been cleared out from under this
1141          * request, so just drop it.  Make sure the credential and vnode are
1142          * in sync: we should have both or neither.
1143          */
1144         if (vp == NULL) {
1145                 KASSERT(cred == NULL, ("ktr_writerequest: cred != NULL"));
1146                 mtx_unlock(&ktrace_mtx);
1147                 return;
1148         }
1149         VREF(vp);
1150         KASSERT(cred != NULL, ("ktr_writerequest: cred == NULL"));
1151         crhold(cred);
1152         mtx_unlock(&ktrace_mtx);
1153
1154         kth = &req->ktr_header;
1155         KASSERT(((u_short)kth->ktr_type & ~KTR_DROP) <
1156             sizeof(data_lengths) / sizeof(data_lengths[0]),
1157             ("data_lengths array overflow"));
1158         datalen = data_lengths[(u_short)kth->ktr_type & ~KTR_DROP];
1159         buflen = kth->ktr_len;
1160         auio.uio_iov = &aiov[0];
1161         auio.uio_offset = 0;
1162         auio.uio_segflg = UIO_SYSSPACE;
1163         auio.uio_rw = UIO_WRITE;
1164         aiov[0].iov_base = (caddr_t)kth;
1165         aiov[0].iov_len = sizeof(struct ktr_header);
1166         auio.uio_resid = sizeof(struct ktr_header);
1167         auio.uio_iovcnt = 1;
1168         auio.uio_td = td;
1169         if (datalen != 0) {
1170                 aiov[1].iov_base = (caddr_t)&req->ktr_data;
1171                 aiov[1].iov_len = datalen;
1172                 auio.uio_resid += datalen;
1173                 auio.uio_iovcnt++;
1174                 kth->ktr_len += datalen;
1175         }
1176         if (buflen != 0) {
1177                 KASSERT(req->ktr_buffer != NULL, ("ktrace: nothing to write"));
1178                 aiov[auio.uio_iovcnt].iov_base = req->ktr_buffer;
1179                 aiov[auio.uio_iovcnt].iov_len = buflen;
1180                 auio.uio_resid += buflen;
1181                 auio.uio_iovcnt++;
1182         }
1183
1184         vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1185         vn_start_write(vp, &mp, V_WAIT);
1186         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1187 #ifdef MAC
1188         error = mac_vnode_check_write(cred, NOCRED, vp);
1189         if (error == 0)
1190 #endif
1191                 error = VOP_WRITE(vp, &auio, IO_UNIT | IO_APPEND, cred);
1192         VOP_UNLOCK(vp, 0);
1193         vn_finished_write(mp);
1194         crfree(cred);
1195         if (!error) {
1196                 vrele(vp);
1197                 VFS_UNLOCK_GIANT(vfslocked);
1198                 return;
1199         }
1200         VFS_UNLOCK_GIANT(vfslocked);
1201
1202         /*
1203          * If error encountered, give up tracing on this vnode.  We defer
1204          * all the vrele()'s on the vnode until after we are finished walking
1205          * the various lists to avoid needlessly holding locks.
1206          * NB: at this point we still hold the vnode reference that must
1207          * not go away as we need the valid vnode to compare with. Thus let
1208          * vrele_count start at 1 and the reference will be freed
1209          * by the loop at the end after our last use of vp.
1210          */
1211         log(LOG_NOTICE, "ktrace write failed, errno %d, tracing stopped\n",
1212             error);
1213         vrele_count = 1;
1214         /*
1215          * First, clear this vnode from being used by any processes in the
1216          * system.
1217          * XXX - If one process gets an EPERM writing to the vnode, should
1218          * we really do this?  Other processes might have suitable
1219          * credentials for the operation.
1220          */
1221         cred = NULL;
1222         sx_slock(&allproc_lock);
1223         FOREACH_PROC_IN_SYSTEM(p) {
1224                 PROC_LOCK(p);
1225                 if (p->p_tracevp == vp) {
1226                         mtx_lock(&ktrace_mtx);
1227                         ktr_freeproc(p, &cred, NULL);
1228                         mtx_unlock(&ktrace_mtx);
1229                         vrele_count++;
1230                 }
1231                 PROC_UNLOCK(p);
1232                 if (cred != NULL) {
1233                         crfree(cred);
1234                         cred = NULL;
1235                 }
1236         }
1237         sx_sunlock(&allproc_lock);
1238
1239         vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1240         while (vrele_count-- > 0)
1241                 vrele(vp);
1242         VFS_UNLOCK_GIANT(vfslocked);
1243 }
1244
1245 /*
1246  * Return true if caller has permission to set the ktracing state
1247  * of target.  Essentially, the target can't possess any
1248  * more permissions than the caller.  KTRFAC_ROOT signifies that
1249  * root previously set the tracing status on the target process, and
1250  * so, only root may further change it.
1251  */
1252 static int
1253 ktrcanset(td, targetp)
1254         struct thread *td;
1255         struct proc *targetp;
1256 {
1257
1258         PROC_LOCK_ASSERT(targetp, MA_OWNED);
1259         if (targetp->p_traceflag & KTRFAC_ROOT &&
1260             priv_check(td, PRIV_KTRACE))
1261                 return (0);
1262
1263         if (p_candebug(td, targetp) != 0)
1264                 return (0);
1265
1266         return (1);
1267 }
1268
1269 #endif /* KTRACE */