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