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