xref: /freebsd/sys/kern/kern_proc.c (revision e17f5b1d)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1989, 1991, 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_proc.c	8.7 (Berkeley) 2/14/95
32  */
33 
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36 
37 #include "opt_ddb.h"
38 #include "opt_ktrace.h"
39 #include "opt_kstack_pages.h"
40 #include "opt_stack.h"
41 
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/bitstring.h>
45 #include <sys/elf.h>
46 #include <sys/eventhandler.h>
47 #include <sys/exec.h>
48 #include <sys/jail.h>
49 #include <sys/kernel.h>
50 #include <sys/limits.h>
51 #include <sys/lock.h>
52 #include <sys/loginclass.h>
53 #include <sys/malloc.h>
54 #include <sys/mman.h>
55 #include <sys/mount.h>
56 #include <sys/mutex.h>
57 #include <sys/proc.h>
58 #include <sys/ptrace.h>
59 #include <sys/refcount.h>
60 #include <sys/resourcevar.h>
61 #include <sys/rwlock.h>
62 #include <sys/sbuf.h>
63 #include <sys/sysent.h>
64 #include <sys/sched.h>
65 #include <sys/smp.h>
66 #include <sys/stack.h>
67 #include <sys/stat.h>
68 #include <sys/sysctl.h>
69 #include <sys/filedesc.h>
70 #include <sys/tty.h>
71 #include <sys/signalvar.h>
72 #include <sys/sdt.h>
73 #include <sys/sx.h>
74 #include <sys/user.h>
75 #include <sys/vnode.h>
76 #include <sys/wait.h>
77 
78 #ifdef DDB
79 #include <ddb/ddb.h>
80 #endif
81 
82 #include <vm/vm.h>
83 #include <vm/vm_param.h>
84 #include <vm/vm_extern.h>
85 #include <vm/pmap.h>
86 #include <vm/vm_map.h>
87 #include <vm/vm_object.h>
88 #include <vm/vm_page.h>
89 #include <vm/uma.h>
90 
91 #ifdef COMPAT_FREEBSD32
92 #include <compat/freebsd32/freebsd32.h>
93 #include <compat/freebsd32/freebsd32_util.h>
94 #endif
95 
96 SDT_PROVIDER_DEFINE(proc);
97 
98 MALLOC_DEFINE(M_PGRP, "pgrp", "process group header");
99 MALLOC_DEFINE(M_SESSION, "session", "session header");
100 static MALLOC_DEFINE(M_PROC, "proc", "Proc structures");
101 MALLOC_DEFINE(M_SUBPROC, "subproc", "Proc sub-structures");
102 
103 static void doenterpgrp(struct proc *, struct pgrp *);
104 static void orphanpg(struct pgrp *pg);
105 static void fill_kinfo_aggregate(struct proc *p, struct kinfo_proc *kp);
106 static void fill_kinfo_proc_only(struct proc *p, struct kinfo_proc *kp);
107 static void fill_kinfo_thread(struct thread *td, struct kinfo_proc *kp,
108     int preferthread);
109 static void pgadjustjobc(struct pgrp *pgrp, int entering);
110 static void pgdelete(struct pgrp *);
111 static int proc_ctor(void *mem, int size, void *arg, int flags);
112 static void proc_dtor(void *mem, int size, void *arg);
113 static int proc_init(void *mem, int size, int flags);
114 static void proc_fini(void *mem, int size);
115 static void pargs_free(struct pargs *pa);
116 
117 /*
118  * Other process lists
119  */
120 struct pidhashhead *pidhashtbl;
121 struct sx *pidhashtbl_lock;
122 u_long pidhash;
123 u_long pidhashlock;
124 struct pgrphashhead *pgrphashtbl;
125 u_long pgrphash;
126 struct proclist allproc;
127 struct sx __exclusive_cache_line allproc_lock;
128 struct sx __exclusive_cache_line proctree_lock;
129 struct mtx __exclusive_cache_line ppeers_lock;
130 struct mtx __exclusive_cache_line procid_lock;
131 uma_zone_t proc_zone;
132 
133 /*
134  * The offset of various fields in struct proc and struct thread.
135  * These are used by kernel debuggers to enumerate kernel threads and
136  * processes.
137  */
138 const int proc_off_p_pid = offsetof(struct proc, p_pid);
139 const int proc_off_p_comm = offsetof(struct proc, p_comm);
140 const int proc_off_p_list = offsetof(struct proc, p_list);
141 const int proc_off_p_threads = offsetof(struct proc, p_threads);
142 const int thread_off_td_tid = offsetof(struct thread, td_tid);
143 const int thread_off_td_name = offsetof(struct thread, td_name);
144 const int thread_off_td_oncpu = offsetof(struct thread, td_oncpu);
145 const int thread_off_td_pcb = offsetof(struct thread, td_pcb);
146 const int thread_off_td_plist = offsetof(struct thread, td_plist);
147 
148 EVENTHANDLER_LIST_DEFINE(process_ctor);
149 EVENTHANDLER_LIST_DEFINE(process_dtor);
150 EVENTHANDLER_LIST_DEFINE(process_init);
151 EVENTHANDLER_LIST_DEFINE(process_fini);
152 EVENTHANDLER_LIST_DEFINE(process_exit);
153 EVENTHANDLER_LIST_DEFINE(process_fork);
154 EVENTHANDLER_LIST_DEFINE(process_exec);
155 
156 int kstack_pages = KSTACK_PAGES;
157 SYSCTL_INT(_kern, OID_AUTO, kstack_pages, CTLFLAG_RD, &kstack_pages, 0,
158     "Kernel stack size in pages");
159 static int vmmap_skip_res_cnt = 0;
160 SYSCTL_INT(_kern, OID_AUTO, proc_vmmap_skip_resident_count, CTLFLAG_RW,
161     &vmmap_skip_res_cnt, 0,
162     "Skip calculation of the pages resident count in kern.proc.vmmap");
163 
164 CTASSERT(sizeof(struct kinfo_proc) == KINFO_PROC_SIZE);
165 #ifdef COMPAT_FREEBSD32
166 CTASSERT(sizeof(struct kinfo_proc32) == KINFO_PROC32_SIZE);
167 #endif
168 
169 /*
170  * Initialize global process hashing structures.
171  */
172 void
173 procinit(void)
174 {
175 	u_long i;
176 
177 	sx_init(&allproc_lock, "allproc");
178 	sx_init(&proctree_lock, "proctree");
179 	mtx_init(&ppeers_lock, "p_peers", NULL, MTX_DEF);
180 	mtx_init(&procid_lock, "procid", NULL, MTX_DEF);
181 	LIST_INIT(&allproc);
182 	pidhashtbl = hashinit(maxproc / 4, M_PROC, &pidhash);
183 	pidhashlock = (pidhash + 1) / 64;
184 	if (pidhashlock > 0)
185 		pidhashlock--;
186 	pidhashtbl_lock = malloc(sizeof(*pidhashtbl_lock) * (pidhashlock + 1),
187 	    M_PROC, M_WAITOK | M_ZERO);
188 	for (i = 0; i < pidhashlock + 1; i++)
189 		sx_init_flags(&pidhashtbl_lock[i], "pidhash", SX_DUPOK);
190 	pgrphashtbl = hashinit(maxproc / 4, M_PROC, &pgrphash);
191 	proc_zone = uma_zcreate("PROC", sched_sizeof_proc(),
192 	    proc_ctor, proc_dtor, proc_init, proc_fini,
193 	    UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
194 	uihashinit();
195 }
196 
197 /*
198  * Prepare a proc for use.
199  */
200 static int
201 proc_ctor(void *mem, int size, void *arg, int flags)
202 {
203 	struct proc *p;
204 	struct thread *td;
205 
206 	p = (struct proc *)mem;
207 	EVENTHANDLER_DIRECT_INVOKE(process_ctor, p);
208 	td = FIRST_THREAD_IN_PROC(p);
209 	if (td != NULL) {
210 		/* Make sure all thread constructors are executed */
211 		EVENTHANDLER_DIRECT_INVOKE(thread_ctor, td);
212 	}
213 	return (0);
214 }
215 
216 /*
217  * Reclaim a proc after use.
218  */
219 static void
220 proc_dtor(void *mem, int size, void *arg)
221 {
222 	struct proc *p;
223 	struct thread *td;
224 
225 	/* INVARIANTS checks go here */
226 	p = (struct proc *)mem;
227 	td = FIRST_THREAD_IN_PROC(p);
228 	if (td != NULL) {
229 #ifdef INVARIANTS
230 		KASSERT((p->p_numthreads == 1),
231 		    ("bad number of threads in exiting process"));
232 		KASSERT(STAILQ_EMPTY(&p->p_ktr), ("proc_dtor: non-empty p_ktr"));
233 #endif
234 		/* Free all OSD associated to this thread. */
235 		osd_thread_exit(td);
236 		td_softdep_cleanup(td);
237 		MPASS(td->td_su == NULL);
238 
239 		/* Make sure all thread destructors are executed */
240 		EVENTHANDLER_DIRECT_INVOKE(thread_dtor, td);
241 	}
242 	EVENTHANDLER_DIRECT_INVOKE(process_dtor, p);
243 	if (p->p_ksi != NULL)
244 		KASSERT(! KSI_ONQ(p->p_ksi), ("SIGCHLD queue"));
245 }
246 
247 /*
248  * Initialize type-stable parts of a proc (when newly created).
249  */
250 static int
251 proc_init(void *mem, int size, int flags)
252 {
253 	struct proc *p;
254 
255 	p = (struct proc *)mem;
256 	mtx_init(&p->p_mtx, "process lock", NULL, MTX_DEF | MTX_DUPOK | MTX_NEW);
257 	mtx_init(&p->p_slock, "process slock", NULL, MTX_SPIN | MTX_NEW);
258 	mtx_init(&p->p_statmtx, "pstatl", NULL, MTX_SPIN | MTX_NEW);
259 	mtx_init(&p->p_itimmtx, "pitiml", NULL, MTX_SPIN | MTX_NEW);
260 	mtx_init(&p->p_profmtx, "pprofl", NULL, MTX_SPIN | MTX_NEW);
261 	cv_init(&p->p_pwait, "ppwait");
262 	TAILQ_INIT(&p->p_threads);	     /* all threads in proc */
263 	EVENTHANDLER_DIRECT_INVOKE(process_init, p);
264 	p->p_stats = pstats_alloc();
265 	p->p_pgrp = NULL;
266 	return (0);
267 }
268 
269 /*
270  * UMA should ensure that this function is never called.
271  * Freeing a proc structure would violate type stability.
272  */
273 static void
274 proc_fini(void *mem, int size)
275 {
276 #ifdef notnow
277 	struct proc *p;
278 
279 	p = (struct proc *)mem;
280 	EVENTHANDLER_DIRECT_INVOKE(process_fini, p);
281 	pstats_free(p->p_stats);
282 	thread_free(FIRST_THREAD_IN_PROC(p));
283 	mtx_destroy(&p->p_mtx);
284 	if (p->p_ksi != NULL)
285 		ksiginfo_free(p->p_ksi);
286 #else
287 	panic("proc reclaimed");
288 #endif
289 }
290 
291 /*
292  * PID space management.
293  *
294  * These bitmaps are used by fork_findpid.
295  */
296 bitstr_t bit_decl(proc_id_pidmap, PID_MAX);
297 bitstr_t bit_decl(proc_id_grpidmap, PID_MAX);
298 bitstr_t bit_decl(proc_id_sessidmap, PID_MAX);
299 bitstr_t bit_decl(proc_id_reapmap, PID_MAX);
300 
301 static bitstr_t *proc_id_array[] = {
302 	proc_id_pidmap,
303 	proc_id_grpidmap,
304 	proc_id_sessidmap,
305 	proc_id_reapmap,
306 };
307 
308 void
309 proc_id_set(int type, pid_t id)
310 {
311 
312 	KASSERT(type >= 0 && type < nitems(proc_id_array),
313 	    ("invalid type %d\n", type));
314 	mtx_lock(&procid_lock);
315 	KASSERT(bit_test(proc_id_array[type], id) == 0,
316 	    ("bit %d already set in %d\n", id, type));
317 	bit_set(proc_id_array[type], id);
318 	mtx_unlock(&procid_lock);
319 }
320 
321 void
322 proc_id_set_cond(int type, pid_t id)
323 {
324 
325 	KASSERT(type >= 0 && type < nitems(proc_id_array),
326 	    ("invalid type %d\n", type));
327 	if (bit_test(proc_id_array[type], id))
328 		return;
329 	mtx_lock(&procid_lock);
330 	bit_set(proc_id_array[type], id);
331 	mtx_unlock(&procid_lock);
332 }
333 
334 void
335 proc_id_clear(int type, pid_t id)
336 {
337 
338 	KASSERT(type >= 0 && type < nitems(proc_id_array),
339 	    ("invalid type %d\n", type));
340 	mtx_lock(&procid_lock);
341 	KASSERT(bit_test(proc_id_array[type], id) != 0,
342 	    ("bit %d not set in %d\n", id, type));
343 	bit_clear(proc_id_array[type], id);
344 	mtx_unlock(&procid_lock);
345 }
346 
347 /*
348  * Is p an inferior of the current process?
349  */
350 int
351 inferior(struct proc *p)
352 {
353 
354 	sx_assert(&proctree_lock, SX_LOCKED);
355 	PROC_LOCK_ASSERT(p, MA_OWNED);
356 	for (; p != curproc; p = proc_realparent(p)) {
357 		if (p->p_pid == 0)
358 			return (0);
359 	}
360 	return (1);
361 }
362 
363 /*
364  * Shared lock all the pid hash lists.
365  */
366 void
367 pidhash_slockall(void)
368 {
369 	u_long i;
370 
371 	for (i = 0; i < pidhashlock + 1; i++)
372 		sx_slock(&pidhashtbl_lock[i]);
373 }
374 
375 /*
376  * Shared unlock all the pid hash lists.
377  */
378 void
379 pidhash_sunlockall(void)
380 {
381 	u_long i;
382 
383 	for (i = 0; i < pidhashlock + 1; i++)
384 		sx_sunlock(&pidhashtbl_lock[i]);
385 }
386 
387 /*
388  * Similar to pfind_any(), this function finds zombies.
389  */
390 struct proc *
391 pfind_any_locked(pid_t pid)
392 {
393 	struct proc *p;
394 
395 	sx_assert(PIDHASHLOCK(pid), SX_LOCKED);
396 	LIST_FOREACH(p, PIDHASH(pid), p_hash) {
397 		if (p->p_pid == pid) {
398 			PROC_LOCK(p);
399 			if (p->p_state == PRS_NEW) {
400 				PROC_UNLOCK(p);
401 				p = NULL;
402 			}
403 			break;
404 		}
405 	}
406 	return (p);
407 }
408 
409 /*
410  * Locate a process by number.
411  *
412  * By not returning processes in the PRS_NEW state, we allow callers to avoid
413  * testing for that condition to avoid dereferencing p_ucred, et al.
414  */
415 static __always_inline struct proc *
416 _pfind(pid_t pid, bool zombie)
417 {
418 	struct proc *p;
419 
420 	p = curproc;
421 	if (p->p_pid == pid) {
422 		PROC_LOCK(p);
423 		return (p);
424 	}
425 	sx_slock(PIDHASHLOCK(pid));
426 	LIST_FOREACH(p, PIDHASH(pid), p_hash) {
427 		if (p->p_pid == pid) {
428 			PROC_LOCK(p);
429 			if (p->p_state == PRS_NEW ||
430 			    (!zombie && p->p_state == PRS_ZOMBIE)) {
431 				PROC_UNLOCK(p);
432 				p = NULL;
433 			}
434 			break;
435 		}
436 	}
437 	sx_sunlock(PIDHASHLOCK(pid));
438 	return (p);
439 }
440 
441 struct proc *
442 pfind(pid_t pid)
443 {
444 
445 	return (_pfind(pid, false));
446 }
447 
448 /*
449  * Same as pfind but allow zombies.
450  */
451 struct proc *
452 pfind_any(pid_t pid)
453 {
454 
455 	return (_pfind(pid, true));
456 }
457 
458 /*
459  * Locate a process group by number.
460  * The caller must hold proctree_lock.
461  */
462 struct pgrp *
463 pgfind(pid_t pgid)
464 {
465 	struct pgrp *pgrp;
466 
467 	sx_assert(&proctree_lock, SX_LOCKED);
468 
469 	LIST_FOREACH(pgrp, PGRPHASH(pgid), pg_hash) {
470 		if (pgrp->pg_id == pgid) {
471 			PGRP_LOCK(pgrp);
472 			return (pgrp);
473 		}
474 	}
475 	return (NULL);
476 }
477 
478 /*
479  * Locate process and do additional manipulations, depending on flags.
480  */
481 int
482 pget(pid_t pid, int flags, struct proc **pp)
483 {
484 	struct proc *p;
485 	struct thread *td1;
486 	int error;
487 
488 	p = curproc;
489 	if (p->p_pid == pid) {
490 		PROC_LOCK(p);
491 	} else {
492 		p = NULL;
493 		if (pid <= PID_MAX) {
494 			if ((flags & PGET_NOTWEXIT) == 0)
495 				p = pfind_any(pid);
496 			else
497 				p = pfind(pid);
498 		} else if ((flags & PGET_NOTID) == 0) {
499 			td1 = tdfind(pid, -1);
500 			if (td1 != NULL)
501 				p = td1->td_proc;
502 		}
503 		if (p == NULL)
504 			return (ESRCH);
505 		if ((flags & PGET_CANSEE) != 0) {
506 			error = p_cansee(curthread, p);
507 			if (error != 0)
508 				goto errout;
509 		}
510 	}
511 	if ((flags & PGET_CANDEBUG) != 0) {
512 		error = p_candebug(curthread, p);
513 		if (error != 0)
514 			goto errout;
515 	}
516 	if ((flags & PGET_ISCURRENT) != 0 && curproc != p) {
517 		error = EPERM;
518 		goto errout;
519 	}
520 	if ((flags & PGET_NOTWEXIT) != 0 && (p->p_flag & P_WEXIT) != 0) {
521 		error = ESRCH;
522 		goto errout;
523 	}
524 	if ((flags & PGET_NOTINEXEC) != 0 && (p->p_flag & P_INEXEC) != 0) {
525 		/*
526 		 * XXXRW: Not clear ESRCH is the right error during proc
527 		 * execve().
528 		 */
529 		error = ESRCH;
530 		goto errout;
531 	}
532 	if ((flags & PGET_HOLD) != 0) {
533 		_PHOLD(p);
534 		PROC_UNLOCK(p);
535 	}
536 	*pp = p;
537 	return (0);
538 errout:
539 	PROC_UNLOCK(p);
540 	return (error);
541 }
542 
543 /*
544  * Create a new process group.
545  * pgid must be equal to the pid of p.
546  * Begin a new session if required.
547  */
548 int
549 enterpgrp(struct proc *p, pid_t pgid, struct pgrp *pgrp, struct session *sess)
550 {
551 
552 	sx_assert(&proctree_lock, SX_XLOCKED);
553 
554 	KASSERT(pgrp != NULL, ("enterpgrp: pgrp == NULL"));
555 	KASSERT(p->p_pid == pgid,
556 	    ("enterpgrp: new pgrp and pid != pgid"));
557 	KASSERT(pgfind(pgid) == NULL,
558 	    ("enterpgrp: pgrp with pgid exists"));
559 	KASSERT(!SESS_LEADER(p),
560 	    ("enterpgrp: session leader attempted setpgrp"));
561 
562 	mtx_init(&pgrp->pg_mtx, "process group", NULL, MTX_DEF | MTX_DUPOK);
563 
564 	if (sess != NULL) {
565 		/*
566 		 * new session
567 		 */
568 		mtx_init(&sess->s_mtx, "session", NULL, MTX_DEF);
569 		PROC_LOCK(p);
570 		p->p_flag &= ~P_CONTROLT;
571 		PROC_UNLOCK(p);
572 		PGRP_LOCK(pgrp);
573 		sess->s_leader = p;
574 		sess->s_sid = p->p_pid;
575 		proc_id_set(PROC_ID_SESSION, p->p_pid);
576 		refcount_init(&sess->s_count, 1);
577 		sess->s_ttyvp = NULL;
578 		sess->s_ttydp = NULL;
579 		sess->s_ttyp = NULL;
580 		bcopy(p->p_session->s_login, sess->s_login,
581 			    sizeof(sess->s_login));
582 		pgrp->pg_session = sess;
583 		KASSERT(p == curproc,
584 		    ("enterpgrp: mksession and p != curproc"));
585 	} else {
586 		pgrp->pg_session = p->p_session;
587 		sess_hold(pgrp->pg_session);
588 		PGRP_LOCK(pgrp);
589 	}
590 	pgrp->pg_id = pgid;
591 	proc_id_set(PROC_ID_GROUP, p->p_pid);
592 	LIST_INIT(&pgrp->pg_members);
593 
594 	/*
595 	 * As we have an exclusive lock of proctree_lock,
596 	 * this should not deadlock.
597 	 */
598 	LIST_INSERT_HEAD(PGRPHASH(pgid), pgrp, pg_hash);
599 	pgrp->pg_jobc = 0;
600 	SLIST_INIT(&pgrp->pg_sigiolst);
601 	PGRP_UNLOCK(pgrp);
602 
603 	doenterpgrp(p, pgrp);
604 
605 	return (0);
606 }
607 
608 /*
609  * Move p to an existing process group
610  */
611 int
612 enterthispgrp(struct proc *p, struct pgrp *pgrp)
613 {
614 
615 	sx_assert(&proctree_lock, SX_XLOCKED);
616 	PROC_LOCK_ASSERT(p, MA_NOTOWNED);
617 	PGRP_LOCK_ASSERT(pgrp, MA_NOTOWNED);
618 	PGRP_LOCK_ASSERT(p->p_pgrp, MA_NOTOWNED);
619 	SESS_LOCK_ASSERT(p->p_session, MA_NOTOWNED);
620 	KASSERT(pgrp->pg_session == p->p_session,
621 		("%s: pgrp's session %p, p->p_session %p.\n",
622 		__func__,
623 		pgrp->pg_session,
624 		p->p_session));
625 	KASSERT(pgrp != p->p_pgrp,
626 		("%s: p belongs to pgrp.", __func__));
627 
628 	doenterpgrp(p, pgrp);
629 
630 	return (0);
631 }
632 
633 /*
634  * Move p to a process group
635  */
636 static void
637 doenterpgrp(struct proc *p, struct pgrp *pgrp)
638 {
639 	struct pgrp *savepgrp;
640 
641 	sx_assert(&proctree_lock, SX_XLOCKED);
642 	PROC_LOCK_ASSERT(p, MA_NOTOWNED);
643 	PGRP_LOCK_ASSERT(pgrp, MA_NOTOWNED);
644 	PGRP_LOCK_ASSERT(p->p_pgrp, MA_NOTOWNED);
645 	SESS_LOCK_ASSERT(p->p_session, MA_NOTOWNED);
646 
647 	savepgrp = p->p_pgrp;
648 
649 	/*
650 	 * Adjust eligibility of affected pgrps to participate in job control.
651 	 * Increment eligibility counts before decrementing, otherwise we
652 	 * could reach 0 spuriously during the first call.
653 	 */
654 	fixjobc(p, pgrp, 1);
655 	fixjobc(p, p->p_pgrp, 0);
656 
657 	PGRP_LOCK(pgrp);
658 	PGRP_LOCK(savepgrp);
659 	PROC_LOCK(p);
660 	LIST_REMOVE(p, p_pglist);
661 	p->p_pgrp = pgrp;
662 	PROC_UNLOCK(p);
663 	LIST_INSERT_HEAD(&pgrp->pg_members, p, p_pglist);
664 	PGRP_UNLOCK(savepgrp);
665 	PGRP_UNLOCK(pgrp);
666 	if (LIST_EMPTY(&savepgrp->pg_members))
667 		pgdelete(savepgrp);
668 }
669 
670 /*
671  * remove process from process group
672  */
673 int
674 leavepgrp(struct proc *p)
675 {
676 	struct pgrp *savepgrp;
677 
678 	sx_assert(&proctree_lock, SX_XLOCKED);
679 	savepgrp = p->p_pgrp;
680 	PGRP_LOCK(savepgrp);
681 	PROC_LOCK(p);
682 	LIST_REMOVE(p, p_pglist);
683 	p->p_pgrp = NULL;
684 	PROC_UNLOCK(p);
685 	PGRP_UNLOCK(savepgrp);
686 	if (LIST_EMPTY(&savepgrp->pg_members))
687 		pgdelete(savepgrp);
688 	return (0);
689 }
690 
691 /*
692  * delete a process group
693  */
694 static void
695 pgdelete(struct pgrp *pgrp)
696 {
697 	struct session *savesess;
698 	struct tty *tp;
699 
700 	sx_assert(&proctree_lock, SX_XLOCKED);
701 	PGRP_LOCK_ASSERT(pgrp, MA_NOTOWNED);
702 	SESS_LOCK_ASSERT(pgrp->pg_session, MA_NOTOWNED);
703 
704 	/*
705 	 * Reset any sigio structures pointing to us as a result of
706 	 * F_SETOWN with our pgid.
707 	 */
708 	funsetownlst(&pgrp->pg_sigiolst);
709 
710 	PGRP_LOCK(pgrp);
711 	tp = pgrp->pg_session->s_ttyp;
712 	LIST_REMOVE(pgrp, pg_hash);
713 	savesess = pgrp->pg_session;
714 	PGRP_UNLOCK(pgrp);
715 
716 	/* Remove the reference to the pgrp before deallocating it. */
717 	if (tp != NULL) {
718 		tty_lock(tp);
719 		tty_rel_pgrp(tp, pgrp);
720 	}
721 
722 	proc_id_clear(PROC_ID_GROUP, pgrp->pg_id);
723 	mtx_destroy(&pgrp->pg_mtx);
724 	free(pgrp, M_PGRP);
725 	sess_release(savesess);
726 }
727 
728 static void
729 pgadjustjobc(struct pgrp *pgrp, int entering)
730 {
731 
732 	PGRP_LOCK(pgrp);
733 	if (entering) {
734 #ifdef notyet
735 		MPASS(pgrp->pg_jobc >= 0);
736 #endif
737 		pgrp->pg_jobc++;
738 	} else {
739 #ifdef notyet
740 		MPASS(pgrp->pg_jobc > 0);
741 #endif
742 		--pgrp->pg_jobc;
743 		if (pgrp->pg_jobc == 0)
744 			orphanpg(pgrp);
745 	}
746 	PGRP_UNLOCK(pgrp);
747 }
748 
749 /*
750  * Adjust pgrp jobc counters when specified process changes process group.
751  * We count the number of processes in each process group that "qualify"
752  * the group for terminal job control (those with a parent in a different
753  * process group of the same session).  If that count reaches zero, the
754  * process group becomes orphaned.  Check both the specified process'
755  * process group and that of its children.
756  * entering == 0 => p is leaving specified group.
757  * entering == 1 => p is entering specified group.
758  */
759 void
760 fixjobc(struct proc *p, struct pgrp *pgrp, int entering)
761 {
762 	struct pgrp *hispgrp;
763 	struct session *mysession;
764 	struct proc *q;
765 
766 	sx_assert(&proctree_lock, SX_LOCKED);
767 	PROC_LOCK_ASSERT(p, MA_NOTOWNED);
768 	PGRP_LOCK_ASSERT(pgrp, MA_NOTOWNED);
769 	SESS_LOCK_ASSERT(pgrp->pg_session, MA_NOTOWNED);
770 
771 	/*
772 	 * Check p's parent to see whether p qualifies its own process
773 	 * group; if so, adjust count for p's process group.
774 	 */
775 	mysession = pgrp->pg_session;
776 	if ((hispgrp = p->p_pptr->p_pgrp) != pgrp &&
777 	    hispgrp->pg_session == mysession)
778 		pgadjustjobc(pgrp, entering);
779 
780 	/*
781 	 * Check this process' children to see whether they qualify
782 	 * their process groups; if so, adjust counts for children's
783 	 * process groups.
784 	 */
785 	LIST_FOREACH(q, &p->p_children, p_sibling) {
786 		hispgrp = q->p_pgrp;
787 		if (hispgrp == pgrp ||
788 		    hispgrp->pg_session != mysession)
789 			continue;
790 		if (q->p_state == PRS_ZOMBIE)
791 			continue;
792 		pgadjustjobc(hispgrp, entering);
793 	}
794 }
795 
796 void
797 killjobc(void)
798 {
799 	struct session *sp;
800 	struct tty *tp;
801 	struct proc *p;
802 	struct vnode *ttyvp;
803 
804 	p = curproc;
805 	MPASS(p->p_flag & P_WEXIT);
806 	/*
807 	 * Do a quick check to see if there is anything to do with the
808 	 * proctree_lock held. pgrp and LIST_EMPTY checks are for fixjobc().
809 	 */
810 	PROC_LOCK(p);
811 	if (!SESS_LEADER(p) &&
812 	    (p->p_pgrp == p->p_pptr->p_pgrp) &&
813 	    LIST_EMPTY(&p->p_children)) {
814 		PROC_UNLOCK(p);
815 		return;
816 	}
817 	PROC_UNLOCK(p);
818 
819 	sx_xlock(&proctree_lock);
820 	if (SESS_LEADER(p)) {
821 		sp = p->p_session;
822 
823 		/*
824 		 * s_ttyp is not zero'd; we use this to indicate that
825 		 * the session once had a controlling terminal. (for
826 		 * logging and informational purposes)
827 		 */
828 		SESS_LOCK(sp);
829 		ttyvp = sp->s_ttyvp;
830 		tp = sp->s_ttyp;
831 		sp->s_ttyvp = NULL;
832 		sp->s_ttydp = NULL;
833 		sp->s_leader = NULL;
834 		SESS_UNLOCK(sp);
835 
836 		/*
837 		 * Signal foreground pgrp and revoke access to
838 		 * controlling terminal if it has not been revoked
839 		 * already.
840 		 *
841 		 * Because the TTY may have been revoked in the mean
842 		 * time and could already have a new session associated
843 		 * with it, make sure we don't send a SIGHUP to a
844 		 * foreground process group that does not belong to this
845 		 * session.
846 		 */
847 
848 		if (tp != NULL) {
849 			tty_lock(tp);
850 			if (tp->t_session == sp)
851 				tty_signal_pgrp(tp, SIGHUP);
852 			tty_unlock(tp);
853 		}
854 
855 		if (ttyvp != NULL) {
856 			sx_xunlock(&proctree_lock);
857 			if (vn_lock(ttyvp, LK_EXCLUSIVE) == 0) {
858 				VOP_REVOKE(ttyvp, REVOKEALL);
859 				VOP_UNLOCK(ttyvp);
860 			}
861 			vrele(ttyvp);
862 			sx_xlock(&proctree_lock);
863 		}
864 	}
865 	fixjobc(p, p->p_pgrp, 0);
866 	sx_xunlock(&proctree_lock);
867 }
868 
869 /*
870  * A process group has become orphaned;
871  * if there are any stopped processes in the group,
872  * hang-up all process in that group.
873  */
874 static void
875 orphanpg(struct pgrp *pg)
876 {
877 	struct proc *p;
878 
879 	PGRP_LOCK_ASSERT(pg, MA_OWNED);
880 
881 	LIST_FOREACH(p, &pg->pg_members, p_pglist) {
882 		PROC_LOCK(p);
883 		if (P_SHOULDSTOP(p) == P_STOPPED_SIG) {
884 			PROC_UNLOCK(p);
885 			LIST_FOREACH(p, &pg->pg_members, p_pglist) {
886 				PROC_LOCK(p);
887 				kern_psignal(p, SIGHUP);
888 				kern_psignal(p, SIGCONT);
889 				PROC_UNLOCK(p);
890 			}
891 			return;
892 		}
893 		PROC_UNLOCK(p);
894 	}
895 }
896 
897 void
898 sess_hold(struct session *s)
899 {
900 
901 	refcount_acquire(&s->s_count);
902 }
903 
904 void
905 sess_release(struct session *s)
906 {
907 
908 	if (refcount_release(&s->s_count)) {
909 		if (s->s_ttyp != NULL) {
910 			tty_lock(s->s_ttyp);
911 			tty_rel_sess(s->s_ttyp, s);
912 		}
913 		proc_id_clear(PROC_ID_SESSION, s->s_sid);
914 		mtx_destroy(&s->s_mtx);
915 		free(s, M_SESSION);
916 	}
917 }
918 
919 #ifdef DDB
920 
921 DB_SHOW_COMMAND(pgrpdump, pgrpdump)
922 {
923 	struct pgrp *pgrp;
924 	struct proc *p;
925 	int i;
926 
927 	for (i = 0; i <= pgrphash; i++) {
928 		if (!LIST_EMPTY(&pgrphashtbl[i])) {
929 			printf("\tindx %d\n", i);
930 			LIST_FOREACH(pgrp, &pgrphashtbl[i], pg_hash) {
931 				printf(
932 			"\tpgrp %p, pgid %ld, sess %p, sesscnt %d, mem %p\n",
933 				    (void *)pgrp, (long)pgrp->pg_id,
934 				    (void *)pgrp->pg_session,
935 				    pgrp->pg_session->s_count,
936 				    (void *)LIST_FIRST(&pgrp->pg_members));
937 				LIST_FOREACH(p, &pgrp->pg_members, p_pglist) {
938 					printf("\t\tpid %ld addr %p pgrp %p\n",
939 					    (long)p->p_pid, (void *)p,
940 					    (void *)p->p_pgrp);
941 				}
942 			}
943 		}
944 	}
945 }
946 #endif /* DDB */
947 
948 /*
949  * Calculate the kinfo_proc members which contain process-wide
950  * informations.
951  * Must be called with the target process locked.
952  */
953 static void
954 fill_kinfo_aggregate(struct proc *p, struct kinfo_proc *kp)
955 {
956 	struct thread *td;
957 
958 	PROC_LOCK_ASSERT(p, MA_OWNED);
959 
960 	kp->ki_estcpu = 0;
961 	kp->ki_pctcpu = 0;
962 	FOREACH_THREAD_IN_PROC(p, td) {
963 		thread_lock(td);
964 		kp->ki_pctcpu += sched_pctcpu(td);
965 		kp->ki_estcpu += sched_estcpu(td);
966 		thread_unlock(td);
967 	}
968 }
969 
970 /*
971  * Clear kinfo_proc and fill in any information that is common
972  * to all threads in the process.
973  * Must be called with the target process locked.
974  */
975 static void
976 fill_kinfo_proc_only(struct proc *p, struct kinfo_proc *kp)
977 {
978 	struct thread *td0;
979 	struct tty *tp;
980 	struct session *sp;
981 	struct ucred *cred;
982 	struct sigacts *ps;
983 	struct timeval boottime;
984 
985 	PROC_LOCK_ASSERT(p, MA_OWNED);
986 	bzero(kp, sizeof(*kp));
987 
988 	kp->ki_structsize = sizeof(*kp);
989 	kp->ki_paddr = p;
990 	kp->ki_addr =/* p->p_addr; */0; /* XXX */
991 	kp->ki_args = p->p_args;
992 	kp->ki_textvp = p->p_textvp;
993 #ifdef KTRACE
994 	kp->ki_tracep = p->p_tracevp;
995 	kp->ki_traceflag = p->p_traceflag;
996 #endif
997 	kp->ki_fd = p->p_fd;
998 	kp->ki_vmspace = p->p_vmspace;
999 	kp->ki_flag = p->p_flag;
1000 	kp->ki_flag2 = p->p_flag2;
1001 	cred = p->p_ucred;
1002 	if (cred) {
1003 		kp->ki_uid = cred->cr_uid;
1004 		kp->ki_ruid = cred->cr_ruid;
1005 		kp->ki_svuid = cred->cr_svuid;
1006 		kp->ki_cr_flags = 0;
1007 		if (cred->cr_flags & CRED_FLAG_CAPMODE)
1008 			kp->ki_cr_flags |= KI_CRF_CAPABILITY_MODE;
1009 		/* XXX bde doesn't like KI_NGROUPS */
1010 		if (cred->cr_ngroups > KI_NGROUPS) {
1011 			kp->ki_ngroups = KI_NGROUPS;
1012 			kp->ki_cr_flags |= KI_CRF_GRP_OVERFLOW;
1013 		} else
1014 			kp->ki_ngroups = cred->cr_ngroups;
1015 		bcopy(cred->cr_groups, kp->ki_groups,
1016 		    kp->ki_ngroups * sizeof(gid_t));
1017 		kp->ki_rgid = cred->cr_rgid;
1018 		kp->ki_svgid = cred->cr_svgid;
1019 		/* If jailed(cred), emulate the old P_JAILED flag. */
1020 		if (jailed(cred)) {
1021 			kp->ki_flag |= P_JAILED;
1022 			/* If inside the jail, use 0 as a jail ID. */
1023 			if (cred->cr_prison != curthread->td_ucred->cr_prison)
1024 				kp->ki_jid = cred->cr_prison->pr_id;
1025 		}
1026 		strlcpy(kp->ki_loginclass, cred->cr_loginclass->lc_name,
1027 		    sizeof(kp->ki_loginclass));
1028 	}
1029 	ps = p->p_sigacts;
1030 	if (ps) {
1031 		mtx_lock(&ps->ps_mtx);
1032 		kp->ki_sigignore = ps->ps_sigignore;
1033 		kp->ki_sigcatch = ps->ps_sigcatch;
1034 		mtx_unlock(&ps->ps_mtx);
1035 	}
1036 	if (p->p_state != PRS_NEW &&
1037 	    p->p_state != PRS_ZOMBIE &&
1038 	    p->p_vmspace != NULL) {
1039 		struct vmspace *vm = p->p_vmspace;
1040 
1041 		kp->ki_size = vm->vm_map.size;
1042 		kp->ki_rssize = vmspace_resident_count(vm); /*XXX*/
1043 		FOREACH_THREAD_IN_PROC(p, td0) {
1044 			if (!TD_IS_SWAPPED(td0))
1045 				kp->ki_rssize += td0->td_kstack_pages;
1046 		}
1047 		kp->ki_swrss = vm->vm_swrss;
1048 		kp->ki_tsize = vm->vm_tsize;
1049 		kp->ki_dsize = vm->vm_dsize;
1050 		kp->ki_ssize = vm->vm_ssize;
1051 	} else if (p->p_state == PRS_ZOMBIE)
1052 		kp->ki_stat = SZOMB;
1053 	if (kp->ki_flag & P_INMEM)
1054 		kp->ki_sflag = PS_INMEM;
1055 	else
1056 		kp->ki_sflag = 0;
1057 	/* Calculate legacy swtime as seconds since 'swtick'. */
1058 	kp->ki_swtime = (ticks - p->p_swtick) / hz;
1059 	kp->ki_pid = p->p_pid;
1060 	kp->ki_nice = p->p_nice;
1061 	kp->ki_fibnum = p->p_fibnum;
1062 	kp->ki_start = p->p_stats->p_start;
1063 	getboottime(&boottime);
1064 	timevaladd(&kp->ki_start, &boottime);
1065 	PROC_STATLOCK(p);
1066 	rufetch(p, &kp->ki_rusage);
1067 	kp->ki_runtime = cputick2usec(p->p_rux.rux_runtime);
1068 	calcru(p, &kp->ki_rusage.ru_utime, &kp->ki_rusage.ru_stime);
1069 	PROC_STATUNLOCK(p);
1070 	calccru(p, &kp->ki_childutime, &kp->ki_childstime);
1071 	/* Some callers want child times in a single value. */
1072 	kp->ki_childtime = kp->ki_childstime;
1073 	timevaladd(&kp->ki_childtime, &kp->ki_childutime);
1074 
1075 	FOREACH_THREAD_IN_PROC(p, td0)
1076 		kp->ki_cow += td0->td_cow;
1077 
1078 	tp = NULL;
1079 	if (p->p_pgrp) {
1080 		kp->ki_pgid = p->p_pgrp->pg_id;
1081 		kp->ki_jobc = p->p_pgrp->pg_jobc;
1082 		sp = p->p_pgrp->pg_session;
1083 
1084 		if (sp != NULL) {
1085 			kp->ki_sid = sp->s_sid;
1086 			SESS_LOCK(sp);
1087 			strlcpy(kp->ki_login, sp->s_login,
1088 			    sizeof(kp->ki_login));
1089 			if (sp->s_ttyvp)
1090 				kp->ki_kiflag |= KI_CTTY;
1091 			if (SESS_LEADER(p))
1092 				kp->ki_kiflag |= KI_SLEADER;
1093 			/* XXX proctree_lock */
1094 			tp = sp->s_ttyp;
1095 			SESS_UNLOCK(sp);
1096 		}
1097 	}
1098 	if ((p->p_flag & P_CONTROLT) && tp != NULL) {
1099 		kp->ki_tdev = tty_udev(tp);
1100 		kp->ki_tdev_freebsd11 = kp->ki_tdev; /* truncate */
1101 		kp->ki_tpgid = tp->t_pgrp ? tp->t_pgrp->pg_id : NO_PID;
1102 		if (tp->t_session)
1103 			kp->ki_tsid = tp->t_session->s_sid;
1104 	} else {
1105 		kp->ki_tdev = NODEV;
1106 		kp->ki_tdev_freebsd11 = kp->ki_tdev; /* truncate */
1107 	}
1108 	if (p->p_comm[0] != '\0')
1109 		strlcpy(kp->ki_comm, p->p_comm, sizeof(kp->ki_comm));
1110 	if (p->p_sysent && p->p_sysent->sv_name != NULL &&
1111 	    p->p_sysent->sv_name[0] != '\0')
1112 		strlcpy(kp->ki_emul, p->p_sysent->sv_name, sizeof(kp->ki_emul));
1113 	kp->ki_siglist = p->p_siglist;
1114 	kp->ki_xstat = KW_EXITCODE(p->p_xexit, p->p_xsig);
1115 	kp->ki_acflag = p->p_acflag;
1116 	kp->ki_lock = p->p_lock;
1117 	if (p->p_pptr) {
1118 		kp->ki_ppid = p->p_oppid;
1119 		if (p->p_flag & P_TRACED)
1120 			kp->ki_tracer = p->p_pptr->p_pid;
1121 	}
1122 }
1123 
1124 /*
1125  * Fill in information that is thread specific.  Must be called with
1126  * target process locked.  If 'preferthread' is set, overwrite certain
1127  * process-related fields that are maintained for both threads and
1128  * processes.
1129  */
1130 static void
1131 fill_kinfo_thread(struct thread *td, struct kinfo_proc *kp, int preferthread)
1132 {
1133 	struct proc *p;
1134 
1135 	p = td->td_proc;
1136 	kp->ki_tdaddr = td;
1137 	PROC_LOCK_ASSERT(p, MA_OWNED);
1138 
1139 	if (preferthread)
1140 		PROC_STATLOCK(p);
1141 	thread_lock(td);
1142 	if (td->td_wmesg != NULL)
1143 		strlcpy(kp->ki_wmesg, td->td_wmesg, sizeof(kp->ki_wmesg));
1144 	else
1145 		bzero(kp->ki_wmesg, sizeof(kp->ki_wmesg));
1146 	if (strlcpy(kp->ki_tdname, td->td_name, sizeof(kp->ki_tdname)) >=
1147 	    sizeof(kp->ki_tdname)) {
1148 		strlcpy(kp->ki_moretdname,
1149 		    td->td_name + sizeof(kp->ki_tdname) - 1,
1150 		    sizeof(kp->ki_moretdname));
1151 	} else {
1152 		bzero(kp->ki_moretdname, sizeof(kp->ki_moretdname));
1153 	}
1154 	if (TD_ON_LOCK(td)) {
1155 		kp->ki_kiflag |= KI_LOCKBLOCK;
1156 		strlcpy(kp->ki_lockname, td->td_lockname,
1157 		    sizeof(kp->ki_lockname));
1158 	} else {
1159 		kp->ki_kiflag &= ~KI_LOCKBLOCK;
1160 		bzero(kp->ki_lockname, sizeof(kp->ki_lockname));
1161 	}
1162 
1163 	if (p->p_state == PRS_NORMAL) { /* approximate. */
1164 		if (TD_ON_RUNQ(td) ||
1165 		    TD_CAN_RUN(td) ||
1166 		    TD_IS_RUNNING(td)) {
1167 			kp->ki_stat = SRUN;
1168 		} else if (P_SHOULDSTOP(p)) {
1169 			kp->ki_stat = SSTOP;
1170 		} else if (TD_IS_SLEEPING(td)) {
1171 			kp->ki_stat = SSLEEP;
1172 		} else if (TD_ON_LOCK(td)) {
1173 			kp->ki_stat = SLOCK;
1174 		} else {
1175 			kp->ki_stat = SWAIT;
1176 		}
1177 	} else if (p->p_state == PRS_ZOMBIE) {
1178 		kp->ki_stat = SZOMB;
1179 	} else {
1180 		kp->ki_stat = SIDL;
1181 	}
1182 
1183 	/* Things in the thread */
1184 	kp->ki_wchan = td->td_wchan;
1185 	kp->ki_pri.pri_level = td->td_priority;
1186 	kp->ki_pri.pri_native = td->td_base_pri;
1187 
1188 	/*
1189 	 * Note: legacy fields; clamp at the old NOCPU value and/or
1190 	 * the maximum u_char CPU value.
1191 	 */
1192 	if (td->td_lastcpu == NOCPU)
1193 		kp->ki_lastcpu_old = NOCPU_OLD;
1194 	else if (td->td_lastcpu > MAXCPU_OLD)
1195 		kp->ki_lastcpu_old = MAXCPU_OLD;
1196 	else
1197 		kp->ki_lastcpu_old = td->td_lastcpu;
1198 
1199 	if (td->td_oncpu == NOCPU)
1200 		kp->ki_oncpu_old = NOCPU_OLD;
1201 	else if (td->td_oncpu > MAXCPU_OLD)
1202 		kp->ki_oncpu_old = MAXCPU_OLD;
1203 	else
1204 		kp->ki_oncpu_old = td->td_oncpu;
1205 
1206 	kp->ki_lastcpu = td->td_lastcpu;
1207 	kp->ki_oncpu = td->td_oncpu;
1208 	kp->ki_tdflags = td->td_flags;
1209 	kp->ki_tid = td->td_tid;
1210 	kp->ki_numthreads = p->p_numthreads;
1211 	kp->ki_pcb = td->td_pcb;
1212 	kp->ki_kstack = (void *)td->td_kstack;
1213 	kp->ki_slptime = (ticks - td->td_slptick) / hz;
1214 	kp->ki_pri.pri_class = td->td_pri_class;
1215 	kp->ki_pri.pri_user = td->td_user_pri;
1216 
1217 	if (preferthread) {
1218 		rufetchtd(td, &kp->ki_rusage);
1219 		kp->ki_runtime = cputick2usec(td->td_rux.rux_runtime);
1220 		kp->ki_pctcpu = sched_pctcpu(td);
1221 		kp->ki_estcpu = sched_estcpu(td);
1222 		kp->ki_cow = td->td_cow;
1223 	}
1224 
1225 	/* We can't get this anymore but ps etc never used it anyway. */
1226 	kp->ki_rqindex = 0;
1227 
1228 	if (preferthread)
1229 		kp->ki_siglist = td->td_siglist;
1230 	kp->ki_sigmask = td->td_sigmask;
1231 	thread_unlock(td);
1232 	if (preferthread)
1233 		PROC_STATUNLOCK(p);
1234 }
1235 
1236 /*
1237  * Fill in a kinfo_proc structure for the specified process.
1238  * Must be called with the target process locked.
1239  */
1240 void
1241 fill_kinfo_proc(struct proc *p, struct kinfo_proc *kp)
1242 {
1243 
1244 	MPASS(FIRST_THREAD_IN_PROC(p) != NULL);
1245 
1246 	fill_kinfo_proc_only(p, kp);
1247 	fill_kinfo_thread(FIRST_THREAD_IN_PROC(p), kp, 0);
1248 	fill_kinfo_aggregate(p, kp);
1249 }
1250 
1251 struct pstats *
1252 pstats_alloc(void)
1253 {
1254 
1255 	return (malloc(sizeof(struct pstats), M_SUBPROC, M_ZERO|M_WAITOK));
1256 }
1257 
1258 /*
1259  * Copy parts of p_stats; zero the rest of p_stats (statistics).
1260  */
1261 void
1262 pstats_fork(struct pstats *src, struct pstats *dst)
1263 {
1264 
1265 	bzero(&dst->pstat_startzero,
1266 	    __rangeof(struct pstats, pstat_startzero, pstat_endzero));
1267 	bcopy(&src->pstat_startcopy, &dst->pstat_startcopy,
1268 	    __rangeof(struct pstats, pstat_startcopy, pstat_endcopy));
1269 }
1270 
1271 void
1272 pstats_free(struct pstats *ps)
1273 {
1274 
1275 	free(ps, M_SUBPROC);
1276 }
1277 
1278 #ifdef COMPAT_FREEBSD32
1279 
1280 /*
1281  * This function is typically used to copy out the kernel address, so
1282  * it can be replaced by assignment of zero.
1283  */
1284 static inline uint32_t
1285 ptr32_trim(const void *ptr)
1286 {
1287 	uintptr_t uptr;
1288 
1289 	uptr = (uintptr_t)ptr;
1290 	return ((uptr > UINT_MAX) ? 0 : uptr);
1291 }
1292 
1293 #define PTRTRIM_CP(src,dst,fld) \
1294 	do { (dst).fld = ptr32_trim((src).fld); } while (0)
1295 
1296 static void
1297 freebsd32_kinfo_proc_out(const struct kinfo_proc *ki, struct kinfo_proc32 *ki32)
1298 {
1299 	int i;
1300 
1301 	bzero(ki32, sizeof(struct kinfo_proc32));
1302 	ki32->ki_structsize = sizeof(struct kinfo_proc32);
1303 	CP(*ki, *ki32, ki_layout);
1304 	PTRTRIM_CP(*ki, *ki32, ki_args);
1305 	PTRTRIM_CP(*ki, *ki32, ki_paddr);
1306 	PTRTRIM_CP(*ki, *ki32, ki_addr);
1307 	PTRTRIM_CP(*ki, *ki32, ki_tracep);
1308 	PTRTRIM_CP(*ki, *ki32, ki_textvp);
1309 	PTRTRIM_CP(*ki, *ki32, ki_fd);
1310 	PTRTRIM_CP(*ki, *ki32, ki_vmspace);
1311 	PTRTRIM_CP(*ki, *ki32, ki_wchan);
1312 	CP(*ki, *ki32, ki_pid);
1313 	CP(*ki, *ki32, ki_ppid);
1314 	CP(*ki, *ki32, ki_pgid);
1315 	CP(*ki, *ki32, ki_tpgid);
1316 	CP(*ki, *ki32, ki_sid);
1317 	CP(*ki, *ki32, ki_tsid);
1318 	CP(*ki, *ki32, ki_jobc);
1319 	CP(*ki, *ki32, ki_tdev);
1320 	CP(*ki, *ki32, ki_tdev_freebsd11);
1321 	CP(*ki, *ki32, ki_siglist);
1322 	CP(*ki, *ki32, ki_sigmask);
1323 	CP(*ki, *ki32, ki_sigignore);
1324 	CP(*ki, *ki32, ki_sigcatch);
1325 	CP(*ki, *ki32, ki_uid);
1326 	CP(*ki, *ki32, ki_ruid);
1327 	CP(*ki, *ki32, ki_svuid);
1328 	CP(*ki, *ki32, ki_rgid);
1329 	CP(*ki, *ki32, ki_svgid);
1330 	CP(*ki, *ki32, ki_ngroups);
1331 	for (i = 0; i < KI_NGROUPS; i++)
1332 		CP(*ki, *ki32, ki_groups[i]);
1333 	CP(*ki, *ki32, ki_size);
1334 	CP(*ki, *ki32, ki_rssize);
1335 	CP(*ki, *ki32, ki_swrss);
1336 	CP(*ki, *ki32, ki_tsize);
1337 	CP(*ki, *ki32, ki_dsize);
1338 	CP(*ki, *ki32, ki_ssize);
1339 	CP(*ki, *ki32, ki_xstat);
1340 	CP(*ki, *ki32, ki_acflag);
1341 	CP(*ki, *ki32, ki_pctcpu);
1342 	CP(*ki, *ki32, ki_estcpu);
1343 	CP(*ki, *ki32, ki_slptime);
1344 	CP(*ki, *ki32, ki_swtime);
1345 	CP(*ki, *ki32, ki_cow);
1346 	CP(*ki, *ki32, ki_runtime);
1347 	TV_CP(*ki, *ki32, ki_start);
1348 	TV_CP(*ki, *ki32, ki_childtime);
1349 	CP(*ki, *ki32, ki_flag);
1350 	CP(*ki, *ki32, ki_kiflag);
1351 	CP(*ki, *ki32, ki_traceflag);
1352 	CP(*ki, *ki32, ki_stat);
1353 	CP(*ki, *ki32, ki_nice);
1354 	CP(*ki, *ki32, ki_lock);
1355 	CP(*ki, *ki32, ki_rqindex);
1356 	CP(*ki, *ki32, ki_oncpu);
1357 	CP(*ki, *ki32, ki_lastcpu);
1358 
1359 	/* XXX TODO: wrap cpu value as appropriate */
1360 	CP(*ki, *ki32, ki_oncpu_old);
1361 	CP(*ki, *ki32, ki_lastcpu_old);
1362 
1363 	bcopy(ki->ki_tdname, ki32->ki_tdname, TDNAMLEN + 1);
1364 	bcopy(ki->ki_wmesg, ki32->ki_wmesg, WMESGLEN + 1);
1365 	bcopy(ki->ki_login, ki32->ki_login, LOGNAMELEN + 1);
1366 	bcopy(ki->ki_lockname, ki32->ki_lockname, LOCKNAMELEN + 1);
1367 	bcopy(ki->ki_comm, ki32->ki_comm, COMMLEN + 1);
1368 	bcopy(ki->ki_emul, ki32->ki_emul, KI_EMULNAMELEN + 1);
1369 	bcopy(ki->ki_loginclass, ki32->ki_loginclass, LOGINCLASSLEN + 1);
1370 	bcopy(ki->ki_moretdname, ki32->ki_moretdname, MAXCOMLEN - TDNAMLEN + 1);
1371 	CP(*ki, *ki32, ki_tracer);
1372 	CP(*ki, *ki32, ki_flag2);
1373 	CP(*ki, *ki32, ki_fibnum);
1374 	CP(*ki, *ki32, ki_cr_flags);
1375 	CP(*ki, *ki32, ki_jid);
1376 	CP(*ki, *ki32, ki_numthreads);
1377 	CP(*ki, *ki32, ki_tid);
1378 	CP(*ki, *ki32, ki_pri);
1379 	freebsd32_rusage_out(&ki->ki_rusage, &ki32->ki_rusage);
1380 	freebsd32_rusage_out(&ki->ki_rusage_ch, &ki32->ki_rusage_ch);
1381 	PTRTRIM_CP(*ki, *ki32, ki_pcb);
1382 	PTRTRIM_CP(*ki, *ki32, ki_kstack);
1383 	PTRTRIM_CP(*ki, *ki32, ki_udata);
1384 	PTRTRIM_CP(*ki, *ki32, ki_tdaddr);
1385 	CP(*ki, *ki32, ki_sflag);
1386 	CP(*ki, *ki32, ki_tdflags);
1387 }
1388 #endif
1389 
1390 static ssize_t
1391 kern_proc_out_size(struct proc *p, int flags)
1392 {
1393 	ssize_t size = 0;
1394 
1395 	PROC_LOCK_ASSERT(p, MA_OWNED);
1396 
1397 	if ((flags & KERN_PROC_NOTHREADS) != 0) {
1398 #ifdef COMPAT_FREEBSD32
1399 		if ((flags & KERN_PROC_MASK32) != 0) {
1400 			size += sizeof(struct kinfo_proc32);
1401 		} else
1402 #endif
1403 			size += sizeof(struct kinfo_proc);
1404 	} else {
1405 #ifdef COMPAT_FREEBSD32
1406 		if ((flags & KERN_PROC_MASK32) != 0)
1407 			size += sizeof(struct kinfo_proc32) * p->p_numthreads;
1408 		else
1409 #endif
1410 			size += sizeof(struct kinfo_proc) * p->p_numthreads;
1411 	}
1412 	PROC_UNLOCK(p);
1413 	return (size);
1414 }
1415 
1416 int
1417 kern_proc_out(struct proc *p, struct sbuf *sb, int flags)
1418 {
1419 	struct thread *td;
1420 	struct kinfo_proc ki;
1421 #ifdef COMPAT_FREEBSD32
1422 	struct kinfo_proc32 ki32;
1423 #endif
1424 	int error;
1425 
1426 	PROC_LOCK_ASSERT(p, MA_OWNED);
1427 	MPASS(FIRST_THREAD_IN_PROC(p) != NULL);
1428 
1429 	error = 0;
1430 	fill_kinfo_proc(p, &ki);
1431 	if ((flags & KERN_PROC_NOTHREADS) != 0) {
1432 #ifdef COMPAT_FREEBSD32
1433 		if ((flags & KERN_PROC_MASK32) != 0) {
1434 			freebsd32_kinfo_proc_out(&ki, &ki32);
1435 			if (sbuf_bcat(sb, &ki32, sizeof(ki32)) != 0)
1436 				error = ENOMEM;
1437 		} else
1438 #endif
1439 			if (sbuf_bcat(sb, &ki, sizeof(ki)) != 0)
1440 				error = ENOMEM;
1441 	} else {
1442 		FOREACH_THREAD_IN_PROC(p, td) {
1443 			fill_kinfo_thread(td, &ki, 1);
1444 #ifdef COMPAT_FREEBSD32
1445 			if ((flags & KERN_PROC_MASK32) != 0) {
1446 				freebsd32_kinfo_proc_out(&ki, &ki32);
1447 				if (sbuf_bcat(sb, &ki32, sizeof(ki32)) != 0)
1448 					error = ENOMEM;
1449 			} else
1450 #endif
1451 				if (sbuf_bcat(sb, &ki, sizeof(ki)) != 0)
1452 					error = ENOMEM;
1453 			if (error != 0)
1454 				break;
1455 		}
1456 	}
1457 	PROC_UNLOCK(p);
1458 	return (error);
1459 }
1460 
1461 static int
1462 sysctl_out_proc(struct proc *p, struct sysctl_req *req, int flags)
1463 {
1464 	struct sbuf sb;
1465 	struct kinfo_proc ki;
1466 	int error, error2;
1467 
1468 	if (req->oldptr == NULL)
1469 		return (SYSCTL_OUT(req, 0, kern_proc_out_size(p, flags)));
1470 
1471 	sbuf_new_for_sysctl(&sb, (char *)&ki, sizeof(ki), req);
1472 	sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
1473 	error = kern_proc_out(p, &sb, flags);
1474 	error2 = sbuf_finish(&sb);
1475 	sbuf_delete(&sb);
1476 	if (error != 0)
1477 		return (error);
1478 	else if (error2 != 0)
1479 		return (error2);
1480 	return (0);
1481 }
1482 
1483 int
1484 proc_iterate(int (*cb)(struct proc *, void *), void *cbarg)
1485 {
1486 	struct proc *p;
1487 	int error, i, j;
1488 
1489 	for (i = 0; i < pidhashlock + 1; i++) {
1490 		sx_slock(&pidhashtbl_lock[i]);
1491 		for (j = i; j <= pidhash; j += pidhashlock + 1) {
1492 			LIST_FOREACH(p, &pidhashtbl[j], p_hash) {
1493 				if (p->p_state == PRS_NEW)
1494 					continue;
1495 				error = cb(p, cbarg);
1496 				PROC_LOCK_ASSERT(p, MA_NOTOWNED);
1497 				if (error != 0) {
1498 					sx_sunlock(&pidhashtbl_lock[i]);
1499 					return (error);
1500 				}
1501 			}
1502 		}
1503 		sx_sunlock(&pidhashtbl_lock[i]);
1504 	}
1505 	return (0);
1506 }
1507 
1508 struct kern_proc_out_args {
1509 	struct sysctl_req *req;
1510 	int flags;
1511 	int oid_number;
1512 	int *name;
1513 };
1514 
1515 static int
1516 sysctl_kern_proc_iterate(struct proc *p, void *origarg)
1517 {
1518 	struct kern_proc_out_args *arg = origarg;
1519 	int *name = arg->name;
1520 	int oid_number = arg->oid_number;
1521 	int flags = arg->flags;
1522 	struct sysctl_req *req = arg->req;
1523 	int error = 0;
1524 
1525 	PROC_LOCK(p);
1526 
1527 	KASSERT(p->p_ucred != NULL,
1528 	    ("process credential is NULL for non-NEW proc"));
1529 	/*
1530 	 * Show a user only appropriate processes.
1531 	 */
1532 	if (p_cansee(curthread, p))
1533 		goto skip;
1534 	/*
1535 	 * TODO - make more efficient (see notes below).
1536 	 * do by session.
1537 	 */
1538 	switch (oid_number) {
1539 
1540 	case KERN_PROC_GID:
1541 		if (p->p_ucred->cr_gid != (gid_t)name[0])
1542 			goto skip;
1543 		break;
1544 
1545 	case KERN_PROC_PGRP:
1546 		/* could do this by traversing pgrp */
1547 		if (p->p_pgrp == NULL ||
1548 		    p->p_pgrp->pg_id != (pid_t)name[0])
1549 			goto skip;
1550 		break;
1551 
1552 	case KERN_PROC_RGID:
1553 		if (p->p_ucred->cr_rgid != (gid_t)name[0])
1554 			goto skip;
1555 		break;
1556 
1557 	case KERN_PROC_SESSION:
1558 		if (p->p_session == NULL ||
1559 		    p->p_session->s_sid != (pid_t)name[0])
1560 			goto skip;
1561 		break;
1562 
1563 	case KERN_PROC_TTY:
1564 		if ((p->p_flag & P_CONTROLT) == 0 ||
1565 		    p->p_session == NULL)
1566 			goto skip;
1567 		/* XXX proctree_lock */
1568 		SESS_LOCK(p->p_session);
1569 		if (p->p_session->s_ttyp == NULL ||
1570 		    tty_udev(p->p_session->s_ttyp) !=
1571 		    (dev_t)name[0]) {
1572 			SESS_UNLOCK(p->p_session);
1573 			goto skip;
1574 		}
1575 		SESS_UNLOCK(p->p_session);
1576 		break;
1577 
1578 	case KERN_PROC_UID:
1579 		if (p->p_ucred->cr_uid != (uid_t)name[0])
1580 			goto skip;
1581 		break;
1582 
1583 	case KERN_PROC_RUID:
1584 		if (p->p_ucred->cr_ruid != (uid_t)name[0])
1585 			goto skip;
1586 		break;
1587 
1588 	case KERN_PROC_PROC:
1589 		break;
1590 
1591 	default:
1592 		break;
1593 
1594 	}
1595 	error = sysctl_out_proc(p, req, flags);
1596 	PROC_LOCK_ASSERT(p, MA_NOTOWNED);
1597 	return (error);
1598 skip:
1599 	PROC_UNLOCK(p);
1600 	return (0);
1601 }
1602 
1603 static int
1604 sysctl_kern_proc(SYSCTL_HANDLER_ARGS)
1605 {
1606 	struct kern_proc_out_args iterarg;
1607 	int *name = (int *)arg1;
1608 	u_int namelen = arg2;
1609 	struct proc *p;
1610 	int flags, oid_number;
1611 	int error = 0;
1612 
1613 	oid_number = oidp->oid_number;
1614 	if (oid_number != KERN_PROC_ALL &&
1615 	    (oid_number & KERN_PROC_INC_THREAD) == 0)
1616 		flags = KERN_PROC_NOTHREADS;
1617 	else {
1618 		flags = 0;
1619 		oid_number &= ~KERN_PROC_INC_THREAD;
1620 	}
1621 #ifdef COMPAT_FREEBSD32
1622 	if (req->flags & SCTL_MASK32)
1623 		flags |= KERN_PROC_MASK32;
1624 #endif
1625 	if (oid_number == KERN_PROC_PID) {
1626 		if (namelen != 1)
1627 			return (EINVAL);
1628 		error = sysctl_wire_old_buffer(req, 0);
1629 		if (error)
1630 			return (error);
1631 		error = pget((pid_t)name[0], PGET_CANSEE, &p);
1632 		if (error == 0)
1633 			error = sysctl_out_proc(p, req, flags);
1634 		return (error);
1635 	}
1636 
1637 	switch (oid_number) {
1638 	case KERN_PROC_ALL:
1639 		if (namelen != 0)
1640 			return (EINVAL);
1641 		break;
1642 	case KERN_PROC_PROC:
1643 		if (namelen != 0 && namelen != 1)
1644 			return (EINVAL);
1645 		break;
1646 	default:
1647 		if (namelen != 1)
1648 			return (EINVAL);
1649 		break;
1650 	}
1651 
1652 	if (req->oldptr == NULL) {
1653 		/* overestimate by 5 procs */
1654 		error = SYSCTL_OUT(req, 0, sizeof (struct kinfo_proc) * 5);
1655 		if (error)
1656 			return (error);
1657 	} else {
1658 		error = sysctl_wire_old_buffer(req, 0);
1659 		if (error != 0)
1660 			return (error);
1661 	}
1662 	iterarg.flags = flags;
1663 	iterarg.oid_number = oid_number;
1664 	iterarg.req = req;
1665 	iterarg.name = name;
1666 	error = proc_iterate(sysctl_kern_proc_iterate, &iterarg);
1667 	return (error);
1668 }
1669 
1670 struct pargs *
1671 pargs_alloc(int len)
1672 {
1673 	struct pargs *pa;
1674 
1675 	pa = malloc(sizeof(struct pargs) + len, M_PARGS,
1676 		M_WAITOK);
1677 	refcount_init(&pa->ar_ref, 1);
1678 	pa->ar_length = len;
1679 	return (pa);
1680 }
1681 
1682 static void
1683 pargs_free(struct pargs *pa)
1684 {
1685 
1686 	free(pa, M_PARGS);
1687 }
1688 
1689 void
1690 pargs_hold(struct pargs *pa)
1691 {
1692 
1693 	if (pa == NULL)
1694 		return;
1695 	refcount_acquire(&pa->ar_ref);
1696 }
1697 
1698 void
1699 pargs_drop(struct pargs *pa)
1700 {
1701 
1702 	if (pa == NULL)
1703 		return;
1704 	if (refcount_release(&pa->ar_ref))
1705 		pargs_free(pa);
1706 }
1707 
1708 static int
1709 proc_read_string(struct thread *td, struct proc *p, const char *sptr, char *buf,
1710     size_t len)
1711 {
1712 	ssize_t n;
1713 
1714 	/*
1715 	 * This may return a short read if the string is shorter than the chunk
1716 	 * and is aligned at the end of the page, and the following page is not
1717 	 * mapped.
1718 	 */
1719 	n = proc_readmem(td, p, (vm_offset_t)sptr, buf, len);
1720 	if (n <= 0)
1721 		return (ENOMEM);
1722 	return (0);
1723 }
1724 
1725 #define PROC_AUXV_MAX	256	/* Safety limit on auxv size. */
1726 
1727 enum proc_vector_type {
1728 	PROC_ARG,
1729 	PROC_ENV,
1730 	PROC_AUX,
1731 };
1732 
1733 #ifdef COMPAT_FREEBSD32
1734 static int
1735 get_proc_vector32(struct thread *td, struct proc *p, char ***proc_vectorp,
1736     size_t *vsizep, enum proc_vector_type type)
1737 {
1738 	struct freebsd32_ps_strings pss;
1739 	Elf32_Auxinfo aux;
1740 	vm_offset_t vptr, ptr;
1741 	uint32_t *proc_vector32;
1742 	char **proc_vector;
1743 	size_t vsize, size;
1744 	int i, error;
1745 
1746 	error = 0;
1747 	if (proc_readmem(td, p, (vm_offset_t)p->p_sysent->sv_psstrings, &pss,
1748 	    sizeof(pss)) != sizeof(pss))
1749 		return (ENOMEM);
1750 	switch (type) {
1751 	case PROC_ARG:
1752 		vptr = (vm_offset_t)PTRIN(pss.ps_argvstr);
1753 		vsize = pss.ps_nargvstr;
1754 		if (vsize > ARG_MAX)
1755 			return (ENOEXEC);
1756 		size = vsize * sizeof(int32_t);
1757 		break;
1758 	case PROC_ENV:
1759 		vptr = (vm_offset_t)PTRIN(pss.ps_envstr);
1760 		vsize = pss.ps_nenvstr;
1761 		if (vsize > ARG_MAX)
1762 			return (ENOEXEC);
1763 		size = vsize * sizeof(int32_t);
1764 		break;
1765 	case PROC_AUX:
1766 		vptr = (vm_offset_t)PTRIN(pss.ps_envstr) +
1767 		    (pss.ps_nenvstr + 1) * sizeof(int32_t);
1768 		if (vptr % 4 != 0)
1769 			return (ENOEXEC);
1770 		for (ptr = vptr, i = 0; i < PROC_AUXV_MAX; i++) {
1771 			if (proc_readmem(td, p, ptr, &aux, sizeof(aux)) !=
1772 			    sizeof(aux))
1773 				return (ENOMEM);
1774 			if (aux.a_type == AT_NULL)
1775 				break;
1776 			ptr += sizeof(aux);
1777 		}
1778 		if (aux.a_type != AT_NULL)
1779 			return (ENOEXEC);
1780 		vsize = i + 1;
1781 		size = vsize * sizeof(aux);
1782 		break;
1783 	default:
1784 		KASSERT(0, ("Wrong proc vector type: %d", type));
1785 		return (EINVAL);
1786 	}
1787 	proc_vector32 = malloc(size, M_TEMP, M_WAITOK);
1788 	if (proc_readmem(td, p, vptr, proc_vector32, size) != size) {
1789 		error = ENOMEM;
1790 		goto done;
1791 	}
1792 	if (type == PROC_AUX) {
1793 		*proc_vectorp = (char **)proc_vector32;
1794 		*vsizep = vsize;
1795 		return (0);
1796 	}
1797 	proc_vector = malloc(vsize * sizeof(char *), M_TEMP, M_WAITOK);
1798 	for (i = 0; i < (int)vsize; i++)
1799 		proc_vector[i] = PTRIN(proc_vector32[i]);
1800 	*proc_vectorp = proc_vector;
1801 	*vsizep = vsize;
1802 done:
1803 	free(proc_vector32, M_TEMP);
1804 	return (error);
1805 }
1806 #endif
1807 
1808 static int
1809 get_proc_vector(struct thread *td, struct proc *p, char ***proc_vectorp,
1810     size_t *vsizep, enum proc_vector_type type)
1811 {
1812 	struct ps_strings pss;
1813 	Elf_Auxinfo aux;
1814 	vm_offset_t vptr, ptr;
1815 	char **proc_vector;
1816 	size_t vsize, size;
1817 	int i;
1818 
1819 #ifdef COMPAT_FREEBSD32
1820 	if (SV_PROC_FLAG(p, SV_ILP32) != 0)
1821 		return (get_proc_vector32(td, p, proc_vectorp, vsizep, type));
1822 #endif
1823 	if (proc_readmem(td, p, (vm_offset_t)p->p_sysent->sv_psstrings, &pss,
1824 	    sizeof(pss)) != sizeof(pss))
1825 		return (ENOMEM);
1826 	switch (type) {
1827 	case PROC_ARG:
1828 		vptr = (vm_offset_t)pss.ps_argvstr;
1829 		vsize = pss.ps_nargvstr;
1830 		if (vsize > ARG_MAX)
1831 			return (ENOEXEC);
1832 		size = vsize * sizeof(char *);
1833 		break;
1834 	case PROC_ENV:
1835 		vptr = (vm_offset_t)pss.ps_envstr;
1836 		vsize = pss.ps_nenvstr;
1837 		if (vsize > ARG_MAX)
1838 			return (ENOEXEC);
1839 		size = vsize * sizeof(char *);
1840 		break;
1841 	case PROC_AUX:
1842 		/*
1843 		 * The aux array is just above env array on the stack. Check
1844 		 * that the address is naturally aligned.
1845 		 */
1846 		vptr = (vm_offset_t)pss.ps_envstr + (pss.ps_nenvstr + 1)
1847 		    * sizeof(char *);
1848 #if __ELF_WORD_SIZE == 64
1849 		if (vptr % sizeof(uint64_t) != 0)
1850 #else
1851 		if (vptr % sizeof(uint32_t) != 0)
1852 #endif
1853 			return (ENOEXEC);
1854 		/*
1855 		 * We count the array size reading the aux vectors from the
1856 		 * stack until AT_NULL vector is returned.  So (to keep the code
1857 		 * simple) we read the process stack twice: the first time here
1858 		 * to find the size and the second time when copying the vectors
1859 		 * to the allocated proc_vector.
1860 		 */
1861 		for (ptr = vptr, i = 0; i < PROC_AUXV_MAX; i++) {
1862 			if (proc_readmem(td, p, ptr, &aux, sizeof(aux)) !=
1863 			    sizeof(aux))
1864 				return (ENOMEM);
1865 			if (aux.a_type == AT_NULL)
1866 				break;
1867 			ptr += sizeof(aux);
1868 		}
1869 		/*
1870 		 * If the PROC_AUXV_MAX entries are iterated over, and we have
1871 		 * not reached AT_NULL, it is most likely we are reading wrong
1872 		 * data: either the process doesn't have auxv array or data has
1873 		 * been modified. Return the error in this case.
1874 		 */
1875 		if (aux.a_type != AT_NULL)
1876 			return (ENOEXEC);
1877 		vsize = i + 1;
1878 		size = vsize * sizeof(aux);
1879 		break;
1880 	default:
1881 		KASSERT(0, ("Wrong proc vector type: %d", type));
1882 		return (EINVAL); /* In case we are built without INVARIANTS. */
1883 	}
1884 	proc_vector = malloc(size, M_TEMP, M_WAITOK);
1885 	if (proc_readmem(td, p, vptr, proc_vector, size) != size) {
1886 		free(proc_vector, M_TEMP);
1887 		return (ENOMEM);
1888 	}
1889 	*proc_vectorp = proc_vector;
1890 	*vsizep = vsize;
1891 
1892 	return (0);
1893 }
1894 
1895 #define GET_PS_STRINGS_CHUNK_SZ	256	/* Chunk size (bytes) for ps_strings operations. */
1896 
1897 static int
1898 get_ps_strings(struct thread *td, struct proc *p, struct sbuf *sb,
1899     enum proc_vector_type type)
1900 {
1901 	size_t done, len, nchr, vsize;
1902 	int error, i;
1903 	char **proc_vector, *sptr;
1904 	char pss_string[GET_PS_STRINGS_CHUNK_SZ];
1905 
1906 	PROC_ASSERT_HELD(p);
1907 
1908 	/*
1909 	 * We are not going to read more than 2 * (PATH_MAX + ARG_MAX) bytes.
1910 	 */
1911 	nchr = 2 * (PATH_MAX + ARG_MAX);
1912 
1913 	error = get_proc_vector(td, p, &proc_vector, &vsize, type);
1914 	if (error != 0)
1915 		return (error);
1916 	for (done = 0, i = 0; i < (int)vsize && done < nchr; i++) {
1917 		/*
1918 		 * The program may have scribbled into its argv array, e.g. to
1919 		 * remove some arguments.  If that has happened, break out
1920 		 * before trying to read from NULL.
1921 		 */
1922 		if (proc_vector[i] == NULL)
1923 			break;
1924 		for (sptr = proc_vector[i]; ; sptr += GET_PS_STRINGS_CHUNK_SZ) {
1925 			error = proc_read_string(td, p, sptr, pss_string,
1926 			    sizeof(pss_string));
1927 			if (error != 0)
1928 				goto done;
1929 			len = strnlen(pss_string, GET_PS_STRINGS_CHUNK_SZ);
1930 			if (done + len >= nchr)
1931 				len = nchr - done - 1;
1932 			sbuf_bcat(sb, pss_string, len);
1933 			if (len != GET_PS_STRINGS_CHUNK_SZ)
1934 				break;
1935 			done += GET_PS_STRINGS_CHUNK_SZ;
1936 		}
1937 		sbuf_bcat(sb, "", 1);
1938 		done += len + 1;
1939 	}
1940 done:
1941 	free(proc_vector, M_TEMP);
1942 	return (error);
1943 }
1944 
1945 int
1946 proc_getargv(struct thread *td, struct proc *p, struct sbuf *sb)
1947 {
1948 
1949 	return (get_ps_strings(curthread, p, sb, PROC_ARG));
1950 }
1951 
1952 int
1953 proc_getenvv(struct thread *td, struct proc *p, struct sbuf *sb)
1954 {
1955 
1956 	return (get_ps_strings(curthread, p, sb, PROC_ENV));
1957 }
1958 
1959 int
1960 proc_getauxv(struct thread *td, struct proc *p, struct sbuf *sb)
1961 {
1962 	size_t vsize, size;
1963 	char **auxv;
1964 	int error;
1965 
1966 	error = get_proc_vector(td, p, &auxv, &vsize, PROC_AUX);
1967 	if (error == 0) {
1968 #ifdef COMPAT_FREEBSD32
1969 		if (SV_PROC_FLAG(p, SV_ILP32) != 0)
1970 			size = vsize * sizeof(Elf32_Auxinfo);
1971 		else
1972 #endif
1973 			size = vsize * sizeof(Elf_Auxinfo);
1974 		if (sbuf_bcat(sb, auxv, size) != 0)
1975 			error = ENOMEM;
1976 		free(auxv, M_TEMP);
1977 	}
1978 	return (error);
1979 }
1980 
1981 /*
1982  * This sysctl allows a process to retrieve the argument list or process
1983  * title for another process without groping around in the address space
1984  * of the other process.  It also allow a process to set its own "process
1985  * title to a string of its own choice.
1986  */
1987 static int
1988 sysctl_kern_proc_args(SYSCTL_HANDLER_ARGS)
1989 {
1990 	int *name = (int *)arg1;
1991 	u_int namelen = arg2;
1992 	struct pargs *newpa, *pa;
1993 	struct proc *p;
1994 	struct sbuf sb;
1995 	int flags, error = 0, error2;
1996 	pid_t pid;
1997 
1998 	if (namelen != 1)
1999 		return (EINVAL);
2000 
2001 	pid = (pid_t)name[0];
2002 	/*
2003 	 * If the query is for this process and it is single-threaded, there
2004 	 * is nobody to modify pargs, thus we can just read.
2005 	 */
2006 	p = curproc;
2007 	if (pid == p->p_pid && p->p_numthreads == 1 && req->newptr == NULL &&
2008 	    (pa = p->p_args) != NULL)
2009 		return (SYSCTL_OUT(req, pa->ar_args, pa->ar_length));
2010 
2011 	flags = PGET_CANSEE;
2012 	if (req->newptr != NULL)
2013 		flags |= PGET_ISCURRENT;
2014 	error = pget(pid, flags, &p);
2015 	if (error)
2016 		return (error);
2017 
2018 	pa = p->p_args;
2019 	if (pa != NULL) {
2020 		pargs_hold(pa);
2021 		PROC_UNLOCK(p);
2022 		error = SYSCTL_OUT(req, pa->ar_args, pa->ar_length);
2023 		pargs_drop(pa);
2024 	} else if ((p->p_flag & (P_WEXIT | P_SYSTEM)) == 0) {
2025 		_PHOLD(p);
2026 		PROC_UNLOCK(p);
2027 		sbuf_new_for_sysctl(&sb, NULL, GET_PS_STRINGS_CHUNK_SZ, req);
2028 		sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
2029 		error = proc_getargv(curthread, p, &sb);
2030 		error2 = sbuf_finish(&sb);
2031 		PRELE(p);
2032 		sbuf_delete(&sb);
2033 		if (error == 0 && error2 != 0)
2034 			error = error2;
2035 	} else {
2036 		PROC_UNLOCK(p);
2037 	}
2038 	if (error != 0 || req->newptr == NULL)
2039 		return (error);
2040 
2041 	if (req->newlen > ps_arg_cache_limit - sizeof(struct pargs))
2042 		return (ENOMEM);
2043 
2044 	if (req->newlen == 0) {
2045 		/*
2046 		 * Clear the argument pointer, so that we'll fetch arguments
2047 		 * with proc_getargv() until further notice.
2048 		 */
2049 		newpa = NULL;
2050 	} else {
2051 		newpa = pargs_alloc(req->newlen);
2052 		error = SYSCTL_IN(req, newpa->ar_args, req->newlen);
2053 		if (error != 0) {
2054 			pargs_free(newpa);
2055 			return (error);
2056 		}
2057 	}
2058 	PROC_LOCK(p);
2059 	pa = p->p_args;
2060 	p->p_args = newpa;
2061 	PROC_UNLOCK(p);
2062 	pargs_drop(pa);
2063 	return (0);
2064 }
2065 
2066 /*
2067  * This sysctl allows a process to retrieve environment of another process.
2068  */
2069 static int
2070 sysctl_kern_proc_env(SYSCTL_HANDLER_ARGS)
2071 {
2072 	int *name = (int *)arg1;
2073 	u_int namelen = arg2;
2074 	struct proc *p;
2075 	struct sbuf sb;
2076 	int error, error2;
2077 
2078 	if (namelen != 1)
2079 		return (EINVAL);
2080 
2081 	error = pget((pid_t)name[0], PGET_WANTREAD, &p);
2082 	if (error != 0)
2083 		return (error);
2084 	if ((p->p_flag & P_SYSTEM) != 0) {
2085 		PRELE(p);
2086 		return (0);
2087 	}
2088 
2089 	sbuf_new_for_sysctl(&sb, NULL, GET_PS_STRINGS_CHUNK_SZ, req);
2090 	sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
2091 	error = proc_getenvv(curthread, p, &sb);
2092 	error2 = sbuf_finish(&sb);
2093 	PRELE(p);
2094 	sbuf_delete(&sb);
2095 	return (error != 0 ? error : error2);
2096 }
2097 
2098 /*
2099  * This sysctl allows a process to retrieve ELF auxiliary vector of
2100  * another process.
2101  */
2102 static int
2103 sysctl_kern_proc_auxv(SYSCTL_HANDLER_ARGS)
2104 {
2105 	int *name = (int *)arg1;
2106 	u_int namelen = arg2;
2107 	struct proc *p;
2108 	struct sbuf sb;
2109 	int error, error2;
2110 
2111 	if (namelen != 1)
2112 		return (EINVAL);
2113 
2114 	error = pget((pid_t)name[0], PGET_WANTREAD, &p);
2115 	if (error != 0)
2116 		return (error);
2117 	if ((p->p_flag & P_SYSTEM) != 0) {
2118 		PRELE(p);
2119 		return (0);
2120 	}
2121 	sbuf_new_for_sysctl(&sb, NULL, GET_PS_STRINGS_CHUNK_SZ, req);
2122 	sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
2123 	error = proc_getauxv(curthread, p, &sb);
2124 	error2 = sbuf_finish(&sb);
2125 	PRELE(p);
2126 	sbuf_delete(&sb);
2127 	return (error != 0 ? error : error2);
2128 }
2129 
2130 /*
2131  * This sysctl allows a process to retrieve the path of the executable for
2132  * itself or another process.
2133  */
2134 static int
2135 sysctl_kern_proc_pathname(SYSCTL_HANDLER_ARGS)
2136 {
2137 	pid_t *pidp = (pid_t *)arg1;
2138 	unsigned int arglen = arg2;
2139 	struct proc *p;
2140 	struct vnode *vp;
2141 	char *retbuf, *freebuf;
2142 	int error;
2143 
2144 	if (arglen != 1)
2145 		return (EINVAL);
2146 	if (*pidp == -1) {	/* -1 means this process */
2147 		p = req->td->td_proc;
2148 	} else {
2149 		error = pget(*pidp, PGET_CANSEE, &p);
2150 		if (error != 0)
2151 			return (error);
2152 	}
2153 
2154 	vp = p->p_textvp;
2155 	if (vp == NULL) {
2156 		if (*pidp != -1)
2157 			PROC_UNLOCK(p);
2158 		return (0);
2159 	}
2160 	vref(vp);
2161 	if (*pidp != -1)
2162 		PROC_UNLOCK(p);
2163 	error = vn_fullpath(req->td, vp, &retbuf, &freebuf);
2164 	vrele(vp);
2165 	if (error)
2166 		return (error);
2167 	error = SYSCTL_OUT(req, retbuf, strlen(retbuf) + 1);
2168 	free(freebuf, M_TEMP);
2169 	return (error);
2170 }
2171 
2172 static int
2173 sysctl_kern_proc_sv_name(SYSCTL_HANDLER_ARGS)
2174 {
2175 	struct proc *p;
2176 	char *sv_name;
2177 	int *name;
2178 	int namelen;
2179 	int error;
2180 
2181 	namelen = arg2;
2182 	if (namelen != 1)
2183 		return (EINVAL);
2184 
2185 	name = (int *)arg1;
2186 	error = pget((pid_t)name[0], PGET_CANSEE, &p);
2187 	if (error != 0)
2188 		return (error);
2189 	sv_name = p->p_sysent->sv_name;
2190 	PROC_UNLOCK(p);
2191 	return (sysctl_handle_string(oidp, sv_name, 0, req));
2192 }
2193 
2194 #ifdef KINFO_OVMENTRY_SIZE
2195 CTASSERT(sizeof(struct kinfo_ovmentry) == KINFO_OVMENTRY_SIZE);
2196 #endif
2197 
2198 #ifdef COMPAT_FREEBSD7
2199 static int
2200 sysctl_kern_proc_ovmmap(SYSCTL_HANDLER_ARGS)
2201 {
2202 	vm_map_entry_t entry, tmp_entry;
2203 	unsigned int last_timestamp;
2204 	char *fullpath, *freepath;
2205 	struct kinfo_ovmentry *kve;
2206 	struct vattr va;
2207 	struct ucred *cred;
2208 	int error, *name;
2209 	struct vnode *vp;
2210 	struct proc *p;
2211 	vm_map_t map;
2212 	struct vmspace *vm;
2213 
2214 	name = (int *)arg1;
2215 	error = pget((pid_t)name[0], PGET_WANTREAD, &p);
2216 	if (error != 0)
2217 		return (error);
2218 	vm = vmspace_acquire_ref(p);
2219 	if (vm == NULL) {
2220 		PRELE(p);
2221 		return (ESRCH);
2222 	}
2223 	kve = malloc(sizeof(*kve), M_TEMP, M_WAITOK);
2224 
2225 	map = &vm->vm_map;
2226 	vm_map_lock_read(map);
2227 	VM_MAP_ENTRY_FOREACH(entry, map) {
2228 		vm_object_t obj, tobj, lobj;
2229 		vm_offset_t addr;
2230 
2231 		if (entry->eflags & MAP_ENTRY_IS_SUB_MAP)
2232 			continue;
2233 
2234 		bzero(kve, sizeof(*kve));
2235 		kve->kve_structsize = sizeof(*kve);
2236 
2237 		kve->kve_private_resident = 0;
2238 		obj = entry->object.vm_object;
2239 		if (obj != NULL) {
2240 			VM_OBJECT_RLOCK(obj);
2241 			if (obj->shadow_count == 1)
2242 				kve->kve_private_resident =
2243 				    obj->resident_page_count;
2244 		}
2245 		kve->kve_resident = 0;
2246 		addr = entry->start;
2247 		while (addr < entry->end) {
2248 			if (pmap_extract(map->pmap, addr))
2249 				kve->kve_resident++;
2250 			addr += PAGE_SIZE;
2251 		}
2252 
2253 		for (lobj = tobj = obj; tobj; tobj = tobj->backing_object) {
2254 			if (tobj != obj) {
2255 				VM_OBJECT_RLOCK(tobj);
2256 				kve->kve_offset += tobj->backing_object_offset;
2257 			}
2258 			if (lobj != obj)
2259 				VM_OBJECT_RUNLOCK(lobj);
2260 			lobj = tobj;
2261 		}
2262 
2263 		kve->kve_start = (void*)entry->start;
2264 		kve->kve_end = (void*)entry->end;
2265 		kve->kve_offset += (off_t)entry->offset;
2266 
2267 		if (entry->protection & VM_PROT_READ)
2268 			kve->kve_protection |= KVME_PROT_READ;
2269 		if (entry->protection & VM_PROT_WRITE)
2270 			kve->kve_protection |= KVME_PROT_WRITE;
2271 		if (entry->protection & VM_PROT_EXECUTE)
2272 			kve->kve_protection |= KVME_PROT_EXEC;
2273 
2274 		if (entry->eflags & MAP_ENTRY_COW)
2275 			kve->kve_flags |= KVME_FLAG_COW;
2276 		if (entry->eflags & MAP_ENTRY_NEEDS_COPY)
2277 			kve->kve_flags |= KVME_FLAG_NEEDS_COPY;
2278 		if (entry->eflags & MAP_ENTRY_NOCOREDUMP)
2279 			kve->kve_flags |= KVME_FLAG_NOCOREDUMP;
2280 
2281 		last_timestamp = map->timestamp;
2282 		vm_map_unlock_read(map);
2283 
2284 		kve->kve_fileid = 0;
2285 		kve->kve_fsid = 0;
2286 		freepath = NULL;
2287 		fullpath = "";
2288 		if (lobj) {
2289 			kve->kve_type = vm_object_kvme_type(lobj, &vp);
2290 			if (kve->kve_type == KVME_TYPE_MGTDEVICE)
2291 				kve->kve_type = KVME_TYPE_UNKNOWN;
2292 			if (vp != NULL)
2293 				vref(vp);
2294 			if (lobj != obj)
2295 				VM_OBJECT_RUNLOCK(lobj);
2296 
2297 			kve->kve_ref_count = obj->ref_count;
2298 			kve->kve_shadow_count = obj->shadow_count;
2299 			VM_OBJECT_RUNLOCK(obj);
2300 			if (vp != NULL) {
2301 				vn_fullpath(curthread, vp, &fullpath,
2302 				    &freepath);
2303 				cred = curthread->td_ucred;
2304 				vn_lock(vp, LK_SHARED | LK_RETRY);
2305 				if (VOP_GETATTR(vp, &va, cred) == 0) {
2306 					kve->kve_fileid = va.va_fileid;
2307 					/* truncate */
2308 					kve->kve_fsid = va.va_fsid;
2309 				}
2310 				vput(vp);
2311 			}
2312 		} else {
2313 			kve->kve_type = KVME_TYPE_NONE;
2314 			kve->kve_ref_count = 0;
2315 			kve->kve_shadow_count = 0;
2316 		}
2317 
2318 		strlcpy(kve->kve_path, fullpath, sizeof(kve->kve_path));
2319 		if (freepath != NULL)
2320 			free(freepath, M_TEMP);
2321 
2322 		error = SYSCTL_OUT(req, kve, sizeof(*kve));
2323 		vm_map_lock_read(map);
2324 		if (error)
2325 			break;
2326 		if (last_timestamp != map->timestamp) {
2327 			vm_map_lookup_entry(map, addr - 1, &tmp_entry);
2328 			entry = tmp_entry;
2329 		}
2330 	}
2331 	vm_map_unlock_read(map);
2332 	vmspace_free(vm);
2333 	PRELE(p);
2334 	free(kve, M_TEMP);
2335 	return (error);
2336 }
2337 #endif	/* COMPAT_FREEBSD7 */
2338 
2339 #ifdef KINFO_VMENTRY_SIZE
2340 CTASSERT(sizeof(struct kinfo_vmentry) == KINFO_VMENTRY_SIZE);
2341 #endif
2342 
2343 void
2344 kern_proc_vmmap_resident(vm_map_t map, vm_map_entry_t entry,
2345     int *resident_count, bool *super)
2346 {
2347 	vm_object_t obj, tobj;
2348 	vm_page_t m, m_adv;
2349 	vm_offset_t addr;
2350 	vm_paddr_t pa;
2351 	vm_pindex_t pi, pi_adv, pindex;
2352 
2353 	*super = false;
2354 	*resident_count = 0;
2355 	if (vmmap_skip_res_cnt)
2356 		return;
2357 
2358 	pa = 0;
2359 	obj = entry->object.vm_object;
2360 	addr = entry->start;
2361 	m_adv = NULL;
2362 	pi = OFF_TO_IDX(entry->offset);
2363 	for (; addr < entry->end; addr += IDX_TO_OFF(pi_adv), pi += pi_adv) {
2364 		if (m_adv != NULL) {
2365 			m = m_adv;
2366 		} else {
2367 			pi_adv = atop(entry->end - addr);
2368 			pindex = pi;
2369 			for (tobj = obj;; tobj = tobj->backing_object) {
2370 				m = vm_page_find_least(tobj, pindex);
2371 				if (m != NULL) {
2372 					if (m->pindex == pindex)
2373 						break;
2374 					if (pi_adv > m->pindex - pindex) {
2375 						pi_adv = m->pindex - pindex;
2376 						m_adv = m;
2377 					}
2378 				}
2379 				if (tobj->backing_object == NULL)
2380 					goto next;
2381 				pindex += OFF_TO_IDX(tobj->
2382 				    backing_object_offset);
2383 			}
2384 		}
2385 		m_adv = NULL;
2386 		if (m->psind != 0 && addr + pagesizes[1] <= entry->end &&
2387 		    (addr & (pagesizes[1] - 1)) == 0 &&
2388 		    (pmap_mincore(map->pmap, addr, &pa) & MINCORE_SUPER) != 0) {
2389 			*super = true;
2390 			pi_adv = atop(pagesizes[1]);
2391 		} else {
2392 			/*
2393 			 * We do not test the found page on validity.
2394 			 * Either the page is busy and being paged in,
2395 			 * or it was invalidated.  The first case
2396 			 * should be counted as resident, the second
2397 			 * is not so clear; we do account both.
2398 			 */
2399 			pi_adv = 1;
2400 		}
2401 		*resident_count += pi_adv;
2402 next:;
2403 	}
2404 }
2405 
2406 /*
2407  * Must be called with the process locked and will return unlocked.
2408  */
2409 int
2410 kern_proc_vmmap_out(struct proc *p, struct sbuf *sb, ssize_t maxlen, int flags)
2411 {
2412 	vm_map_entry_t entry, tmp_entry;
2413 	struct vattr va;
2414 	vm_map_t map;
2415 	vm_object_t obj, tobj, lobj;
2416 	char *fullpath, *freepath;
2417 	struct kinfo_vmentry *kve;
2418 	struct ucred *cred;
2419 	struct vnode *vp;
2420 	struct vmspace *vm;
2421 	vm_offset_t addr;
2422 	unsigned int last_timestamp;
2423 	int error;
2424 	bool super;
2425 
2426 	PROC_LOCK_ASSERT(p, MA_OWNED);
2427 
2428 	_PHOLD(p);
2429 	PROC_UNLOCK(p);
2430 	vm = vmspace_acquire_ref(p);
2431 	if (vm == NULL) {
2432 		PRELE(p);
2433 		return (ESRCH);
2434 	}
2435 	kve = malloc(sizeof(*kve), M_TEMP, M_WAITOK | M_ZERO);
2436 
2437 	error = 0;
2438 	map = &vm->vm_map;
2439 	vm_map_lock_read(map);
2440 	VM_MAP_ENTRY_FOREACH(entry, map) {
2441 		if (entry->eflags & MAP_ENTRY_IS_SUB_MAP)
2442 			continue;
2443 
2444 		addr = entry->end;
2445 		bzero(kve, sizeof(*kve));
2446 		obj = entry->object.vm_object;
2447 		if (obj != NULL) {
2448 			for (tobj = obj; tobj != NULL;
2449 			    tobj = tobj->backing_object) {
2450 				VM_OBJECT_RLOCK(tobj);
2451 				kve->kve_offset += tobj->backing_object_offset;
2452 				lobj = tobj;
2453 			}
2454 			if (obj->backing_object == NULL)
2455 				kve->kve_private_resident =
2456 				    obj->resident_page_count;
2457 			kern_proc_vmmap_resident(map, entry,
2458 			    &kve->kve_resident, &super);
2459 			if (super)
2460 				kve->kve_flags |= KVME_FLAG_SUPER;
2461 			for (tobj = obj; tobj != NULL;
2462 			    tobj = tobj->backing_object) {
2463 				if (tobj != obj && tobj != lobj)
2464 					VM_OBJECT_RUNLOCK(tobj);
2465 			}
2466 		} else {
2467 			lobj = NULL;
2468 		}
2469 
2470 		kve->kve_start = entry->start;
2471 		kve->kve_end = entry->end;
2472 		kve->kve_offset += entry->offset;
2473 
2474 		if (entry->protection & VM_PROT_READ)
2475 			kve->kve_protection |= KVME_PROT_READ;
2476 		if (entry->protection & VM_PROT_WRITE)
2477 			kve->kve_protection |= KVME_PROT_WRITE;
2478 		if (entry->protection & VM_PROT_EXECUTE)
2479 			kve->kve_protection |= KVME_PROT_EXEC;
2480 
2481 		if (entry->eflags & MAP_ENTRY_COW)
2482 			kve->kve_flags |= KVME_FLAG_COW;
2483 		if (entry->eflags & MAP_ENTRY_NEEDS_COPY)
2484 			kve->kve_flags |= KVME_FLAG_NEEDS_COPY;
2485 		if (entry->eflags & MAP_ENTRY_NOCOREDUMP)
2486 			kve->kve_flags |= KVME_FLAG_NOCOREDUMP;
2487 		if (entry->eflags & MAP_ENTRY_GROWS_UP)
2488 			kve->kve_flags |= KVME_FLAG_GROWS_UP;
2489 		if (entry->eflags & MAP_ENTRY_GROWS_DOWN)
2490 			kve->kve_flags |= KVME_FLAG_GROWS_DOWN;
2491 		if (entry->eflags & MAP_ENTRY_USER_WIRED)
2492 			kve->kve_flags |= KVME_FLAG_USER_WIRED;
2493 
2494 		last_timestamp = map->timestamp;
2495 		vm_map_unlock_read(map);
2496 
2497 		freepath = NULL;
2498 		fullpath = "";
2499 		if (lobj != NULL) {
2500 			kve->kve_type = vm_object_kvme_type(lobj, &vp);
2501 			if (vp != NULL)
2502 				vref(vp);
2503 			if (lobj != obj)
2504 				VM_OBJECT_RUNLOCK(lobj);
2505 
2506 			kve->kve_ref_count = obj->ref_count;
2507 			kve->kve_shadow_count = obj->shadow_count;
2508 			VM_OBJECT_RUNLOCK(obj);
2509 			if (vp != NULL) {
2510 				vn_fullpath(curthread, vp, &fullpath,
2511 				    &freepath);
2512 				kve->kve_vn_type = vntype_to_kinfo(vp->v_type);
2513 				cred = curthread->td_ucred;
2514 				vn_lock(vp, LK_SHARED | LK_RETRY);
2515 				if (VOP_GETATTR(vp, &va, cred) == 0) {
2516 					kve->kve_vn_fileid = va.va_fileid;
2517 					kve->kve_vn_fsid = va.va_fsid;
2518 					kve->kve_vn_fsid_freebsd11 =
2519 					    kve->kve_vn_fsid; /* truncate */
2520 					kve->kve_vn_mode =
2521 					    MAKEIMODE(va.va_type, va.va_mode);
2522 					kve->kve_vn_size = va.va_size;
2523 					kve->kve_vn_rdev = va.va_rdev;
2524 					kve->kve_vn_rdev_freebsd11 =
2525 					    kve->kve_vn_rdev; /* truncate */
2526 					kve->kve_status = KF_ATTR_VALID;
2527 				}
2528 				vput(vp);
2529 			}
2530 		} else {
2531 			kve->kve_type = KVME_TYPE_NONE;
2532 			kve->kve_ref_count = 0;
2533 			kve->kve_shadow_count = 0;
2534 		}
2535 
2536 		strlcpy(kve->kve_path, fullpath, sizeof(kve->kve_path));
2537 		if (freepath != NULL)
2538 			free(freepath, M_TEMP);
2539 
2540 		/* Pack record size down */
2541 		if ((flags & KERN_VMMAP_PACK_KINFO) != 0)
2542 			kve->kve_structsize =
2543 			    offsetof(struct kinfo_vmentry, kve_path) +
2544 			    strlen(kve->kve_path) + 1;
2545 		else
2546 			kve->kve_structsize = sizeof(*kve);
2547 		kve->kve_structsize = roundup(kve->kve_structsize,
2548 		    sizeof(uint64_t));
2549 
2550 		/* Halt filling and truncate rather than exceeding maxlen */
2551 		if (maxlen != -1 && maxlen < kve->kve_structsize) {
2552 			error = 0;
2553 			vm_map_lock_read(map);
2554 			break;
2555 		} else if (maxlen != -1)
2556 			maxlen -= kve->kve_structsize;
2557 
2558 		if (sbuf_bcat(sb, kve, kve->kve_structsize) != 0)
2559 			error = ENOMEM;
2560 		vm_map_lock_read(map);
2561 		if (error != 0)
2562 			break;
2563 		if (last_timestamp != map->timestamp) {
2564 			vm_map_lookup_entry(map, addr - 1, &tmp_entry);
2565 			entry = tmp_entry;
2566 		}
2567 	}
2568 	vm_map_unlock_read(map);
2569 	vmspace_free(vm);
2570 	PRELE(p);
2571 	free(kve, M_TEMP);
2572 	return (error);
2573 }
2574 
2575 static int
2576 sysctl_kern_proc_vmmap(SYSCTL_HANDLER_ARGS)
2577 {
2578 	struct proc *p;
2579 	struct sbuf sb;
2580 	int error, error2, *name;
2581 
2582 	name = (int *)arg1;
2583 	sbuf_new_for_sysctl(&sb, NULL, sizeof(struct kinfo_vmentry), req);
2584 	sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
2585 	error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
2586 	if (error != 0) {
2587 		sbuf_delete(&sb);
2588 		return (error);
2589 	}
2590 	error = kern_proc_vmmap_out(p, &sb, -1, KERN_VMMAP_PACK_KINFO);
2591 	error2 = sbuf_finish(&sb);
2592 	sbuf_delete(&sb);
2593 	return (error != 0 ? error : error2);
2594 }
2595 
2596 #if defined(STACK) || defined(DDB)
2597 static int
2598 sysctl_kern_proc_kstack(SYSCTL_HANDLER_ARGS)
2599 {
2600 	struct kinfo_kstack *kkstp;
2601 	int error, i, *name, numthreads;
2602 	lwpid_t *lwpidarray;
2603 	struct thread *td;
2604 	struct stack *st;
2605 	struct sbuf sb;
2606 	struct proc *p;
2607 
2608 	name = (int *)arg1;
2609 	error = pget((pid_t)name[0], PGET_NOTINEXEC | PGET_WANTREAD, &p);
2610 	if (error != 0)
2611 		return (error);
2612 
2613 	kkstp = malloc(sizeof(*kkstp), M_TEMP, M_WAITOK);
2614 	st = stack_create(M_WAITOK);
2615 
2616 	lwpidarray = NULL;
2617 	PROC_LOCK(p);
2618 	do {
2619 		if (lwpidarray != NULL) {
2620 			free(lwpidarray, M_TEMP);
2621 			lwpidarray = NULL;
2622 		}
2623 		numthreads = p->p_numthreads;
2624 		PROC_UNLOCK(p);
2625 		lwpidarray = malloc(sizeof(*lwpidarray) * numthreads, M_TEMP,
2626 		    M_WAITOK | M_ZERO);
2627 		PROC_LOCK(p);
2628 	} while (numthreads < p->p_numthreads);
2629 
2630 	/*
2631 	 * XXXRW: During the below loop, execve(2) and countless other sorts
2632 	 * of changes could have taken place.  Should we check to see if the
2633 	 * vmspace has been replaced, or the like, in order to prevent
2634 	 * giving a snapshot that spans, say, execve(2), with some threads
2635 	 * before and some after?  Among other things, the credentials could
2636 	 * have changed, in which case the right to extract debug info might
2637 	 * no longer be assured.
2638 	 */
2639 	i = 0;
2640 	FOREACH_THREAD_IN_PROC(p, td) {
2641 		KASSERT(i < numthreads,
2642 		    ("sysctl_kern_proc_kstack: numthreads"));
2643 		lwpidarray[i] = td->td_tid;
2644 		i++;
2645 	}
2646 	numthreads = i;
2647 	for (i = 0; i < numthreads; i++) {
2648 		td = thread_find(p, lwpidarray[i]);
2649 		if (td == NULL) {
2650 			continue;
2651 		}
2652 		bzero(kkstp, sizeof(*kkstp));
2653 		(void)sbuf_new(&sb, kkstp->kkst_trace,
2654 		    sizeof(kkstp->kkst_trace), SBUF_FIXEDLEN);
2655 		thread_lock(td);
2656 		kkstp->kkst_tid = td->td_tid;
2657 		if (TD_IS_SWAPPED(td))
2658 			kkstp->kkst_state = KKST_STATE_SWAPPED;
2659 		else if (stack_save_td(st, td) == 0)
2660 			kkstp->kkst_state = KKST_STATE_STACKOK;
2661 		else
2662 			kkstp->kkst_state = KKST_STATE_RUNNING;
2663 		thread_unlock(td);
2664 		PROC_UNLOCK(p);
2665 		stack_sbuf_print(&sb, st);
2666 		sbuf_finish(&sb);
2667 		sbuf_delete(&sb);
2668 		error = SYSCTL_OUT(req, kkstp, sizeof(*kkstp));
2669 		PROC_LOCK(p);
2670 		if (error)
2671 			break;
2672 	}
2673 	_PRELE(p);
2674 	PROC_UNLOCK(p);
2675 	if (lwpidarray != NULL)
2676 		free(lwpidarray, M_TEMP);
2677 	stack_destroy(st);
2678 	free(kkstp, M_TEMP);
2679 	return (error);
2680 }
2681 #endif
2682 
2683 /*
2684  * This sysctl allows a process to retrieve the full list of groups from
2685  * itself or another process.
2686  */
2687 static int
2688 sysctl_kern_proc_groups(SYSCTL_HANDLER_ARGS)
2689 {
2690 	pid_t *pidp = (pid_t *)arg1;
2691 	unsigned int arglen = arg2;
2692 	struct proc *p;
2693 	struct ucred *cred;
2694 	int error;
2695 
2696 	if (arglen != 1)
2697 		return (EINVAL);
2698 	if (*pidp == -1) {	/* -1 means this process */
2699 		p = req->td->td_proc;
2700 		PROC_LOCK(p);
2701 	} else {
2702 		error = pget(*pidp, PGET_CANSEE, &p);
2703 		if (error != 0)
2704 			return (error);
2705 	}
2706 
2707 	cred = crhold(p->p_ucred);
2708 	PROC_UNLOCK(p);
2709 
2710 	error = SYSCTL_OUT(req, cred->cr_groups,
2711 	    cred->cr_ngroups * sizeof(gid_t));
2712 	crfree(cred);
2713 	return (error);
2714 }
2715 
2716 /*
2717  * This sysctl allows a process to retrieve or/and set the resource limit for
2718  * another process.
2719  */
2720 static int
2721 sysctl_kern_proc_rlimit(SYSCTL_HANDLER_ARGS)
2722 {
2723 	int *name = (int *)arg1;
2724 	u_int namelen = arg2;
2725 	struct rlimit rlim;
2726 	struct proc *p;
2727 	u_int which;
2728 	int flags, error;
2729 
2730 	if (namelen != 2)
2731 		return (EINVAL);
2732 
2733 	which = (u_int)name[1];
2734 	if (which >= RLIM_NLIMITS)
2735 		return (EINVAL);
2736 
2737 	if (req->newptr != NULL && req->newlen != sizeof(rlim))
2738 		return (EINVAL);
2739 
2740 	flags = PGET_HOLD | PGET_NOTWEXIT;
2741 	if (req->newptr != NULL)
2742 		flags |= PGET_CANDEBUG;
2743 	else
2744 		flags |= PGET_CANSEE;
2745 	error = pget((pid_t)name[0], flags, &p);
2746 	if (error != 0)
2747 		return (error);
2748 
2749 	/*
2750 	 * Retrieve limit.
2751 	 */
2752 	if (req->oldptr != NULL) {
2753 		PROC_LOCK(p);
2754 		lim_rlimit_proc(p, which, &rlim);
2755 		PROC_UNLOCK(p);
2756 	}
2757 	error = SYSCTL_OUT(req, &rlim, sizeof(rlim));
2758 	if (error != 0)
2759 		goto errout;
2760 
2761 	/*
2762 	 * Set limit.
2763 	 */
2764 	if (req->newptr != NULL) {
2765 		error = SYSCTL_IN(req, &rlim, sizeof(rlim));
2766 		if (error == 0)
2767 			error = kern_proc_setrlimit(curthread, p, which, &rlim);
2768 	}
2769 
2770 errout:
2771 	PRELE(p);
2772 	return (error);
2773 }
2774 
2775 /*
2776  * This sysctl allows a process to retrieve ps_strings structure location of
2777  * another process.
2778  */
2779 static int
2780 sysctl_kern_proc_ps_strings(SYSCTL_HANDLER_ARGS)
2781 {
2782 	int *name = (int *)arg1;
2783 	u_int namelen = arg2;
2784 	struct proc *p;
2785 	vm_offset_t ps_strings;
2786 	int error;
2787 #ifdef COMPAT_FREEBSD32
2788 	uint32_t ps_strings32;
2789 #endif
2790 
2791 	if (namelen != 1)
2792 		return (EINVAL);
2793 
2794 	error = pget((pid_t)name[0], PGET_CANDEBUG, &p);
2795 	if (error != 0)
2796 		return (error);
2797 #ifdef COMPAT_FREEBSD32
2798 	if ((req->flags & SCTL_MASK32) != 0) {
2799 		/*
2800 		 * We return 0 if the 32 bit emulation request is for a 64 bit
2801 		 * process.
2802 		 */
2803 		ps_strings32 = SV_PROC_FLAG(p, SV_ILP32) != 0 ?
2804 		    PTROUT(p->p_sysent->sv_psstrings) : 0;
2805 		PROC_UNLOCK(p);
2806 		error = SYSCTL_OUT(req, &ps_strings32, sizeof(ps_strings32));
2807 		return (error);
2808 	}
2809 #endif
2810 	ps_strings = p->p_sysent->sv_psstrings;
2811 	PROC_UNLOCK(p);
2812 	error = SYSCTL_OUT(req, &ps_strings, sizeof(ps_strings));
2813 	return (error);
2814 }
2815 
2816 /*
2817  * This sysctl allows a process to retrieve umask of another process.
2818  */
2819 static int
2820 sysctl_kern_proc_umask(SYSCTL_HANDLER_ARGS)
2821 {
2822 	int *name = (int *)arg1;
2823 	u_int namelen = arg2;
2824 	struct proc *p;
2825 	int error;
2826 	u_short fd_cmask;
2827 	pid_t pid;
2828 
2829 	if (namelen != 1)
2830 		return (EINVAL);
2831 
2832 	pid = (pid_t)name[0];
2833 	p = curproc;
2834 	if (pid == p->p_pid || pid == 0) {
2835 		fd_cmask = p->p_fd->fd_cmask;
2836 		goto out;
2837 	}
2838 
2839 	error = pget(pid, PGET_WANTREAD, &p);
2840 	if (error != 0)
2841 		return (error);
2842 
2843 	fd_cmask = p->p_fd->fd_cmask;
2844 	PRELE(p);
2845 out:
2846 	error = SYSCTL_OUT(req, &fd_cmask, sizeof(fd_cmask));
2847 	return (error);
2848 }
2849 
2850 /*
2851  * This sysctl allows a process to set and retrieve binary osreldate of
2852  * another process.
2853  */
2854 static int
2855 sysctl_kern_proc_osrel(SYSCTL_HANDLER_ARGS)
2856 {
2857 	int *name = (int *)arg1;
2858 	u_int namelen = arg2;
2859 	struct proc *p;
2860 	int flags, error, osrel;
2861 
2862 	if (namelen != 1)
2863 		return (EINVAL);
2864 
2865 	if (req->newptr != NULL && req->newlen != sizeof(osrel))
2866 		return (EINVAL);
2867 
2868 	flags = PGET_HOLD | PGET_NOTWEXIT;
2869 	if (req->newptr != NULL)
2870 		flags |= PGET_CANDEBUG;
2871 	else
2872 		flags |= PGET_CANSEE;
2873 	error = pget((pid_t)name[0], flags, &p);
2874 	if (error != 0)
2875 		return (error);
2876 
2877 	error = SYSCTL_OUT(req, &p->p_osrel, sizeof(p->p_osrel));
2878 	if (error != 0)
2879 		goto errout;
2880 
2881 	if (req->newptr != NULL) {
2882 		error = SYSCTL_IN(req, &osrel, sizeof(osrel));
2883 		if (error != 0)
2884 			goto errout;
2885 		if (osrel < 0) {
2886 			error = EINVAL;
2887 			goto errout;
2888 		}
2889 		p->p_osrel = osrel;
2890 	}
2891 errout:
2892 	PRELE(p);
2893 	return (error);
2894 }
2895 
2896 static int
2897 sysctl_kern_proc_sigtramp(SYSCTL_HANDLER_ARGS)
2898 {
2899 	int *name = (int *)arg1;
2900 	u_int namelen = arg2;
2901 	struct proc *p;
2902 	struct kinfo_sigtramp kst;
2903 	const struct sysentvec *sv;
2904 	int error;
2905 #ifdef COMPAT_FREEBSD32
2906 	struct kinfo_sigtramp32 kst32;
2907 #endif
2908 
2909 	if (namelen != 1)
2910 		return (EINVAL);
2911 
2912 	error = pget((pid_t)name[0], PGET_CANDEBUG, &p);
2913 	if (error != 0)
2914 		return (error);
2915 	sv = p->p_sysent;
2916 #ifdef COMPAT_FREEBSD32
2917 	if ((req->flags & SCTL_MASK32) != 0) {
2918 		bzero(&kst32, sizeof(kst32));
2919 		if (SV_PROC_FLAG(p, SV_ILP32)) {
2920 			if (sv->sv_sigcode_base != 0) {
2921 				kst32.ksigtramp_start = sv->sv_sigcode_base;
2922 				kst32.ksigtramp_end = sv->sv_sigcode_base +
2923 				    *sv->sv_szsigcode;
2924 			} else {
2925 				kst32.ksigtramp_start = sv->sv_psstrings -
2926 				    *sv->sv_szsigcode;
2927 				kst32.ksigtramp_end = sv->sv_psstrings;
2928 			}
2929 		}
2930 		PROC_UNLOCK(p);
2931 		error = SYSCTL_OUT(req, &kst32, sizeof(kst32));
2932 		return (error);
2933 	}
2934 #endif
2935 	bzero(&kst, sizeof(kst));
2936 	if (sv->sv_sigcode_base != 0) {
2937 		kst.ksigtramp_start = (char *)sv->sv_sigcode_base;
2938 		kst.ksigtramp_end = (char *)sv->sv_sigcode_base +
2939 		    *sv->sv_szsigcode;
2940 	} else {
2941 		kst.ksigtramp_start = (char *)sv->sv_psstrings -
2942 		    *sv->sv_szsigcode;
2943 		kst.ksigtramp_end = (char *)sv->sv_psstrings;
2944 	}
2945 	PROC_UNLOCK(p);
2946 	error = SYSCTL_OUT(req, &kst, sizeof(kst));
2947 	return (error);
2948 }
2949 
2950 static int
2951 sysctl_kern_proc_sigfastblk(SYSCTL_HANDLER_ARGS)
2952 {
2953 	int *name = (int *)arg1;
2954 	u_int namelen = arg2;
2955 	pid_t pid;
2956 	struct proc *p;
2957 	struct thread *td1;
2958 	uintptr_t addr;
2959 #ifdef COMPAT_FREEBSD32
2960 	uint32_t addr32;
2961 #endif
2962 	int error;
2963 
2964 	if (namelen != 1 || req->newptr != NULL)
2965 		return (EINVAL);
2966 
2967 	pid = (pid_t)name[0];
2968 	error = pget(pid, PGET_HOLD | PGET_NOTWEXIT | PGET_CANDEBUG, &p);
2969 	if (error != 0)
2970 		return (error);
2971 
2972 	PROC_LOCK(p);
2973 #ifdef COMPAT_FREEBSD32
2974 	if (SV_CURPROC_FLAG(SV_ILP32)) {
2975 		if (!SV_PROC_FLAG(p, SV_ILP32)) {
2976 			error = EINVAL;
2977 			goto errlocked;
2978 		}
2979 	}
2980 #endif
2981 	if (pid <= PID_MAX) {
2982 		td1 = FIRST_THREAD_IN_PROC(p);
2983 	} else {
2984 		FOREACH_THREAD_IN_PROC(p, td1) {
2985 			if (td1->td_tid == pid)
2986 				break;
2987 		}
2988 	}
2989 	if (td1 == NULL) {
2990 		error = ESRCH;
2991 		goto errlocked;
2992 	}
2993 	/*
2994 	 * The access to the private thread flags.  It is fine as far
2995 	 * as no out-of-thin-air values are read from td_pflags, and
2996 	 * usermode read of the td_sigblock_ptr is racy inherently,
2997 	 * since target process might have already changed it
2998 	 * meantime.
2999 	 */
3000 	if ((td1->td_pflags & TDP_SIGFASTBLOCK) != 0)
3001 		addr = (uintptr_t)td1->td_sigblock_ptr;
3002 	else
3003 		error = ENOTTY;
3004 
3005 errlocked:
3006 	_PRELE(p);
3007 	PROC_UNLOCK(p);
3008 	if (error != 0)
3009 		return (error);
3010 
3011 #ifdef COMPAT_FREEBSD32
3012 	if (SV_CURPROC_FLAG(SV_ILP32)) {
3013 		addr32 = addr;
3014 		error = SYSCTL_OUT(req, &addr32, sizeof(addr32));
3015 	} else
3016 #endif
3017 		error = SYSCTL_OUT(req, &addr, sizeof(addr));
3018 	return (error);
3019 }
3020 
3021 SYSCTL_NODE(_kern, KERN_PROC, proc, CTLFLAG_RD | CTLFLAG_MPSAFE,  0,
3022     "Process table");
3023 
3024 SYSCTL_PROC(_kern_proc, KERN_PROC_ALL, all, CTLFLAG_RD|CTLTYPE_STRUCT|
3025 	CTLFLAG_MPSAFE, 0, 0, sysctl_kern_proc, "S,proc",
3026 	"Return entire process table");
3027 
3028 static SYSCTL_NODE(_kern_proc, KERN_PROC_GID, gid, CTLFLAG_RD | CTLFLAG_MPSAFE,
3029 	sysctl_kern_proc, "Process table");
3030 
3031 static SYSCTL_NODE(_kern_proc, KERN_PROC_PGRP, pgrp, CTLFLAG_RD | CTLFLAG_MPSAFE,
3032 	sysctl_kern_proc, "Process table");
3033 
3034 static SYSCTL_NODE(_kern_proc, KERN_PROC_RGID, rgid, CTLFLAG_RD | CTLFLAG_MPSAFE,
3035 	sysctl_kern_proc, "Process table");
3036 
3037 static SYSCTL_NODE(_kern_proc, KERN_PROC_SESSION, sid, CTLFLAG_RD |
3038 	CTLFLAG_MPSAFE, sysctl_kern_proc, "Process table");
3039 
3040 static SYSCTL_NODE(_kern_proc, KERN_PROC_TTY, tty, CTLFLAG_RD | CTLFLAG_MPSAFE,
3041 	sysctl_kern_proc, "Process table");
3042 
3043 static SYSCTL_NODE(_kern_proc, KERN_PROC_UID, uid, CTLFLAG_RD | CTLFLAG_MPSAFE,
3044 	sysctl_kern_proc, "Process table");
3045 
3046 static SYSCTL_NODE(_kern_proc, KERN_PROC_RUID, ruid, CTLFLAG_RD | CTLFLAG_MPSAFE,
3047 	sysctl_kern_proc, "Process table");
3048 
3049 static SYSCTL_NODE(_kern_proc, KERN_PROC_PID, pid, CTLFLAG_RD | CTLFLAG_MPSAFE,
3050 	sysctl_kern_proc, "Process table");
3051 
3052 static SYSCTL_NODE(_kern_proc, KERN_PROC_PROC, proc, CTLFLAG_RD | CTLFLAG_MPSAFE,
3053 	sysctl_kern_proc, "Return process table, no threads");
3054 
3055 static SYSCTL_NODE(_kern_proc, KERN_PROC_ARGS, args,
3056 	CTLFLAG_RW | CTLFLAG_CAPWR | CTLFLAG_ANYBODY | CTLFLAG_MPSAFE,
3057 	sysctl_kern_proc_args, "Process argument list");
3058 
3059 static SYSCTL_NODE(_kern_proc, KERN_PROC_ENV, env, CTLFLAG_RD | CTLFLAG_MPSAFE,
3060 	sysctl_kern_proc_env, "Process environment");
3061 
3062 static SYSCTL_NODE(_kern_proc, KERN_PROC_AUXV, auxv, CTLFLAG_RD |
3063 	CTLFLAG_MPSAFE, sysctl_kern_proc_auxv, "Process ELF auxiliary vector");
3064 
3065 static SYSCTL_NODE(_kern_proc, KERN_PROC_PATHNAME, pathname, CTLFLAG_RD |
3066 	CTLFLAG_MPSAFE, sysctl_kern_proc_pathname, "Process executable path");
3067 
3068 static SYSCTL_NODE(_kern_proc, KERN_PROC_SV_NAME, sv_name, CTLFLAG_RD |
3069 	CTLFLAG_MPSAFE, sysctl_kern_proc_sv_name,
3070 	"Process syscall vector name (ABI type)");
3071 
3072 static SYSCTL_NODE(_kern_proc, (KERN_PROC_GID | KERN_PROC_INC_THREAD), gid_td,
3073 	CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_kern_proc, "Process table");
3074 
3075 static SYSCTL_NODE(_kern_proc, (KERN_PROC_PGRP | KERN_PROC_INC_THREAD), pgrp_td,
3076 	CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_kern_proc, "Process table");
3077 
3078 static SYSCTL_NODE(_kern_proc, (KERN_PROC_RGID | KERN_PROC_INC_THREAD), rgid_td,
3079 	CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_kern_proc, "Process table");
3080 
3081 static SYSCTL_NODE(_kern_proc, (KERN_PROC_SESSION | KERN_PROC_INC_THREAD),
3082 	sid_td, CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_kern_proc, "Process table");
3083 
3084 static SYSCTL_NODE(_kern_proc, (KERN_PROC_TTY | KERN_PROC_INC_THREAD), tty_td,
3085 	CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_kern_proc, "Process table");
3086 
3087 static SYSCTL_NODE(_kern_proc, (KERN_PROC_UID | KERN_PROC_INC_THREAD), uid_td,
3088 	CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_kern_proc, "Process table");
3089 
3090 static SYSCTL_NODE(_kern_proc, (KERN_PROC_RUID | KERN_PROC_INC_THREAD), ruid_td,
3091 	CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_kern_proc, "Process table");
3092 
3093 static SYSCTL_NODE(_kern_proc, (KERN_PROC_PID | KERN_PROC_INC_THREAD), pid_td,
3094 	CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_kern_proc, "Process table");
3095 
3096 static SYSCTL_NODE(_kern_proc, (KERN_PROC_PROC | KERN_PROC_INC_THREAD), proc_td,
3097 	CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_kern_proc,
3098 	"Return process table, no threads");
3099 
3100 #ifdef COMPAT_FREEBSD7
3101 static SYSCTL_NODE(_kern_proc, KERN_PROC_OVMMAP, ovmmap, CTLFLAG_RD |
3102 	CTLFLAG_MPSAFE, sysctl_kern_proc_ovmmap, "Old Process vm map entries");
3103 #endif
3104 
3105 static SYSCTL_NODE(_kern_proc, KERN_PROC_VMMAP, vmmap, CTLFLAG_RD |
3106 	CTLFLAG_MPSAFE, sysctl_kern_proc_vmmap, "Process vm map entries");
3107 
3108 #if defined(STACK) || defined(DDB)
3109 static SYSCTL_NODE(_kern_proc, KERN_PROC_KSTACK, kstack, CTLFLAG_RD |
3110 	CTLFLAG_MPSAFE, sysctl_kern_proc_kstack, "Process kernel stacks");
3111 #endif
3112 
3113 static SYSCTL_NODE(_kern_proc, KERN_PROC_GROUPS, groups, CTLFLAG_RD |
3114 	CTLFLAG_MPSAFE, sysctl_kern_proc_groups, "Process groups");
3115 
3116 static SYSCTL_NODE(_kern_proc, KERN_PROC_RLIMIT, rlimit, CTLFLAG_RW |
3117 	CTLFLAG_ANYBODY | CTLFLAG_MPSAFE, sysctl_kern_proc_rlimit,
3118 	"Process resource limits");
3119 
3120 static SYSCTL_NODE(_kern_proc, KERN_PROC_PS_STRINGS, ps_strings, CTLFLAG_RD |
3121 	CTLFLAG_MPSAFE, sysctl_kern_proc_ps_strings,
3122 	"Process ps_strings location");
3123 
3124 static SYSCTL_NODE(_kern_proc, KERN_PROC_UMASK, umask, CTLFLAG_RD |
3125 	CTLFLAG_MPSAFE, sysctl_kern_proc_umask, "Process umask");
3126 
3127 static SYSCTL_NODE(_kern_proc, KERN_PROC_OSREL, osrel, CTLFLAG_RW |
3128 	CTLFLAG_ANYBODY | CTLFLAG_MPSAFE, sysctl_kern_proc_osrel,
3129 	"Process binary osreldate");
3130 
3131 static SYSCTL_NODE(_kern_proc, KERN_PROC_SIGTRAMP, sigtramp, CTLFLAG_RD |
3132 	CTLFLAG_MPSAFE, sysctl_kern_proc_sigtramp,
3133 	"Process signal trampoline location");
3134 
3135 static SYSCTL_NODE(_kern_proc, KERN_PROC_SIGFASTBLK, sigfastblk, CTLFLAG_RD |
3136 	CTLFLAG_ANYBODY | CTLFLAG_MPSAFE, sysctl_kern_proc_sigfastblk,
3137 	"Thread sigfastblock address");
3138 
3139 int allproc_gen;
3140 
3141 /*
3142  * stop_all_proc() purpose is to stop all process which have usermode,
3143  * except current process for obvious reasons.  This makes it somewhat
3144  * unreliable when invoked from multithreaded process.  The service
3145  * must not be user-callable anyway.
3146  */
3147 void
3148 stop_all_proc(void)
3149 {
3150 	struct proc *cp, *p;
3151 	int r, gen;
3152 	bool restart, seen_stopped, seen_exiting, stopped_some;
3153 
3154 	cp = curproc;
3155 allproc_loop:
3156 	sx_xlock(&allproc_lock);
3157 	gen = allproc_gen;
3158 	seen_exiting = seen_stopped = stopped_some = restart = false;
3159 	LIST_REMOVE(cp, p_list);
3160 	LIST_INSERT_HEAD(&allproc, cp, p_list);
3161 	for (;;) {
3162 		p = LIST_NEXT(cp, p_list);
3163 		if (p == NULL)
3164 			break;
3165 		LIST_REMOVE(cp, p_list);
3166 		LIST_INSERT_AFTER(p, cp, p_list);
3167 		PROC_LOCK(p);
3168 		if ((p->p_flag & (P_KPROC | P_SYSTEM | P_TOTAL_STOP)) != 0) {
3169 			PROC_UNLOCK(p);
3170 			continue;
3171 		}
3172 		if ((p->p_flag & P_WEXIT) != 0) {
3173 			seen_exiting = true;
3174 			PROC_UNLOCK(p);
3175 			continue;
3176 		}
3177 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
3178 			/*
3179 			 * Stopped processes are tolerated when there
3180 			 * are no other processes which might continue
3181 			 * them.  P_STOPPED_SINGLE but not
3182 			 * P_TOTAL_STOP process still has at least one
3183 			 * thread running.
3184 			 */
3185 			seen_stopped = true;
3186 			PROC_UNLOCK(p);
3187 			continue;
3188 		}
3189 		sx_xunlock(&allproc_lock);
3190 		_PHOLD(p);
3191 		r = thread_single(p, SINGLE_ALLPROC);
3192 		if (r != 0)
3193 			restart = true;
3194 		else
3195 			stopped_some = true;
3196 		_PRELE(p);
3197 		PROC_UNLOCK(p);
3198 		sx_xlock(&allproc_lock);
3199 	}
3200 	/* Catch forked children we did not see in iteration. */
3201 	if (gen != allproc_gen)
3202 		restart = true;
3203 	sx_xunlock(&allproc_lock);
3204 	if (restart || stopped_some || seen_exiting || seen_stopped) {
3205 		kern_yield(PRI_USER);
3206 		goto allproc_loop;
3207 	}
3208 }
3209 
3210 void
3211 resume_all_proc(void)
3212 {
3213 	struct proc *cp, *p;
3214 
3215 	cp = curproc;
3216 	sx_xlock(&allproc_lock);
3217 again:
3218 	LIST_REMOVE(cp, p_list);
3219 	LIST_INSERT_HEAD(&allproc, cp, p_list);
3220 	for (;;) {
3221 		p = LIST_NEXT(cp, p_list);
3222 		if (p == NULL)
3223 			break;
3224 		LIST_REMOVE(cp, p_list);
3225 		LIST_INSERT_AFTER(p, cp, p_list);
3226 		PROC_LOCK(p);
3227 		if ((p->p_flag & P_TOTAL_STOP) != 0) {
3228 			sx_xunlock(&allproc_lock);
3229 			_PHOLD(p);
3230 			thread_single_end(p, SINGLE_ALLPROC);
3231 			_PRELE(p);
3232 			PROC_UNLOCK(p);
3233 			sx_xlock(&allproc_lock);
3234 		} else {
3235 			PROC_UNLOCK(p);
3236 		}
3237 	}
3238 	/*  Did the loop above missed any stopped process ? */
3239 	FOREACH_PROC_IN_SYSTEM(p) {
3240 		/* No need for proc lock. */
3241 		if ((p->p_flag & P_TOTAL_STOP) != 0)
3242 			goto again;
3243 	}
3244 	sx_xunlock(&allproc_lock);
3245 }
3246 
3247 /* #define	TOTAL_STOP_DEBUG	1 */
3248 #ifdef TOTAL_STOP_DEBUG
3249 volatile static int ap_resume;
3250 #include <sys/mount.h>
3251 
3252 static int
3253 sysctl_debug_stop_all_proc(SYSCTL_HANDLER_ARGS)
3254 {
3255 	int error, val;
3256 
3257 	val = 0;
3258 	ap_resume = 0;
3259 	error = sysctl_handle_int(oidp, &val, 0, req);
3260 	if (error != 0 || req->newptr == NULL)
3261 		return (error);
3262 	if (val != 0) {
3263 		stop_all_proc();
3264 		syncer_suspend();
3265 		while (ap_resume == 0)
3266 			;
3267 		syncer_resume();
3268 		resume_all_proc();
3269 	}
3270 	return (0);
3271 }
3272 
3273 SYSCTL_PROC(_debug, OID_AUTO, stop_all_proc, CTLTYPE_INT | CTLFLAG_RW |
3274     CTLFLAG_MPSAFE, __DEVOLATILE(int *, &ap_resume), 0,
3275     sysctl_debug_stop_all_proc, "I",
3276     "");
3277 #endif
3278