kern_ktrace.c revision 1.120.4.1 1 /* $NetBSD: kern_ktrace.c,v 1.120.4.1 2007/03/29 19:27:57 reinoud Exp $ */
2
3 /*
4 * Copyright (c) 1989, 1993
5 * The Regents of the University of California. All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 *
31 * @(#)kern_ktrace.c 8.5 (Berkeley) 5/14/95
32 */
33
34 #include <sys/cdefs.h>
35 __KERNEL_RCSID(0, "$NetBSD: kern_ktrace.c,v 1.120.4.1 2007/03/29 19:27:57 reinoud Exp $");
36
37 #include "opt_ktrace.h"
38 #include "opt_compat_mach.h"
39
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/proc.h>
43 #include <sys/file.h>
44 #include <sys/namei.h>
45 #include <sys/vnode.h>
46 #include <sys/kernel.h>
47 #include <sys/kthread.h>
48 #include <sys/ktrace.h>
49 #include <sys/kmem.h>
50 #include <sys/syslog.h>
51 #include <sys/filedesc.h>
52 #include <sys/ioctl.h>
53 #include <sys/callout.h>
54 #include <sys/kauth.h>
55
56 #include <sys/mount.h>
57 #include <sys/syscallargs.h>
58
59 #ifdef KTRACE
60
61 /*
62 * TODO:
63 * - need better error reporting?
64 * - userland utility to sort ktrace.out by timestamp.
65 * - keep minimum information in ktrace_entry when rest of alloc failed.
66 * - per trace control of configurable parameters.
67 */
68
69 struct ktrace_entry {
70 TAILQ_ENTRY(ktrace_entry) kte_list;
71 struct ktr_header kte_kth;
72 void *kte_buf;
73 size_t kte_bufsz;
74 #define KTE_SPACE 32
75 uint8_t kte_space[KTE_SPACE];
76 };
77
78 struct ktr_desc {
79 TAILQ_ENTRY(ktr_desc) ktd_list;
80 int ktd_flags;
81 #define KTDF_WAIT 0x0001
82 #define KTDF_DONE 0x0002
83 #define KTDF_BLOCKING 0x0004
84 #define KTDF_INTERACTIVE 0x0008
85 int ktd_error;
86 #define KTDE_ENOMEM 0x0001
87 #define KTDE_ENOSPC 0x0002
88 int ktd_errcnt;
89 int ktd_ref; /* # of reference */
90 int ktd_qcount; /* # of entry in the queue */
91
92 /*
93 * Params to control behaviour.
94 */
95 int ktd_delayqcnt; /* # of entry allowed to delay */
96 int ktd_wakedelay; /* delay of wakeup in *tick* */
97 int ktd_intrwakdl; /* ditto, but when interactive */
98
99 struct file *ktd_fp; /* trace output file */
100 struct proc *ktd_proc; /* our kernel thread */
101 TAILQ_HEAD(, ktrace_entry) ktd_queue;
102 struct callout ktd_wakch; /* delayed wakeup */
103 kcondvar_t ktd_sync_cv;
104 kcondvar_t ktd_cv;
105 };
106
107 static int ktealloc(struct ktrace_entry **, void **, struct lwp *, int,
108 size_t);
109 static void ktrwrite(struct ktr_desc *, struct ktrace_entry *);
110 static int ktrace_common(struct lwp *, int, int, int, struct file *);
111 static int ktrops(struct lwp *, struct proc *, int, int,
112 struct ktr_desc *);
113 static int ktrsetchildren(struct lwp *, struct proc *, int, int,
114 struct ktr_desc *);
115 static int ktrcanset(struct lwp *, struct proc *);
116 static int ktrsamefile(struct file *, struct file *);
117
118 static struct ktr_desc *
119 ktd_lookup(struct file *);
120 static void ktdrel(struct ktr_desc *);
121 static void ktdref(struct ktr_desc *);
122 static void ktraddentry(struct lwp *, struct ktrace_entry *, int);
123 /* Flags for ktraddentry (3rd arg) */
124 #define KTA_NOWAIT 0x0000
125 #define KTA_WAITOK 0x0001
126 #define KTA_LARGE 0x0002
127 static void ktefree(struct ktrace_entry *);
128 static void ktd_logerrl(struct ktr_desc *, int);
129 static void ktrace_thread(void *);
130 static int ktrderefall(struct ktr_desc *, int);
131
132 /*
133 * Default vaules.
134 */
135 #define KTD_MAXENTRY 1000 /* XXX: tune */
136 #define KTD_TIMEOUT 5 /* XXX: tune */
137 #define KTD_DELAYQCNT 100 /* XXX: tune */
138 #define KTD_WAKEDELAY 5000 /* XXX: tune */
139 #define KTD_INTRWAKDL 100 /* XXX: tune */
140
141 /*
142 * Patchable variables.
143 */
144 int ktd_maxentry = KTD_MAXENTRY; /* max # of entry in the queue */
145 int ktd_timeout = KTD_TIMEOUT; /* timeout in seconds */
146 int ktd_delayqcnt = KTD_DELAYQCNT; /* # of entry allowed to delay */
147 int ktd_wakedelay = KTD_WAKEDELAY; /* delay of wakeup in *ms* */
148 int ktd_intrwakdl = KTD_INTRWAKDL; /* ditto, but when interactive */
149
150 kmutex_t ktrace_mutex;
151 static TAILQ_HEAD(, ktr_desc) ktdq = TAILQ_HEAD_INITIALIZER(ktdq);
152
153 MALLOC_DEFINE(M_KTRACE, "ktrace", "ktrace data buffer");
154 POOL_INIT(kte_pool, sizeof(struct ktrace_entry), 0, 0, 0,
155 "ktepl", &pool_allocator_nointr, IPL_NONE);
156
157 static void
158 ktd_wakeup(struct ktr_desc *ktd)
159 {
160
161 callout_stop(&ktd->ktd_wakch);
162 cv_signal(&ktd->ktd_cv);
163 }
164
165 static void
166 ktd_callout(void *arg)
167 {
168
169 /*
170 * XXXSMP Should be acquiring ktrace_mutex, but that
171 * is not yet possible from a callout. For now, we'll
172 * rely on the callout & ktrace thread both holding the
173 * kernel_lock.
174 */
175 ktd_wakeup(arg);
176 }
177
178 static void
179 ktd_logerrl(struct ktr_desc *ktd, int error)
180 {
181
182 ktd->ktd_error |= error;
183 ktd->ktd_errcnt++;
184 }
185
186 #if 0
187 static void
188 ktd_logerr(struct proc *p, int error)
189 {
190 struct ktr_desc *ktd;
191
192 KASSERT(mutex_owned(&ktrace_mutex));
193
194 ktd = p->p_tracep;
195 if (ktd == NULL)
196 return;
197
198 ktd_logerrl(ktd, error);
199 }
200 #endif
201
202 static inline int
203 ktrenter(struct lwp *l)
204 {
205
206 if ((l->l_pflag & LP_KTRACTIVE) != 0)
207 return 1;
208 l->l_pflag |= LP_KTRACTIVE;
209 return 0;
210 }
211
212 static inline void
213 ktrexit(struct lwp *l)
214 {
215
216 l->l_pflag &= ~LP_KTRACTIVE;
217 }
218
219 /*
220 * Initialise the ktrace system.
221 */
222 void
223 ktrinit(void)
224 {
225
226 mutex_init(&ktrace_mutex, MUTEX_DEFAULT, IPL_NONE);
227 }
228
229 /*
230 * Release a reference. Called with ktrace_mutex held.
231 */
232 void
233 ktdrel(struct ktr_desc *ktd)
234 {
235
236 KASSERT(mutex_owned(&ktrace_mutex));
237
238 KDASSERT(ktd->ktd_ref != 0);
239 KASSERT(ktd->ktd_ref > 0);
240 if (--ktd->ktd_ref <= 0) {
241 ktd->ktd_flags |= KTDF_DONE;
242 cv_signal(&ktd->ktd_cv);
243 }
244 }
245
246 void
247 ktdref(struct ktr_desc *ktd)
248 {
249
250 KASSERT(mutex_owned(&ktrace_mutex));
251
252 ktd->ktd_ref++;
253 }
254
255 struct ktr_desc *
256 ktd_lookup(struct file *fp)
257 {
258 struct ktr_desc *ktd;
259
260 KASSERT(mutex_owned(&ktrace_mutex));
261
262 for (ktd = TAILQ_FIRST(&ktdq); ktd != NULL;
263 ktd = TAILQ_NEXT(ktd, ktd_list)) {
264 if (ktrsamefile(ktd->ktd_fp, fp)) {
265 ktd->ktd_ref++;
266 break;
267 }
268 }
269
270 return (ktd);
271 }
272
273 void
274 ktraddentry(struct lwp *l, struct ktrace_entry *kte, int flags)
275 {
276 struct proc *p = l->l_proc;
277 struct ktr_desc *ktd;
278 #ifdef DEBUG
279 struct timeval t1, t2;
280 #endif
281
282 mutex_enter(&ktrace_mutex);
283
284 if (p->p_traceflag & KTRFAC_TRC_EMUL) {
285 /* Add emulation trace before first entry for this process */
286 p->p_traceflag &= ~KTRFAC_TRC_EMUL;
287 mutex_exit(&ktrace_mutex);
288 ktrexit(l);
289 ktremul(l);
290 (void)ktrenter(l);
291 mutex_enter(&ktrace_mutex);
292 }
293
294 /*
295 * Tracing may be canceled while we were sleeping waiting for
296 * memory.
297 */
298 ktd = p->p_tracep;
299 if (ktd == NULL)
300 goto freekte;
301
302 /*
303 * Bump reference count so that the object will remain while
304 * we are here. Note that the trace is controlled by other
305 * process.
306 */
307 ktdref(ktd);
308
309 if (ktd->ktd_flags & KTDF_DONE)
310 goto relktd;
311
312 if (ktd->ktd_qcount > ktd_maxentry) {
313 ktd_logerrl(ktd, KTDE_ENOSPC);
314 goto relktd;
315 }
316 TAILQ_INSERT_TAIL(&ktd->ktd_queue, kte, kte_list);
317 ktd->ktd_qcount++;
318 if (ktd->ktd_flags & KTDF_BLOCKING)
319 goto skip_sync;
320
321 if (flags & KTA_WAITOK &&
322 (/* flags & KTA_LARGE */0 || ktd->ktd_flags & KTDF_WAIT ||
323 ktd->ktd_qcount > ktd_maxentry >> 1))
324 /*
325 * Sync with writer thread since we're requesting rather
326 * big one or many requests are pending.
327 */
328 do {
329 ktd->ktd_flags |= KTDF_WAIT;
330 ktd_wakeup(ktd);
331 #ifdef DEBUG
332 getmicrouptime(&t1);
333 #endif
334 if (cv_timedwait(&ktd->ktd_sync_cv, &ktrace_mutex,
335 ktd_timeout * hz) != 0) {
336 ktd->ktd_flags |= KTDF_BLOCKING;
337 /*
338 * Maybe the writer thread is blocking
339 * completely for some reason, but
340 * don't stop target process forever.
341 */
342 log(LOG_NOTICE, "ktrace timeout\n");
343 break;
344 }
345 #ifdef DEBUG
346 getmicrouptime(&t2);
347 timersub(&t2, &t1, &t2);
348 if (t2.tv_sec > 0)
349 log(LOG_NOTICE,
350 "ktrace long wait: %ld.%06ld\n",
351 t2.tv_sec, t2.tv_usec);
352 #endif
353 } while (p->p_tracep == ktd &&
354 (ktd->ktd_flags & (KTDF_WAIT | KTDF_DONE)) == KTDF_WAIT);
355 else {
356 /* Schedule delayed wakeup */
357 if (ktd->ktd_qcount > ktd->ktd_delayqcnt)
358 ktd_wakeup(ktd); /* Wakeup now */
359 else if (!callout_pending(&ktd->ktd_wakch))
360 callout_reset(&ktd->ktd_wakch,
361 ktd->ktd_flags & KTDF_INTERACTIVE ?
362 ktd->ktd_intrwakdl : ktd->ktd_wakedelay,
363 ktd_callout, ktd);
364 }
365
366 skip_sync:
367 ktdrel(ktd);
368 mutex_exit(&ktrace_mutex);
369 ktrexit(l);
370 return;
371
372 relktd:
373 ktdrel(ktd);
374
375 freekte:
376 mutex_exit(&ktrace_mutex);
377 ktefree(kte);
378 ktrexit(l);
379 }
380
381 void
382 ktefree(struct ktrace_entry *kte)
383 {
384
385 KERNEL_LOCK(1, curlwp); /* XXXSMP */
386 if (kte->kte_buf != kte->kte_space)
387 kmem_free(kte->kte_buf, kte->kte_bufsz);
388 pool_put(&kte_pool, kte);
389 KERNEL_UNLOCK_ONE(curlwp); /* XXXSMP */
390 }
391
392 /*
393 * "deep" compare of two files for the purposes of clearing a trace.
394 * Returns true if they're the same open file, or if they point at the
395 * same underlying vnode/socket.
396 */
397
398 int
399 ktrsamefile(struct file *f1, struct file *f2)
400 {
401
402 return ((f1 == f2) ||
403 ((f1 != NULL) && (f2 != NULL) &&
404 (f1->f_type == f2->f_type) &&
405 (f1->f_data == f2->f_data)));
406 }
407
408 void
409 ktrderef(struct proc *p)
410 {
411 struct ktr_desc *ktd = p->p_tracep;
412
413 KASSERT(mutex_owned(&ktrace_mutex));
414
415 p->p_traceflag = 0;
416 if (ktd == NULL)
417 return;
418 p->p_tracep = NULL;
419
420 cv_broadcast(&ktd->ktd_sync_cv);
421 ktdrel(ktd);
422 }
423
424 void
425 ktradref(struct proc *p)
426 {
427 struct ktr_desc *ktd = p->p_tracep;
428
429 KASSERT(mutex_owned(&ktrace_mutex));
430
431 ktdref(ktd);
432 }
433
434 int
435 ktrderefall(struct ktr_desc *ktd, int auth)
436 {
437 struct lwp *curl = curlwp;
438 struct proc *p;
439 int error = 0;
440
441 mutex_enter(&proclist_lock);
442 PROCLIST_FOREACH(p, &allproc) {
443 if (p->p_tracep != ktd)
444 continue;
445 mutex_enter(&p->p_mutex);
446 mutex_enter(&ktrace_mutex);
447 if (p->p_tracep == ktd) {
448 if (!auth || ktrcanset(curl, p))
449 ktrderef(p);
450 else
451 error = EPERM;
452 }
453 mutex_exit(&ktrace_mutex);
454 mutex_exit(&p->p_mutex);
455 }
456 mutex_exit(&proclist_lock);
457
458 return error;
459 }
460
461 int
462 ktealloc(struct ktrace_entry **ktep, void **bufp, struct lwp *l, int type,
463 size_t sz)
464 {
465 struct proc *p = l->l_proc;
466 struct ktrace_entry *kte;
467 struct ktr_header *kth;
468 void *buf;
469
470 if (ktrenter(l))
471 return EAGAIN;
472
473 KERNEL_LOCK(1, l); /* XXXSMP */
474 kte = pool_get(&kte_pool, PR_WAITOK);
475 if (sz > sizeof(kte->kte_space)) {
476 if ((buf = kmem_alloc(sz, KM_SLEEP)) == NULL) {
477 pool_put(&kte_pool, kte);
478 KERNEL_UNLOCK_ONE(l); /* XXXSMP */
479 ktrexit(l);
480 return ENOMEM;
481 }
482 } else
483 buf = kte->kte_space;
484 KERNEL_UNLOCK_ONE(l); /* XXXSMP */
485
486 kte->kte_bufsz = sz;
487 kte->kte_buf = buf;
488
489 kth = &kte->kte_kth;
490 (void)memset(kth, 0, sizeof(*kth));
491 kth->ktr_len = sz;
492 kth->ktr_type = type;
493 kth->ktr_pid = p->p_pid;
494 memcpy(kth->ktr_comm, p->p_comm, MAXCOMLEN);
495 kth->ktr_version = KTRFAC_VERSION(p->p_traceflag);
496
497 switch (KTRFAC_VERSION(p->p_traceflag)) {
498 case 0:
499 /* This is the original format */
500 microtime(&kth->ktr_tv);
501 break;
502 case 1:
503 kth->ktr_lid = l->l_lid;
504 nanotime(&kth->ktr_time);
505 break;
506 default:
507 break;
508 }
509
510 *ktep = kte;
511 *bufp = buf;
512
513 return 0;
514 }
515
516 void
517 ktrsyscall(struct lwp *l, register_t code, register_t realcode,
518 const struct sysent *callp, register_t args[])
519 {
520 struct proc *p = l->l_proc;
521 struct ktrace_entry *kte;
522 struct ktr_syscall *ktp;
523 register_t *argp;
524 int argsize;
525 size_t len;
526 u_int i;
527
528 if (callp == NULL)
529 callp = p->p_emul->e_sysent;
530
531 argsize = callp[code].sy_argsize;
532 #ifdef _LP64
533 if (p->p_flag & PK_32)
534 argsize = argsize << 1;
535 #endif
536 len = sizeof(struct ktr_syscall) + argsize;
537
538 if (ktealloc(&kte, (void *)&ktp, l, KTR_SYSCALL, len))
539 return;
540
541 ktp->ktr_code = realcode;
542 ktp->ktr_argsize = argsize;
543 argp = (register_t *)(ktp + 1);
544 for (i = 0; i < (argsize / sizeof(*argp)); i++)
545 *argp++ = args[i];
546
547 ktraddentry(l, kte, KTA_WAITOK);
548 }
549
550 void
551 ktrsysret(struct lwp *l, register_t code, int error, register_t *retval)
552 {
553 struct ktrace_entry *kte;
554 struct ktr_sysret *ktp;
555
556 if (ktealloc(&kte, (void *)&ktp, l, KTR_SYSRET,
557 sizeof(struct ktr_sysret)))
558 return;
559
560 ktp->ktr_code = code;
561 ktp->ktr_eosys = 0; /* XXX unused */
562 ktp->ktr_error = error;
563 ktp->ktr_retval = retval ? retval[0] : 0;
564 ktp->ktr_retval_1 = retval ? retval[1] : 0;
565
566 ktraddentry(l, kte, KTA_WAITOK);
567 }
568
569 /*
570 * XXX: ndp->ni_pathlen should be passed.
571 */
572 void
573 ktrnamei(struct lwp *l, char *path)
574 {
575
576 ktrkmem(l, KTR_NAMEI, path, strlen(path));
577 }
578
579 void
580 ktremul(struct lwp *l)
581 {
582 const char *emul = l->l_proc->p_emul->e_name;
583
584 ktrkmem(l, KTR_EMUL, emul, strlen(emul));
585 }
586
587 void
588 ktrkmem(struct lwp *l, int type, const void *bf, size_t len)
589 {
590 struct ktrace_entry *kte;
591 void *buf;
592
593 if (ktealloc(&kte, &buf, l, type, len))
594 return;
595 memcpy(buf, bf, len);
596 ktraddentry(l, kte, KTA_WAITOK);
597 }
598
599 void
600 ktrgenio(struct lwp *l, int fd, enum uio_rw rw, struct iovec *iov,
601 int len, int error)
602 {
603 struct ktrace_entry *kte;
604 struct ktr_genio *ktp;
605 int resid = len, cnt;
606 void *cp;
607 int buflen;
608
609 if (error)
610 return;
611
612 next:
613 buflen = min(PAGE_SIZE, resid + sizeof(struct ktr_genio));
614
615 if (ktealloc(&kte, (void *)&ktp, l, KTR_GENIO, buflen))
616 return;
617
618 ktp->ktr_fd = fd;
619 ktp->ktr_rw = rw;
620
621 cp = (void *)(ktp + 1);
622 buflen -= sizeof(struct ktr_genio);
623 kte->kte_kth.ktr_len = sizeof(struct ktr_genio);
624
625 while (buflen > 0) {
626 cnt = min(iov->iov_len, buflen);
627 if (copyin(iov->iov_base, cp, cnt) != 0)
628 goto out;
629 kte->kte_kth.ktr_len += cnt;
630 buflen -= cnt;
631 resid -= cnt;
632 iov->iov_len -= cnt;
633 if (iov->iov_len == 0)
634 iov++;
635 else
636 iov->iov_base = (char *)iov->iov_base + cnt;
637 }
638
639 /*
640 * Don't push so many entry at once. It will cause kmem map
641 * shortage.
642 */
643 ktraddentry(l, kte, KTA_WAITOK | KTA_LARGE);
644 if (resid > 0) {
645 if (curcpu()->ci_schedstate.spc_flags & SPCF_SHOULDYIELD) {
646 (void)ktrenter(l);
647 preempt();
648 ktrexit(l);
649 }
650
651 goto next;
652 }
653
654 return;
655
656 out:
657 ktefree(kte);
658 ktrexit(l);
659 }
660
661 void
662 ktrpsig(struct lwp *l, int sig, sig_t action, const sigset_t *mask,
663 const ksiginfo_t *ksi)
664 {
665 struct ktrace_entry *kte;
666 struct {
667 struct ktr_psig kp;
668 siginfo_t si;
669 } *kbuf;
670
671 if (ktealloc(&kte, (void *)&kbuf, l, KTR_PSIG, sizeof(*kbuf)))
672 return;
673
674 kbuf->kp.signo = (char)sig;
675 kbuf->kp.action = action;
676 kbuf->kp.mask = *mask;
677
678 if (ksi) {
679 kbuf->kp.code = KSI_TRAPCODE(ksi);
680 (void)memset(&kbuf->si, 0, sizeof(kbuf->si));
681 kbuf->si._info = ksi->ksi_info;
682 kte->kte_kth.ktr_len = sizeof(*kbuf);
683 } else {
684 kbuf->kp.code = 0;
685 kte->kte_kth.ktr_len = sizeof(struct ktr_psig);
686 }
687
688 ktraddentry(l, kte, KTA_WAITOK);
689 }
690
691 void
692 ktrcsw(struct lwp *l, int out, int user)
693 {
694 struct proc *p = l->l_proc;
695 struct ktrace_entry *kte;
696 struct ktr_csw *kc;
697
698 /*
699 * Don't record context switches resulting from blocking on
700 * locks; it's too easy to get duff results.
701 */
702 if (l->l_syncobj == &mutex_syncobj || l->l_syncobj == &rw_syncobj)
703 return;
704
705 /*
706 * We can't sleep if we're already going to sleep (if original
707 * condition is met during sleep, we hang up).
708 *
709 * XXX This is not ideal: it would be better to maintain a pool
710 * of ktes and actually push this to the kthread when context
711 * switch happens, however given the points where we are called
712 * from that is difficult to do.
713 */
714 if (out) {
715 if (ktrenter(l))
716 return;
717
718 switch (KTRFAC_VERSION(p->p_traceflag)) {
719 case 0:
720 /* This is the original format */
721 microtime(&l->l_ktrcsw.tv);
722 l->l_pflag |= LP_KTRCSW;
723 break;
724 case 1:
725 nanotime(&l->l_ktrcsw.ts);
726 l->l_pflag |= LP_KTRCSW;
727 break;
728 default:
729 break;
730 }
731
732 if (user)
733 l->l_pflag |= LP_KTRCSWUSER;
734 else
735 l->l_pflag &= ~LP_KTRCSWUSER;
736
737 ktrexit(l);
738 return;
739 }
740
741 /*
742 * On the way back in, we need to record twice: once for entry, and
743 * once for exit.
744 */
745 if ((l->l_pflag & LP_KTRCSW) != 0) {
746 l->l_pflag &= ~LP_KTRCSW;
747
748 if (ktealloc(&kte, (void *)&kc, l, KTR_CSW, sizeof(*kc)))
749 return;
750
751 kc->out = 1;
752 kc->user = ((l->l_pflag & LP_KTRCSWUSER) != 0);
753
754 switch (KTRFAC_VERSION(p->p_traceflag)) {
755 case 0:
756 /* This is the original format */
757 memcpy(&kte->kte_kth.ktr_tv, &l->l_ktrcsw.tv,
758 sizeof(kte->kte_kth.ktr_tv));
759 break;
760 case 1:
761 memcpy(&kte->kte_kth.ktr_time, &l->l_ktrcsw.ts,
762 sizeof(kte->kte_kth.ktr_time));
763 break;
764 default:
765 break;
766 }
767
768 ktraddentry(l, kte, KTA_WAITOK);
769 }
770
771 if (ktealloc(&kte, (void *)&kc, l, KTR_CSW, sizeof(*kc)))
772 return;
773
774 kc->out = 0;
775 kc->user = user;
776
777 ktraddentry(l, kte, KTA_WAITOK);
778 }
779
780 int
781 ktruser(struct lwp *l, const char *id, void *addr, size_t len, int ustr)
782 {
783 struct ktrace_entry *kte;
784 struct ktr_user *ktp;
785 void *user_dta;
786 int error;
787
788 if (len > KTR_USER_MAXLEN)
789 return ENOSPC;
790
791 error = ktealloc(&kte, (void *)&ktp, l, KTR_USER, sizeof(*ktp) + len);
792 if (error != 0)
793 return error;
794
795 if (ustr) {
796 if (copyinstr(id, ktp->ktr_id, KTR_USER_MAXIDLEN, NULL) != 0)
797 ktp->ktr_id[0] = '\0';
798 } else
799 strncpy(ktp->ktr_id, id, KTR_USER_MAXIDLEN);
800 ktp->ktr_id[KTR_USER_MAXIDLEN-1] = '\0';
801
802 user_dta = (void *)(ktp + 1);
803 if ((error = copyin(addr, (void *)user_dta, len)) != 0)
804 len = 0;
805
806 ktraddentry(l, kte, KTA_WAITOK);
807 return error;
808 }
809
810 void
811 ktrmmsg(struct lwp *l, const void *msgh, size_t size)
812 {
813 ktrkmem(l, KTR_MMSG, msgh, size);
814 }
815
816 void
817 ktrmool(struct lwp *l, const void *kaddr, size_t size, const void *uaddr)
818 {
819 struct ktrace_entry *kte;
820 struct ktr_mool *kp;
821 struct ktr_mool *bf;
822
823 if (ktealloc(&kte, (void *)&kp, l, KTR_MOOL, size + sizeof(*kp)))
824 return;
825
826 kp->uaddr = uaddr;
827 kp->size = size;
828 bf = kp + 1; /* Skip uaddr and size */
829 (void)memcpy(bf, kaddr, size);
830
831 ktraddentry(l, kte, KTA_WAITOK);
832 }
833
834 void
835 ktrmib(struct lwp *l, const int *name, u_int namelen)
836 {
837 struct ktrace_entry *kte;
838 int *namep;
839 size_t size;
840
841 size = namelen * sizeof(*name);
842
843 if (ktealloc(&kte, (void *)&namep, l, KTR_MIB, size))
844 return;
845
846 (void)memcpy(namep, name, namelen * sizeof(*name));
847
848 ktraddentry(l, kte, KTA_WAITOK);
849 }
850
851 /* Interface and common routines */
852
853 int
854 ktrace_common(struct lwp *curl, int ops, int facs, int pid, struct file *fp)
855 {
856 struct proc *curp;
857 struct proc *p;
858 struct pgrp *pg;
859 struct ktr_desc *ktd = NULL;
860 int ret = 0;
861 int error = 0;
862 int descend;
863
864 curp = curl->l_proc;
865 descend = ops & KTRFLAG_DESCEND;
866 facs = facs & ~((unsigned) KTRFAC_ROOT);
867
868 (void)ktrenter(curl);
869
870 switch (KTROP(ops)) {
871
872 case KTROP_CLEARFILE:
873 /*
874 * Clear all uses of the tracefile
875 */
876 mutex_enter(&ktrace_mutex);
877 ktd = ktd_lookup(fp);
878 mutex_exit(&ktrace_mutex);
879 if (ktd == NULL)
880 goto done;
881 error = ktrderefall(ktd, 1);
882 goto done;
883
884 case KTROP_SET:
885 mutex_enter(&ktrace_mutex);
886 ktd = ktd_lookup(fp);
887 mutex_exit(&ktrace_mutex);
888 if (ktd == NULL) {
889 ktd = kmem_alloc(sizeof(*ktd), KM_SLEEP);
890 TAILQ_INIT(&ktd->ktd_queue);
891 callout_init(&ktd->ktd_wakch);
892 cv_init(&ktd->ktd_cv, "ktrwait");
893 cv_init(&ktd->ktd_sync_cv, "ktrsync");
894 ktd->ktd_flags = ktd->ktd_qcount =
895 ktd->ktd_error = ktd->ktd_errcnt = 0;
896 ktd->ktd_ref = 1;
897 ktd->ktd_delayqcnt = ktd_delayqcnt;
898 ktd->ktd_wakedelay = mstohz(ktd_wakedelay);
899 ktd->ktd_intrwakdl = mstohz(ktd_intrwakdl);
900 /*
901 * XXX: not correct. needs an way to detect
902 * whether ktruss or ktrace.
903 */
904 if (fp->f_type == DTYPE_PIPE)
905 ktd->ktd_flags |= KTDF_INTERACTIVE;
906
907 error = kthread_create1(ktrace_thread, ktd,
908 &ktd->ktd_proc, "ktr %p", ktd);
909 if (error != 0) {
910 kmem_free(ktd, sizeof(*ktd));
911 goto done;
912 }
913
914 simple_lock(&fp->f_slock);
915 fp->f_count++;
916 simple_unlock(&fp->f_slock);
917 ktd->ktd_fp = fp;
918
919 mutex_enter(&ktrace_mutex);
920 if (ktd_lookup(fp) != NULL) {
921 ktdrel(ktd);
922 ktd = NULL;
923 } else
924 TAILQ_INSERT_TAIL(&ktdq, ktd, ktd_list);
925 mutex_exit(&ktrace_mutex);
926 if (ktd == NULL) {
927 tsleep(&lbolt, PWAIT, "ktrzzz", 0);
928 goto done;
929 }
930 }
931 break;
932
933 case KTROP_CLEAR:
934 break;
935 }
936
937 /*
938 * need something to (un)trace (XXX - why is this here?)
939 */
940 if (!facs) {
941 error = EINVAL;
942 goto done;
943 }
944
945 /*
946 * do it
947 */
948 mutex_enter(&proclist_lock);
949 if (pid < 0) {
950 /*
951 * by process group
952 */
953 pg = pg_find(-pid, PFIND_LOCKED);
954 if (pg == NULL)
955 error = ESRCH;
956 else {
957 LIST_FOREACH(p, &pg->pg_members, p_pglist) {
958 if (descend)
959 ret |= ktrsetchildren(curl, p, ops,
960 facs, ktd);
961 else
962 ret |= ktrops(curl, p, ops, facs,
963 ktd);
964 }
965 }
966
967 } else {
968 /*
969 * by pid
970 */
971 p = p_find(pid, PFIND_LOCKED);
972 if (p == NULL)
973 error = ESRCH;
974 else if (descend)
975 ret |= ktrsetchildren(curl, p, ops, facs, ktd);
976 else
977 ret |= ktrops(curl, p, ops, facs, ktd);
978 }
979 mutex_exit(&proclist_lock);
980 if (error == 0 && !ret)
981 error = EPERM;
982 done:
983 if (ktd != NULL) {
984 mutex_enter(&ktrace_mutex);
985 if (error != 0) {
986 /*
987 * Wakeup the thread so that it can be die if we
988 * can't trace any process.
989 */
990 ktd_wakeup(ktd);
991 }
992 if (KTROP(ops) == KTROP_SET || KTROP(ops) == KTROP_CLEARFILE)
993 ktdrel(ktd);
994 mutex_exit(&ktrace_mutex);
995 }
996 ktrexit(curl);
997 return (error);
998 }
999
1000 /*
1001 * fktrace system call
1002 */
1003 /* ARGSUSED */
1004 int
1005 sys_fktrace(struct lwp *l, void *v, register_t *retval)
1006 {
1007 struct sys_fktrace_args /* {
1008 syscallarg(int) fd;
1009 syscallarg(int) ops;
1010 syscallarg(int) facs;
1011 syscallarg(int) pid;
1012 } */ *uap = v;
1013 struct file *fp = NULL;
1014 struct filedesc *fdp = l->l_proc->p_fd;
1015 int error;
1016
1017 fdp = l->l_proc->p_fd;
1018 if ((fp = fd_getfile(fdp, SCARG(uap, fd))) == NULL)
1019 return (EBADF);
1020
1021 FILE_USE(fp);
1022
1023 if ((fp->f_flag & FWRITE) == 0)
1024 error = EBADF;
1025 else
1026 error = ktrace_common(l, SCARG(uap, ops),
1027 SCARG(uap, facs), SCARG(uap, pid), fp);
1028
1029 FILE_UNUSE(fp, l);
1030
1031 return error;
1032 }
1033
1034 /*
1035 * ktrace system call
1036 */
1037 /* ARGSUSED */
1038 int
1039 sys_ktrace(struct lwp *l, void *v, register_t *retval)
1040 {
1041 struct sys_ktrace_args /* {
1042 syscallarg(const char *) fname;
1043 syscallarg(int) ops;
1044 syscallarg(int) facs;
1045 syscallarg(int) pid;
1046 } */ *uap = v;
1047 struct vnode *vp = NULL;
1048 struct file *fp = NULL;
1049 struct nameidata nd;
1050 int error = 0;
1051 int fd;
1052
1053 if (ktrenter(l))
1054 return EAGAIN;
1055
1056 if (KTROP(SCARG(uap, ops)) != KTROP_CLEAR) {
1057 /*
1058 * an operation which requires a file argument.
1059 */
1060 NDINIT(&nd, LOOKUP, FOLLOW, UIO_USERSPACE, SCARG(uap, fname),
1061 l);
1062 if ((error = vn_open(&nd, FREAD|FWRITE, 0)) != 0) {
1063 ktrexit(l);
1064 return (error);
1065 }
1066 vp = nd.ni_vp;
1067 VOP_UNLOCK(vp, 0);
1068 if (vp->v_type != VREG) {
1069 (void) vn_close(vp, FREAD|FWRITE, l->l_cred, l);
1070 ktrexit(l);
1071 return (EACCES);
1072 }
1073 /*
1074 * XXX This uses up a file descriptor slot in the
1075 * tracing process for the duration of this syscall.
1076 * This is not expected to be a problem. If
1077 * falloc(NULL, ...) DTRT we could skip that part, but
1078 * that would require changing its interface to allow
1079 * the caller to pass in a ucred..
1080 *
1081 * This will FILE_USE the fp it returns, if any.
1082 * Keep it in use until we return.
1083 */
1084 if ((error = falloc(l, &fp, &fd)) != 0)
1085 goto done;
1086
1087 fp->f_flag = FWRITE;
1088 fp->f_type = DTYPE_VNODE;
1089 fp->f_ops = &vnops;
1090 fp->f_data = (void *)vp;
1091 FILE_SET_MATURE(fp);
1092 vp = NULL;
1093 }
1094 error = ktrace_common(l, SCARG(uap, ops), SCARG(uap, facs),
1095 SCARG(uap, pid), fp);
1096 done:
1097 if (vp != NULL)
1098 (void) vn_close(vp, FWRITE, l->l_cred, l);
1099 if (fp != NULL) {
1100 FILE_UNUSE(fp, l); /* release file */
1101 fdrelease(l, fd); /* release fd table slot */
1102 }
1103 return (error);
1104 }
1105
1106 int
1107 ktrops(struct lwp *curl, struct proc *p, int ops, int facs,
1108 struct ktr_desc *ktd)
1109 {
1110 int vers = ops & KTRFAC_VER_MASK;
1111 int error = 0;
1112
1113 mutex_enter(&p->p_mutex);
1114 mutex_enter(&ktrace_mutex);
1115
1116 if (!ktrcanset(curl, p))
1117 goto out;
1118
1119 switch (vers) {
1120 case KTRFACv0:
1121 case KTRFACv1:
1122 break;
1123 default:
1124 error = EINVAL;
1125 goto out;
1126 }
1127
1128 if (KTROP(ops) == KTROP_SET) {
1129 if (p->p_tracep != ktd) {
1130 /*
1131 * if trace file already in use, relinquish
1132 */
1133 ktrderef(p);
1134 p->p_tracep = ktd;
1135 ktradref(p);
1136 }
1137 p->p_traceflag |= facs;
1138 if (kauth_authorize_generic(curl->l_cred,
1139 KAUTH_GENERIC_ISSUSER, NULL) == 0)
1140 p->p_traceflag |= KTRFAC_ROOT;
1141 } else {
1142 /* KTROP_CLEAR */
1143 if (((p->p_traceflag &= ~facs) & KTRFAC_MASK) == 0) {
1144 /* no more tracing */
1145 ktrderef(p);
1146 }
1147 }
1148
1149 if (p->p_traceflag)
1150 p->p_traceflag |= vers;
1151 /*
1152 * Emit an emulation record, every time there is a ktrace
1153 * change/attach request.
1154 */
1155 if (KTRPOINT(p, KTR_EMUL))
1156 p->p_traceflag |= KTRFAC_TRC_EMUL;
1157 #ifdef __HAVE_SYSCALL_INTERN
1158 (*p->p_emul->e_syscall_intern)(p);
1159 #endif
1160
1161 out:
1162 mutex_exit(&ktrace_mutex);
1163 mutex_exit(&p->p_mutex);
1164
1165 return (1);
1166 }
1167
1168 int
1169 ktrsetchildren(struct lwp *curl, struct proc *top, int ops, int facs,
1170 struct ktr_desc *ktd)
1171 {
1172 struct proc *p;
1173 int ret = 0;
1174
1175 KASSERT(mutex_owned(&proclist_lock));
1176
1177 p = top;
1178 for (;;) {
1179 ret |= ktrops(curl, p, ops, facs, ktd);
1180 /*
1181 * If this process has children, descend to them next,
1182 * otherwise do any siblings, and if done with this level,
1183 * follow back up the tree (but not past top).
1184 */
1185 if (LIST_FIRST(&p->p_children) != NULL) {
1186 p = LIST_FIRST(&p->p_children);
1187 continue;
1188 }
1189 for (;;) {
1190 if (p == top)
1191 return (ret);
1192 if (LIST_NEXT(p, p_sibling) != NULL) {
1193 p = LIST_NEXT(p, p_sibling);
1194 break;
1195 }
1196 p = p->p_pptr;
1197 }
1198 }
1199 /*NOTREACHED*/
1200 }
1201
1202 void
1203 ktrwrite(struct ktr_desc *ktd, struct ktrace_entry *kte)
1204 {
1205 struct uio auio;
1206 struct iovec aiov[64], *iov;
1207 struct ktrace_entry *top = kte;
1208 struct ktr_header *kth;
1209 struct file *fp = ktd->ktd_fp;
1210 int error;
1211 next:
1212 auio.uio_iov = iov = &aiov[0];
1213 auio.uio_offset = 0;
1214 auio.uio_rw = UIO_WRITE;
1215 auio.uio_resid = 0;
1216 auio.uio_iovcnt = 0;
1217 UIO_SETUP_SYSSPACE(&auio);
1218 do {
1219 kth = &kte->kte_kth;
1220
1221 if (kth->ktr_version == 0) {
1222 /*
1223 * Convert back to the old format fields
1224 */
1225 TIMESPEC_TO_TIMEVAL(&kth->ktr_tv, &kth->ktr_time);
1226 kth->ktr_unused = NULL;
1227 }
1228 iov->iov_base = (void *)kth;
1229 iov++->iov_len = sizeof(struct ktr_header);
1230 auio.uio_resid += sizeof(struct ktr_header);
1231 auio.uio_iovcnt++;
1232 if (kth->ktr_len > 0) {
1233 iov->iov_base = kte->kte_buf;
1234 iov++->iov_len = kth->ktr_len;
1235 auio.uio_resid += kth->ktr_len;
1236 auio.uio_iovcnt++;
1237 }
1238 } while ((kte = TAILQ_NEXT(kte, kte_list)) != NULL &&
1239 auio.uio_iovcnt < sizeof(aiov) / sizeof(aiov[0]) - 1);
1240
1241 again:
1242 simple_lock(&fp->f_slock);
1243 FILE_USE(fp);
1244 error = (*fp->f_ops->fo_write)(fp, &fp->f_offset, &auio,
1245 fp->f_cred, FOF_UPDATE_OFFSET);
1246 FILE_UNUSE(fp, NULL);
1247 switch (error) {
1248
1249 case 0:
1250 if (auio.uio_resid > 0)
1251 goto again;
1252 if (kte != NULL)
1253 goto next;
1254 break;
1255
1256 case EWOULDBLOCK:
1257 kpause("ktrzzz", false, 1, NULL);
1258 goto again;
1259
1260 default:
1261 /*
1262 * If error encountered, give up tracing on this
1263 * vnode. Don't report EPIPE as this can easily
1264 * happen with fktrace()/ktruss.
1265 */
1266 #ifndef DEBUG
1267 if (error != EPIPE)
1268 #endif
1269 log(LOG_NOTICE,
1270 "ktrace write failed, errno %d, tracing stopped\n",
1271 error);
1272 (void)ktrderefall(ktd, 0);
1273 }
1274
1275 while ((kte = top) != NULL) {
1276 top = TAILQ_NEXT(top, kte_list);
1277 ktefree(kte);
1278 }
1279 }
1280
1281 void
1282 ktrace_thread(void *arg)
1283 {
1284 struct ktr_desc *ktd = arg;
1285 struct file *fp = ktd->ktd_fp;
1286 struct ktrace_entry *kte;
1287 int ktrerr, errcnt;
1288
1289 mutex_enter(&ktrace_mutex);
1290 for (;;) {
1291 kte = TAILQ_FIRST(&ktd->ktd_queue);
1292 if (kte == NULL) {
1293 if (ktd->ktd_flags & KTDF_WAIT) {
1294 ktd->ktd_flags &= ~(KTDF_WAIT | KTDF_BLOCKING);
1295 cv_broadcast(&ktd->ktd_sync_cv);
1296 }
1297 if (ktd->ktd_ref == 0)
1298 break;
1299 cv_wait(&ktd->ktd_cv, &ktrace_mutex);
1300 continue;
1301 }
1302 TAILQ_INIT(&ktd->ktd_queue);
1303 ktd->ktd_qcount = 0;
1304 ktrerr = ktd->ktd_error;
1305 errcnt = ktd->ktd_errcnt;
1306 ktd->ktd_error = ktd->ktd_errcnt = 0;
1307 mutex_exit(&ktrace_mutex);
1308
1309 if (ktrerr) {
1310 log(LOG_NOTICE,
1311 "ktrace failed, fp %p, error 0x%x, total %d\n",
1312 fp, ktrerr, errcnt);
1313 }
1314 ktrwrite(ktd, kte);
1315 mutex_enter(&ktrace_mutex);
1316 }
1317
1318 TAILQ_REMOVE(&ktdq, ktd, ktd_list);
1319 mutex_exit(&ktrace_mutex);
1320
1321 simple_lock(&fp->f_slock);
1322 FILE_USE(fp);
1323
1324 /*
1325 * ktrace file descriptor can't be watched (are not visible to
1326 * userspace), so no kqueue stuff here
1327 * XXX: The above comment is wrong, because the fktrace file
1328 * descriptor is available in userland.
1329 */
1330 closef(fp, NULL);
1331
1332 callout_stop(&ktd->ktd_wakch);
1333 kmem_free(ktd, sizeof(*ktd));
1334
1335 kthread_exit(0);
1336 }
1337
1338 /*
1339 * Return true if caller has permission to set the ktracing state
1340 * of target. Essentially, the target can't possess any
1341 * more permissions than the caller. KTRFAC_ROOT signifies that
1342 * root previously set the tracing status on the target process, and
1343 * so, only root may further change it.
1344 *
1345 * TODO: check groups. use caller effective gid.
1346 */
1347 int
1348 ktrcanset(struct lwp *calll, struct proc *targetp)
1349 {
1350 KASSERT(mutex_owned(&targetp->p_mutex));
1351 KASSERT(mutex_owned(&ktrace_mutex));
1352
1353 if (kauth_authorize_process(calll->l_cred, KAUTH_PROCESS_CANKTRACE,
1354 targetp, NULL, NULL, NULL) == 0)
1355 return (1);
1356
1357 return (0);
1358 }
1359 #endif /* KTRACE */
1360
1361 /*
1362 * Put user defined entry to ktrace records.
1363 */
1364 int
1365 sys_utrace(struct lwp *l, void *v, register_t *retval)
1366 {
1367 #ifdef KTRACE
1368 struct sys_utrace_args /* {
1369 syscallarg(const char *) label;
1370 syscallarg(void *) addr;
1371 syscallarg(size_t) len;
1372 } */ *uap = v;
1373 struct proc *p = l->l_proc;
1374
1375 if (!KTRPOINT(p, KTR_USER))
1376 return (0);
1377
1378 return ktruser(l, SCARG(uap, label), SCARG(uap, addr),
1379 SCARG(uap, len), 1);
1380 #else /* !KTRACE */
1381 return ENOSYS;
1382 #endif /* KTRACE */
1383 }
1384