xref: /dflybsd-src/sys/kern/kern_proc.c (revision 6693db176654a0f25095ec64d0a74d58dcf0e47e)
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.45 2008/06/12 23:25:02 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 <machine/smp.h>
55 
56 #include <sys/spinlock2.h>
57 #include <sys/mplock2.h>
58 
59 static MALLOC_DEFINE(M_PGRP, "pgrp", "process group header");
60 MALLOC_DEFINE(M_SESSION, "session", "session header");
61 MALLOC_DEFINE(M_PROC, "proc", "Proc structures");
62 MALLOC_DEFINE(M_LWP, "lwp", "lwp structures");
63 MALLOC_DEFINE(M_SUBPROC, "subproc", "Proc sub-structures");
64 
65 int ps_showallprocs = 1;
66 static int ps_showallthreads = 1;
67 SYSCTL_INT(_security, OID_AUTO, ps_showallprocs, CTLFLAG_RW,
68     &ps_showallprocs, 0,
69     "Unprivileged processes can see proccesses with different UID/GID");
70 SYSCTL_INT(_security, OID_AUTO, ps_showallthreads, CTLFLAG_RW,
71     &ps_showallthreads, 0,
72     "Unprivileged processes can see kernel threads");
73 
74 static void pgdelete(struct pgrp *);
75 static void orphanpg(struct pgrp *pg);
76 static pid_t proc_getnewpid_locked(int random_offset);
77 
78 /*
79  * Other process lists
80  */
81 struct pidhashhead *pidhashtbl;
82 u_long pidhash;
83 struct pgrphashhead *pgrphashtbl;
84 u_long pgrphash;
85 struct proclist allproc;
86 struct proclist zombproc;
87 struct spinlock allproc_spin;
88 
89 /*
90  * Random component to nextpid generation.  We mix in a random factor to make
91  * it a little harder to predict.  We sanity check the modulus value to avoid
92  * doing it in critical paths.  Don't let it be too small or we pointlessly
93  * waste randomness entropy, and don't let it be impossibly large.  Using a
94  * modulus that is too big causes a LOT more process table scans and slows
95  * down fork processing as the pidchecked caching is defeated.
96  */
97 static int randompid = 0;
98 
99 static int
100 sysctl_kern_randompid(SYSCTL_HANDLER_ARGS)
101 {
102 	int error, pid;
103 
104 	pid = randompid;
105 	error = sysctl_handle_int(oidp, &pid, 0, req);
106 	if (error || !req->newptr)
107 		return (error);
108 	if (pid < 0 || pid > PID_MAX - 100)     /* out of range */
109 		pid = PID_MAX - 100;
110 	else if (pid < 2)                       /* NOP */
111 		pid = 0;
112 	else if (pid < 100)                     /* Make it reasonable */
113 		pid = 100;
114 	randompid = pid;
115 	return (error);
116 }
117 
118 SYSCTL_PROC(_kern, OID_AUTO, randompid, CTLTYPE_INT|CTLFLAG_RW,
119 	    0, 0, sysctl_kern_randompid, "I", "Random PID modulus");
120 
121 /*
122  * Initialize global process hashing structures.
123  */
124 void
125 procinit(void)
126 {
127 	LIST_INIT(&allproc);
128 	LIST_INIT(&zombproc);
129 	spin_init(&allproc_spin);
130 	lwkt_init();
131 	pidhashtbl = hashinit(maxproc / 4, M_PROC, &pidhash);
132 	pgrphashtbl = hashinit(maxproc / 4, M_PROC, &pgrphash);
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 		lockinit(&pgrp->pg_lock, "pgwt", 0, 0);
232 	} else if (pgrp == p->p_pgrp)
233 		return (0);
234 
235 	/*
236 	 * Adjust eligibility of affected pgrps to participate in job control.
237 	 * Increment eligibility counts before decrementing, otherwise we
238 	 * could reach 0 spuriously during the first call.
239 	 */
240 	fixjobc(p, pgrp, 1);
241 	fixjobc(p, p->p_pgrp, 0);
242 
243 	LIST_REMOVE(p, p_pglist);
244 	if (LIST_EMPTY(&p->p_pgrp->pg_members))
245 		pgdelete(p->p_pgrp);
246 	p->p_pgrp = pgrp;
247 	LIST_INSERT_HEAD(&pgrp->pg_members, p, p_pglist);
248 	return (0);
249 }
250 
251 /*
252  * remove process from process group
253  */
254 int
255 leavepgrp(struct proc *p)
256 {
257 
258 	LIST_REMOVE(p, p_pglist);
259 	if (LIST_EMPTY(&p->p_pgrp->pg_members))
260 		pgdelete(p->p_pgrp);
261 	p->p_pgrp = 0;
262 	return (0);
263 }
264 
265 /*
266  * delete a process group
267  */
268 static void
269 pgdelete(struct pgrp *pgrp)
270 {
271 
272 	/*
273 	 * Reset any sigio structures pointing to us as a result of
274 	 * F_SETOWN with our pgid.
275 	 */
276 	funsetownlst(&pgrp->pg_sigiolst);
277 
278 	if (pgrp->pg_session->s_ttyp != NULL &&
279 	    pgrp->pg_session->s_ttyp->t_pgrp == pgrp)
280 		pgrp->pg_session->s_ttyp->t_pgrp = NULL;
281 	LIST_REMOVE(pgrp, pg_hash);
282 	sess_rele(pgrp->pg_session);
283 	kfree(pgrp, M_PGRP);
284 }
285 
286 /*
287  * Adjust the ref count on a session structure.  When the ref count falls to
288  * zero the tty is disassociated from the session and the session structure
289  * is freed.  Note that tty assocation is not itself ref-counted.
290  */
291 void
292 sess_hold(struct session *sp)
293 {
294 	++sp->s_count;
295 }
296 
297 void
298 sess_rele(struct session *sp)
299 {
300 	KKASSERT(sp->s_count > 0);
301 	if (--sp->s_count == 0) {
302 		if (sp->s_ttyp && sp->s_ttyp->t_session) {
303 #ifdef TTY_DO_FULL_CLOSE
304 			/* FULL CLOSE, see ttyclearsession() */
305 			KKASSERT(sp->s_ttyp->t_session == sp);
306 			sp->s_ttyp->t_session = NULL;
307 #else
308 			/* HALF CLOSE, see ttyclearsession() */
309 			if (sp->s_ttyp->t_session == sp)
310 				sp->s_ttyp->t_session = NULL;
311 #endif
312 		}
313 		kfree(sp, M_SESSION);
314 	}
315 }
316 
317 /*
318  * Adjust pgrp jobc counters when specified process changes process group.
319  * We count the number of processes in each process group that "qualify"
320  * the group for terminal job control (those with a parent in a different
321  * process group of the same session).  If that count reaches zero, the
322  * process group becomes orphaned.  Check both the specified process'
323  * process group and that of its children.
324  * entering == 0 => p is leaving specified group.
325  * entering == 1 => p is entering specified group.
326  */
327 void
328 fixjobc(struct proc *p, struct pgrp *pgrp, int entering)
329 {
330 	struct pgrp *hispgrp;
331 	struct session *mysession = pgrp->pg_session;
332 
333 	/*
334 	 * Check p's parent to see whether p qualifies its own process
335 	 * group; if so, adjust count for p's process group.
336 	 */
337 	if ((hispgrp = p->p_pptr->p_pgrp) != pgrp &&
338 	    hispgrp->pg_session == mysession) {
339 		if (entering)
340 			pgrp->pg_jobc++;
341 		else if (--pgrp->pg_jobc == 0)
342 			orphanpg(pgrp);
343 	}
344 
345 	/*
346 	 * Check this process' children to see whether they qualify
347 	 * their process groups; if so, adjust counts for children's
348 	 * process groups.
349 	 */
350 	LIST_FOREACH(p, &p->p_children, p_sibling)
351 		if ((hispgrp = p->p_pgrp) != pgrp &&
352 		    hispgrp->pg_session == mysession &&
353 		    p->p_stat != SZOMB) {
354 			if (entering)
355 				hispgrp->pg_jobc++;
356 			else if (--hispgrp->pg_jobc == 0)
357 				orphanpg(hispgrp);
358 		}
359 }
360 
361 /*
362  * A process group has become orphaned;
363  * if there are any stopped processes in the group,
364  * hang-up all process in that group.
365  */
366 static void
367 orphanpg(struct pgrp *pg)
368 {
369 	struct proc *p;
370 
371 	LIST_FOREACH(p, &pg->pg_members, p_pglist) {
372 		if (p->p_stat == SSTOP) {
373 			LIST_FOREACH(p, &pg->pg_members, p_pglist) {
374 				ksignal(p, SIGHUP);
375 				ksignal(p, SIGCONT);
376 			}
377 			return;
378 		}
379 	}
380 }
381 
382 /*
383  * Add a new process to the allproc list and the PID hash.  This
384  * also assigns a pid to the new process.
385  *
386  * MPALMOSTSAFE - acquires mplock for karc4random() call
387  */
388 void
389 proc_add_allproc(struct proc *p)
390 {
391 	int random_offset;
392 
393 	if ((random_offset = randompid) != 0) {
394 		get_mplock();
395 		random_offset = karc4random() % random_offset;
396 		rel_mplock();
397 	}
398 
399 	spin_lock_wr(&allproc_spin);
400 	p->p_pid = proc_getnewpid_locked(random_offset);
401 	LIST_INSERT_HEAD(&allproc, p, p_list);
402 	LIST_INSERT_HEAD(PIDHASH(p->p_pid), p, p_hash);
403 	spin_unlock_wr(&allproc_spin);
404 }
405 
406 /*
407  * Calculate a new process pid.  This function is integrated into
408  * proc_add_allproc() to guarentee that the new pid is not reused before
409  * the new process can be added to the allproc list.
410  *
411  * MPSAFE - must be called with allproc_spin held.
412  */
413 static
414 pid_t
415 proc_getnewpid_locked(int random_offset)
416 {
417 	static pid_t nextpid;
418 	static pid_t pidchecked;
419 	struct proc *p;
420 
421 	/*
422 	 * Find an unused process ID.  We remember a range of unused IDs
423 	 * ready to use (from nextpid+1 through pidchecked-1).
424 	 */
425 	nextpid = nextpid + 1 + random_offset;
426 retry:
427 	/*
428 	 * If the process ID prototype has wrapped around,
429 	 * restart somewhat above 0, as the low-numbered procs
430 	 * tend to include daemons that don't exit.
431 	 */
432 	if (nextpid >= PID_MAX) {
433 		nextpid = nextpid % PID_MAX;
434 		if (nextpid < 100)
435 			nextpid += 100;
436 		pidchecked = 0;
437 	}
438 	if (nextpid >= pidchecked) {
439 		int doingzomb = 0;
440 
441 		pidchecked = PID_MAX;
442 		/*
443 		 * Scan the active and zombie procs to check whether this pid
444 		 * is in use.  Remember the lowest pid that's greater
445 		 * than nextpid, so we can avoid checking for a while.
446 		 */
447 		p = LIST_FIRST(&allproc);
448 again:
449 		for (; p != 0; p = LIST_NEXT(p, p_list)) {
450 			while (p->p_pid == nextpid ||
451 			    p->p_pgrp->pg_id == nextpid ||
452 			    p->p_session->s_sid == nextpid) {
453 				nextpid++;
454 				if (nextpid >= pidchecked)
455 					goto retry;
456 			}
457 			if (p->p_pid > nextpid && pidchecked > p->p_pid)
458 				pidchecked = p->p_pid;
459 			if (p->p_pgrp->pg_id > nextpid &&
460 			    pidchecked > p->p_pgrp->pg_id)
461 				pidchecked = p->p_pgrp->pg_id;
462 			if (p->p_session->s_sid > nextpid &&
463 			    pidchecked > p->p_session->s_sid)
464 				pidchecked = p->p_session->s_sid;
465 		}
466 		if (!doingzomb) {
467 			doingzomb = 1;
468 			p = LIST_FIRST(&zombproc);
469 			goto again;
470 		}
471 	}
472 	return(nextpid);
473 }
474 
475 /*
476  * Called from exit1 to remove a process from the allproc
477  * list and move it to the zombie list.
478  *
479  * MPSAFE
480  */
481 void
482 proc_move_allproc_zombie(struct proc *p)
483 {
484 	spin_lock_wr(&allproc_spin);
485 	while (p->p_lock) {
486 		spin_unlock_wr(&allproc_spin);
487 		tsleep(p, 0, "reap1", hz / 10);
488 		spin_lock_wr(&allproc_spin);
489 	}
490 	LIST_REMOVE(p, p_list);
491 	LIST_INSERT_HEAD(&zombproc, p, p_list);
492 	LIST_REMOVE(p, p_hash);
493 	p->p_stat = SZOMB;
494 	spin_unlock_wr(&allproc_spin);
495 }
496 
497 /*
498  * This routine is called from kern_wait() and will remove the process
499  * from the zombie list and the sibling list.  This routine will block
500  * if someone has a lock on the proces (p_lock).
501  *
502  * MPSAFE
503  */
504 void
505 proc_remove_zombie(struct proc *p)
506 {
507 	spin_lock_wr(&allproc_spin);
508 	while (p->p_lock) {
509 		spin_unlock_wr(&allproc_spin);
510 		tsleep(p, 0, "reap1", hz / 10);
511 		spin_lock_wr(&allproc_spin);
512 	}
513 	LIST_REMOVE(p, p_list); /* off zombproc */
514 	LIST_REMOVE(p, p_sibling);
515 	spin_unlock_wr(&allproc_spin);
516 }
517 
518 /*
519  * Scan all processes on the allproc list.  The process is automatically
520  * held for the callback.  A return value of -1 terminates the loop.
521  *
522  * MPSAFE
523  */
524 void
525 allproc_scan(int (*callback)(struct proc *, void *), void *data)
526 {
527 	struct proc *p;
528 	int r;
529 
530 	spin_lock_rd(&allproc_spin);
531 	LIST_FOREACH(p, &allproc, p_list) {
532 		PHOLD(p);
533 		spin_unlock_rd(&allproc_spin);
534 		r = callback(p, data);
535 		spin_lock_rd(&allproc_spin);
536 		PRELE(p);
537 		if (r < 0)
538 			break;
539 	}
540 	spin_unlock_rd(&allproc_spin);
541 }
542 
543 /*
544  * Scan all lwps of processes on the allproc list.  The lwp is automatically
545  * held for the callback.  A return value of -1 terminates the loop.
546  *
547  * possibly not MPSAFE, needs to access foreingn proc structures
548  */
549 void
550 alllwp_scan(int (*callback)(struct lwp *, void *), void *data)
551 {
552 	struct proc *p;
553 	struct lwp *lp;
554 	int r = 0;
555 
556 	spin_lock_rd(&allproc_spin);
557 	LIST_FOREACH(p, &allproc, p_list) {
558 		PHOLD(p);
559 		spin_unlock_rd(&allproc_spin);
560 		FOREACH_LWP_IN_PROC(lp, p) {
561 			LWPHOLD(lp);
562 			r = callback(lp, data);
563 			LWPRELE(lp);
564 		}
565 		spin_lock_rd(&allproc_spin);
566 		PRELE(p);
567 		if (r < 0)
568 			break;
569 	}
570 	spin_unlock_rd(&allproc_spin);
571 }
572 
573 /*
574  * Scan all processes on the zombproc list.  The process is automatically
575  * held for the callback.  A return value of -1 terminates the loop.
576  *
577  * MPSAFE
578  */
579 void
580 zombproc_scan(int (*callback)(struct proc *, void *), void *data)
581 {
582 	struct proc *p;
583 	int r;
584 
585 	spin_lock_rd(&allproc_spin);
586 	LIST_FOREACH(p, &zombproc, p_list) {
587 		PHOLD(p);
588 		spin_unlock_rd(&allproc_spin);
589 		r = callback(p, data);
590 		spin_lock_rd(&allproc_spin);
591 		PRELE(p);
592 		if (r < 0)
593 			break;
594 	}
595 	spin_unlock_rd(&allproc_spin);
596 }
597 
598 #include "opt_ddb.h"
599 #ifdef DDB
600 #include <ddb/ddb.h>
601 
602 DB_SHOW_COMMAND(pgrpdump, pgrpdump)
603 {
604 	struct pgrp *pgrp;
605 	struct proc *p;
606 	int i;
607 
608 	for (i = 0; i <= pgrphash; i++) {
609 		if (!LIST_EMPTY(&pgrphashtbl[i])) {
610 			kprintf("\tindx %d\n", i);
611 			LIST_FOREACH(pgrp, &pgrphashtbl[i], pg_hash) {
612 				kprintf(
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 					kprintf("\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  * Locate a process on the zombie list.  Return a held process or NULL.
631  */
632 struct proc *
633 zpfind(pid_t pid)
634 {
635 	struct proc *p;
636 
637 	LIST_FOREACH(p, &zombproc, p_list)
638 		if (p->p_pid == pid)
639 			return (p);
640 	return (NULL);
641 }
642 
643 static int
644 sysctl_out_proc(struct proc *p, struct sysctl_req *req, int flags)
645 {
646 	struct kinfo_proc ki;
647 	struct lwp *lp;
648 	int skp = 0, had_output = 0;
649 	int error;
650 
651 	bzero(&ki, sizeof(ki));
652 	fill_kinfo_proc(p, &ki);
653 	if ((flags & KERN_PROC_FLAG_LWP) == 0)
654 		skp = 1;
655 	error = 0;
656 	FOREACH_LWP_IN_PROC(lp, p) {
657 		LWPHOLD(lp);
658 		fill_kinfo_lwp(lp, &ki.kp_lwp);
659 		had_output = 1;
660 		error = SYSCTL_OUT(req, &ki, sizeof(ki));
661 		LWPRELE(lp);
662 		if (error)
663 			break;
664 		if (skp)
665 			break;
666 	}
667 	/* We need to output at least the proc, even if there is no lwp. */
668 	if (had_output == 0) {
669 		error = SYSCTL_OUT(req, &ki, sizeof(ki));
670 	}
671 	return (error);
672 }
673 
674 static int
675 sysctl_out_proc_kthread(struct thread *td, struct sysctl_req *req, int flags)
676 {
677 	struct kinfo_proc ki;
678 	int error;
679 
680 	fill_kinfo_proc_kthread(td, &ki);
681 	error = SYSCTL_OUT(req, &ki, sizeof(ki));
682 	if (error)
683 		return error;
684 	return(0);
685 }
686 
687 static int
688 sysctl_kern_proc(SYSCTL_HANDLER_ARGS)
689 {
690 	int *name = (int*) arg1;
691 	int oid = oidp->oid_number;
692 	u_int namelen = arg2;
693 	struct proc *p;
694 	struct proclist *plist;
695 	struct thread *td;
696 	int doingzomb, flags = 0;
697 	int error = 0;
698 	int n;
699 	int origcpu;
700 	struct ucred *cr1 = curproc->p_ucred;
701 
702 	flags = oid & KERN_PROC_FLAGMASK;
703 	oid &= ~KERN_PROC_FLAGMASK;
704 
705 	if ((oid == KERN_PROC_ALL && namelen != 0) ||
706 	    (oid != KERN_PROC_ALL && namelen != 1))
707 		return (EINVAL);
708 
709 	if (oid == KERN_PROC_PID) {
710 		p = pfind((pid_t)name[0]);
711 		if (!p)
712 			return (0);
713 		if (!PRISON_CHECK(cr1, p->p_ucred))
714 			return (0);
715 		PHOLD(p);
716 		error = sysctl_out_proc(p, req, flags);
717 		PRELE(p);
718 		return (error);
719 	}
720 
721 	if (!req->oldptr) {
722 		/* overestimate by 5 procs */
723 		error = SYSCTL_OUT(req, 0, sizeof (struct kinfo_proc) * 5);
724 		if (error)
725 			return (error);
726 	}
727 	for (doingzomb = 0; doingzomb <= 1; doingzomb++) {
728 		if (doingzomb)
729 			plist = &zombproc;
730 		else
731 			plist = &allproc;
732 		LIST_FOREACH(p, plist, p_list) {
733 			/*
734 			 * Show a user only their processes.
735 			 */
736 			if ((!ps_showallprocs) && p_trespass(cr1, p->p_ucred))
737 				continue;
738 			/*
739 			 * Skip embryonic processes.
740 			 */
741 			if (p->p_stat == SIDL)
742 				continue;
743 			/*
744 			 * TODO - make more efficient (see notes below).
745 			 * do by session.
746 			 */
747 			switch (oid) {
748 			case KERN_PROC_PGRP:
749 				/* could do this by traversing pgrp */
750 				if (p->p_pgrp == NULL ||
751 				    p->p_pgrp->pg_id != (pid_t)name[0])
752 					continue;
753 				break;
754 
755 			case KERN_PROC_TTY:
756 				if ((p->p_flag & P_CONTROLT) == 0 ||
757 				    p->p_session == NULL ||
758 				    p->p_session->s_ttyp == NULL ||
759 				    dev2udev(p->p_session->s_ttyp->t_dev) !=
760 					(udev_t)name[0])
761 					continue;
762 				break;
763 
764 			case KERN_PROC_UID:
765 				if (p->p_ucred == NULL ||
766 				    p->p_ucred->cr_uid != (uid_t)name[0])
767 					continue;
768 				break;
769 
770 			case KERN_PROC_RUID:
771 				if (p->p_ucred == NULL ||
772 				    p->p_ucred->cr_ruid != (uid_t)name[0])
773 					continue;
774 				break;
775 			}
776 
777 			if (!PRISON_CHECK(cr1, p->p_ucred))
778 				continue;
779 			PHOLD(p);
780 			error = sysctl_out_proc(p, req, flags);
781 			PRELE(p);
782 			if (error)
783 				return (error);
784 		}
785 	}
786 
787 	/*
788 	 * Iterate over all active cpus and scan their thread list.  Start
789 	 * with the next logical cpu and end with our original cpu.  We
790 	 * migrate our own thread to each target cpu in order to safely scan
791 	 * its thread list.  In the last loop we migrate back to our original
792 	 * cpu.
793 	 */
794 	origcpu = mycpu->gd_cpuid;
795 	if (!ps_showallthreads || jailed(cr1))
796 		goto post_threads;
797 	for (n = 1; n <= ncpus; ++n) {
798 		globaldata_t rgd;
799 		int nid;
800 
801 		nid = (origcpu + n) % ncpus;
802 		if ((smp_active_mask & (1 << nid)) == 0)
803 			continue;
804 		rgd = globaldata_find(nid);
805 		lwkt_setcpu_self(rgd);
806 
807 		TAILQ_FOREACH(td, &mycpu->gd_tdallq, td_allq) {
808 			if (td->td_proc)
809 				continue;
810 			switch (oid) {
811 			case KERN_PROC_PGRP:
812 			case KERN_PROC_TTY:
813 			case KERN_PROC_UID:
814 			case KERN_PROC_RUID:
815 				continue;
816 			default:
817 				break;
818 			}
819 			lwkt_hold(td);
820 			error = sysctl_out_proc_kthread(td, req, doingzomb);
821 			lwkt_rele(td);
822 			if (error)
823 				return (error);
824 		}
825 	}
826 post_threads:
827 	return (0);
828 }
829 
830 /*
831  * This sysctl allows a process to retrieve the argument list or process
832  * title for another process without groping around in the address space
833  * of the other process.  It also allow a process to set its own "process
834  * title to a string of its own choice.
835  */
836 static int
837 sysctl_kern_proc_args(SYSCTL_HANDLER_ARGS)
838 {
839 	int *name = (int*) arg1;
840 	u_int namelen = arg2;
841 	struct proc *p;
842 	struct pargs *pa;
843 	int error = 0;
844 	struct ucred *cr1 = curproc->p_ucred;
845 
846 	if (namelen != 1)
847 		return (EINVAL);
848 
849 	p = pfind((pid_t)name[0]);
850 	if (!p)
851 		return (0);
852 
853 	if ((!ps_argsopen) && p_trespass(cr1, p->p_ucred))
854 		return (0);
855 
856 	if (req->newptr && curproc != p)
857 		return (EPERM);
858 
859 	if (req->oldptr && p->p_args != NULL)
860 		error = SYSCTL_OUT(req, p->p_args->ar_args, p->p_args->ar_length);
861 	if (req->newptr == NULL)
862 		return (error);
863 
864 	if (p->p_args && --p->p_args->ar_ref == 0)
865 		FREE(p->p_args, M_PARGS);
866 	p->p_args = NULL;
867 
868 	if (req->newlen + sizeof(struct pargs) > ps_arg_cache_limit)
869 		return (error);
870 
871 	MALLOC(pa, struct pargs *, sizeof(struct pargs) + req->newlen,
872 	    M_PARGS, M_WAITOK);
873 	pa->ar_ref = 1;
874 	pa->ar_length = req->newlen;
875 	error = SYSCTL_IN(req, pa->ar_args, req->newlen);
876 	if (!error)
877 		p->p_args = pa;
878 	else
879 		FREE(pa, M_PARGS);
880 	return (error);
881 }
882 
883 SYSCTL_NODE(_kern, KERN_PROC, proc, CTLFLAG_RD,  0, "Process table");
884 
885 SYSCTL_PROC(_kern_proc, KERN_PROC_ALL, all, CTLFLAG_RD|CTLTYPE_STRUCT,
886 	0, 0, sysctl_kern_proc, "S,proc", "Return entire process table");
887 
888 SYSCTL_NODE(_kern_proc, KERN_PROC_PGRP, pgrp, CTLFLAG_RD,
889 	sysctl_kern_proc, "Process table");
890 
891 SYSCTL_NODE(_kern_proc, KERN_PROC_TTY, tty, CTLFLAG_RD,
892 	sysctl_kern_proc, "Process table");
893 
894 SYSCTL_NODE(_kern_proc, KERN_PROC_UID, uid, CTLFLAG_RD,
895 	sysctl_kern_proc, "Process table");
896 
897 SYSCTL_NODE(_kern_proc, KERN_PROC_RUID, ruid, CTLFLAG_RD,
898 	sysctl_kern_proc, "Process table");
899 
900 SYSCTL_NODE(_kern_proc, KERN_PROC_PID, pid, CTLFLAG_RD,
901 	sysctl_kern_proc, "Process table");
902 
903 SYSCTL_NODE(_kern_proc, (KERN_PROC_ALL | KERN_PROC_FLAG_LWP), all_lwp, CTLFLAG_RD,
904 	sysctl_kern_proc, "Process table");
905 
906 SYSCTL_NODE(_kern_proc, (KERN_PROC_PGRP | KERN_PROC_FLAG_LWP), pgrp_lwp, CTLFLAG_RD,
907 	sysctl_kern_proc, "Process table");
908 
909 SYSCTL_NODE(_kern_proc, (KERN_PROC_TTY | KERN_PROC_FLAG_LWP), tty_lwp, CTLFLAG_RD,
910 	sysctl_kern_proc, "Process table");
911 
912 SYSCTL_NODE(_kern_proc, (KERN_PROC_UID | KERN_PROC_FLAG_LWP), uid_lwp, CTLFLAG_RD,
913 	sysctl_kern_proc, "Process table");
914 
915 SYSCTL_NODE(_kern_proc, (KERN_PROC_RUID | KERN_PROC_FLAG_LWP), ruid_lwp, CTLFLAG_RD,
916 	sysctl_kern_proc, "Process table");
917 
918 SYSCTL_NODE(_kern_proc, (KERN_PROC_PID | KERN_PROC_FLAG_LWP), pid_lwp, CTLFLAG_RD,
919 	sysctl_kern_proc, "Process table");
920 
921 SYSCTL_NODE(_kern_proc, KERN_PROC_ARGS, args, CTLFLAG_RW | CTLFLAG_ANYBODY,
922 	sysctl_kern_proc_args, "Process argument list");
923