xref: /freebsd-13-stable/sys/kern/kern_ktrace.c (revision f702110bc4bcc593b38674ec6e4fadf6c4626432)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1989, 1993
5  *	The Regents of the University of California.
6  * Copyright (c) 2005 Robert N. M. Watson
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *	@(#)kern_ktrace.c	8.2 (Berkeley) 9/23/93
34  */
35 
36 #include <sys/cdefs.h>
37 #include "opt_ktrace.h"
38 
39 #include <sys/param.h>
40 #include <sys/capsicum.h>
41 #include <sys/systm.h>
42 #include <sys/fcntl.h>
43 #include <sys/kernel.h>
44 #include <sys/kthread.h>
45 #include <sys/lock.h>
46 #include <sys/mutex.h>
47 #include <sys/malloc.h>
48 #include <sys/mount.h>
49 #include <sys/namei.h>
50 #include <sys/priv.h>
51 #include <sys/proc.h>
52 #include <sys/resourcevar.h>
53 #include <sys/unistd.h>
54 #include <sys/vnode.h>
55 #include <sys/socket.h>
56 #include <sys/stat.h>
57 #include <sys/ktrace.h>
58 #include <sys/sx.h>
59 #include <sys/sysctl.h>
60 #include <sys/sysent.h>
61 #include <sys/syslog.h>
62 #include <sys/sysproto.h>
63 
64 #include <security/mac/mac_framework.h>
65 
66 /*
67  * The ktrace facility allows the tracing of certain key events in user space
68  * processes, such as system calls, signal delivery, context switches, and
69  * user generated events using utrace(2).  It works by streaming event
70  * records and data to a vnode associated with the process using the
71  * ktrace(2) system call.  In general, records can be written directly from
72  * the context that generates the event.  One important exception to this is
73  * during a context switch, where sleeping is not permitted.  To handle this
74  * case, trace events are generated using in-kernel ktr_request records, and
75  * then delivered to disk at a convenient moment -- either immediately, the
76  * next traceable event, at system call return, or at process exit.
77  *
78  * When dealing with multiple threads or processes writing to the same event
79  * log, ordering guarantees are weak: specifically, if an event has multiple
80  * records (i.e., system call enter and return), they may be interlaced with
81  * records from another event.  Process and thread ID information is provided
82  * in the record, and user applications can de-interlace events if required.
83  */
84 
85 static MALLOC_DEFINE(M_KTRACE, "KTRACE", "KTRACE");
86 
87 #ifdef KTRACE
88 
89 FEATURE(ktrace, "Kernel support for system-call tracing");
90 
91 #ifndef KTRACE_REQUEST_POOL
92 #define	KTRACE_REQUEST_POOL	100
93 #endif
94 
95 struct ktr_request {
96 	struct	ktr_header ktr_header;
97 	void	*ktr_buffer;
98 	union {
99 		struct	ktr_proc_ctor ktr_proc_ctor;
100 		struct	ktr_cap_fail ktr_cap_fail;
101 		struct	ktr_syscall ktr_syscall;
102 		struct	ktr_sysret ktr_sysret;
103 		struct	ktr_genio ktr_genio;
104 		struct	ktr_psig ktr_psig;
105 		struct	ktr_csw ktr_csw;
106 		struct	ktr_fault ktr_fault;
107 		struct	ktr_faultend ktr_faultend;
108 		struct  ktr_struct_array ktr_struct_array;
109 	} ktr_data;
110 	STAILQ_ENTRY(ktr_request) ktr_list;
111 };
112 
113 static const int data_lengths[] = {
114 	[KTR_SYSCALL] = offsetof(struct ktr_syscall, ktr_args),
115 	[KTR_SYSRET] = sizeof(struct ktr_sysret),
116 	[KTR_NAMEI] = 0,
117 	[KTR_GENIO] = sizeof(struct ktr_genio),
118 	[KTR_PSIG] = sizeof(struct ktr_psig),
119 	[KTR_CSW] = sizeof(struct ktr_csw),
120 	[KTR_USER] = 0,
121 	[KTR_STRUCT] = 0,
122 	[KTR_SYSCTL] = 0,
123 	[KTR_PROCCTOR] = sizeof(struct ktr_proc_ctor),
124 	[KTR_PROCDTOR] = 0,
125 	[KTR_CAPFAIL] = sizeof(struct ktr_cap_fail),
126 	[KTR_FAULT] = sizeof(struct ktr_fault),
127 	[KTR_FAULTEND] = sizeof(struct ktr_faultend),
128 	[KTR_STRUCT_ARRAY] = sizeof(struct ktr_struct_array),
129 };
130 
131 static STAILQ_HEAD(, ktr_request) ktr_free;
132 
133 static SYSCTL_NODE(_kern, OID_AUTO, ktrace, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
134     "KTRACE options");
135 
136 static u_int ktr_requestpool = KTRACE_REQUEST_POOL;
137 TUNABLE_INT("kern.ktrace.request_pool", &ktr_requestpool);
138 
139 u_int ktr_geniosize = PAGE_SIZE;
140 SYSCTL_UINT(_kern_ktrace, OID_AUTO, genio_size, CTLFLAG_RWTUN, &ktr_geniosize,
141     0, "Maximum size of genio event payload");
142 
143 /*
144  * Allow to not to send signal to traced process, in which context the
145  * ktr record is written.  The limit is applied from the process that
146  * set up ktrace, so killing the traced process is not completely fair.
147  */
148 int ktr_filesize_limit_signal = 0;
149 SYSCTL_INT(_kern_ktrace, OID_AUTO, filesize_limit_signal, CTLFLAG_RWTUN,
150     &ktr_filesize_limit_signal, 0,
151     "Send SIGXFSZ to the traced process when the log size limit is exceeded");
152 
153 static int print_message = 1;
154 static struct mtx ktrace_mtx;
155 static struct sx ktrace_sx;
156 
157 struct ktr_io_params {
158 	struct vnode	*vp;
159 	struct ucred	*cr;
160 	off_t		lim;
161 	u_int		refs;
162 };
163 
164 static void ktrace_init(void *dummy);
165 static int sysctl_kern_ktrace_request_pool(SYSCTL_HANDLER_ARGS);
166 static u_int ktrace_resize_pool(u_int oldsize, u_int newsize);
167 static struct ktr_request *ktr_getrequest_entered(struct thread *td, int type);
168 static struct ktr_request *ktr_getrequest(int type);
169 static void ktr_submitrequest(struct thread *td, struct ktr_request *req);
170 static struct ktr_io_params *ktr_freeproc(struct proc *p);
171 static void ktr_freerequest(struct ktr_request *req);
172 static void ktr_freerequest_locked(struct ktr_request *req);
173 static void ktr_writerequest(struct thread *td, struct ktr_request *req);
174 static int ktrcanset(struct thread *,struct proc *);
175 static int ktrsetchildren(struct thread *, struct proc *, int, int,
176     struct ktr_io_params *);
177 static int ktrops(struct thread *, struct proc *, int, int,
178     struct ktr_io_params *);
179 static void ktrprocctor_entered(struct thread *, struct proc *);
180 
181 /*
182  * ktrace itself generates events, such as context switches, which we do not
183  * wish to trace.  Maintain a flag, TDP_INKTRACE, on each thread to determine
184  * whether or not it is in a region where tracing of events should be
185  * suppressed.
186  */
187 static void
ktrace_enter(struct thread * td)188 ktrace_enter(struct thread *td)
189 {
190 
191 	KASSERT(!(td->td_pflags & TDP_INKTRACE), ("ktrace_enter: flag set"));
192 	td->td_pflags |= TDP_INKTRACE;
193 }
194 
195 static void
ktrace_exit(struct thread * td)196 ktrace_exit(struct thread *td)
197 {
198 
199 	KASSERT(td->td_pflags & TDP_INKTRACE, ("ktrace_exit: flag not set"));
200 	td->td_pflags &= ~TDP_INKTRACE;
201 }
202 
203 static void
ktrace_assert(struct thread * td)204 ktrace_assert(struct thread *td)
205 {
206 
207 	KASSERT(td->td_pflags & TDP_INKTRACE, ("ktrace_assert: flag not set"));
208 }
209 
210 static void
ktrace_init(void * dummy)211 ktrace_init(void *dummy)
212 {
213 	struct ktr_request *req;
214 	int i;
215 
216 	mtx_init(&ktrace_mtx, "ktrace", NULL, MTX_DEF | MTX_QUIET);
217 	sx_init(&ktrace_sx, "ktrace_sx");
218 	STAILQ_INIT(&ktr_free);
219 	for (i = 0; i < ktr_requestpool; i++) {
220 		req = malloc(sizeof(struct ktr_request), M_KTRACE, M_WAITOK |
221 		    M_ZERO);
222 		STAILQ_INSERT_HEAD(&ktr_free, req, ktr_list);
223 	}
224 }
225 SYSINIT(ktrace_init, SI_SUB_KTRACE, SI_ORDER_ANY, ktrace_init, NULL);
226 
227 static int
sysctl_kern_ktrace_request_pool(SYSCTL_HANDLER_ARGS)228 sysctl_kern_ktrace_request_pool(SYSCTL_HANDLER_ARGS)
229 {
230 	struct thread *td;
231 	u_int newsize, oldsize, wantsize;
232 	int error;
233 
234 	/* Handle easy read-only case first to avoid warnings from GCC. */
235 	if (!req->newptr) {
236 		oldsize = ktr_requestpool;
237 		return (SYSCTL_OUT(req, &oldsize, sizeof(u_int)));
238 	}
239 
240 	error = SYSCTL_IN(req, &wantsize, sizeof(u_int));
241 	if (error)
242 		return (error);
243 	td = curthread;
244 	ktrace_enter(td);
245 	oldsize = ktr_requestpool;
246 	newsize = ktrace_resize_pool(oldsize, wantsize);
247 	ktrace_exit(td);
248 	error = SYSCTL_OUT(req, &oldsize, sizeof(u_int));
249 	if (error)
250 		return (error);
251 	if (wantsize > oldsize && newsize < wantsize)
252 		return (ENOSPC);
253 	return (0);
254 }
255 SYSCTL_PROC(_kern_ktrace, OID_AUTO, request_pool,
256     CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_NEEDGIANT, &ktr_requestpool, 0,
257     sysctl_kern_ktrace_request_pool, "IU",
258     "Pool buffer size for ktrace(1)");
259 
260 static u_int
ktrace_resize_pool(u_int oldsize,u_int newsize)261 ktrace_resize_pool(u_int oldsize, u_int newsize)
262 {
263 	STAILQ_HEAD(, ktr_request) ktr_new;
264 	struct ktr_request *req;
265 	int bound;
266 
267 	print_message = 1;
268 	bound = newsize - oldsize;
269 	if (bound == 0)
270 		return (ktr_requestpool);
271 	if (bound < 0) {
272 		mtx_lock(&ktrace_mtx);
273 		/* Shrink pool down to newsize if possible. */
274 		while (bound++ < 0) {
275 			req = STAILQ_FIRST(&ktr_free);
276 			if (req == NULL)
277 				break;
278 			STAILQ_REMOVE_HEAD(&ktr_free, ktr_list);
279 			ktr_requestpool--;
280 			free(req, M_KTRACE);
281 		}
282 	} else {
283 		/* Grow pool up to newsize. */
284 		STAILQ_INIT(&ktr_new);
285 		while (bound-- > 0) {
286 			req = malloc(sizeof(struct ktr_request), M_KTRACE,
287 			    M_WAITOK | M_ZERO);
288 			STAILQ_INSERT_HEAD(&ktr_new, req, ktr_list);
289 		}
290 		mtx_lock(&ktrace_mtx);
291 		STAILQ_CONCAT(&ktr_free, &ktr_new);
292 		ktr_requestpool += (newsize - oldsize);
293 	}
294 	mtx_unlock(&ktrace_mtx);
295 	return (ktr_requestpool);
296 }
297 
298 /* ktr_getrequest() assumes that ktr_comm[] is the same size as td_name[]. */
299 CTASSERT(sizeof(((struct ktr_header *)NULL)->ktr_comm) ==
300     (sizeof((struct thread *)NULL)->td_name));
301 
302 static struct ktr_request *
ktr_getrequest_entered(struct thread * td,int type)303 ktr_getrequest_entered(struct thread *td, int type)
304 {
305 	struct ktr_request *req;
306 	struct proc *p = td->td_proc;
307 	int pm;
308 
309 	mtx_lock(&ktrace_mtx);
310 	if (!KTRCHECK(td, type)) {
311 		mtx_unlock(&ktrace_mtx);
312 		return (NULL);
313 	}
314 	req = STAILQ_FIRST(&ktr_free);
315 	if (req != NULL) {
316 		STAILQ_REMOVE_HEAD(&ktr_free, ktr_list);
317 		req->ktr_header.ktr_type = type;
318 		if (p->p_traceflag & KTRFAC_DROP) {
319 			req->ktr_header.ktr_type |= KTR_DROP;
320 			p->p_traceflag &= ~KTRFAC_DROP;
321 		}
322 		mtx_unlock(&ktrace_mtx);
323 		microtime(&req->ktr_header.ktr_time);
324 		req->ktr_header.ktr_pid = p->p_pid;
325 		req->ktr_header.ktr_tid = td->td_tid;
326 		bcopy(td->td_name, req->ktr_header.ktr_comm,
327 		    sizeof(req->ktr_header.ktr_comm));
328 		req->ktr_buffer = NULL;
329 		req->ktr_header.ktr_len = 0;
330 	} else {
331 		p->p_traceflag |= KTRFAC_DROP;
332 		pm = print_message;
333 		print_message = 0;
334 		mtx_unlock(&ktrace_mtx);
335 		if (pm)
336 			printf("Out of ktrace request objects.\n");
337 	}
338 	return (req);
339 }
340 
341 static struct ktr_request *
ktr_getrequest(int type)342 ktr_getrequest(int type)
343 {
344 	struct thread *td = curthread;
345 	struct ktr_request *req;
346 
347 	ktrace_enter(td);
348 	req = ktr_getrequest_entered(td, type);
349 	if (req == NULL)
350 		ktrace_exit(td);
351 
352 	return (req);
353 }
354 
355 /*
356  * Some trace generation environments don't permit direct access to VFS,
357  * such as during a context switch where sleeping is not allowed.  Under these
358  * circumstances, queue a request to the thread to be written asynchronously
359  * later.
360  */
361 static void
ktr_enqueuerequest(struct thread * td,struct ktr_request * req)362 ktr_enqueuerequest(struct thread *td, struct ktr_request *req)
363 {
364 
365 	mtx_lock(&ktrace_mtx);
366 	STAILQ_INSERT_TAIL(&td->td_proc->p_ktr, req, ktr_list);
367 	mtx_unlock(&ktrace_mtx);
368 	thread_lock(td);
369 	td->td_flags |= TDF_ASTPENDING;
370 	thread_unlock(td);
371 }
372 
373 /*
374  * Drain any pending ktrace records from the per-thread queue to disk.  This
375  * is used both internally before committing other records, and also on
376  * system call return.  We drain all the ones we can find at the time when
377  * drain is requested, but don't keep draining after that as those events
378  * may be approximately "after" the current event.
379  */
380 static void
ktr_drain(struct thread * td)381 ktr_drain(struct thread *td)
382 {
383 	struct ktr_request *queued_req;
384 	STAILQ_HEAD(, ktr_request) local_queue;
385 
386 	ktrace_assert(td);
387 	sx_assert(&ktrace_sx, SX_XLOCKED);
388 
389 	STAILQ_INIT(&local_queue);
390 
391 	if (!STAILQ_EMPTY(&td->td_proc->p_ktr)) {
392 		mtx_lock(&ktrace_mtx);
393 		STAILQ_CONCAT(&local_queue, &td->td_proc->p_ktr);
394 		mtx_unlock(&ktrace_mtx);
395 
396 		while ((queued_req = STAILQ_FIRST(&local_queue))) {
397 			STAILQ_REMOVE_HEAD(&local_queue, ktr_list);
398 			ktr_writerequest(td, queued_req);
399 			ktr_freerequest(queued_req);
400 		}
401 	}
402 }
403 
404 /*
405  * Submit a trace record for immediate commit to disk -- to be used only
406  * where entering VFS is OK.  First drain any pending records that may have
407  * been cached in the thread.
408  */
409 static void
ktr_submitrequest(struct thread * td,struct ktr_request * req)410 ktr_submitrequest(struct thread *td, struct ktr_request *req)
411 {
412 
413 	ktrace_assert(td);
414 
415 	sx_xlock(&ktrace_sx);
416 	ktr_drain(td);
417 	ktr_writerequest(td, req);
418 	ktr_freerequest(req);
419 	sx_xunlock(&ktrace_sx);
420 	ktrace_exit(td);
421 }
422 
423 static void
ktr_freerequest(struct ktr_request * req)424 ktr_freerequest(struct ktr_request *req)
425 {
426 
427 	mtx_lock(&ktrace_mtx);
428 	ktr_freerequest_locked(req);
429 	mtx_unlock(&ktrace_mtx);
430 }
431 
432 static void
ktr_freerequest_locked(struct ktr_request * req)433 ktr_freerequest_locked(struct ktr_request *req)
434 {
435 
436 	mtx_assert(&ktrace_mtx, MA_OWNED);
437 	if (req->ktr_buffer != NULL)
438 		free(req->ktr_buffer, M_KTRACE);
439 	STAILQ_INSERT_HEAD(&ktr_free, req, ktr_list);
440 }
441 
442 static void
ktr_io_params_ref(struct ktr_io_params * kiop)443 ktr_io_params_ref(struct ktr_io_params *kiop)
444 {
445 	mtx_assert(&ktrace_mtx, MA_OWNED);
446 	kiop->refs++;
447 }
448 
449 static struct ktr_io_params *
ktr_io_params_rele(struct ktr_io_params * kiop)450 ktr_io_params_rele(struct ktr_io_params *kiop)
451 {
452 	mtx_assert(&ktrace_mtx, MA_OWNED);
453 	if (kiop == NULL)
454 		return (NULL);
455 	KASSERT(kiop->refs > 0, ("kiop ref == 0 %p", kiop));
456 	return (--(kiop->refs) == 0 ? kiop : NULL);
457 }
458 
459 void
ktr_io_params_free(struct ktr_io_params * kiop)460 ktr_io_params_free(struct ktr_io_params *kiop)
461 {
462 	if (kiop == NULL)
463 		return;
464 
465 	MPASS(kiop->refs == 0);
466 	vn_close(kiop->vp, FWRITE, kiop->cr, curthread);
467 	crfree(kiop->cr);
468 	free(kiop, M_KTRACE);
469 }
470 
471 static struct ktr_io_params *
ktr_io_params_alloc(struct thread * td,struct vnode * vp)472 ktr_io_params_alloc(struct thread *td, struct vnode *vp)
473 {
474 	struct ktr_io_params *res;
475 
476 	res = malloc(sizeof(struct ktr_io_params), M_KTRACE, M_WAITOK);
477 	res->vp = vp;
478 	res->cr = crhold(td->td_ucred);
479 	res->lim = lim_cur(td, RLIMIT_FSIZE);
480 	res->refs = 1;
481 	return (res);
482 }
483 
484 /*
485  * Disable tracing for a process and release all associated resources.
486  * The caller is responsible for releasing a reference on the returned
487  * vnode and credentials.
488  */
489 static struct ktr_io_params *
ktr_freeproc(struct proc * p)490 ktr_freeproc(struct proc *p)
491 {
492 	struct ktr_io_params *kiop;
493 	struct ktr_request *req;
494 
495 	PROC_LOCK_ASSERT(p, MA_OWNED);
496 	mtx_assert(&ktrace_mtx, MA_OWNED);
497 	kiop = ktr_io_params_rele(p->p_ktrioparms);
498 	p->p_ktrioparms = NULL;
499 	p->p_traceflag = 0;
500 	while ((req = STAILQ_FIRST(&p->p_ktr)) != NULL) {
501 		STAILQ_REMOVE_HEAD(&p->p_ktr, ktr_list);
502 		ktr_freerequest_locked(req);
503 	}
504 	return (kiop);
505 }
506 
507 struct vnode *
ktr_get_tracevp(struct proc * p,bool ref)508 ktr_get_tracevp(struct proc *p, bool ref)
509 {
510 	struct vnode *vp;
511 
512 	PROC_LOCK_ASSERT(p, MA_OWNED);
513 
514 	if (p->p_ktrioparms != NULL) {
515 		vp = p->p_ktrioparms->vp;
516 		if (ref)
517 			vrefact(vp);
518 	} else {
519 		vp = NULL;
520 	}
521 	return (vp);
522 }
523 
524 void
ktrsyscall(int code,int narg,register_t args[])525 ktrsyscall(int code, int narg, register_t args[])
526 {
527 	struct ktr_request *req;
528 	struct ktr_syscall *ktp;
529 	size_t buflen;
530 	char *buf = NULL;
531 
532 	if (__predict_false(curthread->td_pflags & TDP_INKTRACE))
533 		return;
534 
535 	buflen = sizeof(register_t) * narg;
536 	if (buflen > 0) {
537 		buf = malloc(buflen, M_KTRACE, M_WAITOK);
538 		bcopy(args, buf, buflen);
539 	}
540 	req = ktr_getrequest(KTR_SYSCALL);
541 	if (req == NULL) {
542 		if (buf != NULL)
543 			free(buf, M_KTRACE);
544 		return;
545 	}
546 	ktp = &req->ktr_data.ktr_syscall;
547 	ktp->ktr_code = code;
548 	ktp->ktr_narg = narg;
549 	if (buflen > 0) {
550 		req->ktr_header.ktr_len = buflen;
551 		req->ktr_buffer = buf;
552 	}
553 	ktr_submitrequest(curthread, req);
554 }
555 
556 void
ktrsysret(int code,int error,register_t retval)557 ktrsysret(int code, int error, register_t retval)
558 {
559 	struct ktr_request *req;
560 	struct ktr_sysret *ktp;
561 
562 	if (__predict_false(curthread->td_pflags & TDP_INKTRACE))
563 		return;
564 
565 	req = ktr_getrequest(KTR_SYSRET);
566 	if (req == NULL)
567 		return;
568 	ktp = &req->ktr_data.ktr_sysret;
569 	ktp->ktr_code = code;
570 	ktp->ktr_error = error;
571 	ktp->ktr_retval = ((error == 0) ? retval: 0);		/* what about val2 ? */
572 	ktr_submitrequest(curthread, req);
573 }
574 
575 /*
576  * When a setuid process execs, disable tracing.
577  *
578  * XXX: We toss any pending asynchronous records.
579  */
580 struct ktr_io_params *
ktrprocexec(struct proc * p)581 ktrprocexec(struct proc *p)
582 {
583 	struct ktr_io_params *kiop;
584 
585 	PROC_LOCK_ASSERT(p, MA_OWNED);
586 
587 	kiop = p->p_ktrioparms;
588 	if (kiop == NULL || priv_check_cred(kiop->cr, PRIV_DEBUG_DIFFCRED) == 0)
589 		return (NULL);
590 
591 	mtx_lock(&ktrace_mtx);
592 	kiop = ktr_freeproc(p);
593 	mtx_unlock(&ktrace_mtx);
594 	return (kiop);
595 }
596 
597 /*
598  * When a process exits, drain per-process asynchronous trace records
599  * and disable tracing.
600  */
601 void
ktrprocexit(struct thread * td)602 ktrprocexit(struct thread *td)
603 {
604 	struct ktr_request *req;
605 	struct proc *p;
606 	struct ktr_io_params *kiop;
607 
608 	p = td->td_proc;
609 	if (p->p_traceflag == 0)
610 		return;
611 
612 	ktrace_enter(td);
613 	req = ktr_getrequest_entered(td, KTR_PROCDTOR);
614 	if (req != NULL)
615 		ktr_enqueuerequest(td, req);
616 	sx_xlock(&ktrace_sx);
617 	ktr_drain(td);
618 	sx_xunlock(&ktrace_sx);
619 	PROC_LOCK(p);
620 	mtx_lock(&ktrace_mtx);
621 	kiop = ktr_freeproc(p);
622 	mtx_unlock(&ktrace_mtx);
623 	PROC_UNLOCK(p);
624 	ktr_io_params_free(kiop);
625 	ktrace_exit(td);
626 }
627 
628 static void
ktrprocctor_entered(struct thread * td,struct proc * p)629 ktrprocctor_entered(struct thread *td, struct proc *p)
630 {
631 	struct ktr_proc_ctor *ktp;
632 	struct ktr_request *req;
633 	struct thread *td2;
634 
635 	ktrace_assert(td);
636 	td2 = FIRST_THREAD_IN_PROC(p);
637 	req = ktr_getrequest_entered(td2, KTR_PROCCTOR);
638 	if (req == NULL)
639 		return;
640 	ktp = &req->ktr_data.ktr_proc_ctor;
641 	ktp->sv_flags = p->p_sysent->sv_flags;
642 	ktr_enqueuerequest(td2, req);
643 }
644 
645 void
ktrprocctor(struct proc * p)646 ktrprocctor(struct proc *p)
647 {
648 	struct thread *td = curthread;
649 
650 	if ((p->p_traceflag & KTRFAC_MASK) == 0)
651 		return;
652 
653 	ktrace_enter(td);
654 	ktrprocctor_entered(td, p);
655 	ktrace_exit(td);
656 }
657 
658 /*
659  * When a process forks, enable tracing in the new process if needed.
660  */
661 void
ktrprocfork(struct proc * p1,struct proc * p2)662 ktrprocfork(struct proc *p1, struct proc *p2)
663 {
664 
665 	MPASS(p2->p_ktrioparms == NULL);
666 	MPASS(p2->p_traceflag == 0);
667 
668 	if (p1->p_traceflag == 0)
669 		return;
670 
671 	PROC_LOCK(p1);
672 	mtx_lock(&ktrace_mtx);
673 	if (p1->p_traceflag & KTRFAC_INHERIT) {
674 		p2->p_traceflag = p1->p_traceflag;
675 		if ((p2->p_ktrioparms = p1->p_ktrioparms) != NULL)
676 			p1->p_ktrioparms->refs++;
677 	}
678 	mtx_unlock(&ktrace_mtx);
679 	PROC_UNLOCK(p1);
680 
681 	ktrprocctor(p2);
682 }
683 
684 /*
685  * When a thread returns, drain any asynchronous records generated by the
686  * system call.
687  */
688 void
ktruserret(struct thread * td)689 ktruserret(struct thread *td)
690 {
691 
692 	ktrace_enter(td);
693 	sx_xlock(&ktrace_sx);
694 	ktr_drain(td);
695 	sx_xunlock(&ktrace_sx);
696 	ktrace_exit(td);
697 }
698 
699 void
ktrnamei(path)700 ktrnamei(path)
701 	char *path;
702 {
703 	struct ktr_request *req;
704 	int namelen;
705 	char *buf = NULL;
706 
707 	namelen = strlen(path);
708 	if (namelen > 0) {
709 		buf = malloc(namelen, M_KTRACE, M_WAITOK);
710 		bcopy(path, buf, namelen);
711 	}
712 	req = ktr_getrequest(KTR_NAMEI);
713 	if (req == NULL) {
714 		if (buf != NULL)
715 			free(buf, M_KTRACE);
716 		return;
717 	}
718 	if (namelen > 0) {
719 		req->ktr_header.ktr_len = namelen;
720 		req->ktr_buffer = buf;
721 	}
722 	ktr_submitrequest(curthread, req);
723 }
724 
725 void
ktrsysctl(int * name,u_int namelen)726 ktrsysctl(int *name, u_int namelen)
727 {
728 	struct ktr_request *req;
729 	u_int mib[CTL_MAXNAME + 2];
730 	char *mibname;
731 	size_t mibnamelen;
732 	int error;
733 
734 	/* Lookup name of mib. */
735 	KASSERT(namelen <= CTL_MAXNAME, ("sysctl MIB too long"));
736 	mib[0] = 0;
737 	mib[1] = 1;
738 	bcopy(name, mib + 2, namelen * sizeof(*name));
739 	mibnamelen = 128;
740 	mibname = malloc(mibnamelen, M_KTRACE, M_WAITOK);
741 	error = kernel_sysctl(curthread, mib, namelen + 2, mibname, &mibnamelen,
742 	    NULL, 0, &mibnamelen, 0);
743 	if (error) {
744 		free(mibname, M_KTRACE);
745 		return;
746 	}
747 	req = ktr_getrequest(KTR_SYSCTL);
748 	if (req == NULL) {
749 		free(mibname, M_KTRACE);
750 		return;
751 	}
752 	req->ktr_header.ktr_len = mibnamelen;
753 	req->ktr_buffer = mibname;
754 	ktr_submitrequest(curthread, req);
755 }
756 
757 void
ktrgenio(int fd,enum uio_rw rw,struct uio * uio,int error)758 ktrgenio(int fd, enum uio_rw rw, struct uio *uio, int error)
759 {
760 	struct ktr_request *req;
761 	struct ktr_genio *ktg;
762 	int datalen;
763 	char *buf;
764 
765 	if (error) {
766 		free(uio, M_IOV);
767 		return;
768 	}
769 	uio->uio_offset = 0;
770 	uio->uio_rw = UIO_WRITE;
771 	datalen = MIN(uio->uio_resid, ktr_geniosize);
772 	buf = malloc(datalen, M_KTRACE, M_WAITOK);
773 	error = uiomove(buf, datalen, uio);
774 	free(uio, M_IOV);
775 	if (error) {
776 		free(buf, M_KTRACE);
777 		return;
778 	}
779 	req = ktr_getrequest(KTR_GENIO);
780 	if (req == NULL) {
781 		free(buf, M_KTRACE);
782 		return;
783 	}
784 	ktg = &req->ktr_data.ktr_genio;
785 	ktg->ktr_fd = fd;
786 	ktg->ktr_rw = rw;
787 	req->ktr_header.ktr_len = datalen;
788 	req->ktr_buffer = buf;
789 	ktr_submitrequest(curthread, req);
790 }
791 
792 void
ktrpsig(int sig,sig_t action,sigset_t * mask,int code)793 ktrpsig(int sig, sig_t action, sigset_t *mask, int code)
794 {
795 	struct thread *td = curthread;
796 	struct ktr_request *req;
797 	struct ktr_psig	*kp;
798 
799 	req = ktr_getrequest(KTR_PSIG);
800 	if (req == NULL)
801 		return;
802 	kp = &req->ktr_data.ktr_psig;
803 	kp->signo = (char)sig;
804 	kp->action = action;
805 	kp->mask = *mask;
806 	kp->code = code;
807 	ktr_enqueuerequest(td, req);
808 	ktrace_exit(td);
809 }
810 
811 void
ktrcsw(int out,int user,const char * wmesg)812 ktrcsw(int out, int user, const char *wmesg)
813 {
814 	struct thread *td = curthread;
815 	struct ktr_request *req;
816 	struct ktr_csw *kc;
817 
818 	if (__predict_false(curthread->td_pflags & TDP_INKTRACE))
819 		return;
820 
821 	req = ktr_getrequest(KTR_CSW);
822 	if (req == NULL)
823 		return;
824 	kc = &req->ktr_data.ktr_csw;
825 	kc->out = out;
826 	kc->user = user;
827 	if (wmesg != NULL)
828 		strlcpy(kc->wmesg, wmesg, sizeof(kc->wmesg));
829 	else
830 		bzero(kc->wmesg, sizeof(kc->wmesg));
831 	ktr_enqueuerequest(td, req);
832 	ktrace_exit(td);
833 }
834 
835 void
ktrstruct(const char * name,const void * data,size_t datalen)836 ktrstruct(const char *name, const void *data, size_t datalen)
837 {
838 	struct ktr_request *req;
839 	char *buf;
840 	size_t buflen, namelen;
841 
842 	if (__predict_false(curthread->td_pflags & TDP_INKTRACE))
843 		return;
844 
845 	if (data == NULL)
846 		datalen = 0;
847 	namelen = strlen(name) + 1;
848 	buflen = namelen + datalen;
849 	buf = malloc(buflen, M_KTRACE, M_WAITOK);
850 	strcpy(buf, name);
851 	bcopy(data, buf + namelen, datalen);
852 	if ((req = ktr_getrequest(KTR_STRUCT)) == NULL) {
853 		free(buf, M_KTRACE);
854 		return;
855 	}
856 	req->ktr_buffer = buf;
857 	req->ktr_header.ktr_len = buflen;
858 	ktr_submitrequest(curthread, req);
859 }
860 
861 void
ktrstruct_error(const char * name,const void * data,size_t datalen,int error)862 ktrstruct_error(const char *name, const void *data, size_t datalen, int error)
863 {
864 
865 	if (error == 0)
866 		ktrstruct(name, data, datalen);
867 }
868 
869 void
ktrstructarray(const char * name,enum uio_seg seg,const void * data,int num_items,size_t struct_size)870 ktrstructarray(const char *name, enum uio_seg seg, const void *data,
871     int num_items, size_t struct_size)
872 {
873 	struct ktr_request *req;
874 	struct ktr_struct_array *ksa;
875 	char *buf;
876 	size_t buflen, datalen, namelen;
877 	int max_items;
878 
879 	if (__predict_false(curthread->td_pflags & TDP_INKTRACE))
880 		return;
881 	if (num_items < 0)
882 		return;
883 
884 	/* Trim array length to genio size. */
885 	max_items = ktr_geniosize / struct_size;
886 	if (num_items > max_items) {
887 		if (max_items == 0)
888 			num_items = 1;
889 		else
890 			num_items = max_items;
891 	}
892 	datalen = num_items * struct_size;
893 
894 	if (data == NULL)
895 		datalen = 0;
896 
897 	namelen = strlen(name) + 1;
898 	buflen = namelen + datalen;
899 	buf = malloc(buflen, M_KTRACE, M_WAITOK);
900 	strcpy(buf, name);
901 	if (seg == UIO_SYSSPACE)
902 		bcopy(data, buf + namelen, datalen);
903 	else {
904 		if (copyin(data, buf + namelen, datalen) != 0) {
905 			free(buf, M_KTRACE);
906 			return;
907 		}
908 	}
909 	if ((req = ktr_getrequest(KTR_STRUCT_ARRAY)) == NULL) {
910 		free(buf, M_KTRACE);
911 		return;
912 	}
913 	ksa = &req->ktr_data.ktr_struct_array;
914 	ksa->struct_size = struct_size;
915 	req->ktr_buffer = buf;
916 	req->ktr_header.ktr_len = buflen;
917 	ktr_submitrequest(curthread, req);
918 }
919 
920 void
ktrcapfail(enum ktr_cap_fail_type type,const cap_rights_t * needed,const cap_rights_t * held)921 ktrcapfail(enum ktr_cap_fail_type type, const cap_rights_t *needed,
922     const cap_rights_t *held)
923 {
924 	struct thread *td = curthread;
925 	struct ktr_request *req;
926 	struct ktr_cap_fail *kcf;
927 
928 	if (__predict_false(curthread->td_pflags & TDP_INKTRACE))
929 		return;
930 
931 	req = ktr_getrequest(KTR_CAPFAIL);
932 	if (req == NULL)
933 		return;
934 	kcf = &req->ktr_data.ktr_cap_fail;
935 	kcf->cap_type = type;
936 	if (needed != NULL)
937 		kcf->cap_needed = *needed;
938 	else
939 		cap_rights_init(&kcf->cap_needed);
940 	if (held != NULL)
941 		kcf->cap_held = *held;
942 	else
943 		cap_rights_init(&kcf->cap_held);
944 	ktr_enqueuerequest(td, req);
945 	ktrace_exit(td);
946 }
947 
948 void
ktrfault(vm_offset_t vaddr,int type)949 ktrfault(vm_offset_t vaddr, int type)
950 {
951 	struct thread *td = curthread;
952 	struct ktr_request *req;
953 	struct ktr_fault *kf;
954 
955 	if (__predict_false(curthread->td_pflags & TDP_INKTRACE))
956 		return;
957 
958 	req = ktr_getrequest(KTR_FAULT);
959 	if (req == NULL)
960 		return;
961 	kf = &req->ktr_data.ktr_fault;
962 	kf->vaddr = vaddr;
963 	kf->type = type;
964 	ktr_enqueuerequest(td, req);
965 	ktrace_exit(td);
966 }
967 
968 void
ktrfaultend(int result)969 ktrfaultend(int result)
970 {
971 	struct thread *td = curthread;
972 	struct ktr_request *req;
973 	struct ktr_faultend *kf;
974 
975 	if (__predict_false(curthread->td_pflags & TDP_INKTRACE))
976 		return;
977 
978 	req = ktr_getrequest(KTR_FAULTEND);
979 	if (req == NULL)
980 		return;
981 	kf = &req->ktr_data.ktr_faultend;
982 	kf->result = result;
983 	ktr_enqueuerequest(td, req);
984 	ktrace_exit(td);
985 }
986 #endif /* KTRACE */
987 
988 /* Interface and common routines */
989 
990 #ifndef _SYS_SYSPROTO_H_
991 struct ktrace_args {
992 	char	*fname;
993 	int	ops;
994 	int	facs;
995 	int	pid;
996 };
997 #endif
998 /* ARGSUSED */
999 int
sys_ktrace(struct thread * td,struct ktrace_args * uap)1000 sys_ktrace(struct thread *td, struct ktrace_args *uap)
1001 {
1002 #ifdef KTRACE
1003 	struct vnode *vp = NULL;
1004 	struct proc *p;
1005 	struct pgrp *pg;
1006 	int facs = uap->facs & ~KTRFAC_ROOT;
1007 	int ops = KTROP(uap->ops);
1008 	int descend = uap->ops & KTRFLAG_DESCEND;
1009 	int nfound, ret = 0;
1010 	int flags, error = 0;
1011 	struct nameidata nd;
1012 	struct ktr_io_params *kiop, *old_kiop;
1013 
1014 	/*
1015 	 * Need something to (un)trace.
1016 	 */
1017 	if (ops != KTROP_CLEARFILE && facs == 0)
1018 		return (EINVAL);
1019 
1020 	kiop = NULL;
1021 	ktrace_enter(td);
1022 	if (ops != KTROP_CLEAR) {
1023 		/*
1024 		 * an operation which requires a file argument.
1025 		 */
1026 		NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_USERSPACE, uap->fname, td);
1027 		flags = FREAD | FWRITE | O_NOFOLLOW;
1028 		error = vn_open(&nd, &flags, 0, NULL);
1029 		if (error) {
1030 			ktrace_exit(td);
1031 			return (error);
1032 		}
1033 		NDFREE(&nd, NDF_ONLY_PNBUF);
1034 		vp = nd.ni_vp;
1035 		VOP_UNLOCK(vp);
1036 		if (vp->v_type != VREG) {
1037 			(void) vn_close(vp, FREAD|FWRITE, td->td_ucred, td);
1038 			ktrace_exit(td);
1039 			return (EACCES);
1040 		}
1041 		kiop = ktr_io_params_alloc(td, vp);
1042 	}
1043 	/*
1044 	 * Clear all uses of the tracefile.
1045 	 */
1046 	if (ops == KTROP_CLEARFILE) {
1047 restart:
1048 		sx_slock(&allproc_lock);
1049 		FOREACH_PROC_IN_SYSTEM(p) {
1050 			old_kiop = NULL;
1051 			PROC_LOCK(p);
1052 			if (p->p_ktrioparms != NULL &&
1053 			    p->p_ktrioparms->vp == vp) {
1054 				if (ktrcanset(td, p)) {
1055 					mtx_lock(&ktrace_mtx);
1056 					old_kiop = ktr_freeproc(p);
1057 					mtx_unlock(&ktrace_mtx);
1058 				} else
1059 					error = EPERM;
1060 			}
1061 			PROC_UNLOCK(p);
1062 			if (old_kiop != NULL) {
1063 				sx_sunlock(&allproc_lock);
1064 				ktr_io_params_free(old_kiop);
1065 				goto restart;
1066 			}
1067 		}
1068 		sx_sunlock(&allproc_lock);
1069 		goto done;
1070 	}
1071 	/*
1072 	 * do it
1073 	 */
1074 	sx_slock(&proctree_lock);
1075 	if (uap->pid < 0) {
1076 		/*
1077 		 * by process group
1078 		 */
1079 		pg = pgfind(-uap->pid);
1080 		if (pg == NULL) {
1081 			sx_sunlock(&proctree_lock);
1082 			error = ESRCH;
1083 			goto done;
1084 		}
1085 		/*
1086 		 * ktrops() may call vrele(). Lock pg_members
1087 		 * by the proctree_lock rather than pg_mtx.
1088 		 */
1089 		PGRP_UNLOCK(pg);
1090 		nfound = 0;
1091 		LIST_FOREACH(p, &pg->pg_members, p_pglist) {
1092 			PROC_LOCK(p);
1093 			if (p->p_state == PRS_NEW ||
1094 			    p_cansee(td, p) != 0) {
1095 				PROC_UNLOCK(p);
1096 				continue;
1097 			}
1098 			nfound++;
1099 			if (descend)
1100 				ret |= ktrsetchildren(td, p, ops, facs, kiop);
1101 			else
1102 				ret |= ktrops(td, p, ops, facs, kiop);
1103 		}
1104 		if (nfound == 0) {
1105 			sx_sunlock(&proctree_lock);
1106 			error = ESRCH;
1107 			goto done;
1108 		}
1109 	} else {
1110 		/*
1111 		 * by pid
1112 		 */
1113 		p = pfind(uap->pid);
1114 		if (p == NULL)
1115 			error = ESRCH;
1116 		else
1117 			error = p_cansee(td, p);
1118 		if (error) {
1119 			if (p != NULL)
1120 				PROC_UNLOCK(p);
1121 			sx_sunlock(&proctree_lock);
1122 			goto done;
1123 		}
1124 		if (descend)
1125 			ret |= ktrsetchildren(td, p, ops, facs, kiop);
1126 		else
1127 			ret |= ktrops(td, p, ops, facs, kiop);
1128 	}
1129 	sx_sunlock(&proctree_lock);
1130 	if (!ret)
1131 		error = EPERM;
1132 done:
1133 	if (kiop != NULL) {
1134 		mtx_lock(&ktrace_mtx);
1135 		kiop = ktr_io_params_rele(kiop);
1136 		mtx_unlock(&ktrace_mtx);
1137 		ktr_io_params_free(kiop);
1138 	}
1139 	ktrace_exit(td);
1140 	return (error);
1141 #else /* !KTRACE */
1142 	return (ENOSYS);
1143 #endif /* KTRACE */
1144 }
1145 
1146 /* ARGSUSED */
1147 int
sys_utrace(struct thread * td,struct utrace_args * uap)1148 sys_utrace(struct thread *td, struct utrace_args *uap)
1149 {
1150 
1151 #ifdef KTRACE
1152 	struct ktr_request *req;
1153 	void *cp;
1154 	int error;
1155 
1156 	if (!KTRPOINT(td, KTR_USER))
1157 		return (0);
1158 	if (uap->len > KTR_USER_MAXLEN)
1159 		return (EINVAL);
1160 	cp = malloc(uap->len, M_KTRACE, M_WAITOK);
1161 	error = copyin(uap->addr, cp, uap->len);
1162 	if (error) {
1163 		free(cp, M_KTRACE);
1164 		return (error);
1165 	}
1166 	req = ktr_getrequest(KTR_USER);
1167 	if (req == NULL) {
1168 		free(cp, M_KTRACE);
1169 		return (ENOMEM);
1170 	}
1171 	req->ktr_buffer = cp;
1172 	req->ktr_header.ktr_len = uap->len;
1173 	ktr_submitrequest(td, req);
1174 	return (0);
1175 #else /* !KTRACE */
1176 	return (ENOSYS);
1177 #endif /* KTRACE */
1178 }
1179 
1180 #ifdef KTRACE
1181 static int
ktrops(struct thread * td,struct proc * p,int ops,int facs,struct ktr_io_params * new_kiop)1182 ktrops(struct thread *td, struct proc *p, int ops, int facs,
1183     struct ktr_io_params *new_kiop)
1184 {
1185 	struct ktr_io_params *old_kiop;
1186 
1187 	PROC_LOCK_ASSERT(p, MA_OWNED);
1188 	if (!ktrcanset(td, p)) {
1189 		PROC_UNLOCK(p);
1190 		return (0);
1191 	}
1192 	if (p->p_flag & P_WEXIT) {
1193 		/* If the process is exiting, just ignore it. */
1194 		PROC_UNLOCK(p);
1195 		return (1);
1196 	}
1197 	old_kiop = NULL;
1198 	mtx_lock(&ktrace_mtx);
1199 	if (ops == KTROP_SET) {
1200 		if (p->p_ktrioparms != NULL &&
1201 		    p->p_ktrioparms->vp != new_kiop->vp) {
1202 			/* if trace file already in use, relinquish below */
1203 			old_kiop = ktr_io_params_rele(p->p_ktrioparms);
1204 			p->p_ktrioparms = NULL;
1205 		}
1206 		if (p->p_ktrioparms == NULL) {
1207 			p->p_ktrioparms = new_kiop;
1208 			ktr_io_params_ref(new_kiop);
1209 		}
1210 		p->p_traceflag |= facs;
1211 		if (priv_check(td, PRIV_KTRACE) == 0)
1212 			p->p_traceflag |= KTRFAC_ROOT;
1213 	} else {
1214 		/* KTROP_CLEAR */
1215 		if (((p->p_traceflag &= ~facs) & KTRFAC_MASK) == 0)
1216 			/* no more tracing */
1217 			old_kiop = ktr_freeproc(p);
1218 	}
1219 	mtx_unlock(&ktrace_mtx);
1220 	if ((p->p_traceflag & KTRFAC_MASK) != 0)
1221 		ktrprocctor_entered(td, p);
1222 	PROC_UNLOCK(p);
1223 	ktr_io_params_free(old_kiop);
1224 
1225 	return (1);
1226 }
1227 
1228 static int
ktrsetchildren(struct thread * td,struct proc * top,int ops,int facs,struct ktr_io_params * new_kiop)1229 ktrsetchildren(struct thread *td, struct proc *top, int ops, int facs,
1230     struct ktr_io_params *new_kiop)
1231 {
1232 	struct proc *p;
1233 	int ret = 0;
1234 
1235 	p = top;
1236 	PROC_LOCK_ASSERT(p, MA_OWNED);
1237 	sx_assert(&proctree_lock, SX_LOCKED);
1238 	for (;;) {
1239 		ret |= ktrops(td, p, ops, facs, new_kiop);
1240 		/*
1241 		 * If this process has children, descend to them next,
1242 		 * otherwise do any siblings, and if done with this level,
1243 		 * follow back up the tree (but not past top).
1244 		 */
1245 		if (!LIST_EMPTY(&p->p_children))
1246 			p = LIST_FIRST(&p->p_children);
1247 		else for (;;) {
1248 			if (p == top)
1249 				return (ret);
1250 			if (LIST_NEXT(p, p_sibling)) {
1251 				p = LIST_NEXT(p, p_sibling);
1252 				break;
1253 			}
1254 			p = p->p_pptr;
1255 		}
1256 		PROC_LOCK(p);
1257 	}
1258 	/*NOTREACHED*/
1259 }
1260 
1261 static void
ktr_writerequest(struct thread * td,struct ktr_request * req)1262 ktr_writerequest(struct thread *td, struct ktr_request *req)
1263 {
1264 	struct ktr_io_params *kiop, *kiop1;
1265 	struct ktr_header *kth;
1266 	struct vnode *vp;
1267 	struct proc *p;
1268 	struct ucred *cred;
1269 	struct uio auio;
1270 	struct iovec aiov[3];
1271 	struct mount *mp;
1272 	off_t lim;
1273 	int datalen, buflen;
1274 	int error;
1275 
1276 	p = td->td_proc;
1277 
1278 	/*
1279 	 * We reference the kiop for use in I/O in case ktrace is
1280 	 * disabled on the process as we write out the request.
1281 	 */
1282 	mtx_lock(&ktrace_mtx);
1283 	kiop = p->p_ktrioparms;
1284 
1285 	/*
1286 	 * If kiop is NULL, it has been cleared out from under this
1287 	 * request, so just drop it.
1288 	 */
1289 	if (kiop == NULL) {
1290 		mtx_unlock(&ktrace_mtx);
1291 		return;
1292 	}
1293 
1294 	ktr_io_params_ref(kiop);
1295 	vp = kiop->vp;
1296 	cred = kiop->cr;
1297 	lim = kiop->lim;
1298 
1299 	KASSERT(cred != NULL, ("ktr_writerequest: cred == NULL"));
1300 	mtx_unlock(&ktrace_mtx);
1301 
1302 	kth = &req->ktr_header;
1303 	KASSERT(((u_short)kth->ktr_type & ~KTR_DROP) < nitems(data_lengths),
1304 	    ("data_lengths array overflow"));
1305 	datalen = data_lengths[(u_short)kth->ktr_type & ~KTR_DROP];
1306 	buflen = kth->ktr_len;
1307 	auio.uio_iov = &aiov[0];
1308 	auio.uio_offset = 0;
1309 	auio.uio_segflg = UIO_SYSSPACE;
1310 	auio.uio_rw = UIO_WRITE;
1311 	aiov[0].iov_base = (caddr_t)kth;
1312 	aiov[0].iov_len = sizeof(struct ktr_header);
1313 	auio.uio_resid = sizeof(struct ktr_header);
1314 	auio.uio_iovcnt = 1;
1315 	auio.uio_td = td;
1316 	if (datalen != 0) {
1317 		aiov[1].iov_base = (caddr_t)&req->ktr_data;
1318 		aiov[1].iov_len = datalen;
1319 		auio.uio_resid += datalen;
1320 		auio.uio_iovcnt++;
1321 		kth->ktr_len += datalen;
1322 	}
1323 	if (buflen != 0) {
1324 		KASSERT(req->ktr_buffer != NULL, ("ktrace: nothing to write"));
1325 		aiov[auio.uio_iovcnt].iov_base = req->ktr_buffer;
1326 		aiov[auio.uio_iovcnt].iov_len = buflen;
1327 		auio.uio_resid += buflen;
1328 		auio.uio_iovcnt++;
1329 	}
1330 
1331 	vn_start_write(vp, &mp, V_WAIT);
1332 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1333 	td->td_ktr_io_lim = lim;
1334 #ifdef MAC
1335 	error = mac_vnode_check_write(cred, NOCRED, vp);
1336 	if (error == 0)
1337 #endif
1338 		error = VOP_WRITE(vp, &auio, IO_UNIT | IO_APPEND, cred);
1339 	VOP_UNLOCK(vp);
1340 	vn_finished_write(mp);
1341 	if (error == 0) {
1342 		mtx_lock(&ktrace_mtx);
1343 		kiop = ktr_io_params_rele(kiop);
1344 		mtx_unlock(&ktrace_mtx);
1345 		ktr_io_params_free(kiop);
1346 		return;
1347 	}
1348 
1349 	/*
1350 	 * If error encountered, give up tracing on this vnode on this
1351 	 * process.  Other processes might still be suitable for
1352 	 * writes to this vnode.
1353 	 */
1354 	log(LOG_NOTICE,
1355 	    "ktrace write failed, errno %d, tracing stopped for pid %d\n",
1356 	    error, p->p_pid);
1357 
1358 	kiop1 = NULL;
1359 	PROC_LOCK(p);
1360 	mtx_lock(&ktrace_mtx);
1361 	if (p->p_ktrioparms != NULL && p->p_ktrioparms->vp == vp)
1362 		kiop1 = ktr_freeproc(p);
1363 	kiop = ktr_io_params_rele(kiop);
1364 	mtx_unlock(&ktrace_mtx);
1365 	PROC_UNLOCK(p);
1366 	ktr_io_params_free(kiop1);
1367 	ktr_io_params_free(kiop);
1368 }
1369 
1370 /*
1371  * Return true if caller has permission to set the ktracing state
1372  * of target.  Essentially, the target can't possess any
1373  * more permissions than the caller.  KTRFAC_ROOT signifies that
1374  * root previously set the tracing status on the target process, and
1375  * so, only root may further change it.
1376  */
1377 static int
ktrcanset(struct thread * td,struct proc * targetp)1378 ktrcanset(struct thread *td, struct proc *targetp)
1379 {
1380 
1381 	PROC_LOCK_ASSERT(targetp, MA_OWNED);
1382 	if (targetp->p_traceflag & KTRFAC_ROOT &&
1383 	    priv_check(td, PRIV_KTRACE))
1384 		return (0);
1385 
1386 	if (p_candebug(td, targetp) != 0)
1387 		return (0);
1388 
1389 	return (1);
1390 }
1391 
1392 #endif /* KTRACE */
1393