xref: /dragonfly/sys/kern/kern_proc.c (revision 0bb9290e)
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. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *	@(#)kern_proc.c	8.7 (Berkeley) 2/14/95
34  * $FreeBSD: src/sys/kern/kern_proc.c,v 1.63.2.9 2003/05/08 07:47:16 kbyanc Exp $
35  * $DragonFly: src/sys/kern/kern_proc.c,v 1.25 2006/05/24 18:59:48 dillon Exp $
36  */
37 
38 #include <sys/param.h>
39 #include <sys/systm.h>
40 #include <sys/kernel.h>
41 #include <sys/sysctl.h>
42 #include <sys/malloc.h>
43 #include <sys/proc.h>
44 #include <sys/jail.h>
45 #include <sys/filedesc.h>
46 #include <sys/tty.h>
47 #include <sys/signalvar.h>
48 #include <sys/spinlock.h>
49 #include <vm/vm.h>
50 #include <sys/lock.h>
51 #include <vm/pmap.h>
52 #include <vm/vm_map.h>
53 #include <sys/user.h>
54 #include <vm/vm_zone.h>
55 #include <machine/smp.h>
56 
57 #include <sys/spinlock2.h>
58 
59 static MALLOC_DEFINE(M_PGRP, "pgrp", "process group header");
60 MALLOC_DEFINE(M_SESSION, "session", "session header");
61 static MALLOC_DEFINE(M_PROC, "proc", "Proc structures");
62 MALLOC_DEFINE(M_SUBPROC, "subproc", "Proc sub-structures");
63 
64 int ps_showallprocs = 1;
65 static int ps_showallthreads = 1;
66 SYSCTL_INT(_kern, OID_AUTO, ps_showallprocs, CTLFLAG_RW,
67     &ps_showallprocs, 0, "");
68 SYSCTL_INT(_kern, OID_AUTO, ps_showallthreads, CTLFLAG_RW,
69     &ps_showallthreads, 0, "");
70 
71 static void pgdelete(struct pgrp *);
72 static void orphanpg(struct pgrp *pg);
73 static pid_t proc_getnewpid_locked(int random_offset);
74 
75 /*
76  * Other process lists
77  */
78 struct pidhashhead *pidhashtbl;
79 u_long pidhash;
80 struct pgrphashhead *pgrphashtbl;
81 u_long pgrphash;
82 struct proclist allproc;
83 struct proclist zombproc;
84 struct spinlock allproc_spin;
85 vm_zone_t proc_zone;
86 vm_zone_t thread_zone;
87 
88 /*
89  * Random component to nextpid generation.  We mix in a random factor to make
90  * it a little harder to predict.  We sanity check the modulus value to avoid
91  * doing it in critical paths.  Don't let it be too small or we pointlessly
92  * waste randomness entropy, and don't let it be impossibly large.  Using a
93  * modulus that is too big causes a LOT more process table scans and slows
94  * down fork processing as the pidchecked caching is defeated.
95  */
96 static int randompid = 0;
97 
98 static int
99 sysctl_kern_randompid(SYSCTL_HANDLER_ARGS)
100 {
101 	int error, pid;
102 
103 	pid = randompid;
104 	error = sysctl_handle_int(oidp, &pid, 0, req);
105 	if (error || !req->newptr)
106 		return (error);
107 	if (pid < 0 || pid > PID_MAX - 100)     /* out of range */
108 		pid = PID_MAX - 100;
109 	else if (pid < 2)                       /* NOP */
110 		pid = 0;
111 	else if (pid < 100)                     /* Make it reasonable */
112 		pid = 100;
113 	randompid = pid;
114 	return (error);
115 }
116 
117 SYSCTL_PROC(_kern, OID_AUTO, randompid, CTLTYPE_INT|CTLFLAG_RW,
118 	    0, 0, sysctl_kern_randompid, "I", "Random PID modulus");
119 
120 /*
121  * Initialize global process hashing structures.
122  */
123 void
124 procinit(void)
125 {
126 	LIST_INIT(&allproc);
127 	LIST_INIT(&zombproc);
128 	spin_init(&allproc_spin);
129 	pidhashtbl = hashinit(maxproc / 4, M_PROC, &pidhash);
130 	pgrphashtbl = hashinit(maxproc / 4, M_PROC, &pgrphash);
131 	proc_zone = zinit("PROC", sizeof (struct proc), 0, 0, 5);
132 	thread_zone = zinit("THREAD", sizeof (struct thread), 0, 0, 5);
133 	uihashinit();
134 }
135 
136 /*
137  * Is p an inferior of the current process?
138  */
139 int
140 inferior(struct proc *p)
141 {
142 	for (; p != curproc; p = p->p_pptr)
143 		if (p->p_pid == 0)
144 			return (0);
145 	return (1);
146 }
147 
148 /*
149  * Locate a process by number
150  */
151 struct proc *
152 pfind(pid_t pid)
153 {
154 	struct proc *p;
155 
156 	LIST_FOREACH(p, PIDHASH(pid), p_hash) {
157 		if (p->p_pid == pid)
158 			return (p);
159 	}
160 	return (NULL);
161 }
162 
163 /*
164  * Locate a process group by number
165  */
166 struct pgrp *
167 pgfind(pid_t pgid)
168 {
169 	struct pgrp *pgrp;
170 
171 	LIST_FOREACH(pgrp, PGRPHASH(pgid), pg_hash) {
172 		if (pgrp->pg_id == pgid)
173 			return (pgrp);
174 	}
175 	return (NULL);
176 }
177 
178 /*
179  * Move p to a new or existing process group (and session)
180  */
181 int
182 enterpgrp(struct proc *p, pid_t pgid, int mksess)
183 {
184 	struct pgrp *pgrp = pgfind(pgid);
185 
186 	KASSERT(pgrp == NULL || !mksess,
187 	    ("enterpgrp: setsid into non-empty pgrp"));
188 	KASSERT(!SESS_LEADER(p),
189 	    ("enterpgrp: session leader attempted setpgrp"));
190 
191 	if (pgrp == NULL) {
192 		pid_t savepid = p->p_pid;
193 		struct proc *np;
194 		/*
195 		 * new process group
196 		 */
197 		KASSERT(p->p_pid == pgid,
198 		    ("enterpgrp: new pgrp and pid != pgid"));
199 		if ((np = pfind(savepid)) == NULL || np != p)
200 			return (ESRCH);
201 		MALLOC(pgrp, struct pgrp *, sizeof(struct pgrp), M_PGRP,
202 		    M_WAITOK);
203 		if (mksess) {
204 			struct session *sess;
205 
206 			/*
207 			 * new session
208 			 */
209 			MALLOC(sess, struct session *, sizeof(struct session),
210 			    M_SESSION, M_WAITOK);
211 			sess->s_leader = p;
212 			sess->s_sid = p->p_pid;
213 			sess->s_count = 1;
214 			sess->s_ttyvp = NULL;
215 			sess->s_ttyp = NULL;
216 			bcopy(p->p_session->s_login, sess->s_login,
217 			    sizeof(sess->s_login));
218 			p->p_flag &= ~P_CONTROLT;
219 			pgrp->pg_session = sess;
220 			KASSERT(p == curproc,
221 			    ("enterpgrp: mksession and p != curproc"));
222 		} else {
223 			pgrp->pg_session = p->p_session;
224 			sess_hold(pgrp->pg_session);
225 		}
226 		pgrp->pg_id = pgid;
227 		LIST_INIT(&pgrp->pg_members);
228 		LIST_INSERT_HEAD(PGRPHASH(pgid), pgrp, pg_hash);
229 		pgrp->pg_jobc = 0;
230 		SLIST_INIT(&pgrp->pg_sigiolst);
231 	} else if (pgrp == p->p_pgrp)
232 		return (0);
233 
234 	/*
235 	 * Adjust eligibility of affected pgrps to participate in job control.
236 	 * Increment eligibility counts before decrementing, otherwise we
237 	 * could reach 0 spuriously during the first call.
238 	 */
239 	fixjobc(p, pgrp, 1);
240 	fixjobc(p, p->p_pgrp, 0);
241 
242 	LIST_REMOVE(p, p_pglist);
243 	if (LIST_EMPTY(&p->p_pgrp->pg_members))
244 		pgdelete(p->p_pgrp);
245 	p->p_pgrp = pgrp;
246 	LIST_INSERT_HEAD(&pgrp->pg_members, p, p_pglist);
247 	return (0);
248 }
249 
250 /*
251  * remove process from process group
252  */
253 int
254 leavepgrp(struct proc *p)
255 {
256 
257 	LIST_REMOVE(p, p_pglist);
258 	if (LIST_EMPTY(&p->p_pgrp->pg_members))
259 		pgdelete(p->p_pgrp);
260 	p->p_pgrp = 0;
261 	return (0);
262 }
263 
264 /*
265  * delete a process group
266  */
267 static void
268 pgdelete(struct pgrp *pgrp)
269 {
270 
271 	/*
272 	 * Reset any sigio structures pointing to us as a result of
273 	 * F_SETOWN with our pgid.
274 	 */
275 	funsetownlst(&pgrp->pg_sigiolst);
276 
277 	if (pgrp->pg_session->s_ttyp != NULL &&
278 	    pgrp->pg_session->s_ttyp->t_pgrp == pgrp)
279 		pgrp->pg_session->s_ttyp->t_pgrp = NULL;
280 	LIST_REMOVE(pgrp, pg_hash);
281 	sess_rele(pgrp->pg_session);
282 	free(pgrp, M_PGRP);
283 }
284 
285 /*
286  * Adjust the ref count on a session structure.  When the ref count falls to
287  * zero the tty is disassociated from the session and the session structure
288  * is freed.  Note that tty assocation is not itself ref-counted.
289  */
290 void
291 sess_hold(struct session *sp)
292 {
293 	++sp->s_count;
294 }
295 
296 void
297 sess_rele(struct session *sp)
298 {
299 	KKASSERT(sp->s_count > 0);
300 	if (--sp->s_count == 0) {
301 		if (sp->s_ttyp && sp->s_ttyp->t_session) {
302 #ifdef TTY_DO_FULL_CLOSE
303 			/* FULL CLOSE, see ttyclearsession() */
304 			KKASSERT(sp->s_ttyp->t_session == sp);
305 			sp->s_ttyp->t_session = NULL;
306 #else
307 			/* HALF CLOSE, see ttyclearsession() */
308 			if (sp->s_ttyp->t_session == sp)
309 				sp->s_ttyp->t_session = NULL;
310 #endif
311 		}
312 		free(sp, M_SESSION);
313 	}
314 }
315 
316 /*
317  * Adjust pgrp jobc counters when specified process changes process group.
318  * We count the number of processes in each process group that "qualify"
319  * the group for terminal job control (those with a parent in a different
320  * process group of the same session).  If that count reaches zero, the
321  * process group becomes orphaned.  Check both the specified process'
322  * process group and that of its children.
323  * entering == 0 => p is leaving specified group.
324  * entering == 1 => p is entering specified group.
325  */
326 void
327 fixjobc(struct proc *p, struct pgrp *pgrp, int entering)
328 {
329 	struct pgrp *hispgrp;
330 	struct session *mysession = pgrp->pg_session;
331 
332 	/*
333 	 * Check p's parent to see whether p qualifies its own process
334 	 * group; if so, adjust count for p's process group.
335 	 */
336 	if ((hispgrp = p->p_pptr->p_pgrp) != pgrp &&
337 	    hispgrp->pg_session == mysession) {
338 		if (entering)
339 			pgrp->pg_jobc++;
340 		else if (--pgrp->pg_jobc == 0)
341 			orphanpg(pgrp);
342 	}
343 
344 	/*
345 	 * Check this process' children to see whether they qualify
346 	 * their process groups; if so, adjust counts for children's
347 	 * process groups.
348 	 */
349 	LIST_FOREACH(p, &p->p_children, p_sibling)
350 		if ((hispgrp = p->p_pgrp) != pgrp &&
351 		    hispgrp->pg_session == mysession &&
352 		    (p->p_flag & P_ZOMBIE) == 0) {
353 			if (entering)
354 				hispgrp->pg_jobc++;
355 			else if (--hispgrp->pg_jobc == 0)
356 				orphanpg(hispgrp);
357 		}
358 }
359 
360 /*
361  * A process group has become orphaned;
362  * if there are any stopped processes in the group,
363  * hang-up all process in that group.
364  */
365 static void
366 orphanpg(struct pgrp *pg)
367 {
368 	struct proc *p;
369 
370 	LIST_FOREACH(p, &pg->pg_members, p_pglist) {
371 		if (p->p_flag & P_STOPPED) {
372 			LIST_FOREACH(p, &pg->pg_members, p_pglist) {
373 				psignal(p, SIGHUP);
374 				psignal(p, SIGCONT);
375 			}
376 			return;
377 		}
378 	}
379 }
380 
381 /*
382  * Add a new process to the allproc list and the PID hash.  This
383  * also assigns a pid to the new process.
384  *
385  * MPALMOSTSAFE - acquires mplock for arc4random() call
386  */
387 void
388 proc_add_allproc(struct proc *p)
389 {
390 	int random_offset;
391 
392 	if ((random_offset = randompid) != 0) {
393 		get_mplock();
394 		random_offset = arc4random() % random_offset;
395 		rel_mplock();
396 	}
397 
398 	spin_lock_wr(&allproc_spin);
399 	p->p_pid = proc_getnewpid_locked(random_offset);
400 	LIST_INSERT_HEAD(&allproc, p, p_list);
401 	LIST_INSERT_HEAD(PIDHASH(p->p_pid), p, p_hash);
402 	spin_unlock_wr(&allproc_spin);
403 }
404 
405 /*
406  * Calculate a new process pid.  This function is integrated into
407  * proc_add_allproc() to guarentee that the new pid is not reused before
408  * the new process can be added to the allproc list.
409  *
410  * MPSAFE - must be called with allproc_spin held.
411  */
412 static
413 pid_t
414 proc_getnewpid_locked(int random_offset)
415 {
416 	static pid_t nextpid;
417 	static pid_t pidchecked;
418 	struct proc *p;
419 
420 	/*
421 	 * Find an unused process ID.  We remember a range of unused IDs
422 	 * ready to use (from nextpid+1 through pidchecked-1).
423 	 */
424 	nextpid = nextpid + 1 + random_offset;
425 retry:
426 	/*
427 	 * If the process ID prototype has wrapped around,
428 	 * restart somewhat above 0, as the low-numbered procs
429 	 * tend to include daemons that don't exit.
430 	 */
431 	if (nextpid >= PID_MAX) {
432 		nextpid = nextpid % PID_MAX;
433 		if (nextpid < 100)
434 			nextpid += 100;
435 		pidchecked = 0;
436 	}
437 	if (nextpid >= pidchecked) {
438 		int doingzomb = 0;
439 
440 		pidchecked = PID_MAX;
441 		/*
442 		 * Scan the active and zombie procs to check whether this pid
443 		 * is in use.  Remember the lowest pid that's greater
444 		 * than nextpid, so we can avoid checking for a while.
445 		 */
446 		p = LIST_FIRST(&allproc);
447 again:
448 		for (; p != 0; p = LIST_NEXT(p, p_list)) {
449 			while (p->p_pid == nextpid ||
450 			    p->p_pgrp->pg_id == nextpid ||
451 			    p->p_session->s_sid == nextpid) {
452 				nextpid++;
453 				if (nextpid >= pidchecked)
454 					goto retry;
455 			}
456 			if (p->p_pid > nextpid && pidchecked > p->p_pid)
457 				pidchecked = p->p_pid;
458 			if (p->p_pgrp->pg_id > nextpid &&
459 			    pidchecked > p->p_pgrp->pg_id)
460 				pidchecked = p->p_pgrp->pg_id;
461 			if (p->p_session->s_sid > nextpid &&
462 			    pidchecked > p->p_session->s_sid)
463 				pidchecked = p->p_session->s_sid;
464 		}
465 		if (!doingzomb) {
466 			doingzomb = 1;
467 			p = LIST_FIRST(&zombproc);
468 			goto again;
469 		}
470 	}
471 	return(nextpid);
472 }
473 
474 /*
475  * Called from exit1 to remove a process from the allproc
476  * list and move it to the zombie list.
477  *
478  * MPSAFE
479  */
480 void
481 proc_move_allproc_zombie(struct proc *p)
482 {
483 	spin_lock_wr(&allproc_spin);
484 	while (p->p_lock) {
485 		spin_unlock_wr(&allproc_spin);
486 		tsleep(p, 0, "reap1", hz / 10);
487 		spin_lock_wr(&allproc_spin);
488 	}
489 	LIST_REMOVE(p, p_list);
490 	LIST_INSERT_HEAD(&zombproc, p, p_list);
491 	LIST_REMOVE(p, p_hash);
492 	p->p_flag |= P_ZOMBIE;
493 	spin_unlock_wr(&allproc_spin);
494 }
495 
496 /*
497  * This routine is called from kern_wait() and will remove the process
498  * from the zombie list and the sibling list.  This routine will block
499  * if someone has a lock on the proces (p_lock).
500  *
501  * MPSAFE
502  */
503 void
504 proc_remove_zombie(struct proc *p)
505 {
506 	spin_lock_wr(&allproc_spin);
507 	while (p->p_lock) {
508 		spin_unlock_wr(&allproc_spin);
509 		tsleep(p, 0, "reap1", hz / 10);
510 		spin_lock_wr(&allproc_spin);
511 	}
512 	LIST_REMOVE(p, p_list); /* off zombproc */
513 	LIST_REMOVE(p, p_sibling);
514 	spin_unlock_wr(&allproc_spin);
515 }
516 
517 /*
518  * Scan all processes on the allproc list.  The process is automatically
519  * held for the callback.  A return value of -1 terminates the loop.
520  *
521  * MPSAFE
522  */
523 void
524 allproc_scan(int (*callback)(struct proc *, void *), void *data)
525 {
526 	struct proc *p;
527 	int r;
528 
529 	spin_lock_rd(&allproc_spin);
530 	LIST_FOREACH(p, &allproc, p_list) {
531 		PHOLD(p);
532 		spin_unlock_rd(&allproc_spin);
533 		r = callback(p, data);
534 		spin_lock_rd(&allproc_spin);
535 		PRELE(p);
536 		if (r < 0)
537 			break;
538 	}
539 	spin_unlock_rd(&allproc_spin);
540 }
541 
542 /*
543  * Scan all processes on the zombproc list.  The process is automatically
544  * held for the callback.  A return value of -1 terminates the loop.
545  *
546  * MPSAFE
547  */
548 void
549 zombproc_scan(int (*callback)(struct proc *, void *), void *data)
550 {
551 	struct proc *p;
552 	int r;
553 
554 	spin_lock_rd(&allproc_spin);
555 	LIST_FOREACH(p, &zombproc, p_list) {
556 		PHOLD(p);
557 		spin_unlock_rd(&allproc_spin);
558 		r = callback(p, data);
559 		spin_lock_rd(&allproc_spin);
560 		PRELE(p);
561 		if (r < 0)
562 			break;
563 	}
564 	spin_unlock_rd(&allproc_spin);
565 }
566 
567 #include "opt_ddb.h"
568 #ifdef DDB
569 #include <ddb/ddb.h>
570 
571 DB_SHOW_COMMAND(pgrpdump, pgrpdump)
572 {
573 	struct pgrp *pgrp;
574 	struct proc *p;
575 	int i;
576 
577 	for (i = 0; i <= pgrphash; i++) {
578 		if (!LIST_EMPTY(&pgrphashtbl[i])) {
579 			printf("\tindx %d\n", i);
580 			LIST_FOREACH(pgrp, &pgrphashtbl[i], pg_hash) {
581 				printf(
582 			"\tpgrp %p, pgid %ld, sess %p, sesscnt %d, mem %p\n",
583 				    (void *)pgrp, (long)pgrp->pg_id,
584 				    (void *)pgrp->pg_session,
585 				    pgrp->pg_session->s_count,
586 				    (void *)LIST_FIRST(&pgrp->pg_members));
587 				LIST_FOREACH(p, &pgrp->pg_members, p_pglist) {
588 					printf("\t\tpid %ld addr %p pgrp %p\n",
589 					    (long)p->p_pid, (void *)p,
590 					    (void *)p->p_pgrp);
591 				}
592 			}
593 		}
594 	}
595 }
596 #endif /* DDB */
597 
598 /*
599  * Fill in an eproc structure for the specified thread.
600  */
601 void
602 fill_eproc_td(thread_t td, struct eproc *ep, struct proc *xp)
603 {
604 	bzero(ep, sizeof(*ep));
605 
606 	ep->e_uticks = td->td_uticks;
607 	ep->e_sticks = td->td_sticks;
608 	ep->e_iticks = td->td_iticks;
609 	ep->e_tdev = NOUDEV;
610 	ep->e_cpuid = td->td_gd->gd_cpuid;
611 	if (td->td_wmesg) {
612 		strncpy(ep->e_wmesg, td->td_wmesg, WMESGLEN);
613 		ep->e_wmesg[WMESGLEN] = 0;
614 	}
615 
616 	/*
617 	 * Fake up portions of the proc structure copied out by the sysctl
618 	 * to return useful information.  Note that using td_pri directly
619 	 * is messy because it includes critial section data so we fake
620 	 * up an rtprio.prio for threads.
621 	 */
622 	if (xp) {
623 		*xp = *initproc;
624 		xp->p_rtprio.type = RTP_PRIO_THREAD;
625 		xp->p_rtprio.prio = td->td_pri & TDPRI_MASK;
626 		xp->p_pid = -1;
627 	}
628 }
629 
630 /*
631  * Fill in an eproc structure for the specified process.
632  */
633 void
634 fill_eproc(struct proc *p, struct eproc *ep)
635 {
636 	struct tty *tp;
637 
638 	fill_eproc_td(p->p_thread, ep, NULL);
639 
640 	ep->e_paddr = p;
641 	if (p->p_ucred) {
642 		ep->e_ucred = *p->p_ucred;
643 	}
644 	if (p->p_procsig) {
645 		ep->e_procsig = *p->p_procsig;
646 	}
647 	if (p->p_stat != SIDL && (p->p_flag & P_ZOMBIE) == 0 &&
648 	    p->p_vmspace != NULL) {
649 		struct vmspace *vm = p->p_vmspace;
650 		ep->e_vm = *vm;
651 		ep->e_vm.vm_rssize = vmspace_resident_count(vm); /*XXX*/
652 	}
653 	if ((p->p_flag & P_SWAPPEDOUT) == 0 && p->p_stats)
654 		ep->e_stats = *p->p_stats;
655 	if (p->p_pptr)
656 		ep->e_ppid = p->p_pptr->p_pid;
657 	if (p->p_pgrp) {
658 		ep->e_pgid = p->p_pgrp->pg_id;
659 		ep->e_jobc = p->p_pgrp->pg_jobc;
660 		ep->e_sess = p->p_pgrp->pg_session;
661 
662 		if (ep->e_sess) {
663 			bcopy(ep->e_sess->s_login, ep->e_login, sizeof(ep->e_login));
664 			if (ep->e_sess->s_ttyvp)
665 				ep->e_flag = EPROC_CTTY;
666 			if (p->p_session && SESS_LEADER(p))
667 				ep->e_flag |= EPROC_SLEADER;
668 		}
669 	}
670 	if ((p->p_flag & P_CONTROLT) &&
671 	    (ep->e_sess != NULL) &&
672 	    ((tp = ep->e_sess->s_ttyp) != NULL)) {
673 		ep->e_tdev = dev2udev(tp->t_dev);
674 		ep->e_tpgid = tp->t_pgrp ? tp->t_pgrp->pg_id : NO_PID;
675 		ep->e_tsess = tp->t_session;
676 	} else {
677 		ep->e_tdev = NOUDEV;
678 	}
679 	if (p->p_ucred->cr_prison)
680 		ep->e_jailid = p->p_ucred->cr_prison->pr_id;
681 }
682 
683 /*
684  * Locate a process on the zombie list.  Return a held process or NULL.
685  */
686 struct proc *
687 zpfind(pid_t pid)
688 {
689 	struct proc *p;
690 
691 	LIST_FOREACH(p, &zombproc, p_list)
692 		if (p->p_pid == pid)
693 			return (p);
694 	return (NULL);
695 }
696 
697 static int
698 sysctl_out_proc(struct proc *p, struct thread *td, struct sysctl_req *req, int doingzomb)
699 {
700 	struct eproc eproc;
701 	struct proc xproc;
702 	int error;
703 #if 0
704 	pid_t pid = p->p_pid;
705 #endif
706 
707 	if (p) {
708 		td = p->p_thread;
709 		fill_eproc(p, &eproc);
710 		xproc = *p;
711 
712 		/*
713 		 * p_stat fixup.  If we are in a thread sleep mark p_stat
714 		 * as sleeping if the thread is blocked.
715 		 */
716 		if (p->p_stat == SRUN && td && (td->td_flags & TDF_BLOCKED)) {
717 			xproc.p_stat = SSLEEP;
718 		}
719 		/*
720 		 * If the process is being stopped but is in a normal tsleep,
721 		 * mark it as being SSTOP.
722 		 */
723 		if (p->p_stat == SSLEEP && (p->p_flag & P_STOPPED))
724 			xproc.p_stat = SSTOP;
725 		if (p->p_flag & P_ZOMBIE)
726 			xproc.p_stat = SZOMB;
727 	} else if (td) {
728 		fill_eproc_td(td, &eproc, &xproc);
729 	}
730 	error = SYSCTL_OUT(req,(caddr_t)&xproc, sizeof(struct proc));
731 	if (error)
732 		return (error);
733 	error = SYSCTL_OUT(req,(caddr_t)&eproc, sizeof(eproc));
734 	if (error)
735 		return (error);
736 	error = SYSCTL_OUT(req,(caddr_t)td, sizeof(struct thread));
737 	if (error)
738 		return (error);
739 #if 0
740 	if (!doingzomb && pid && (pfind(pid) != p))
741 		return EAGAIN;
742 	if (doingzomb && zpfind(pid) != p)
743 		return EAGAIN;
744 #endif
745 	return (0);
746 }
747 
748 static int
749 sysctl_kern_proc(SYSCTL_HANDLER_ARGS)
750 {
751 	int *name = (int*) arg1;
752 	u_int namelen = arg2;
753 	struct proc *p;
754 	struct thread *td;
755 	int doingzomb;
756 	int error = 0;
757 	int n;
758 	int origcpu;
759 	struct ucred *cr1 = curproc->p_ucred;
760 
761 	if (oidp->oid_number == KERN_PROC_PID) {
762 		if (namelen != 1)
763 			return (EINVAL);
764 		p = pfind((pid_t)name[0]);
765 		if (!p)
766 			return (0);
767 		if (!PRISON_CHECK(cr1, p->p_ucred))
768 			return (0);
769 		error = sysctl_out_proc(p, NULL, req, 0);
770 		return (error);
771 	}
772 	if (oidp->oid_number == KERN_PROC_ALL && !namelen)
773 		;
774 	else if (oidp->oid_number != KERN_PROC_ALL && namelen == 1)
775 		;
776 	else
777 		return (EINVAL);
778 
779 	if (!req->oldptr) {
780 		/* overestimate by 5 procs */
781 		error = SYSCTL_OUT(req, 0, sizeof (struct kinfo_proc) * 5);
782 		if (error)
783 			return (error);
784 	}
785 	for (doingzomb=0 ; doingzomb < 2 ; doingzomb++) {
786 		if (!doingzomb)
787 			p = LIST_FIRST(&allproc);
788 		else
789 			p = LIST_FIRST(&zombproc);
790 		for (; p != 0; p = LIST_NEXT(p, p_list)) {
791 			/*
792 			 * Show a user only their processes.
793 			 */
794 			if ((!ps_showallprocs) && p_trespass(cr1, p->p_ucred))
795 				continue;
796 			/*
797 			 * Skip embryonic processes.
798 			 */
799 			if (p->p_stat == SIDL)
800 				continue;
801 			/*
802 			 * TODO - make more efficient (see notes below).
803 			 * do by session.
804 			 */
805 			switch (oidp->oid_number) {
806 			case KERN_PROC_PGRP:
807 				/* could do this by traversing pgrp */
808 				if (p->p_pgrp == NULL ||
809 				    p->p_pgrp->pg_id != (pid_t)name[0])
810 					continue;
811 				break;
812 
813 			case KERN_PROC_TTY:
814 				if ((p->p_flag & P_CONTROLT) == 0 ||
815 				    p->p_session == NULL ||
816 				    p->p_session->s_ttyp == NULL ||
817 				    dev2udev(p->p_session->s_ttyp->t_dev) !=
818 					(udev_t)name[0])
819 					continue;
820 				break;
821 
822 			case KERN_PROC_UID:
823 				if (p->p_ucred == NULL ||
824 				    p->p_ucred->cr_uid != (uid_t)name[0])
825 					continue;
826 				break;
827 
828 			case KERN_PROC_RUID:
829 				if (p->p_ucred == NULL ||
830 				    p->p_ucred->cr_ruid != (uid_t)name[0])
831 					continue;
832 				break;
833 			}
834 
835 			if (!PRISON_CHECK(cr1, p->p_ucred))
836 				continue;
837 			PHOLD(p);
838 			error = sysctl_out_proc(p, NULL, req, doingzomb);
839 			PRELE(p);
840 			if (error)
841 				return (error);
842 		}
843 	}
844 
845 	/*
846 	 * Iterate over all active cpus and scan their thread list.  Start
847 	 * with the next logical cpu and end with our original cpu.  We
848 	 * migrate our own thread to each target cpu in order to safely scan
849 	 * its thread list.  In the last loop we migrate back to our original
850 	 * cpu.
851 	 */
852 	origcpu = mycpu->gd_cpuid;
853 	if (!ps_showallthreads || jailed(cr1))
854 		goto post_threads;
855 	for (n = 1; n <= ncpus; ++n) {
856 		globaldata_t rgd;
857 		int nid;
858 
859 		nid = (origcpu + n) % ncpus;
860 		if ((smp_active_mask & (1 << nid)) == 0)
861 			continue;
862 		rgd = globaldata_find(nid);
863 		lwkt_setcpu_self(rgd);
864 
865 		TAILQ_FOREACH(td, &mycpu->gd_tdallq, td_allq) {
866 			if (td->td_proc)
867 				continue;
868 			switch (oidp->oid_number) {
869 			case KERN_PROC_PGRP:
870 			case KERN_PROC_TTY:
871 			case KERN_PROC_UID:
872 			case KERN_PROC_RUID:
873 				continue;
874 			default:
875 				break;
876 			}
877 			lwkt_hold(td);
878 			error = sysctl_out_proc(NULL, td, req, doingzomb);
879 			lwkt_rele(td);
880 			if (error)
881 				return (error);
882 		}
883 	}
884 post_threads:
885 	return (0);
886 }
887 
888 /*
889  * This sysctl allows a process to retrieve the argument list or process
890  * title for another process without groping around in the address space
891  * of the other process.  It also allow a process to set its own "process
892  * title to a string of its own choice.
893  */
894 static int
895 sysctl_kern_proc_args(SYSCTL_HANDLER_ARGS)
896 {
897 	int *name = (int*) arg1;
898 	u_int namelen = arg2;
899 	struct proc *p;
900 	struct pargs *pa;
901 	int error = 0;
902 	struct ucred *cr1 = curproc->p_ucred;
903 
904 	if (namelen != 1)
905 		return (EINVAL);
906 
907 	p = pfind((pid_t)name[0]);
908 	if (!p)
909 		return (0);
910 
911 	if ((!ps_argsopen) && p_trespass(cr1, p->p_ucred))
912 		return (0);
913 
914 	if (req->newptr && curproc != p)
915 		return (EPERM);
916 
917 	if (req->oldptr && p->p_args != NULL)
918 		error = SYSCTL_OUT(req, p->p_args->ar_args, p->p_args->ar_length);
919 	if (req->newptr == NULL)
920 		return (error);
921 
922 	if (p->p_args && --p->p_args->ar_ref == 0)
923 		FREE(p->p_args, M_PARGS);
924 	p->p_args = NULL;
925 
926 	if (req->newlen + sizeof(struct pargs) > ps_arg_cache_limit)
927 		return (error);
928 
929 	MALLOC(pa, struct pargs *, sizeof(struct pargs) + req->newlen,
930 	    M_PARGS, M_WAITOK);
931 	pa->ar_ref = 1;
932 	pa->ar_length = req->newlen;
933 	error = SYSCTL_IN(req, pa->ar_args, req->newlen);
934 	if (!error)
935 		p->p_args = pa;
936 	else
937 		FREE(pa, M_PARGS);
938 	return (error);
939 }
940 
941 SYSCTL_NODE(_kern, KERN_PROC, proc, CTLFLAG_RD,  0, "Process table");
942 
943 SYSCTL_PROC(_kern_proc, KERN_PROC_ALL, all, CTLFLAG_RD|CTLTYPE_STRUCT,
944 	0, 0, sysctl_kern_proc, "S,proc", "Return entire process table");
945 
946 SYSCTL_NODE(_kern_proc, KERN_PROC_PGRP, pgrp, CTLFLAG_RD,
947 	sysctl_kern_proc, "Process table");
948 
949 SYSCTL_NODE(_kern_proc, KERN_PROC_TTY, tty, CTLFLAG_RD,
950 	sysctl_kern_proc, "Process table");
951 
952 SYSCTL_NODE(_kern_proc, KERN_PROC_UID, uid, CTLFLAG_RD,
953 	sysctl_kern_proc, "Process table");
954 
955 SYSCTL_NODE(_kern_proc, KERN_PROC_RUID, ruid, CTLFLAG_RD,
956 	sysctl_kern_proc, "Process table");
957 
958 SYSCTL_NODE(_kern_proc, KERN_PROC_PID, pid, CTLFLAG_RD,
959 	sysctl_kern_proc, "Process table");
960 
961 SYSCTL_NODE(_kern_proc, KERN_PROC_ARGS, args, CTLFLAG_RW | CTLFLAG_ANYBODY,
962 	sysctl_kern_proc_args, "Process argument list");
963