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