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