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