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