kern_ktrace.c revision 1.124 1 /* $NetBSD: kern_ktrace.c,v 1.124 2007/07/09 21:10:52 ad 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.124 2007/07/09 21:10:52 ad 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 lwp *ktd_lwp; /* our kernel thread */
101 TAILQ_HEAD(, ktrace_entry) ktd_queue;
102 callout_t 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 void
570 ktrnamei(struct lwp *l, const char *path, size_t pathlen)
571 {
572 ktrkmem(l, KTR_NAMEI, path, pathlen);
573 }
574
575 void
576 ktrnamei2(struct lwp *l, const char *eroot, size_t erootlen,
577 const char *path, size_t pathlen)
578 {
579 struct ktrace_entry *kte;
580 void *buf;
581
582 if (ktealloc(&kte, &buf, l, KTR_NAMEI, erootlen + pathlen))
583 return;
584 memcpy(buf, eroot, erootlen);
585 buf = (char *)buf + erootlen;
586 memcpy(buf, path, pathlen);
587 ktraddentry(l, kte, KTA_WAITOK);
588 }
589
590 void
591 ktremul(struct lwp *l)
592 {
593 const char *emul = l->l_proc->p_emul->e_name;
594
595 ktrkmem(l, KTR_EMUL, emul, strlen(emul));
596 }
597
598 void
599 ktrkmem(struct lwp *l, int type, const void *bf, size_t len)
600 {
601 struct ktrace_entry *kte;
602 void *buf;
603
604 if (ktealloc(&kte, &buf, l, type, len))
605 return;
606 memcpy(buf, bf, len);
607 ktraddentry(l, kte, KTA_WAITOK);
608 }
609
610 void
611 ktrgenio(struct lwp *l, int fd, enum uio_rw rw, struct iovec *iov,
612 int len, int error)
613 {
614 struct ktrace_entry *kte;
615 struct ktr_genio *ktp;
616 int resid = len, cnt;
617 void *cp;
618 int buflen;
619
620 if (error)
621 return;
622
623 next:
624 buflen = min(PAGE_SIZE, resid + sizeof(struct ktr_genio));
625
626 if (ktealloc(&kte, (void *)&ktp, l, KTR_GENIO, buflen))
627 return;
628
629 ktp->ktr_fd = fd;
630 ktp->ktr_rw = rw;
631
632 cp = (void *)(ktp + 1);
633 buflen -= sizeof(struct ktr_genio);
634 kte->kte_kth.ktr_len = sizeof(struct ktr_genio);
635
636 while (buflen > 0) {
637 cnt = min(iov->iov_len, buflen);
638 if (copyin(iov->iov_base, cp, cnt) != 0)
639 goto out;
640 kte->kte_kth.ktr_len += cnt;
641 buflen -= cnt;
642 resid -= cnt;
643 iov->iov_len -= cnt;
644 if (iov->iov_len == 0)
645 iov++;
646 else
647 iov->iov_base = (char *)iov->iov_base + cnt;
648 }
649
650 /*
651 * Don't push so many entry at once. It will cause kmem map
652 * shortage.
653 */
654 ktraddentry(l, kte, KTA_WAITOK | KTA_LARGE);
655 if (resid > 0) {
656 if (curcpu()->ci_schedstate.spc_flags & SPCF_SHOULDYIELD) {
657 (void)ktrenter(l);
658 preempt();
659 ktrexit(l);
660 }
661
662 goto next;
663 }
664
665 return;
666
667 out:
668 ktefree(kte);
669 ktrexit(l);
670 }
671
672 void
673 ktrpsig(struct lwp *l, int sig, sig_t action, const sigset_t *mask,
674 const ksiginfo_t *ksi)
675 {
676 struct ktrace_entry *kte;
677 struct {
678 struct ktr_psig kp;
679 siginfo_t si;
680 } *kbuf;
681
682 if (ktealloc(&kte, (void *)&kbuf, l, KTR_PSIG, sizeof(*kbuf)))
683 return;
684
685 kbuf->kp.signo = (char)sig;
686 kbuf->kp.action = action;
687 kbuf->kp.mask = *mask;
688
689 if (ksi) {
690 kbuf->kp.code = KSI_TRAPCODE(ksi);
691 (void)memset(&kbuf->si, 0, sizeof(kbuf->si));
692 kbuf->si._info = ksi->ksi_info;
693 kte->kte_kth.ktr_len = sizeof(*kbuf);
694 } else {
695 kbuf->kp.code = 0;
696 kte->kte_kth.ktr_len = sizeof(struct ktr_psig);
697 }
698
699 ktraddentry(l, kte, KTA_WAITOK);
700 }
701
702 void
703 ktrcsw(struct lwp *l, int out, int user)
704 {
705 struct proc *p = l->l_proc;
706 struct ktrace_entry *kte;
707 struct ktr_csw *kc;
708
709 /*
710 * Don't record context switches resulting from blocking on
711 * locks; it's too easy to get duff results.
712 */
713 if (l->l_syncobj == &mutex_syncobj || l->l_syncobj == &rw_syncobj)
714 return;
715
716 /*
717 * We can't sleep if we're already going to sleep (if original
718 * condition is met during sleep, we hang up).
719 *
720 * XXX This is not ideal: it would be better to maintain a pool
721 * of ktes and actually push this to the kthread when context
722 * switch happens, however given the points where we are called
723 * from that is difficult to do.
724 */
725 if (out) {
726 if (ktrenter(l))
727 return;
728
729 switch (KTRFAC_VERSION(p->p_traceflag)) {
730 case 0:
731 /* This is the original format */
732 microtime(&l->l_ktrcsw.tv);
733 l->l_pflag |= LP_KTRCSW;
734 break;
735 case 1:
736 nanotime(&l->l_ktrcsw.ts);
737 l->l_pflag |= LP_KTRCSW;
738 break;
739 default:
740 break;
741 }
742
743 if (user)
744 l->l_pflag |= LP_KTRCSWUSER;
745 else
746 l->l_pflag &= ~LP_KTRCSWUSER;
747
748 ktrexit(l);
749 return;
750 }
751
752 /*
753 * On the way back in, we need to record twice: once for entry, and
754 * once for exit.
755 */
756 if ((l->l_pflag & LP_KTRCSW) != 0) {
757 l->l_pflag &= ~LP_KTRCSW;
758
759 if (ktealloc(&kte, (void *)&kc, l, KTR_CSW, sizeof(*kc)))
760 return;
761
762 kc->out = 1;
763 kc->user = ((l->l_pflag & LP_KTRCSWUSER) != 0);
764
765 switch (KTRFAC_VERSION(p->p_traceflag)) {
766 case 0:
767 /* This is the original format */
768 memcpy(&kte->kte_kth.ktr_tv, &l->l_ktrcsw.tv,
769 sizeof(kte->kte_kth.ktr_tv));
770 break;
771 case 1:
772 memcpy(&kte->kte_kth.ktr_time, &l->l_ktrcsw.ts,
773 sizeof(kte->kte_kth.ktr_time));
774 break;
775 default:
776 break;
777 }
778
779 ktraddentry(l, kte, KTA_WAITOK);
780 }
781
782 if (ktealloc(&kte, (void *)&kc, l, KTR_CSW, sizeof(*kc)))
783 return;
784
785 kc->out = 0;
786 kc->user = user;
787
788 ktraddentry(l, kte, KTA_WAITOK);
789 }
790
791 int
792 ktruser(struct lwp *l, const char *id, void *addr, size_t len, int ustr)
793 {
794 struct ktrace_entry *kte;
795 struct ktr_user *ktp;
796 void *user_dta;
797 int error;
798
799 if (len > KTR_USER_MAXLEN)
800 return ENOSPC;
801
802 error = ktealloc(&kte, (void *)&ktp, l, KTR_USER, sizeof(*ktp) + len);
803 if (error != 0)
804 return error;
805
806 if (ustr) {
807 if (copyinstr(id, ktp->ktr_id, KTR_USER_MAXIDLEN, NULL) != 0)
808 ktp->ktr_id[0] = '\0';
809 } else
810 strncpy(ktp->ktr_id, id, KTR_USER_MAXIDLEN);
811 ktp->ktr_id[KTR_USER_MAXIDLEN-1] = '\0';
812
813 user_dta = (void *)(ktp + 1);
814 if ((error = copyin(addr, (void *)user_dta, len)) != 0)
815 len = 0;
816
817 ktraddentry(l, kte, KTA_WAITOK);
818 return error;
819 }
820
821 void
822 ktrkuser(struct lwp *l, const char *id, void *addr, size_t len)
823 {
824 struct ktrace_entry *kte;
825 struct ktr_user *ktp;
826 int error;
827
828 if (len > KTR_USER_MAXLEN)
829 return;
830
831 error = ktealloc(&kte, (void *)&ktp, l, KTR_USER, sizeof(*ktp) + len);
832 if (error != 0)
833 return;
834
835 strlcpy(ktp->ktr_id, id, KTR_USER_MAXIDLEN);
836
837 memcpy(ktp + 1, addr, len);
838
839 ktraddentry(l, kte, KTA_WAITOK);
840 }
841
842 void
843 ktrmmsg(struct lwp *l, const void *msgh, size_t size)
844 {
845 ktrkmem(l, KTR_MMSG, msgh, size);
846 }
847
848 void
849 ktrmool(struct lwp *l, const void *kaddr, size_t size, const void *uaddr)
850 {
851 struct ktrace_entry *kte;
852 struct ktr_mool *kp;
853 struct ktr_mool *bf;
854
855 if (ktealloc(&kte, (void *)&kp, l, KTR_MOOL, size + sizeof(*kp)))
856 return;
857
858 kp->uaddr = uaddr;
859 kp->size = size;
860 bf = kp + 1; /* Skip uaddr and size */
861 (void)memcpy(bf, kaddr, size);
862
863 ktraddentry(l, kte, KTA_WAITOK);
864 }
865
866 void
867 ktrmib(struct lwp *l, const int *name, u_int namelen)
868 {
869 struct ktrace_entry *kte;
870 int *namep;
871 size_t size;
872
873 size = namelen * sizeof(*name);
874
875 if (ktealloc(&kte, (void *)&namep, l, KTR_MIB, size))
876 return;
877
878 (void)memcpy(namep, name, namelen * sizeof(*name));
879
880 ktraddentry(l, kte, KTA_WAITOK);
881 }
882
883 /* Interface and common routines */
884
885 int
886 ktrace_common(struct lwp *curl, int ops, int facs, int pid, struct file *fp)
887 {
888 struct proc *curp;
889 struct proc *p;
890 struct pgrp *pg;
891 struct ktr_desc *ktd = NULL;
892 int ret = 0;
893 int error = 0;
894 int descend;
895
896 curp = curl->l_proc;
897 descend = ops & KTRFLAG_DESCEND;
898 facs = facs & ~((unsigned) KTRFAC_ROOT);
899
900 (void)ktrenter(curl);
901
902 switch (KTROP(ops)) {
903
904 case KTROP_CLEARFILE:
905 /*
906 * Clear all uses of the tracefile
907 */
908 mutex_enter(&ktrace_mutex);
909 ktd = ktd_lookup(fp);
910 mutex_exit(&ktrace_mutex);
911 if (ktd == NULL)
912 goto done;
913 error = ktrderefall(ktd, 1);
914 goto done;
915
916 case KTROP_SET:
917 mutex_enter(&ktrace_mutex);
918 ktd = ktd_lookup(fp);
919 mutex_exit(&ktrace_mutex);
920 if (ktd == NULL) {
921 ktd = kmem_alloc(sizeof(*ktd), KM_SLEEP);
922 TAILQ_INIT(&ktd->ktd_queue);
923 callout_init(&ktd->ktd_wakch, 0);
924 cv_init(&ktd->ktd_cv, "ktrwait");
925 cv_init(&ktd->ktd_sync_cv, "ktrsync");
926 ktd->ktd_flags = ktd->ktd_qcount =
927 ktd->ktd_error = ktd->ktd_errcnt = 0;
928 ktd->ktd_ref = 1;
929 ktd->ktd_delayqcnt = ktd_delayqcnt;
930 ktd->ktd_wakedelay = mstohz(ktd_wakedelay);
931 ktd->ktd_intrwakdl = mstohz(ktd_intrwakdl);
932 /*
933 * XXX: not correct. needs an way to detect
934 * whether ktruss or ktrace.
935 */
936 if (fp->f_type == DTYPE_PIPE)
937 ktd->ktd_flags |= KTDF_INTERACTIVE;
938
939 error = kthread_create(PRI_NONE, 0, NULL,
940 ktrace_thread, ktd, &ktd->ktd_lwp, "ktrace");
941 if (error != 0) {
942 kmem_free(ktd, sizeof(*ktd));
943 goto done;
944 }
945
946 simple_lock(&fp->f_slock);
947 fp->f_count++;
948 simple_unlock(&fp->f_slock);
949 ktd->ktd_fp = fp;
950
951 mutex_enter(&ktrace_mutex);
952 if (ktd_lookup(fp) != NULL) {
953 ktdrel(ktd);
954 ktd = NULL;
955 } else
956 TAILQ_INSERT_TAIL(&ktdq, ktd, ktd_list);
957 if (ktd == NULL)
958 cv_wait(&lbolt, &ktrace_mutex);
959 mutex_exit(&ktrace_mutex);
960 if (ktd == NULL)
961 goto done;
962 }
963 break;
964
965 case KTROP_CLEAR:
966 break;
967 }
968
969 /*
970 * need something to (un)trace (XXX - why is this here?)
971 */
972 if (!facs) {
973 error = EINVAL;
974 goto done;
975 }
976
977 /*
978 * do it
979 */
980 mutex_enter(&proclist_lock);
981 if (pid < 0) {
982 /*
983 * by process group
984 */
985 pg = pg_find(-pid, PFIND_LOCKED);
986 if (pg == NULL)
987 error = ESRCH;
988 else {
989 LIST_FOREACH(p, &pg->pg_members, p_pglist) {
990 if (descend)
991 ret |= ktrsetchildren(curl, p, ops,
992 facs, ktd);
993 else
994 ret |= ktrops(curl, p, ops, facs,
995 ktd);
996 }
997 }
998
999 } else {
1000 /*
1001 * by pid
1002 */
1003 p = p_find(pid, PFIND_LOCKED);
1004 if (p == NULL)
1005 error = ESRCH;
1006 else if (descend)
1007 ret |= ktrsetchildren(curl, p, ops, facs, ktd);
1008 else
1009 ret |= ktrops(curl, p, ops, facs, ktd);
1010 }
1011 mutex_exit(&proclist_lock);
1012 if (error == 0 && !ret)
1013 error = EPERM;
1014 done:
1015 if (ktd != NULL) {
1016 mutex_enter(&ktrace_mutex);
1017 if (error != 0) {
1018 /*
1019 * Wakeup the thread so that it can be die if we
1020 * can't trace any process.
1021 */
1022 ktd_wakeup(ktd);
1023 }
1024 if (KTROP(ops) == KTROP_SET || KTROP(ops) == KTROP_CLEARFILE)
1025 ktdrel(ktd);
1026 mutex_exit(&ktrace_mutex);
1027 }
1028 ktrexit(curl);
1029 return (error);
1030 }
1031
1032 /*
1033 * fktrace system call
1034 */
1035 /* ARGSUSED */
1036 int
1037 sys_fktrace(struct lwp *l, void *v, register_t *retval)
1038 {
1039 struct sys_fktrace_args /* {
1040 syscallarg(int) fd;
1041 syscallarg(int) ops;
1042 syscallarg(int) facs;
1043 syscallarg(int) pid;
1044 } */ *uap = v;
1045 struct file *fp = NULL;
1046 struct filedesc *fdp = l->l_proc->p_fd;
1047 int error;
1048
1049 fdp = l->l_proc->p_fd;
1050 if ((fp = fd_getfile(fdp, SCARG(uap, fd))) == NULL)
1051 return (EBADF);
1052
1053 FILE_USE(fp);
1054
1055 if ((fp->f_flag & FWRITE) == 0)
1056 error = EBADF;
1057 else
1058 error = ktrace_common(l, SCARG(uap, ops),
1059 SCARG(uap, facs), SCARG(uap, pid), fp);
1060
1061 FILE_UNUSE(fp, l);
1062
1063 return error;
1064 }
1065
1066 /*
1067 * ktrace system call
1068 */
1069 /* ARGSUSED */
1070 int
1071 sys_ktrace(struct lwp *l, void *v, register_t *retval)
1072 {
1073 struct sys_ktrace_args /* {
1074 syscallarg(const char *) fname;
1075 syscallarg(int) ops;
1076 syscallarg(int) facs;
1077 syscallarg(int) pid;
1078 } */ *uap = v;
1079 struct vnode *vp = NULL;
1080 struct file *fp = NULL;
1081 struct nameidata nd;
1082 int error = 0;
1083 int fd;
1084
1085 if (ktrenter(l))
1086 return EAGAIN;
1087
1088 if (KTROP(SCARG(uap, ops)) != KTROP_CLEAR) {
1089 /*
1090 * an operation which requires a file argument.
1091 */
1092 NDINIT(&nd, LOOKUP, FOLLOW, UIO_USERSPACE, SCARG(uap, fname),
1093 l);
1094 if ((error = vn_open(&nd, FREAD|FWRITE, 0)) != 0) {
1095 ktrexit(l);
1096 return (error);
1097 }
1098 vp = nd.ni_vp;
1099 VOP_UNLOCK(vp, 0);
1100 if (vp->v_type != VREG) {
1101 (void) vn_close(vp, FREAD|FWRITE, l->l_cred, l);
1102 ktrexit(l);
1103 return (EACCES);
1104 }
1105 /*
1106 * XXX This uses up a file descriptor slot in the
1107 * tracing process for the duration of this syscall.
1108 * This is not expected to be a problem. If
1109 * falloc(NULL, ...) DTRT we could skip that part, but
1110 * that would require changing its interface to allow
1111 * the caller to pass in a ucred..
1112 *
1113 * This will FILE_USE the fp it returns, if any.
1114 * Keep it in use until we return.
1115 */
1116 if ((error = falloc(l, &fp, &fd)) != 0)
1117 goto done;
1118
1119 fp->f_flag = FWRITE;
1120 fp->f_type = DTYPE_VNODE;
1121 fp->f_ops = &vnops;
1122 fp->f_data = (void *)vp;
1123 FILE_SET_MATURE(fp);
1124 vp = NULL;
1125 }
1126 error = ktrace_common(l, SCARG(uap, ops), SCARG(uap, facs),
1127 SCARG(uap, pid), fp);
1128 done:
1129 if (vp != NULL)
1130 (void) vn_close(vp, FWRITE, l->l_cred, l);
1131 if (fp != NULL) {
1132 FILE_UNUSE(fp, l); /* release file */
1133 fdrelease(l, fd); /* release fd table slot */
1134 }
1135 return (error);
1136 }
1137
1138 int
1139 ktrops(struct lwp *curl, struct proc *p, int ops, int facs,
1140 struct ktr_desc *ktd)
1141 {
1142 int vers = ops & KTRFAC_VER_MASK;
1143 int error = 0;
1144
1145 mutex_enter(&p->p_mutex);
1146 mutex_enter(&ktrace_mutex);
1147
1148 if (!ktrcanset(curl, p))
1149 goto out;
1150
1151 switch (vers) {
1152 case KTRFACv0:
1153 case KTRFACv1:
1154 break;
1155 default:
1156 error = EINVAL;
1157 goto out;
1158 }
1159
1160 if (KTROP(ops) == KTROP_SET) {
1161 if (p->p_tracep != ktd) {
1162 /*
1163 * if trace file already in use, relinquish
1164 */
1165 ktrderef(p);
1166 p->p_tracep = ktd;
1167 ktradref(p);
1168 }
1169 p->p_traceflag |= facs;
1170 if (kauth_authorize_generic(curl->l_cred,
1171 KAUTH_GENERIC_ISSUSER, NULL) == 0)
1172 p->p_traceflag |= KTRFAC_ROOT;
1173 } else {
1174 /* KTROP_CLEAR */
1175 if (((p->p_traceflag &= ~facs) & KTRFAC_MASK) == 0) {
1176 /* no more tracing */
1177 ktrderef(p);
1178 }
1179 }
1180
1181 if (p->p_traceflag)
1182 p->p_traceflag |= vers;
1183 /*
1184 * Emit an emulation record, every time there is a ktrace
1185 * change/attach request.
1186 */
1187 if (KTRPOINT(p, KTR_EMUL))
1188 p->p_traceflag |= KTRFAC_TRC_EMUL;
1189 #ifdef __HAVE_SYSCALL_INTERN
1190 (*p->p_emul->e_syscall_intern)(p);
1191 #endif
1192
1193 out:
1194 mutex_exit(&ktrace_mutex);
1195 mutex_exit(&p->p_mutex);
1196
1197 return (1);
1198 }
1199
1200 int
1201 ktrsetchildren(struct lwp *curl, struct proc *top, int ops, int facs,
1202 struct ktr_desc *ktd)
1203 {
1204 struct proc *p;
1205 int ret = 0;
1206
1207 KASSERT(mutex_owned(&proclist_lock));
1208
1209 p = top;
1210 for (;;) {
1211 ret |= ktrops(curl, p, ops, facs, ktd);
1212 /*
1213 * If this process has children, descend to them next,
1214 * otherwise do any siblings, and if done with this level,
1215 * follow back up the tree (but not past top).
1216 */
1217 if (LIST_FIRST(&p->p_children) != NULL) {
1218 p = LIST_FIRST(&p->p_children);
1219 continue;
1220 }
1221 for (;;) {
1222 if (p == top)
1223 return (ret);
1224 if (LIST_NEXT(p, p_sibling) != NULL) {
1225 p = LIST_NEXT(p, p_sibling);
1226 break;
1227 }
1228 p = p->p_pptr;
1229 }
1230 }
1231 /*NOTREACHED*/
1232 }
1233
1234 void
1235 ktrwrite(struct ktr_desc *ktd, struct ktrace_entry *kte)
1236 {
1237 struct uio auio;
1238 struct iovec aiov[64], *iov;
1239 struct ktrace_entry *top = kte;
1240 struct ktr_header *kth;
1241 struct file *fp = ktd->ktd_fp;
1242 int error;
1243 next:
1244 auio.uio_iov = iov = &aiov[0];
1245 auio.uio_offset = 0;
1246 auio.uio_rw = UIO_WRITE;
1247 auio.uio_resid = 0;
1248 auio.uio_iovcnt = 0;
1249 UIO_SETUP_SYSSPACE(&auio);
1250 do {
1251 kth = &kte->kte_kth;
1252
1253 if (kth->ktr_version == 0) {
1254 /*
1255 * Convert back to the old format fields
1256 */
1257 TIMESPEC_TO_TIMEVAL(&kth->ktr_tv, &kth->ktr_time);
1258 kth->ktr_unused = NULL;
1259 }
1260 iov->iov_base = (void *)kth;
1261 iov++->iov_len = sizeof(struct ktr_header);
1262 auio.uio_resid += sizeof(struct ktr_header);
1263 auio.uio_iovcnt++;
1264 if (kth->ktr_len > 0) {
1265 iov->iov_base = kte->kte_buf;
1266 iov++->iov_len = kth->ktr_len;
1267 auio.uio_resid += kth->ktr_len;
1268 auio.uio_iovcnt++;
1269 }
1270 } while ((kte = TAILQ_NEXT(kte, kte_list)) != NULL &&
1271 auio.uio_iovcnt < sizeof(aiov) / sizeof(aiov[0]) - 1);
1272
1273 again:
1274 simple_lock(&fp->f_slock);
1275 FILE_USE(fp);
1276 error = (*fp->f_ops->fo_write)(fp, &fp->f_offset, &auio,
1277 fp->f_cred, FOF_UPDATE_OFFSET);
1278 FILE_UNUSE(fp, NULL);
1279 switch (error) {
1280
1281 case 0:
1282 if (auio.uio_resid > 0)
1283 goto again;
1284 if (kte != NULL)
1285 goto next;
1286 break;
1287
1288 case EWOULDBLOCK:
1289 kpause("ktrzzz", false, 1, NULL);
1290 goto again;
1291
1292 default:
1293 /*
1294 * If error encountered, give up tracing on this
1295 * vnode. Don't report EPIPE as this can easily
1296 * happen with fktrace()/ktruss.
1297 */
1298 #ifndef DEBUG
1299 if (error != EPIPE)
1300 #endif
1301 log(LOG_NOTICE,
1302 "ktrace write failed, errno %d, tracing stopped\n",
1303 error);
1304 (void)ktrderefall(ktd, 0);
1305 }
1306
1307 while ((kte = top) != NULL) {
1308 top = TAILQ_NEXT(top, kte_list);
1309 ktefree(kte);
1310 }
1311 }
1312
1313 void
1314 ktrace_thread(void *arg)
1315 {
1316 struct ktr_desc *ktd = arg;
1317 struct file *fp = ktd->ktd_fp;
1318 struct ktrace_entry *kte;
1319 int ktrerr, errcnt;
1320
1321 mutex_enter(&ktrace_mutex);
1322 for (;;) {
1323 kte = TAILQ_FIRST(&ktd->ktd_queue);
1324 if (kte == NULL) {
1325 if (ktd->ktd_flags & KTDF_WAIT) {
1326 ktd->ktd_flags &= ~(KTDF_WAIT | KTDF_BLOCKING);
1327 cv_broadcast(&ktd->ktd_sync_cv);
1328 }
1329 if (ktd->ktd_ref == 0)
1330 break;
1331 cv_wait(&ktd->ktd_cv, &ktrace_mutex);
1332 continue;
1333 }
1334 TAILQ_INIT(&ktd->ktd_queue);
1335 ktd->ktd_qcount = 0;
1336 ktrerr = ktd->ktd_error;
1337 errcnt = ktd->ktd_errcnt;
1338 ktd->ktd_error = ktd->ktd_errcnt = 0;
1339 mutex_exit(&ktrace_mutex);
1340
1341 if (ktrerr) {
1342 log(LOG_NOTICE,
1343 "ktrace failed, fp %p, error 0x%x, total %d\n",
1344 fp, ktrerr, errcnt);
1345 }
1346 ktrwrite(ktd, kte);
1347 mutex_enter(&ktrace_mutex);
1348 }
1349
1350 TAILQ_REMOVE(&ktdq, ktd, ktd_list);
1351 mutex_exit(&ktrace_mutex);
1352
1353 simple_lock(&fp->f_slock);
1354 FILE_USE(fp);
1355
1356 /*
1357 * ktrace file descriptor can't be watched (are not visible to
1358 * userspace), so no kqueue stuff here
1359 * XXX: The above comment is wrong, because the fktrace file
1360 * descriptor is available in userland.
1361 */
1362 closef(fp, NULL);
1363
1364 callout_stop(&ktd->ktd_wakch);
1365 callout_destroy(&ktd->ktd_wakch);
1366 kmem_free(ktd, sizeof(*ktd));
1367
1368 kthread_exit(0);
1369 }
1370
1371 /*
1372 * Return true if caller has permission to set the ktracing state
1373 * of target. Essentially, the target can't possess any
1374 * more permissions than the caller. KTRFAC_ROOT signifies that
1375 * root previously set the tracing status on the target process, and
1376 * so, only root may further change it.
1377 *
1378 * TODO: check groups. use caller effective gid.
1379 */
1380 int
1381 ktrcanset(struct lwp *calll, struct proc *targetp)
1382 {
1383 KASSERT(mutex_owned(&targetp->p_mutex));
1384 KASSERT(mutex_owned(&ktrace_mutex));
1385
1386 if (kauth_authorize_process(calll->l_cred, KAUTH_PROCESS_CANKTRACE,
1387 targetp, NULL, NULL, NULL) == 0)
1388 return (1);
1389
1390 return (0);
1391 }
1392 #endif /* KTRACE */
1393
1394 /*
1395 * Put user defined entry to ktrace records.
1396 */
1397 int
1398 sys_utrace(struct lwp *l, void *v, register_t *retval)
1399 {
1400 #ifdef KTRACE
1401 struct sys_utrace_args /* {
1402 syscallarg(const char *) label;
1403 syscallarg(void *) addr;
1404 syscallarg(size_t) len;
1405 } */ *uap = v;
1406 struct proc *p = l->l_proc;
1407
1408 if (!KTRPOINT(p, KTR_USER))
1409 return (0);
1410
1411 return ktruser(l, SCARG(uap, label), SCARG(uap, addr),
1412 SCARG(uap, len), 1);
1413 #else /* !KTRACE */
1414 return ENOSYS;
1415 #endif /* KTRACE */
1416 }
1417