xref: /freebsd/sys/kern/kern_proc.c (revision 4fd2d3b6927878771635a3628ae1623daf810d39)
1 /*-
2  * Copyright (c) 1982, 1986, 1989, 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  *	@(#)kern_proc.c	8.7 (Berkeley) 2/14/95
30  */
31 
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34 
35 #include "opt_ddb.h"
36 #include "opt_ktrace.h"
37 #include "opt_kstack_pages.h"
38 #include "opt_stack.h"
39 
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/kernel.h>
43 #include <sys/lock.h>
44 #include <sys/malloc.h>
45 #include <sys/mount.h>
46 #include <sys/mutex.h>
47 #include <sys/proc.h>
48 #include <sys/refcount.h>
49 #include <sys/sbuf.h>
50 #include <sys/sysent.h>
51 #include <sys/sched.h>
52 #include <sys/smp.h>
53 #include <sys/stack.h>
54 #include <sys/sysctl.h>
55 #include <sys/filedesc.h>
56 #include <sys/tty.h>
57 #include <sys/signalvar.h>
58 #include <sys/sx.h>
59 #include <sys/user.h>
60 #include <sys/jail.h>
61 #include <sys/vnode.h>
62 #include <sys/eventhandler.h>
63 #ifdef KTRACE
64 #include <sys/uio.h>
65 #include <sys/ktrace.h>
66 #endif
67 
68 #ifdef DDB
69 #include <ddb/ddb.h>
70 #endif
71 
72 #include <vm/vm.h>
73 #include <vm/vm_extern.h>
74 #include <vm/pmap.h>
75 #include <vm/vm_map.h>
76 #include <vm/vm_object.h>
77 #include <vm/uma.h>
78 
79 MALLOC_DEFINE(M_PGRP, "pgrp", "process group header");
80 MALLOC_DEFINE(M_SESSION, "session", "session header");
81 static MALLOC_DEFINE(M_PROC, "proc", "Proc structures");
82 MALLOC_DEFINE(M_SUBPROC, "subproc", "Proc sub-structures");
83 
84 static void doenterpgrp(struct proc *, struct pgrp *);
85 static void orphanpg(struct pgrp *pg);
86 static void fill_kinfo_proc_only(struct proc *p, struct kinfo_proc *kp);
87 static void fill_kinfo_thread(struct thread *td, struct kinfo_proc *kp,
88     int preferthread);
89 static void pgadjustjobc(struct pgrp *pgrp, int entering);
90 static void pgdelete(struct pgrp *);
91 static int proc_ctor(void *mem, int size, void *arg, int flags);
92 static void proc_dtor(void *mem, int size, void *arg);
93 static int proc_init(void *mem, int size, int flags);
94 static void proc_fini(void *mem, int size);
95 
96 /*
97  * Other process lists
98  */
99 struct pidhashhead *pidhashtbl;
100 u_long pidhash;
101 struct pgrphashhead *pgrphashtbl;
102 u_long pgrphash;
103 struct proclist allproc;
104 struct proclist zombproc;
105 struct sx allproc_lock;
106 struct sx proctree_lock;
107 struct mtx ppeers_lock;
108 uma_zone_t proc_zone;
109 uma_zone_t ithread_zone;
110 
111 int kstack_pages = KSTACK_PAGES;
112 SYSCTL_INT(_kern, OID_AUTO, kstack_pages, CTLFLAG_RD, &kstack_pages, 0, "");
113 
114 CTASSERT(sizeof(struct kinfo_proc) == KINFO_PROC_SIZE);
115 
116 /*
117  * Initialize global process hashing structures.
118  */
119 void
120 procinit()
121 {
122 
123 	sx_init(&allproc_lock, "allproc");
124 	sx_init(&proctree_lock, "proctree");
125 	mtx_init(&ppeers_lock, "p_peers", NULL, MTX_DEF);
126 	LIST_INIT(&allproc);
127 	LIST_INIT(&zombproc);
128 	pidhashtbl = hashinit(maxproc / 4, M_PROC, &pidhash);
129 	pgrphashtbl = hashinit(maxproc / 4, M_PROC, &pgrphash);
130 	proc_zone = uma_zcreate("PROC", sched_sizeof_proc(),
131 	    proc_ctor, proc_dtor, proc_init, proc_fini,
132 	    UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
133 	uihashinit();
134 }
135 
136 /*
137  * Prepare a proc for use.
138  */
139 static int
140 proc_ctor(void *mem, int size, void *arg, int flags)
141 {
142 	struct proc *p;
143 
144 	p = (struct proc *)mem;
145 	EVENTHANDLER_INVOKE(process_ctor, p);
146 	return (0);
147 }
148 
149 /*
150  * Reclaim a proc after use.
151  */
152 static void
153 proc_dtor(void *mem, int size, void *arg)
154 {
155 	struct proc *p;
156 	struct thread *td;
157 
158 	/* INVARIANTS checks go here */
159 	p = (struct proc *)mem;
160 	td = FIRST_THREAD_IN_PROC(p);
161 	if (td != NULL) {
162 #ifdef INVARIANTS
163 		KASSERT((p->p_numthreads == 1),
164 		    ("bad number of threads in exiting process"));
165 		KASSERT(STAILQ_EMPTY(&p->p_ktr), ("proc_dtor: non-empty p_ktr"));
166 #endif
167 		/* Dispose of an alternate kstack, if it exists.
168 		 * XXX What if there are more than one thread in the proc?
169 		 *     The first thread in the proc is special and not
170 		 *     freed, so you gotta do this here.
171 		 */
172 		if (((p->p_flag & P_KTHREAD) != 0) && (td->td_altkstack != 0))
173 			vm_thread_dispose_altkstack(td);
174 	}
175 	EVENTHANDLER_INVOKE(process_dtor, p);
176 	if (p->p_ksi != NULL)
177 		KASSERT(! KSI_ONQ(p->p_ksi), ("SIGCHLD queue"));
178 }
179 
180 /*
181  * Initialize type-stable parts of a proc (when newly created).
182  */
183 static int
184 proc_init(void *mem, int size, int flags)
185 {
186 	struct proc *p;
187 
188 	p = (struct proc *)mem;
189 	p->p_sched = (struct p_sched *)&p[1];
190 	bzero(&p->p_mtx, sizeof(struct mtx));
191 	mtx_init(&p->p_mtx, "process lock", NULL, MTX_DEF | MTX_DUPOK);
192 	mtx_init(&p->p_slock, "process slock", NULL, MTX_SPIN | MTX_RECURSE);
193 	TAILQ_INIT(&p->p_threads);	     /* all threads in proc */
194 	EVENTHANDLER_INVOKE(process_init, p);
195 	p->p_stats = pstats_alloc();
196 	return (0);
197 }
198 
199 /*
200  * UMA should ensure that this function is never called.
201  * Freeing a proc structure would violate type stability.
202  */
203 static void
204 proc_fini(void *mem, int size)
205 {
206 #ifdef notnow
207 	struct proc *p;
208 
209 	p = (struct proc *)mem;
210 	EVENTHANDLER_INVOKE(process_fini, p);
211 	pstats_free(p->p_stats);
212 	thread_free(FIRST_THREAD_IN_PROC(p));
213 	mtx_destroy(&p->p_mtx);
214 	if (p->p_ksi != NULL)
215 		ksiginfo_free(p->p_ksi);
216 #else
217 	panic("proc reclaimed");
218 #endif
219 }
220 
221 /*
222  * Is p an inferior of the current process?
223  */
224 int
225 inferior(p)
226 	register struct proc *p;
227 {
228 
229 	sx_assert(&proctree_lock, SX_LOCKED);
230 	for (; p != curproc; p = p->p_pptr)
231 		if (p->p_pid == 0)
232 			return (0);
233 	return (1);
234 }
235 
236 /*
237  * Locate a process by number; return only "live" processes -- i.e., neither
238  * zombies nor newly born but incompletely initialized processes.  By not
239  * returning processes in the PRS_NEW state, we allow callers to avoid
240  * testing for that condition to avoid dereferencing p_ucred, et al.
241  */
242 struct proc *
243 pfind(pid)
244 	register pid_t pid;
245 {
246 	register struct proc *p;
247 
248 	sx_slock(&allproc_lock);
249 	LIST_FOREACH(p, PIDHASH(pid), p_hash)
250 		if (p->p_pid == pid) {
251 			if (p->p_state == PRS_NEW) {
252 				p = NULL;
253 				break;
254 			}
255 			PROC_LOCK(p);
256 			break;
257 		}
258 	sx_sunlock(&allproc_lock);
259 	return (p);
260 }
261 
262 /*
263  * Locate a process group by number.
264  * The caller must hold proctree_lock.
265  */
266 struct pgrp *
267 pgfind(pgid)
268 	register pid_t pgid;
269 {
270 	register struct pgrp *pgrp;
271 
272 	sx_assert(&proctree_lock, SX_LOCKED);
273 
274 	LIST_FOREACH(pgrp, PGRPHASH(pgid), pg_hash) {
275 		if (pgrp->pg_id == pgid) {
276 			PGRP_LOCK(pgrp);
277 			return (pgrp);
278 		}
279 	}
280 	return (NULL);
281 }
282 
283 /*
284  * Create a new process group.
285  * pgid must be equal to the pid of p.
286  * Begin a new session if required.
287  */
288 int
289 enterpgrp(p, pgid, pgrp, sess)
290 	register struct proc *p;
291 	pid_t pgid;
292 	struct pgrp *pgrp;
293 	struct session *sess;
294 {
295 	struct pgrp *pgrp2;
296 
297 	sx_assert(&proctree_lock, SX_XLOCKED);
298 
299 	KASSERT(pgrp != NULL, ("enterpgrp: pgrp == NULL"));
300 	KASSERT(p->p_pid == pgid,
301 	    ("enterpgrp: new pgrp and pid != pgid"));
302 
303 	pgrp2 = pgfind(pgid);
304 
305 	KASSERT(pgrp2 == NULL,
306 	    ("enterpgrp: pgrp with pgid exists"));
307 	KASSERT(!SESS_LEADER(p),
308 	    ("enterpgrp: session leader attempted setpgrp"));
309 
310 	mtx_init(&pgrp->pg_mtx, "process group", NULL, MTX_DEF | MTX_DUPOK);
311 
312 	if (sess != NULL) {
313 		/*
314 		 * new session
315 		 */
316 		mtx_init(&sess->s_mtx, "session", NULL, MTX_DEF);
317 		mtx_lock(&Giant);       /* XXX TTY */
318 		PROC_LOCK(p);
319 		p->p_flag &= ~P_CONTROLT;
320 		PROC_UNLOCK(p);
321 		PGRP_LOCK(pgrp);
322 		sess->s_leader = p;
323 		sess->s_sid = p->p_pid;
324 		sess->s_count = 1;
325 		sess->s_ttyvp = NULL;
326 		sess->s_ttyp = NULL;
327 		bcopy(p->p_session->s_login, sess->s_login,
328 			    sizeof(sess->s_login));
329 		pgrp->pg_session = sess;
330 		KASSERT(p == curproc,
331 		    ("enterpgrp: mksession and p != curproc"));
332 	} else {
333 		mtx_lock(&Giant);       /* XXX TTY */
334 		pgrp->pg_session = p->p_session;
335 		SESS_LOCK(pgrp->pg_session);
336 		pgrp->pg_session->s_count++;
337 		SESS_UNLOCK(pgrp->pg_session);
338 		PGRP_LOCK(pgrp);
339 	}
340 	pgrp->pg_id = pgid;
341 	LIST_INIT(&pgrp->pg_members);
342 
343 	/*
344 	 * As we have an exclusive lock of proctree_lock,
345 	 * this should not deadlock.
346 	 */
347 	LIST_INSERT_HEAD(PGRPHASH(pgid), pgrp, pg_hash);
348 	pgrp->pg_jobc = 0;
349 	SLIST_INIT(&pgrp->pg_sigiolst);
350 	PGRP_UNLOCK(pgrp);
351 	mtx_unlock(&Giant);       /* XXX TTY */
352 
353 	doenterpgrp(p, pgrp);
354 
355 	return (0);
356 }
357 
358 /*
359  * Move p to an existing process group
360  */
361 int
362 enterthispgrp(p, pgrp)
363 	register struct proc *p;
364 	struct pgrp *pgrp;
365 {
366 
367 	sx_assert(&proctree_lock, SX_XLOCKED);
368 	PROC_LOCK_ASSERT(p, MA_NOTOWNED);
369 	PGRP_LOCK_ASSERT(pgrp, MA_NOTOWNED);
370 	PGRP_LOCK_ASSERT(p->p_pgrp, MA_NOTOWNED);
371 	SESS_LOCK_ASSERT(p->p_session, MA_NOTOWNED);
372 	KASSERT(pgrp->pg_session == p->p_session,
373 		("%s: pgrp's session %p, p->p_session %p.\n",
374 		__func__,
375 		pgrp->pg_session,
376 		p->p_session));
377 	KASSERT(pgrp != p->p_pgrp,
378 		("%s: p belongs to pgrp.", __func__));
379 
380 	doenterpgrp(p, pgrp);
381 
382 	return (0);
383 }
384 
385 /*
386  * Move p to a process group
387  */
388 static void
389 doenterpgrp(p, pgrp)
390 	struct proc *p;
391 	struct pgrp *pgrp;
392 {
393 	struct pgrp *savepgrp;
394 
395 	sx_assert(&proctree_lock, SX_XLOCKED);
396 	PROC_LOCK_ASSERT(p, MA_NOTOWNED);
397 	PGRP_LOCK_ASSERT(pgrp, MA_NOTOWNED);
398 	PGRP_LOCK_ASSERT(p->p_pgrp, MA_NOTOWNED);
399 	SESS_LOCK_ASSERT(p->p_session, MA_NOTOWNED);
400 
401 	savepgrp = p->p_pgrp;
402 
403 	/*
404 	 * Adjust eligibility of affected pgrps to participate in job control.
405 	 * Increment eligibility counts before decrementing, otherwise we
406 	 * could reach 0 spuriously during the first call.
407 	 */
408 	fixjobc(p, pgrp, 1);
409 	fixjobc(p, p->p_pgrp, 0);
410 
411 	mtx_lock(&Giant);       /* XXX TTY */
412 	PGRP_LOCK(pgrp);
413 	PGRP_LOCK(savepgrp);
414 	PROC_LOCK(p);
415 	LIST_REMOVE(p, p_pglist);
416 	p->p_pgrp = pgrp;
417 	PROC_UNLOCK(p);
418 	LIST_INSERT_HEAD(&pgrp->pg_members, p, p_pglist);
419 	PGRP_UNLOCK(savepgrp);
420 	PGRP_UNLOCK(pgrp);
421 	mtx_unlock(&Giant);     /* XXX TTY */
422 	if (LIST_EMPTY(&savepgrp->pg_members))
423 		pgdelete(savepgrp);
424 }
425 
426 /*
427  * remove process from process group
428  */
429 int
430 leavepgrp(p)
431 	register struct proc *p;
432 {
433 	struct pgrp *savepgrp;
434 
435 	sx_assert(&proctree_lock, SX_XLOCKED);
436 	savepgrp = p->p_pgrp;
437 	mtx_lock(&Giant);	/* XXX TTY */
438 	PGRP_LOCK(savepgrp);
439 	PROC_LOCK(p);
440 	LIST_REMOVE(p, p_pglist);
441 	p->p_pgrp = NULL;
442 	PROC_UNLOCK(p);
443 	PGRP_UNLOCK(savepgrp);
444 	mtx_unlock(&Giant);	/* XXX TTY */
445 	if (LIST_EMPTY(&savepgrp->pg_members))
446 		pgdelete(savepgrp);
447 	return (0);
448 }
449 
450 /*
451  * delete a process group
452  */
453 static void
454 pgdelete(pgrp)
455 	register struct pgrp *pgrp;
456 {
457 	struct session *savesess;
458 
459 	sx_assert(&proctree_lock, SX_XLOCKED);
460 	PGRP_LOCK_ASSERT(pgrp, MA_NOTOWNED);
461 	SESS_LOCK_ASSERT(pgrp->pg_session, MA_NOTOWNED);
462 
463 	/*
464 	 * Reset any sigio structures pointing to us as a result of
465 	 * F_SETOWN with our pgid.
466 	 */
467 	funsetownlst(&pgrp->pg_sigiolst);
468 
469 	mtx_lock(&Giant);       /* XXX TTY */
470 	PGRP_LOCK(pgrp);
471 	if (pgrp->pg_session->s_ttyp != NULL &&
472 	    pgrp->pg_session->s_ttyp->t_pgrp == pgrp)
473 		pgrp->pg_session->s_ttyp->t_pgrp = NULL;
474 	LIST_REMOVE(pgrp, pg_hash);
475 	savesess = pgrp->pg_session;
476 	SESSRELE(savesess);
477 	PGRP_UNLOCK(pgrp);
478 	mtx_destroy(&pgrp->pg_mtx);
479 	FREE(pgrp, M_PGRP);
480 	mtx_unlock(&Giant);     /* XXX TTY */
481 }
482 
483 static void
484 pgadjustjobc(pgrp, entering)
485 	struct pgrp *pgrp;
486 	int entering;
487 {
488 
489 	PGRP_LOCK(pgrp);
490 	if (entering)
491 		pgrp->pg_jobc++;
492 	else {
493 		--pgrp->pg_jobc;
494 		if (pgrp->pg_jobc == 0)
495 			orphanpg(pgrp);
496 	}
497 	PGRP_UNLOCK(pgrp);
498 }
499 
500 /*
501  * Adjust pgrp jobc counters when specified process changes process group.
502  * We count the number of processes in each process group that "qualify"
503  * the group for terminal job control (those with a parent in a different
504  * process group of the same session).  If that count reaches zero, the
505  * process group becomes orphaned.  Check both the specified process'
506  * process group and that of its children.
507  * entering == 0 => p is leaving specified group.
508  * entering == 1 => p is entering specified group.
509  */
510 void
511 fixjobc(p, pgrp, entering)
512 	register struct proc *p;
513 	register struct pgrp *pgrp;
514 	int entering;
515 {
516 	register struct pgrp *hispgrp;
517 	register struct session *mysession;
518 
519 	sx_assert(&proctree_lock, SX_LOCKED);
520 	PROC_LOCK_ASSERT(p, MA_NOTOWNED);
521 	PGRP_LOCK_ASSERT(pgrp, MA_NOTOWNED);
522 	SESS_LOCK_ASSERT(pgrp->pg_session, MA_NOTOWNED);
523 
524 	/*
525 	 * Check p's parent to see whether p qualifies its own process
526 	 * group; if so, adjust count for p's process group.
527 	 */
528 	mysession = pgrp->pg_session;
529 	if ((hispgrp = p->p_pptr->p_pgrp) != pgrp &&
530 	    hispgrp->pg_session == mysession)
531 		pgadjustjobc(pgrp, entering);
532 
533 	/*
534 	 * Check this process' children to see whether they qualify
535 	 * their process groups; if so, adjust counts for children's
536 	 * process groups.
537 	 */
538 	LIST_FOREACH(p, &p->p_children, p_sibling) {
539 		hispgrp = p->p_pgrp;
540 		if (hispgrp == pgrp ||
541 		    hispgrp->pg_session != mysession)
542 			continue;
543 		PROC_LOCK(p);
544 		if (p->p_state == PRS_ZOMBIE) {
545 			PROC_UNLOCK(p);
546 			continue;
547 		}
548 		PROC_UNLOCK(p);
549 		pgadjustjobc(hispgrp, entering);
550 	}
551 }
552 
553 /*
554  * A process group has become orphaned;
555  * if there are any stopped processes in the group,
556  * hang-up all process in that group.
557  */
558 static void
559 orphanpg(pg)
560 	struct pgrp *pg;
561 {
562 	register struct proc *p;
563 
564 	PGRP_LOCK_ASSERT(pg, MA_OWNED);
565 
566 	LIST_FOREACH(p, &pg->pg_members, p_pglist) {
567 		PROC_LOCK(p);
568 		if (P_SHOULDSTOP(p)) {
569 			PROC_UNLOCK(p);
570 			LIST_FOREACH(p, &pg->pg_members, p_pglist) {
571 				PROC_LOCK(p);
572 				psignal(p, SIGHUP);
573 				psignal(p, SIGCONT);
574 				PROC_UNLOCK(p);
575 			}
576 			return;
577 		}
578 		PROC_UNLOCK(p);
579 	}
580 }
581 
582 void
583 sessrele(struct session *s)
584 {
585 	int i;
586 
587 	SESS_LOCK(s);
588 	i = --s->s_count;
589 	SESS_UNLOCK(s);
590 	if (i == 0) {
591 		if (s->s_ttyp != NULL)
592 			ttyrel(s->s_ttyp);
593 		mtx_destroy(&s->s_mtx);
594 		FREE(s, M_SESSION);
595 	}
596 }
597 
598 #include "opt_ddb.h"
599 #ifdef DDB
600 #include <ddb/ddb.h>
601 
602 DB_SHOW_COMMAND(pgrpdump, pgrpdump)
603 {
604 	register struct pgrp *pgrp;
605 	register struct proc *p;
606 	register int i;
607 
608 	for (i = 0; i <= pgrphash; i++) {
609 		if (!LIST_EMPTY(&pgrphashtbl[i])) {
610 			printf("\tindx %d\n", i);
611 			LIST_FOREACH(pgrp, &pgrphashtbl[i], pg_hash) {
612 				printf(
613 			"\tpgrp %p, pgid %ld, sess %p, sesscnt %d, mem %p\n",
614 				    (void *)pgrp, (long)pgrp->pg_id,
615 				    (void *)pgrp->pg_session,
616 				    pgrp->pg_session->s_count,
617 				    (void *)LIST_FIRST(&pgrp->pg_members));
618 				LIST_FOREACH(p, &pgrp->pg_members, p_pglist) {
619 					printf("\t\tpid %ld addr %p pgrp %p\n",
620 					    (long)p->p_pid, (void *)p,
621 					    (void *)p->p_pgrp);
622 				}
623 			}
624 		}
625 	}
626 }
627 #endif /* DDB */
628 
629 /*
630  * Clear kinfo_proc and fill in any information that is common
631  * to all threads in the process.
632  * Must be called with the target process locked.
633  */
634 static void
635 fill_kinfo_proc_only(struct proc *p, struct kinfo_proc *kp)
636 {
637 	struct thread *td0;
638 	struct tty *tp;
639 	struct session *sp;
640 	struct ucred *cred;
641 	struct sigacts *ps;
642 
643 	PROC_LOCK_ASSERT(p, MA_OWNED);
644 	bzero(kp, sizeof(*kp));
645 
646 	kp->ki_structsize = sizeof(*kp);
647 	kp->ki_paddr = p;
648 	kp->ki_addr =/* p->p_addr; */0; /* XXX */
649 	kp->ki_args = p->p_args;
650 	kp->ki_textvp = p->p_textvp;
651 #ifdef KTRACE
652 	kp->ki_tracep = p->p_tracevp;
653 	mtx_lock(&ktrace_mtx);
654 	kp->ki_traceflag = p->p_traceflag;
655 	mtx_unlock(&ktrace_mtx);
656 #endif
657 	kp->ki_fd = p->p_fd;
658 	kp->ki_vmspace = p->p_vmspace;
659 	kp->ki_flag = p->p_flag;
660 	cred = p->p_ucred;
661 	if (cred) {
662 		kp->ki_uid = cred->cr_uid;
663 		kp->ki_ruid = cred->cr_ruid;
664 		kp->ki_svuid = cred->cr_svuid;
665 		/* XXX bde doesn't like KI_NGROUPS */
666 		kp->ki_ngroups = min(cred->cr_ngroups, KI_NGROUPS);
667 		bcopy(cred->cr_groups, kp->ki_groups,
668 		    kp->ki_ngroups * sizeof(gid_t));
669 		kp->ki_rgid = cred->cr_rgid;
670 		kp->ki_svgid = cred->cr_svgid;
671 		/* If jailed(cred), emulate the old P_JAILED flag. */
672 		if (jailed(cred)) {
673 			kp->ki_flag |= P_JAILED;
674 			/* If inside a jail, use 0 as a jail ID. */
675 			if (!jailed(curthread->td_ucred))
676 				kp->ki_jid = cred->cr_prison->pr_id;
677 		}
678 	}
679 	ps = p->p_sigacts;
680 	if (ps) {
681 		mtx_lock(&ps->ps_mtx);
682 		kp->ki_sigignore = ps->ps_sigignore;
683 		kp->ki_sigcatch = ps->ps_sigcatch;
684 		mtx_unlock(&ps->ps_mtx);
685 	}
686 	PROC_SLOCK(p);
687 	if (p->p_state != PRS_NEW &&
688 	    p->p_state != PRS_ZOMBIE &&
689 	    p->p_vmspace != NULL) {
690 		struct vmspace *vm = p->p_vmspace;
691 
692 		kp->ki_size = vm->vm_map.size;
693 		kp->ki_rssize = vmspace_resident_count(vm); /*XXX*/
694 		FOREACH_THREAD_IN_PROC(p, td0) {
695 			if (!TD_IS_SWAPPED(td0))
696 				kp->ki_rssize += td0->td_kstack_pages;
697 			if (td0->td_altkstack_obj != NULL)
698 				kp->ki_rssize += td0->td_altkstack_pages;
699 		}
700 		kp->ki_swrss = vm->vm_swrss;
701 		kp->ki_tsize = vm->vm_tsize;
702 		kp->ki_dsize = vm->vm_dsize;
703 		kp->ki_ssize = vm->vm_ssize;
704 	} else if (p->p_state == PRS_ZOMBIE)
705 		kp->ki_stat = SZOMB;
706 	if (kp->ki_flag & P_INMEM)
707 		kp->ki_sflag = PS_INMEM;
708 	else
709 		kp->ki_sflag = 0;
710 	/* Calculate legacy swtime as seconds since 'swtick'. */
711 	kp->ki_swtime = (ticks - p->p_swtick) / hz;
712 	kp->ki_pid = p->p_pid;
713 	kp->ki_nice = p->p_nice;
714 	rufetch(p, &kp->ki_rusage);
715 	kp->ki_runtime = cputick2usec(p->p_rux.rux_runtime);
716 	PROC_SUNLOCK(p);
717 	if ((p->p_flag & P_INMEM) && p->p_stats != NULL) {
718 		kp->ki_start = p->p_stats->p_start;
719 		timevaladd(&kp->ki_start, &boottime);
720 		PROC_SLOCK(p);
721 		calcru(p, &kp->ki_rusage.ru_utime, &kp->ki_rusage.ru_stime);
722 		PROC_SUNLOCK(p);
723 		calccru(p, &kp->ki_childutime, &kp->ki_childstime);
724 
725 		/* Some callers want child-times in a single value */
726 		kp->ki_childtime = kp->ki_childstime;
727 		timevaladd(&kp->ki_childtime, &kp->ki_childutime);
728 	}
729 	tp = NULL;
730 	if (p->p_pgrp) {
731 		kp->ki_pgid = p->p_pgrp->pg_id;
732 		kp->ki_jobc = p->p_pgrp->pg_jobc;
733 		sp = p->p_pgrp->pg_session;
734 
735 		if (sp != NULL) {
736 			kp->ki_sid = sp->s_sid;
737 			SESS_LOCK(sp);
738 			strlcpy(kp->ki_login, sp->s_login,
739 			    sizeof(kp->ki_login));
740 			if (sp->s_ttyvp)
741 				kp->ki_kiflag |= KI_CTTY;
742 			if (SESS_LEADER(p))
743 				kp->ki_kiflag |= KI_SLEADER;
744 			tp = sp->s_ttyp;
745 			SESS_UNLOCK(sp);
746 		}
747 	}
748 	if ((p->p_flag & P_CONTROLT) && tp != NULL) {
749 		kp->ki_tdev = dev2udev(tp->t_dev);
750 		kp->ki_tpgid = tp->t_pgrp ? tp->t_pgrp->pg_id : NO_PID;
751 		if (tp->t_session)
752 			kp->ki_tsid = tp->t_session->s_sid;
753 	} else
754 		kp->ki_tdev = NODEV;
755 	if (p->p_comm[0] != '\0')
756 		strlcpy(kp->ki_comm, p->p_comm, sizeof(kp->ki_comm));
757 	if (p->p_sysent && p->p_sysent->sv_name != NULL &&
758 	    p->p_sysent->sv_name[0] != '\0')
759 		strlcpy(kp->ki_emul, p->p_sysent->sv_name, sizeof(kp->ki_emul));
760 	kp->ki_siglist = p->p_siglist;
761 	kp->ki_xstat = p->p_xstat;
762 	kp->ki_acflag = p->p_acflag;
763 	kp->ki_lock = p->p_lock;
764 	if (p->p_pptr)
765 		kp->ki_ppid = p->p_pptr->p_pid;
766 }
767 
768 /*
769  * Fill in information that is thread specific.  Must be called with p_slock
770  * locked.  If 'preferthread' is set, overwrite certain process-related
771  * fields that are maintained for both threads and processes.
772  */
773 static void
774 fill_kinfo_thread(struct thread *td, struct kinfo_proc *kp, int preferthread)
775 {
776 	struct proc *p;
777 
778 	p = td->td_proc;
779 	PROC_LOCK_ASSERT(p, MA_OWNED);
780 
781 	thread_lock(td);
782 	if (td->td_wmesg != NULL)
783 		strlcpy(kp->ki_wmesg, td->td_wmesg, sizeof(kp->ki_wmesg));
784 	else
785 		bzero(kp->ki_wmesg, sizeof(kp->ki_wmesg));
786 	if (td->td_name[0] != '\0')
787 		strlcpy(kp->ki_ocomm, td->td_name, sizeof(kp->ki_ocomm));
788 	if (TD_ON_LOCK(td)) {
789 		kp->ki_kiflag |= KI_LOCKBLOCK;
790 		strlcpy(kp->ki_lockname, td->td_lockname,
791 		    sizeof(kp->ki_lockname));
792 	} else {
793 		kp->ki_kiflag &= ~KI_LOCKBLOCK;
794 		bzero(kp->ki_lockname, sizeof(kp->ki_lockname));
795 	}
796 
797 	if (p->p_state == PRS_NORMAL) { /* approximate. */
798 		if (TD_ON_RUNQ(td) ||
799 		    TD_CAN_RUN(td) ||
800 		    TD_IS_RUNNING(td)) {
801 			kp->ki_stat = SRUN;
802 		} else if (P_SHOULDSTOP(p)) {
803 			kp->ki_stat = SSTOP;
804 		} else if (TD_IS_SLEEPING(td)) {
805 			kp->ki_stat = SSLEEP;
806 		} else if (TD_ON_LOCK(td)) {
807 			kp->ki_stat = SLOCK;
808 		} else {
809 			kp->ki_stat = SWAIT;
810 		}
811 	} else if (p->p_state == PRS_ZOMBIE) {
812 		kp->ki_stat = SZOMB;
813 	} else {
814 		kp->ki_stat = SIDL;
815 	}
816 
817 	/* Things in the thread */
818 	kp->ki_wchan = td->td_wchan;
819 	kp->ki_pri.pri_level = td->td_priority;
820 	kp->ki_pri.pri_native = td->td_base_pri;
821 	kp->ki_lastcpu = td->td_lastcpu;
822 	kp->ki_oncpu = td->td_oncpu;
823 	kp->ki_tdflags = td->td_flags;
824 	kp->ki_tid = td->td_tid;
825 	kp->ki_numthreads = p->p_numthreads;
826 	kp->ki_pcb = td->td_pcb;
827 	kp->ki_kstack = (void *)td->td_kstack;
828 	kp->ki_pctcpu = sched_pctcpu(td);
829 	kp->ki_estcpu = td->td_estcpu;
830 	kp->ki_slptime = (ticks - td->td_slptick) / hz;
831 	kp->ki_pri.pri_class = td->td_pri_class;
832 	kp->ki_pri.pri_user = td->td_user_pri;
833 
834 	if (preferthread)
835 		kp->ki_runtime = cputick2usec(td->td_runtime);
836 
837 	/* We can't get this anymore but ps etc never used it anyway. */
838 	kp->ki_rqindex = 0;
839 
840 	SIGSETOR(kp->ki_siglist, td->td_siglist);
841 	kp->ki_sigmask = td->td_sigmask;
842 	thread_unlock(td);
843 }
844 
845 /*
846  * Fill in a kinfo_proc structure for the specified process.
847  * Must be called with the target process locked.
848  */
849 void
850 fill_kinfo_proc(struct proc *p, struct kinfo_proc *kp)
851 {
852 
853 	fill_kinfo_proc_only(p, kp);
854 	if (FIRST_THREAD_IN_PROC(p) != NULL)
855 		fill_kinfo_thread(FIRST_THREAD_IN_PROC(p), kp, 0);
856 }
857 
858 struct pstats *
859 pstats_alloc(void)
860 {
861 
862 	return (malloc(sizeof(struct pstats), M_SUBPROC, M_ZERO|M_WAITOK));
863 }
864 
865 /*
866  * Copy parts of p_stats; zero the rest of p_stats (statistics).
867  */
868 void
869 pstats_fork(struct pstats *src, struct pstats *dst)
870 {
871 
872 	bzero(&dst->pstat_startzero,
873 	    __rangeof(struct pstats, pstat_startzero, pstat_endzero));
874 	bcopy(&src->pstat_startcopy, &dst->pstat_startcopy,
875 	    __rangeof(struct pstats, pstat_startcopy, pstat_endcopy));
876 }
877 
878 void
879 pstats_free(struct pstats *ps)
880 {
881 
882 	free(ps, M_SUBPROC);
883 }
884 
885 /*
886  * Locate a zombie process by number
887  */
888 struct proc *
889 zpfind(pid_t pid)
890 {
891 	struct proc *p;
892 
893 	sx_slock(&allproc_lock);
894 	LIST_FOREACH(p, &zombproc, p_list)
895 		if (p->p_pid == pid) {
896 			PROC_LOCK(p);
897 			break;
898 		}
899 	sx_sunlock(&allproc_lock);
900 	return (p);
901 }
902 
903 #define KERN_PROC_ZOMBMASK	0x3
904 #define KERN_PROC_NOTHREADS	0x4
905 
906 /*
907  * Must be called with the process locked and will return with it unlocked.
908  */
909 static int
910 sysctl_out_proc(struct proc *p, struct sysctl_req *req, int flags)
911 {
912 	struct thread *td;
913 	struct kinfo_proc kinfo_proc;
914 	int error = 0;
915 	struct proc *np;
916 	pid_t pid = p->p_pid;
917 
918 	PROC_LOCK_ASSERT(p, MA_OWNED);
919 
920 	fill_kinfo_proc_only(p, &kinfo_proc);
921 	if (flags & KERN_PROC_NOTHREADS) {
922 		if (FIRST_THREAD_IN_PROC(p) != NULL)
923 			fill_kinfo_thread(FIRST_THREAD_IN_PROC(p),
924 			    &kinfo_proc, 0);
925 		error = SYSCTL_OUT(req, (caddr_t)&kinfo_proc,
926 				   sizeof(kinfo_proc));
927 	} else {
928 		if (FIRST_THREAD_IN_PROC(p) != NULL)
929 			FOREACH_THREAD_IN_PROC(p, td) {
930 				fill_kinfo_thread(td, &kinfo_proc, 1);
931 				error = SYSCTL_OUT(req, (caddr_t)&kinfo_proc,
932 						   sizeof(kinfo_proc));
933 				if (error)
934 					break;
935 			}
936 		else
937 			error = SYSCTL_OUT(req, (caddr_t)&kinfo_proc,
938 					   sizeof(kinfo_proc));
939 	}
940 	PROC_UNLOCK(p);
941 	if (error)
942 		return (error);
943 	if (flags & KERN_PROC_ZOMBMASK)
944 		np = zpfind(pid);
945 	else {
946 		if (pid == 0)
947 			return (0);
948 		np = pfind(pid);
949 	}
950 	if (np == NULL)
951 		return EAGAIN;
952 	if (np != p) {
953 		PROC_UNLOCK(np);
954 		return EAGAIN;
955 	}
956 	PROC_UNLOCK(np);
957 	return (0);
958 }
959 
960 static int
961 sysctl_kern_proc(SYSCTL_HANDLER_ARGS)
962 {
963 	int *name = (int*) arg1;
964 	u_int namelen = arg2;
965 	struct proc *p;
966 	int flags, doingzomb, oid_number;
967 	int error = 0;
968 
969 	oid_number = oidp->oid_number;
970 	if (oid_number != KERN_PROC_ALL &&
971 	    (oid_number & KERN_PROC_INC_THREAD) == 0)
972 		flags = KERN_PROC_NOTHREADS;
973 	else {
974 		flags = 0;
975 		oid_number &= ~KERN_PROC_INC_THREAD;
976 	}
977 	if (oid_number == KERN_PROC_PID) {
978 		if (namelen != 1)
979 			return (EINVAL);
980 		error = sysctl_wire_old_buffer(req, 0);
981 		if (error)
982 			return (error);
983 		p = pfind((pid_t)name[0]);
984 		if (!p)
985 			return (ESRCH);
986 		if ((error = p_cansee(curthread, p))) {
987 			PROC_UNLOCK(p);
988 			return (error);
989 		}
990 		error = sysctl_out_proc(p, req, flags);
991 		return (error);
992 	}
993 
994 	switch (oid_number) {
995 	case KERN_PROC_ALL:
996 		if (namelen != 0)
997 			return (EINVAL);
998 		break;
999 	case KERN_PROC_PROC:
1000 		if (namelen != 0 && namelen != 1)
1001 			return (EINVAL);
1002 		break;
1003 	default:
1004 		if (namelen != 1)
1005 			return (EINVAL);
1006 		break;
1007 	}
1008 
1009 	if (!req->oldptr) {
1010 		/* overestimate by 5 procs */
1011 		error = SYSCTL_OUT(req, 0, sizeof (struct kinfo_proc) * 5);
1012 		if (error)
1013 			return (error);
1014 	}
1015 	error = sysctl_wire_old_buffer(req, 0);
1016 	if (error != 0)
1017 		return (error);
1018 	sx_slock(&allproc_lock);
1019 	for (doingzomb=0 ; doingzomb < 2 ; doingzomb++) {
1020 		if (!doingzomb)
1021 			p = LIST_FIRST(&allproc);
1022 		else
1023 			p = LIST_FIRST(&zombproc);
1024 		for (; p != 0; p = LIST_NEXT(p, p_list)) {
1025 			/*
1026 			 * Skip embryonic processes.
1027 			 */
1028 			PROC_SLOCK(p);
1029 			if (p->p_state == PRS_NEW) {
1030 				PROC_SUNLOCK(p);
1031 				continue;
1032 			}
1033 			PROC_SUNLOCK(p);
1034 			PROC_LOCK(p);
1035 			KASSERT(p->p_ucred != NULL,
1036 			    ("process credential is NULL for non-NEW proc"));
1037 			/*
1038 			 * Show a user only appropriate processes.
1039 			 */
1040 			if (p_cansee(curthread, p)) {
1041 				PROC_UNLOCK(p);
1042 				continue;
1043 			}
1044 			/*
1045 			 * TODO - make more efficient (see notes below).
1046 			 * do by session.
1047 			 */
1048 			switch (oid_number) {
1049 
1050 			case KERN_PROC_GID:
1051 				if (p->p_ucred->cr_gid != (gid_t)name[0]) {
1052 					PROC_UNLOCK(p);
1053 					continue;
1054 				}
1055 				break;
1056 
1057 			case KERN_PROC_PGRP:
1058 				/* could do this by traversing pgrp */
1059 				if (p->p_pgrp == NULL ||
1060 				    p->p_pgrp->pg_id != (pid_t)name[0]) {
1061 					PROC_UNLOCK(p);
1062 					continue;
1063 				}
1064 				break;
1065 
1066 			case KERN_PROC_RGID:
1067 				if (p->p_ucred->cr_rgid != (gid_t)name[0]) {
1068 					PROC_UNLOCK(p);
1069 					continue;
1070 				}
1071 				break;
1072 
1073 			case KERN_PROC_SESSION:
1074 				if (p->p_session == NULL ||
1075 				    p->p_session->s_sid != (pid_t)name[0]) {
1076 					PROC_UNLOCK(p);
1077 					continue;
1078 				}
1079 				break;
1080 
1081 			case KERN_PROC_TTY:
1082 				if ((p->p_flag & P_CONTROLT) == 0 ||
1083 				    p->p_session == NULL) {
1084 					PROC_UNLOCK(p);
1085 					continue;
1086 				}
1087 				SESS_LOCK(p->p_session);
1088 				if (p->p_session->s_ttyp == NULL ||
1089 				    dev2udev(p->p_session->s_ttyp->t_dev) !=
1090 				    (dev_t)name[0]) {
1091 					SESS_UNLOCK(p->p_session);
1092 					PROC_UNLOCK(p);
1093 					continue;
1094 				}
1095 				SESS_UNLOCK(p->p_session);
1096 				break;
1097 
1098 			case KERN_PROC_UID:
1099 				if (p->p_ucred->cr_uid != (uid_t)name[0]) {
1100 					PROC_UNLOCK(p);
1101 					continue;
1102 				}
1103 				break;
1104 
1105 			case KERN_PROC_RUID:
1106 				if (p->p_ucred->cr_ruid != (uid_t)name[0]) {
1107 					PROC_UNLOCK(p);
1108 					continue;
1109 				}
1110 				break;
1111 
1112 			case KERN_PROC_PROC:
1113 				break;
1114 
1115 			default:
1116 				break;
1117 
1118 			}
1119 
1120 			error = sysctl_out_proc(p, req, flags | doingzomb);
1121 			if (error) {
1122 				sx_sunlock(&allproc_lock);
1123 				return (error);
1124 			}
1125 		}
1126 	}
1127 	sx_sunlock(&allproc_lock);
1128 	return (0);
1129 }
1130 
1131 struct pargs *
1132 pargs_alloc(int len)
1133 {
1134 	struct pargs *pa;
1135 
1136 	MALLOC(pa, struct pargs *, sizeof(struct pargs) + len, M_PARGS,
1137 		M_WAITOK);
1138 	refcount_init(&pa->ar_ref, 1);
1139 	pa->ar_length = len;
1140 	return (pa);
1141 }
1142 
1143 void
1144 pargs_free(struct pargs *pa)
1145 {
1146 
1147 	FREE(pa, M_PARGS);
1148 }
1149 
1150 void
1151 pargs_hold(struct pargs *pa)
1152 {
1153 
1154 	if (pa == NULL)
1155 		return;
1156 	refcount_acquire(&pa->ar_ref);
1157 }
1158 
1159 void
1160 pargs_drop(struct pargs *pa)
1161 {
1162 
1163 	if (pa == NULL)
1164 		return;
1165 	if (refcount_release(&pa->ar_ref))
1166 		pargs_free(pa);
1167 }
1168 
1169 /*
1170  * This sysctl allows a process to retrieve the argument list or process
1171  * title for another process without groping around in the address space
1172  * of the other process.  It also allow a process to set its own "process
1173  * title to a string of its own choice.
1174  */
1175 static int
1176 sysctl_kern_proc_args(SYSCTL_HANDLER_ARGS)
1177 {
1178 	int *name = (int*) arg1;
1179 	u_int namelen = arg2;
1180 	struct pargs *newpa, *pa;
1181 	struct proc *p;
1182 	int error = 0;
1183 
1184 	if (namelen != 1)
1185 		return (EINVAL);
1186 
1187 	p = pfind((pid_t)name[0]);
1188 	if (!p)
1189 		return (ESRCH);
1190 
1191 	if ((error = p_cansee(curthread, p)) != 0) {
1192 		PROC_UNLOCK(p);
1193 		return (error);
1194 	}
1195 
1196 	if (req->newptr && curproc != p) {
1197 		PROC_UNLOCK(p);
1198 		return (EPERM);
1199 	}
1200 
1201 	pa = p->p_args;
1202 	pargs_hold(pa);
1203 	PROC_UNLOCK(p);
1204 	if (req->oldptr != NULL && pa != NULL)
1205 		error = SYSCTL_OUT(req, pa->ar_args, pa->ar_length);
1206 	pargs_drop(pa);
1207 	if (error != 0 || req->newptr == NULL)
1208 		return (error);
1209 
1210 	if (req->newlen + sizeof(struct pargs) > ps_arg_cache_limit)
1211 		return (ENOMEM);
1212 	newpa = pargs_alloc(req->newlen);
1213 	error = SYSCTL_IN(req, newpa->ar_args, req->newlen);
1214 	if (error != 0) {
1215 		pargs_free(newpa);
1216 		return (error);
1217 	}
1218 	PROC_LOCK(p);
1219 	pa = p->p_args;
1220 	p->p_args = newpa;
1221 	PROC_UNLOCK(p);
1222 	pargs_drop(pa);
1223 	return (0);
1224 }
1225 
1226 /*
1227  * This sysctl allows a process to retrieve the path of the executable for
1228  * itself or another process.
1229  */
1230 static int
1231 sysctl_kern_proc_pathname(SYSCTL_HANDLER_ARGS)
1232 {
1233 	pid_t *pidp = (pid_t *)arg1;
1234 	unsigned int arglen = arg2;
1235 	struct proc *p;
1236 	struct vnode *vp;
1237 	char *retbuf, *freebuf;
1238 	int error;
1239 
1240 	if (arglen != 1)
1241 		return (EINVAL);
1242 	if (*pidp == -1) {	/* -1 means this process */
1243 		p = req->td->td_proc;
1244 	} else {
1245 		p = pfind(*pidp);
1246 		if (p == NULL)
1247 			return (ESRCH);
1248 		if ((error = p_cansee(curthread, p)) != 0) {
1249 			PROC_UNLOCK(p);
1250 			return (error);
1251 		}
1252 	}
1253 
1254 	vp = p->p_textvp;
1255 	if (vp == NULL) {
1256 		if (*pidp != -1)
1257 			PROC_UNLOCK(p);
1258 		return (0);
1259 	}
1260 	vref(vp);
1261 	if (*pidp != -1)
1262 		PROC_UNLOCK(p);
1263 	error = vn_fullpath(req->td, vp, &retbuf, &freebuf);
1264 	vrele(vp);
1265 	if (error)
1266 		return (error);
1267 	error = SYSCTL_OUT(req, retbuf, strlen(retbuf) + 1);
1268 	free(freebuf, M_TEMP);
1269 	return (error);
1270 }
1271 
1272 static int
1273 sysctl_kern_proc_sv_name(SYSCTL_HANDLER_ARGS)
1274 {
1275 	struct proc *p;
1276 	char *sv_name;
1277 	int *name;
1278 	int namelen;
1279 	int error;
1280 
1281 	namelen = arg2;
1282 	if (namelen != 1)
1283 		return (EINVAL);
1284 
1285 	name = (int *)arg1;
1286 	if ((p = pfind((pid_t)name[0])) == NULL)
1287 		return (ESRCH);
1288 	if ((error = p_cansee(curthread, p))) {
1289 		PROC_UNLOCK(p);
1290 		return (error);
1291 	}
1292 	sv_name = p->p_sysent->sv_name;
1293 	PROC_UNLOCK(p);
1294 	return (sysctl_handle_string(oidp, sv_name, 0, req));
1295 }
1296 
1297 static int
1298 sysctl_kern_proc_vmmap(SYSCTL_HANDLER_ARGS)
1299 {
1300 	vm_map_entry_t entry, tmp_entry;
1301 	unsigned int last_timestamp;
1302 	char *fullpath, *freepath;
1303 	struct kinfo_vmentry *kve;
1304 	int error, *name;
1305 	struct vnode *vp;
1306 	struct proc *p;
1307 	vm_map_t map;
1308 
1309 	name = (int *)arg1;
1310 	if ((p = pfind((pid_t)name[0])) == NULL)
1311 		return (ESRCH);
1312 	if (p->p_flag & P_WEXIT) {
1313 		PROC_UNLOCK(p);
1314 		return (ESRCH);
1315 	}
1316 	if ((error = p_candebug(curthread, p))) {
1317 		PROC_UNLOCK(p);
1318 		return (error);
1319 	}
1320 	_PHOLD(p);
1321 	PROC_UNLOCK(p);
1322 
1323 	kve = malloc(sizeof(*kve), M_TEMP, M_WAITOK);
1324 
1325 	map = &p->p_vmspace->vm_map;	/* XXXRW: More locking required? */
1326 	vm_map_lock_read(map);
1327 	for (entry = map->header.next; entry != &map->header;
1328 	    entry = entry->next) {
1329 		vm_object_t obj, tobj, lobj;
1330 		vm_offset_t addr;
1331 		int vfslocked;
1332 
1333 		if (entry->eflags & MAP_ENTRY_IS_SUB_MAP)
1334 			continue;
1335 
1336 		bzero(kve, sizeof(*kve));
1337 		kve->kve_structsize = sizeof(*kve);
1338 
1339 		kve->kve_private_resident = 0;
1340 		obj = entry->object.vm_object;
1341 		if (obj != NULL) {
1342 			VM_OBJECT_LOCK(obj);
1343 			if (obj->shadow_count == 1)
1344 				kve->kve_private_resident =
1345 				    obj->resident_page_count;
1346 		}
1347 		kve->kve_resident = 0;
1348 		addr = entry->start;
1349 		while (addr < entry->end) {
1350 			if (pmap_extract(map->pmap, addr))
1351 				kve->kve_resident++;
1352 			addr += PAGE_SIZE;
1353 		}
1354 
1355 		for (lobj = tobj = obj; tobj; tobj = tobj->backing_object) {
1356 			if (tobj != obj)
1357 				VM_OBJECT_LOCK(tobj);
1358 			if (lobj != obj)
1359 				VM_OBJECT_UNLOCK(lobj);
1360 			lobj = tobj;
1361 		}
1362 
1363 		freepath = NULL;
1364 		fullpath = "";
1365 		if (lobj) {
1366 			vp = NULL;
1367 			switch(lobj->type) {
1368 			case OBJT_DEFAULT:
1369 				kve->kve_type = KVME_TYPE_DEFAULT;
1370 				break;
1371 			case OBJT_VNODE:
1372 				kve->kve_type = KVME_TYPE_VNODE;
1373 				vp = lobj->handle;
1374 				vref(vp);
1375 				break;
1376 			case OBJT_SWAP:
1377 				kve->kve_type = KVME_TYPE_SWAP;
1378 				break;
1379 			case OBJT_DEVICE:
1380 				kve->kve_type = KVME_TYPE_DEVICE;
1381 				break;
1382 			case OBJT_PHYS:
1383 				kve->kve_type = KVME_TYPE_PHYS;
1384 				break;
1385 			case OBJT_DEAD:
1386 				kve->kve_type = KVME_TYPE_DEAD;
1387 				break;
1388 			default:
1389 				kve->kve_type = KVME_TYPE_UNKNOWN;
1390 				break;
1391 			}
1392 			if (lobj != obj)
1393 				VM_OBJECT_UNLOCK(lobj);
1394 
1395 			kve->kve_ref_count = obj->ref_count;
1396 			kve->kve_shadow_count = obj->shadow_count;
1397 			VM_OBJECT_UNLOCK(obj);
1398 			if (vp != NULL) {
1399 				vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1400 				vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1401 				vn_fullpath(curthread, vp, &fullpath,
1402 				    &freepath);
1403 				vput(vp);
1404 				VFS_UNLOCK_GIANT(vfslocked);
1405 			}
1406 		} else {
1407 			kve->kve_type = KVME_TYPE_NONE;
1408 			kve->kve_ref_count = 0;
1409 			kve->kve_shadow_count = 0;
1410 		}
1411 
1412 		kve->kve_start = (void*)entry->start;
1413 		kve->kve_end = (void*)entry->end;
1414 
1415 		if (entry->protection & VM_PROT_READ)
1416 			kve->kve_protection |= KVME_PROT_READ;
1417 		if (entry->protection & VM_PROT_WRITE)
1418 			kve->kve_protection |= KVME_PROT_WRITE;
1419 		if (entry->protection & VM_PROT_EXECUTE)
1420 			kve->kve_protection |= KVME_PROT_EXEC;
1421 
1422 		if (entry->eflags & MAP_ENTRY_COW)
1423 			kve->kve_flags |= KVME_FLAG_COW;
1424 		if (entry->eflags & MAP_ENTRY_NEEDS_COPY)
1425 			kve->kve_flags |= KVME_FLAG_NEEDS_COPY;
1426 
1427 		strlcpy(kve->kve_path, fullpath, sizeof(kve->kve_path));
1428 		if (freepath != NULL)
1429 			free(freepath, M_TEMP);
1430 
1431 		last_timestamp = map->timestamp;
1432 		vm_map_unlock_read(map);
1433 		error = SYSCTL_OUT(req, kve, sizeof(*kve));
1434 		vm_map_lock_read(map);
1435 		if (error)
1436 			break;
1437 		if (last_timestamp + 1 != map->timestamp) {
1438 			vm_map_lookup_entry(map, addr - 1, &tmp_entry);
1439 			entry = tmp_entry;
1440 		}
1441 	}
1442 	vm_map_unlock_read(map);
1443 	PRELE(p);
1444 	free(kve, M_TEMP);
1445 	return (error);
1446 }
1447 
1448 #if defined(STACK) || defined(DDB)
1449 static int
1450 sysctl_kern_proc_kstack(SYSCTL_HANDLER_ARGS)
1451 {
1452 	struct kinfo_kstack *kkstp;
1453 	int error, i, *name, numthreads;
1454 	lwpid_t *lwpidarray;
1455 	struct thread *td;
1456 	struct stack *st;
1457 	struct sbuf sb;
1458 	struct proc *p;
1459 
1460 	name = (int *)arg1;
1461 	if ((p = pfind((pid_t)name[0])) == NULL)
1462 		return (ESRCH);
1463 	/* XXXRW: Not clear ESRCH is the right error during proc execve(). */
1464 	if (p->p_flag & P_WEXIT || p->p_flag & P_INEXEC) {
1465 		PROC_UNLOCK(p);
1466 		return (ESRCH);
1467 	}
1468 	if ((error = p_candebug(curthread, p))) {
1469 		PROC_UNLOCK(p);
1470 		return (error);
1471 	}
1472 	_PHOLD(p);
1473 	PROC_UNLOCK(p);
1474 
1475 	kkstp = malloc(sizeof(*kkstp), M_TEMP, M_WAITOK);
1476 	st = stack_create();
1477 
1478 	lwpidarray = NULL;
1479 	numthreads = 0;
1480 	PROC_LOCK(p);
1481 repeat:
1482 	if (numthreads < p->p_numthreads) {
1483 		if (lwpidarray != NULL) {
1484 			free(lwpidarray, M_TEMP);
1485 			lwpidarray = NULL;
1486 		}
1487 		numthreads = p->p_numthreads;
1488 		PROC_UNLOCK(p);
1489 		lwpidarray = malloc(sizeof(*lwpidarray) * numthreads, M_TEMP,
1490 		    M_WAITOK | M_ZERO);
1491 		PROC_LOCK(p);
1492 		goto repeat;
1493 	}
1494 	i = 0;
1495 
1496 	/*
1497 	 * XXXRW: During the below loop, execve(2) and countless other sorts
1498 	 * of changes could have taken place.  Should we check to see if the
1499 	 * vmspace has been replaced, or the like, in order to prevent
1500 	 * giving a snapshot that spans, say, execve(2), with some threads
1501 	 * before and some after?  Among other things, the credentials could
1502 	 * have changed, in which case the right to extract debug info might
1503 	 * no longer be assured.
1504 	 */
1505 	FOREACH_THREAD_IN_PROC(p, td) {
1506 		KASSERT(i < numthreads,
1507 		    ("sysctl_kern_proc_kstack: numthreads"));
1508 		lwpidarray[i] = td->td_tid;
1509 		i++;
1510 	}
1511 	numthreads = i;
1512 	for (i = 0; i < numthreads; i++) {
1513 		td = thread_find(p, lwpidarray[i]);
1514 		if (td == NULL) {
1515 			continue;
1516 		}
1517 		bzero(kkstp, sizeof(*kkstp));
1518 		(void)sbuf_new(&sb, kkstp->kkst_trace,
1519 		    sizeof(kkstp->kkst_trace), SBUF_FIXEDLEN);
1520 		thread_lock(td);
1521 		kkstp->kkst_tid = td->td_tid;
1522 		if (TD_IS_SWAPPED(td))
1523 			kkstp->kkst_state = KKST_STATE_SWAPPED;
1524 		else if (TD_IS_RUNNING(td))
1525 			kkstp->kkst_state = KKST_STATE_RUNNING;
1526 		else {
1527 			kkstp->kkst_state = KKST_STATE_STACKOK;
1528 			stack_save_td(st, td);
1529 		}
1530 		thread_unlock(td);
1531 		PROC_UNLOCK(p);
1532 		stack_sbuf_print(&sb, st);
1533 		sbuf_finish(&sb);
1534 		sbuf_delete(&sb);
1535 		error = SYSCTL_OUT(req, kkstp, sizeof(*kkstp));
1536 		PROC_LOCK(p);
1537 		if (error)
1538 			break;
1539 	}
1540 	_PRELE(p);
1541 	PROC_UNLOCK(p);
1542 	if (lwpidarray != NULL)
1543 		free(lwpidarray, M_TEMP);
1544 	stack_destroy(st);
1545 	free(kkstp, M_TEMP);
1546 	return (error);
1547 }
1548 #endif
1549 
1550 SYSCTL_NODE(_kern, KERN_PROC, proc, CTLFLAG_RD,  0, "Process table");
1551 
1552 SYSCTL_PROC(_kern_proc, KERN_PROC_ALL, all, CTLFLAG_RD|CTLTYPE_STRUCT,
1553 	0, 0, sysctl_kern_proc, "S,proc", "Return entire process table");
1554 
1555 static SYSCTL_NODE(_kern_proc, KERN_PROC_GID, gid, CTLFLAG_RD,
1556 	sysctl_kern_proc, "Process table");
1557 
1558 static SYSCTL_NODE(_kern_proc, KERN_PROC_PGRP, pgrp, CTLFLAG_RD,
1559 	sysctl_kern_proc, "Process table");
1560 
1561 static SYSCTL_NODE(_kern_proc, KERN_PROC_RGID, rgid, CTLFLAG_RD,
1562 	sysctl_kern_proc, "Process table");
1563 
1564 static SYSCTL_NODE(_kern_proc, KERN_PROC_SESSION, sid, CTLFLAG_RD,
1565 	sysctl_kern_proc, "Process table");
1566 
1567 static SYSCTL_NODE(_kern_proc, KERN_PROC_TTY, tty, CTLFLAG_RD,
1568 	sysctl_kern_proc, "Process table");
1569 
1570 static SYSCTL_NODE(_kern_proc, KERN_PROC_UID, uid, CTLFLAG_RD,
1571 	sysctl_kern_proc, "Process table");
1572 
1573 static SYSCTL_NODE(_kern_proc, KERN_PROC_RUID, ruid, CTLFLAG_RD,
1574 	sysctl_kern_proc, "Process table");
1575 
1576 static SYSCTL_NODE(_kern_proc, KERN_PROC_PID, pid, CTLFLAG_RD,
1577 	sysctl_kern_proc, "Process table");
1578 
1579 static SYSCTL_NODE(_kern_proc, KERN_PROC_PROC, proc, CTLFLAG_RD,
1580 	sysctl_kern_proc, "Return process table, no threads");
1581 
1582 static SYSCTL_NODE(_kern_proc, KERN_PROC_ARGS, args,
1583 	CTLFLAG_RW | CTLFLAG_ANYBODY,
1584 	sysctl_kern_proc_args, "Process argument list");
1585 
1586 static SYSCTL_NODE(_kern_proc, KERN_PROC_PATHNAME, pathname, CTLFLAG_RD,
1587 	sysctl_kern_proc_pathname, "Process executable path");
1588 
1589 static SYSCTL_NODE(_kern_proc, KERN_PROC_SV_NAME, sv_name, CTLFLAG_RD,
1590 	sysctl_kern_proc_sv_name, "Process syscall vector name (ABI type)");
1591 
1592 static SYSCTL_NODE(_kern_proc, (KERN_PROC_GID | KERN_PROC_INC_THREAD), gid_td,
1593 	CTLFLAG_RD, sysctl_kern_proc, "Process table");
1594 
1595 static SYSCTL_NODE(_kern_proc, (KERN_PROC_PGRP | KERN_PROC_INC_THREAD), pgrp_td,
1596 	CTLFLAG_RD, sysctl_kern_proc, "Process table");
1597 
1598 static SYSCTL_NODE(_kern_proc, (KERN_PROC_RGID | KERN_PROC_INC_THREAD), rgid_td,
1599 	CTLFLAG_RD, sysctl_kern_proc, "Process table");
1600 
1601 static SYSCTL_NODE(_kern_proc, (KERN_PROC_SESSION | KERN_PROC_INC_THREAD),
1602 	sid_td, CTLFLAG_RD, sysctl_kern_proc, "Process table");
1603 
1604 static SYSCTL_NODE(_kern_proc, (KERN_PROC_TTY | KERN_PROC_INC_THREAD), tty_td,
1605 	CTLFLAG_RD, sysctl_kern_proc, "Process table");
1606 
1607 static SYSCTL_NODE(_kern_proc, (KERN_PROC_UID | KERN_PROC_INC_THREAD), uid_td,
1608 	CTLFLAG_RD, sysctl_kern_proc, "Process table");
1609 
1610 static SYSCTL_NODE(_kern_proc, (KERN_PROC_RUID | KERN_PROC_INC_THREAD), ruid_td,
1611 	CTLFLAG_RD, sysctl_kern_proc, "Process table");
1612 
1613 static SYSCTL_NODE(_kern_proc, (KERN_PROC_PID | KERN_PROC_INC_THREAD), pid_td,
1614 	CTLFLAG_RD, sysctl_kern_proc, "Process table");
1615 
1616 static SYSCTL_NODE(_kern_proc, (KERN_PROC_PROC | KERN_PROC_INC_THREAD), proc_td,
1617 	CTLFLAG_RD, sysctl_kern_proc, "Return process table, no threads");
1618 
1619 static SYSCTL_NODE(_kern_proc, KERN_PROC_VMMAP, vmmap, CTLFLAG_RD,
1620 	sysctl_kern_proc_vmmap, "Process vm map entries");
1621 
1622 #if defined(STACK) || defined(DDB)
1623 static SYSCTL_NODE(_kern_proc, KERN_PROC_KSTACK, kstack, CTLFLAG_RD,
1624 	sysctl_kern_proc_kstack, "Process kernel stacks");
1625 #endif
1626