xref: /dflybsd-src/sys/kern/kern_proc.c (revision dae741e33c840b92a8a53bf9f01157ede145e256)
1 /*
2  * (MPSAFE)
3  *
4  * Copyright (c) 1982, 1986, 1989, 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *	This product includes software developed by the University of
18  *	California, Berkeley and its contributors.
19  * 4. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  *
35  *	@(#)kern_proc.c	8.7 (Berkeley) 2/14/95
36  * $FreeBSD: src/sys/kern/kern_proc.c,v 1.63.2.9 2003/05/08 07:47:16 kbyanc Exp $
37  * $DragonFly: src/sys/kern/kern_proc.c,v 1.45 2008/06/12 23:25:02 dillon Exp $
38  */
39 
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/kernel.h>
43 #include <sys/sysctl.h>
44 #include <sys/malloc.h>
45 #include <sys/proc.h>
46 #include <sys/jail.h>
47 #include <sys/filedesc.h>
48 #include <sys/tty.h>
49 #include <sys/dsched.h>
50 #include <sys/signalvar.h>
51 #include <sys/spinlock.h>
52 #include <vm/vm.h>
53 #include <sys/lock.h>
54 #include <vm/pmap.h>
55 #include <vm/vm_map.h>
56 #include <sys/user.h>
57 #include <machine/smp.h>
58 
59 #include <sys/refcount.h>
60 #include <sys/spinlock2.h>
61 #include <sys/mplock2.h>
62 
63 static MALLOC_DEFINE(M_PGRP, "pgrp", "process group header");
64 MALLOC_DEFINE(M_SESSION, "session", "session header");
65 MALLOC_DEFINE(M_PROC, "proc", "Proc structures");
66 MALLOC_DEFINE(M_LWP, "lwp", "lwp structures");
67 MALLOC_DEFINE(M_SUBPROC, "subproc", "Proc sub-structures");
68 
69 int ps_showallprocs = 1;
70 static int ps_showallthreads = 1;
71 SYSCTL_INT(_security, OID_AUTO, ps_showallprocs, CTLFLAG_RW,
72     &ps_showallprocs, 0,
73     "Unprivileged processes can see proccesses with different UID/GID");
74 SYSCTL_INT(_security, OID_AUTO, ps_showallthreads, CTLFLAG_RW,
75     &ps_showallthreads, 0,
76     "Unprivileged processes can see kernel threads");
77 
78 static void pgdelete(struct pgrp *);
79 static void orphanpg(struct pgrp *pg);
80 static pid_t proc_getnewpid_locked(int random_offset);
81 
82 /*
83  * Other process lists
84  */
85 struct pidhashhead *pidhashtbl;
86 u_long pidhash;
87 struct pgrphashhead *pgrphashtbl;
88 u_long pgrphash;
89 struct proclist allproc;
90 struct proclist zombproc;
91 
92 /*
93  * Random component to nextpid generation.  We mix in a random factor to make
94  * it a little harder to predict.  We sanity check the modulus value to avoid
95  * doing it in critical paths.  Don't let it be too small or we pointlessly
96  * waste randomness entropy, and don't let it be impossibly large.  Using a
97  * modulus that is too big causes a LOT more process table scans and slows
98  * down fork processing as the pidchecked caching is defeated.
99  */
100 static int randompid = 0;
101 
102 /*
103  * No requirements.
104  */
105 static int
106 sysctl_kern_randompid(SYSCTL_HANDLER_ARGS)
107 {
108 	int error, pid;
109 
110 	pid = randompid;
111 	error = sysctl_handle_int(oidp, &pid, 0, req);
112 	if (error || !req->newptr)
113 		return (error);
114 	if (pid < 0 || pid > PID_MAX - 100)     /* out of range */
115 		pid = PID_MAX - 100;
116 	else if (pid < 2)                       /* NOP */
117 		pid = 0;
118 	else if (pid < 100)                     /* Make it reasonable */
119 		pid = 100;
120 	randompid = pid;
121 	return (error);
122 }
123 
124 SYSCTL_PROC(_kern, OID_AUTO, randompid, CTLTYPE_INT|CTLFLAG_RW,
125 	    0, 0, sysctl_kern_randompid, "I", "Random PID modulus");
126 
127 /*
128  * Initialize global process hashing structures.
129  *
130  * Called from the low level boot code only.
131  */
132 void
133 procinit(void)
134 {
135 	LIST_INIT(&allproc);
136 	LIST_INIT(&zombproc);
137 	lwkt_init();
138 	pidhashtbl = hashinit(maxproc / 4, M_PROC, &pidhash);
139 	pgrphashtbl = hashinit(maxproc / 4, M_PROC, &pgrphash);
140 	uihashinit();
141 }
142 
143 /*
144  * Is p an inferior of the current process?
145  *
146  * No requirements.
147  * The caller must hold proc_token if the caller wishes a stable result.
148  */
149 int
150 inferior(struct proc *p)
151 {
152 	lwkt_gettoken(&proc_token);
153 	while (p != curproc) {
154 		if (p->p_pid == 0) {
155 			lwkt_reltoken(&proc_token);
156 			return (0);
157 		}
158 		p = p->p_pptr;
159 	}
160 	lwkt_reltoken(&proc_token);
161 	return (1);
162 }
163 
164 /*
165  * Locate a process by number.  The returned process will be referenced and
166  * must be released with PRELE().
167  *
168  * No requirements.
169  */
170 struct proc *
171 pfind(pid_t pid)
172 {
173 	struct proc *p;
174 
175 	lwkt_gettoken(&proc_token);
176 	LIST_FOREACH(p, PIDHASH(pid), p_hash) {
177 		if (p->p_pid == pid) {
178 			PHOLD(p);
179 			lwkt_reltoken(&proc_token);
180 			return (p);
181 		}
182 	}
183 	lwkt_reltoken(&proc_token);
184 	return (NULL);
185 }
186 
187 /*
188  * Locate a process by number.  The returned process is NOT referenced.
189  * The caller should hold proc_token if the caller wishes a stable result.
190  *
191  * No requirements.
192  */
193 struct proc *
194 pfindn(pid_t pid)
195 {
196 	struct proc *p;
197 
198 	lwkt_gettoken(&proc_token);
199 	LIST_FOREACH(p, PIDHASH(pid), p_hash) {
200 		if (p->p_pid == pid) {
201 			lwkt_reltoken(&proc_token);
202 			return (p);
203 		}
204 	}
205 	lwkt_reltoken(&proc_token);
206 	return (NULL);
207 }
208 
209 void
210 pgref(struct pgrp *pgrp)
211 {
212 	refcount_acquire(&pgrp->pg_refs);
213 }
214 
215 void
216 pgrel(struct pgrp *pgrp)
217 {
218 	if (refcount_release(&pgrp->pg_refs))
219 		pgdelete(pgrp);
220 }
221 
222 /*
223  * Locate a process group by number.  The returned process group will be
224  * referenced w/pgref() and must be released with pgrel() (or assigned
225  * somewhere if you wish to keep the reference).
226  *
227  * No requirements.
228  */
229 struct pgrp *
230 pgfind(pid_t pgid)
231 {
232 	struct pgrp *pgrp;
233 
234 	lwkt_gettoken(&proc_token);
235 	LIST_FOREACH(pgrp, PGRPHASH(pgid), pg_hash) {
236 		if (pgrp->pg_id == pgid) {
237 			refcount_acquire(&pgrp->pg_refs);
238 			lwkt_reltoken(&proc_token);
239 			return (pgrp);
240 		}
241 	}
242 	lwkt_reltoken(&proc_token);
243 	return (NULL);
244 }
245 
246 /*
247  * Move p to a new or existing process group (and session)
248  *
249  * No requirements.
250  */
251 int
252 enterpgrp(struct proc *p, pid_t pgid, int mksess)
253 {
254 	struct pgrp *pgrp;
255 	struct pgrp *opgrp;
256 	int error;
257 
258 	pgrp = pgfind(pgid);
259 
260 	KASSERT(pgrp == NULL || !mksess,
261 		("enterpgrp: setsid into non-empty pgrp"));
262 	KASSERT(!SESS_LEADER(p),
263 		("enterpgrp: session leader attempted setpgrp"));
264 
265 	if (pgrp == NULL) {
266 		pid_t savepid = p->p_pid;
267 		struct proc *np;
268 		/*
269 		 * new process group
270 		 */
271 		KASSERT(p->p_pid == pgid,
272 			("enterpgrp: new pgrp and pid != pgid"));
273 		if ((np = pfindn(savepid)) == NULL || np != p) {
274 			error = ESRCH;
275 			goto fatal;
276 		}
277 		MALLOC(pgrp, struct pgrp *, sizeof(struct pgrp),
278 		       M_PGRP, M_WAITOK);
279 		if (mksess) {
280 			struct session *sess;
281 
282 			/*
283 			 * new session
284 			 */
285 			MALLOC(sess, struct session *, sizeof(struct session),
286 			       M_SESSION, M_WAITOK);
287 			sess->s_leader = p;
288 			sess->s_sid = p->p_pid;
289 			sess->s_count = 1;
290 			sess->s_ttyvp = NULL;
291 			sess->s_ttyp = NULL;
292 			bcopy(p->p_session->s_login, sess->s_login,
293 			      sizeof(sess->s_login));
294 			pgrp->pg_session = sess;
295 			KASSERT(p == curproc,
296 				("enterpgrp: mksession and p != curproc"));
297 			lwkt_gettoken(&p->p_token);
298 			p->p_flag &= ~P_CONTROLT;
299 			lwkt_reltoken(&p->p_token);
300 		} else {
301 			pgrp->pg_session = p->p_session;
302 			sess_hold(pgrp->pg_session);
303 		}
304 		pgrp->pg_id = pgid;
305 		LIST_INIT(&pgrp->pg_members);
306 		LIST_INSERT_HEAD(PGRPHASH(pgid), pgrp, pg_hash);
307 		pgrp->pg_jobc = 0;
308 		SLIST_INIT(&pgrp->pg_sigiolst);
309 		lwkt_token_init(&pgrp->pg_token, "pgrp_token");
310 		refcount_init(&pgrp->pg_refs, 1);
311 		lockinit(&pgrp->pg_lock, "pgwt", 0, 0);
312 	} else if (pgrp == p->p_pgrp) {
313 		pgrel(pgrp);
314 		goto done;
315 	} /* else pgfind() referenced the pgrp */
316 
317 	/*
318 	 * Adjust eligibility of affected pgrps to participate in job control.
319 	 * Increment eligibility counts before decrementing, otherwise we
320 	 * could reach 0 spuriously during the first call.
321 	 */
322 	lwkt_gettoken(&pgrp->pg_token);
323 	lwkt_gettoken(&p->p_token);
324 	fixjobc(p, pgrp, 1);
325 	fixjobc(p, p->p_pgrp, 0);
326 	while ((opgrp = p->p_pgrp) != NULL) {
327 		opgrp = p->p_pgrp;
328 		lwkt_gettoken(&opgrp->pg_token);
329 		LIST_REMOVE(p, p_pglist);
330 		p->p_pgrp = NULL;
331 		lwkt_reltoken(&opgrp->pg_token);
332 		pgrel(opgrp);
333 	}
334 	p->p_pgrp = pgrp;
335 	LIST_INSERT_HEAD(&pgrp->pg_members, p, p_pglist);
336 	lwkt_reltoken(&p->p_token);
337 	lwkt_reltoken(&pgrp->pg_token);
338 done:
339 	error = 0;
340 fatal:
341 	return (error);
342 }
343 
344 /*
345  * Remove process from process group
346  *
347  * No requirements.
348  */
349 int
350 leavepgrp(struct proc *p)
351 {
352 	struct pgrp *pg = p->p_pgrp;
353 
354 	lwkt_gettoken(&p->p_token);
355 	pg = p->p_pgrp;
356 	if (pg) {
357 		pgref(pg);
358 		lwkt_gettoken(&pg->pg_token);
359 		if (p->p_pgrp == pg) {
360 			p->p_pgrp = NULL;
361 			LIST_REMOVE(p, p_pglist);
362 			pgrel(pg);
363 		}
364 		lwkt_reltoken(&pg->pg_token);
365 		lwkt_reltoken(&p->p_token);	/* avoid chaining on rel */
366 		pgrel(pg);
367 	} else {
368 		lwkt_reltoken(&p->p_token);
369 	}
370 	return (0);
371 }
372 
373 /*
374  * Delete a process group.  Must be called only after the last ref has been
375  * released.
376  */
377 static void
378 pgdelete(struct pgrp *pgrp)
379 {
380 	/*
381 	 * Reset any sigio structures pointing to us as a result of
382 	 * F_SETOWN with our pgid.
383 	 */
384 	funsetownlst(&pgrp->pg_sigiolst);
385 
386 	if (pgrp->pg_session->s_ttyp != NULL &&
387 	    pgrp->pg_session->s_ttyp->t_pgrp == pgrp)
388 		pgrp->pg_session->s_ttyp->t_pgrp = NULL;
389 	LIST_REMOVE(pgrp, pg_hash);
390 	sess_rele(pgrp->pg_session);
391 	kfree(pgrp, M_PGRP);
392 }
393 
394 /*
395  * Adjust the ref count on a session structure.  When the ref count falls to
396  * zero the tty is disassociated from the session and the session structure
397  * is freed.  Note that tty assocation is not itself ref-counted.
398  *
399  * No requirements.
400  */
401 void
402 sess_hold(struct session *sp)
403 {
404 	lwkt_gettoken(&tty_token);
405 	++sp->s_count;
406 	lwkt_reltoken(&tty_token);
407 }
408 
409 /*
410  * No requirements.
411  */
412 void
413 sess_rele(struct session *sp)
414 {
415 	struct tty *tp;
416 
417 	KKASSERT(sp->s_count > 0);
418 	lwkt_gettoken(&tty_token);
419 	if (--sp->s_count == 0) {
420 		if (sp->s_ttyp && sp->s_ttyp->t_session) {
421 #ifdef TTY_DO_FULL_CLOSE
422 			/* FULL CLOSE, see ttyclearsession() */
423 			KKASSERT(sp->s_ttyp->t_session == sp);
424 			sp->s_ttyp->t_session = NULL;
425 #else
426 			/* HALF CLOSE, see ttyclearsession() */
427 			if (sp->s_ttyp->t_session == sp)
428 				sp->s_ttyp->t_session = NULL;
429 #endif
430 		}
431 		if ((tp = sp->s_ttyp) != NULL) {
432 			sp->s_ttyp = NULL;
433 			ttyunhold(tp);
434 		}
435 		kfree(sp, M_SESSION);
436 	}
437 	lwkt_reltoken(&tty_token);
438 }
439 
440 /*
441  * Adjust pgrp jobc counters when specified process changes process group.
442  * We count the number of processes in each process group that "qualify"
443  * the group for terminal job control (those with a parent in a different
444  * process group of the same session).  If that count reaches zero, the
445  * process group becomes orphaned.  Check both the specified process'
446  * process group and that of its children.
447  * entering == 0 => p is leaving specified group.
448  * entering == 1 => p is entering specified group.
449  *
450  * No requirements.
451  */
452 void
453 fixjobc(struct proc *p, struct pgrp *pgrp, int entering)
454 {
455 	struct pgrp *hispgrp;
456 	struct session *mysession;
457 	struct proc *np;
458 
459 	/*
460 	 * Check p's parent to see whether p qualifies its own process
461 	 * group; if so, adjust count for p's process group.
462 	 */
463 	lwkt_gettoken(&p->p_token);	/* p_children scan */
464 	lwkt_gettoken(&pgrp->pg_token);
465 
466 	mysession = pgrp->pg_session;
467 	if ((hispgrp = p->p_pptr->p_pgrp) != pgrp &&
468 	    hispgrp->pg_session == mysession) {
469 		if (entering)
470 			pgrp->pg_jobc++;
471 		else if (--pgrp->pg_jobc == 0)
472 			orphanpg(pgrp);
473 	}
474 
475 	/*
476 	 * Check this process' children to see whether they qualify
477 	 * their process groups; if so, adjust counts for children's
478 	 * process groups.
479 	 */
480 	LIST_FOREACH(np, &p->p_children, p_sibling) {
481 		PHOLD(np);
482 		lwkt_gettoken(&np->p_token);
483 		if ((hispgrp = np->p_pgrp) != pgrp &&
484 		    hispgrp->pg_session == mysession &&
485 		    np->p_stat != SZOMB) {
486 			pgref(hispgrp);
487 			lwkt_gettoken(&hispgrp->pg_token);
488 			if (entering)
489 				hispgrp->pg_jobc++;
490 			else if (--hispgrp->pg_jobc == 0)
491 				orphanpg(hispgrp);
492 			lwkt_reltoken(&hispgrp->pg_token);
493 			pgrel(hispgrp);
494 		}
495 		lwkt_reltoken(&np->p_token);
496 		PRELE(np);
497 	}
498 	KKASSERT(pgrp->pg_refs > 0);
499 	lwkt_reltoken(&pgrp->pg_token);
500 	lwkt_reltoken(&p->p_token);
501 }
502 
503 /*
504  * A process group has become orphaned;
505  * if there are any stopped processes in the group,
506  * hang-up all process in that group.
507  *
508  * The caller must hold pg_token.
509  */
510 static void
511 orphanpg(struct pgrp *pg)
512 {
513 	struct proc *p;
514 
515 	LIST_FOREACH(p, &pg->pg_members, p_pglist) {
516 		if (p->p_stat == SSTOP) {
517 			LIST_FOREACH(p, &pg->pg_members, p_pglist) {
518 				ksignal(p, SIGHUP);
519 				ksignal(p, SIGCONT);
520 			}
521 			return;
522 		}
523 	}
524 }
525 
526 /*
527  * Add a new process to the allproc list and the PID hash.  This
528  * also assigns a pid to the new process.
529  *
530  * No requirements.
531  */
532 void
533 proc_add_allproc(struct proc *p)
534 {
535 	int random_offset;
536 
537 	if ((random_offset = randompid) != 0) {
538 		get_mplock();
539 		random_offset = karc4random() % random_offset;
540 		rel_mplock();
541 	}
542 
543 	lwkt_gettoken(&proc_token);
544 	p->p_pid = proc_getnewpid_locked(random_offset);
545 	LIST_INSERT_HEAD(&allproc, p, p_list);
546 	LIST_INSERT_HEAD(PIDHASH(p->p_pid), p, p_hash);
547 	lwkt_reltoken(&proc_token);
548 }
549 
550 /*
551  * Calculate a new process pid.  This function is integrated into
552  * proc_add_allproc() to guarentee that the new pid is not reused before
553  * the new process can be added to the allproc list.
554  *
555  * The caller must hold proc_token.
556  */
557 static
558 pid_t
559 proc_getnewpid_locked(int random_offset)
560 {
561 	static pid_t nextpid;
562 	static pid_t pidchecked;
563 	struct proc *p;
564 
565 	/*
566 	 * Find an unused process ID.  We remember a range of unused IDs
567 	 * ready to use (from nextpid+1 through pidchecked-1).
568 	 */
569 	nextpid = nextpid + 1 + random_offset;
570 retry:
571 	/*
572 	 * If the process ID prototype has wrapped around,
573 	 * restart somewhat above 0, as the low-numbered procs
574 	 * tend to include daemons that don't exit.
575 	 */
576 	if (nextpid >= PID_MAX) {
577 		nextpid = nextpid % PID_MAX;
578 		if (nextpid < 100)
579 			nextpid += 100;
580 		pidchecked = 0;
581 	}
582 	if (nextpid >= pidchecked) {
583 		int doingzomb = 0;
584 
585 		pidchecked = PID_MAX;
586 
587 		/*
588 		 * Scan the active and zombie procs to check whether this pid
589 		 * is in use.  Remember the lowest pid that's greater
590 		 * than nextpid, so we can avoid checking for a while.
591 		 *
592 		 * NOTE: Processes in the midst of being forked may not
593 		 *	 yet have p_pgrp and p_pgrp->pg_session set up
594 		 *	 yet, so we have to check for NULL.
595 		 *
596 		 *	 Processes being torn down should be interlocked
597 		 *	 with proc_token prior to the clearing of their
598 		 *	 p_pgrp.
599 		 */
600 		p = LIST_FIRST(&allproc);
601 again:
602 		for (; p != NULL; p = LIST_NEXT(p, p_list)) {
603 			while (p->p_pid == nextpid ||
604 			    (p->p_pgrp && p->p_pgrp->pg_id == nextpid) ||
605 			    (p->p_pgrp && p->p_session &&
606 			     p->p_session->s_sid == nextpid)) {
607 				nextpid++;
608 				if (nextpid >= pidchecked)
609 					goto retry;
610 			}
611 			if (p->p_pid > nextpid && pidchecked > p->p_pid)
612 				pidchecked = p->p_pid;
613 			if (p->p_pgrp &&
614 			    p->p_pgrp->pg_id > nextpid &&
615 			    pidchecked > p->p_pgrp->pg_id) {
616 				pidchecked = p->p_pgrp->pg_id;
617 			}
618 			if (p->p_pgrp && p->p_session &&
619 			    p->p_session->s_sid > nextpid &&
620 			    pidchecked > p->p_session->s_sid) {
621 				pidchecked = p->p_session->s_sid;
622 			}
623 		}
624 		if (!doingzomb) {
625 			doingzomb = 1;
626 			p = LIST_FIRST(&zombproc);
627 			goto again;
628 		}
629 	}
630 	return(nextpid);
631 }
632 
633 /*
634  * Called from exit1 to remove a process from the allproc
635  * list and move it to the zombie list.
636  *
637  * No requirements.
638  */
639 void
640 proc_move_allproc_zombie(struct proc *p)
641 {
642 	lwkt_gettoken(&proc_token);
643 	while (p->p_lock) {
644 		tsleep(p, 0, "reap1", hz / 10);
645 	}
646 	LIST_REMOVE(p, p_list);
647 	LIST_INSERT_HEAD(&zombproc, p, p_list);
648 	LIST_REMOVE(p, p_hash);
649 	p->p_stat = SZOMB;
650 	lwkt_reltoken(&proc_token);
651 	dsched_exit_proc(p);
652 }
653 
654 /*
655  * This routine is called from kern_wait() and will remove the process
656  * from the zombie list and the sibling list.  This routine will block
657  * if someone has a lock on the proces (p_lock).
658  *
659  * No requirements.
660  */
661 void
662 proc_remove_zombie(struct proc *p)
663 {
664 	lwkt_gettoken(&proc_token);
665 	while (p->p_lock) {
666 		tsleep(p, 0, "reap1", hz / 10);
667 	}
668 	LIST_REMOVE(p, p_list); /* off zombproc */
669 	LIST_REMOVE(p, p_sibling);
670 	lwkt_reltoken(&proc_token);
671 }
672 
673 /*
674  * Scan all processes on the allproc list.  The process is automatically
675  * held for the callback.  A return value of -1 terminates the loop.
676  *
677  * The callback is made with the process held and proc_token held.
678  *
679  * We limit the scan to the number of processes as-of the start of
680  * the scan so as not to get caught up in an endless loop if new processes
681  * are created more quickly than we can scan the old ones.  Add a little
682  * slop to try to catch edge cases since nprocs can race.
683  *
684  * No requirements.
685  */
686 void
687 allproc_scan(int (*callback)(struct proc *, void *), void *data)
688 {
689 	struct proc *p;
690 	int r;
691 	int limit = nprocs + ncpus;
692 
693 	lwkt_gettoken(&proc_token);
694 	LIST_FOREACH(p, &allproc, p_list) {
695 		PHOLD(p);
696 		r = callback(p, data);
697 		PRELE(p);
698 		if (r < 0)
699 			break;
700 		if (--limit < 0)
701 			break;
702 	}
703 	lwkt_reltoken(&proc_token);
704 }
705 
706 /*
707  * Scan all lwps of processes on the allproc list.  The lwp is automatically
708  * held for the callback.  A return value of -1 terminates the loop.
709  *
710  * No requirements.
711  * The callback is made with the proces and lwp both held, and proc_token held.
712  */
713 void
714 alllwp_scan(int (*callback)(struct lwp *, void *), void *data)
715 {
716 	struct proc *p;
717 	struct lwp *lp;
718 	int r = 0;
719 
720 	lwkt_gettoken(&proc_token);
721 	LIST_FOREACH(p, &allproc, p_list) {
722 		PHOLD(p);
723 		FOREACH_LWP_IN_PROC(lp, p) {
724 			LWPHOLD(lp);
725 			r = callback(lp, data);
726 			LWPRELE(lp);
727 		}
728 		PRELE(p);
729 		if (r < 0)
730 			break;
731 	}
732 	lwkt_reltoken(&proc_token);
733 }
734 
735 /*
736  * Scan all processes on the zombproc list.  The process is automatically
737  * held for the callback.  A return value of -1 terminates the loop.
738  *
739  * No requirements.
740  * The callback is made with the proces held and proc_token held.
741  */
742 void
743 zombproc_scan(int (*callback)(struct proc *, void *), void *data)
744 {
745 	struct proc *p;
746 	int r;
747 
748 	lwkt_gettoken(&proc_token);
749 	LIST_FOREACH(p, &zombproc, p_list) {
750 		PHOLD(p);
751 		r = callback(p, data);
752 		PRELE(p);
753 		if (r < 0)
754 			break;
755 	}
756 	lwkt_reltoken(&proc_token);
757 }
758 
759 #include "opt_ddb.h"
760 #ifdef DDB
761 #include <ddb/ddb.h>
762 
763 /*
764  * Debugging only
765  */
766 DB_SHOW_COMMAND(pgrpdump, pgrpdump)
767 {
768 	struct pgrp *pgrp;
769 	struct proc *p;
770 	int i;
771 
772 	for (i = 0; i <= pgrphash; i++) {
773 		if (!LIST_EMPTY(&pgrphashtbl[i])) {
774 			kprintf("\tindx %d\n", i);
775 			LIST_FOREACH(pgrp, &pgrphashtbl[i], pg_hash) {
776 				kprintf(
777 			"\tpgrp %p, pgid %ld, sess %p, sesscnt %d, mem %p\n",
778 				    (void *)pgrp, (long)pgrp->pg_id,
779 				    (void *)pgrp->pg_session,
780 				    pgrp->pg_session->s_count,
781 				    (void *)LIST_FIRST(&pgrp->pg_members));
782 				LIST_FOREACH(p, &pgrp->pg_members, p_pglist) {
783 					kprintf("\t\tpid %ld addr %p pgrp %p\n",
784 					    (long)p->p_pid, (void *)p,
785 					    (void *)p->p_pgrp);
786 				}
787 			}
788 		}
789 	}
790 }
791 #endif /* DDB */
792 
793 /*
794  * Locate a process on the zombie list.  Return a process or NULL.
795  * The returned process will be referenced and the caller must release
796  * it with PRELE().
797  *
798  * No other requirements.
799  */
800 struct proc *
801 zpfind(pid_t pid)
802 {
803 	struct proc *p;
804 
805 	lwkt_gettoken(&proc_token);
806 	LIST_FOREACH(p, &zombproc, p_list) {
807 		if (p->p_pid == pid) {
808 			PHOLD(p);
809 			lwkt_reltoken(&proc_token);
810 			return (p);
811 		}
812 	}
813 	lwkt_reltoken(&proc_token);
814 	return (NULL);
815 }
816 
817 /*
818  * The caller must hold proc_token.
819  */
820 static int
821 sysctl_out_proc(struct proc *p, struct sysctl_req *req, int flags)
822 {
823 	struct kinfo_proc ki;
824 	struct lwp *lp;
825 	int skp = 0, had_output = 0;
826 	int error;
827 
828 	bzero(&ki, sizeof(ki));
829 	fill_kinfo_proc(p, &ki);
830 	if ((flags & KERN_PROC_FLAG_LWP) == 0)
831 		skp = 1;
832 	error = 0;
833 	FOREACH_LWP_IN_PROC(lp, p) {
834 		LWPHOLD(lp);
835 		fill_kinfo_lwp(lp, &ki.kp_lwp);
836 		had_output = 1;
837 		error = SYSCTL_OUT(req, &ki, sizeof(ki));
838 		LWPRELE(lp);
839 		if (error)
840 			break;
841 		if (skp)
842 			break;
843 	}
844 	/* We need to output at least the proc, even if there is no lwp. */
845 	if (had_output == 0) {
846 		error = SYSCTL_OUT(req, &ki, sizeof(ki));
847 	}
848 	return (error);
849 }
850 
851 /*
852  * The caller must hold proc_token.
853  */
854 static int
855 sysctl_out_proc_kthread(struct thread *td, struct sysctl_req *req, int flags)
856 {
857 	struct kinfo_proc ki;
858 	int error;
859 
860 	fill_kinfo_proc_kthread(td, &ki);
861 	error = SYSCTL_OUT(req, &ki, sizeof(ki));
862 	if (error)
863 		return error;
864 	return(0);
865 }
866 
867 /*
868  * No requirements.
869  */
870 static int
871 sysctl_kern_proc(SYSCTL_HANDLER_ARGS)
872 {
873 	int *name = (int*) arg1;
874 	int oid = oidp->oid_number;
875 	u_int namelen = arg2;
876 	struct proc *p;
877 	struct proclist *plist;
878 	struct thread *td;
879 	int doingzomb, flags = 0;
880 	int error = 0;
881 	int n;
882 	int origcpu;
883 	struct ucred *cr1 = curproc->p_ucred;
884 
885 	flags = oid & KERN_PROC_FLAGMASK;
886 	oid &= ~KERN_PROC_FLAGMASK;
887 
888 	if ((oid == KERN_PROC_ALL && namelen != 0) ||
889 	    (oid != KERN_PROC_ALL && namelen != 1))
890 		return (EINVAL);
891 
892 	lwkt_gettoken(&proc_token);
893 	if (oid == KERN_PROC_PID) {
894 		p = pfindn((pid_t)name[0]);
895 		if (p == NULL)
896 			goto post_threads;
897 		if (!PRISON_CHECK(cr1, p->p_ucred))
898 			goto post_threads;
899 		PHOLD(p);
900 		error = sysctl_out_proc(p, req, flags);
901 		PRELE(p);
902 		goto post_threads;
903 	}
904 
905 	if (!req->oldptr) {
906 		/* overestimate by 5 procs */
907 		error = SYSCTL_OUT(req, 0, sizeof (struct kinfo_proc) * 5);
908 		if (error)
909 			goto post_threads;
910 	}
911 	for (doingzomb = 0; doingzomb <= 1; doingzomb++) {
912 		if (doingzomb)
913 			plist = &zombproc;
914 		else
915 			plist = &allproc;
916 		LIST_FOREACH(p, plist, p_list) {
917 			/*
918 			 * Show a user only their processes.
919 			 */
920 			if ((!ps_showallprocs) && p_trespass(cr1, p->p_ucred))
921 				continue;
922 			/*
923 			 * Skip embryonic processes.
924 			 */
925 			if (p->p_stat == SIDL)
926 				continue;
927 			/*
928 			 * TODO - make more efficient (see notes below).
929 			 * do by session.
930 			 */
931 			switch (oid) {
932 			case KERN_PROC_PGRP:
933 				/* could do this by traversing pgrp */
934 				if (p->p_pgrp == NULL ||
935 				    p->p_pgrp->pg_id != (pid_t)name[0])
936 					continue;
937 				break;
938 
939 			case KERN_PROC_TTY:
940 				if ((p->p_flag & P_CONTROLT) == 0 ||
941 				    p->p_session == NULL ||
942 				    p->p_session->s_ttyp == NULL ||
943 				    dev2udev(p->p_session->s_ttyp->t_dev) !=
944 					(udev_t)name[0])
945 					continue;
946 				break;
947 
948 			case KERN_PROC_UID:
949 				if (p->p_ucred == NULL ||
950 				    p->p_ucred->cr_uid != (uid_t)name[0])
951 					continue;
952 				break;
953 
954 			case KERN_PROC_RUID:
955 				if (p->p_ucred == NULL ||
956 				    p->p_ucred->cr_ruid != (uid_t)name[0])
957 					continue;
958 				break;
959 			}
960 
961 			if (!PRISON_CHECK(cr1, p->p_ucred))
962 				continue;
963 			PHOLD(p);
964 			error = sysctl_out_proc(p, req, flags);
965 			PRELE(p);
966 			if (error)
967 				goto post_threads;
968 		}
969 	}
970 
971 	/*
972 	 * Iterate over all active cpus and scan their thread list.  Start
973 	 * with the next logical cpu and end with our original cpu.  We
974 	 * migrate our own thread to each target cpu in order to safely scan
975 	 * its thread list.  In the last loop we migrate back to our original
976 	 * cpu.
977 	 */
978 	origcpu = mycpu->gd_cpuid;
979 	if (!ps_showallthreads || jailed(cr1))
980 		goto post_threads;
981 
982 	for (n = 1; n <= ncpus; ++n) {
983 		globaldata_t rgd;
984 		int nid;
985 
986 		nid = (origcpu + n) % ncpus;
987 		if ((smp_active_mask & CPUMASK(nid)) == 0)
988 			continue;
989 		rgd = globaldata_find(nid);
990 		lwkt_setcpu_self(rgd);
991 
992 		TAILQ_FOREACH(td, &mycpu->gd_tdallq, td_allq) {
993 			if (td->td_proc)
994 				continue;
995 			switch (oid) {
996 			case KERN_PROC_PGRP:
997 			case KERN_PROC_TTY:
998 			case KERN_PROC_UID:
999 			case KERN_PROC_RUID:
1000 				continue;
1001 			default:
1002 				break;
1003 			}
1004 			lwkt_hold(td);
1005 			error = sysctl_out_proc_kthread(td, req, doingzomb);
1006 			lwkt_rele(td);
1007 			if (error)
1008 				goto post_threads;
1009 		}
1010 	}
1011 post_threads:
1012 	lwkt_reltoken(&proc_token);
1013 	return (error);
1014 }
1015 
1016 /*
1017  * This sysctl allows a process to retrieve the argument list or process
1018  * title for another process without groping around in the address space
1019  * of the other process.  It also allow a process to set its own "process
1020  * title to a string of its own choice.
1021  *
1022  * No requirements.
1023  */
1024 static int
1025 sysctl_kern_proc_args(SYSCTL_HANDLER_ARGS)
1026 {
1027 	int *name = (int*) arg1;
1028 	u_int namelen = arg2;
1029 	struct proc *p;
1030 	struct pargs *opa;
1031 	struct pargs *pa;
1032 	int error = 0;
1033 	struct ucred *cr1 = curproc->p_ucred;
1034 
1035 	if (namelen != 1)
1036 		return (EINVAL);
1037 
1038 	p = pfindn((pid_t)name[0]);
1039 	if (p == NULL)
1040 		goto done2;
1041 	lwkt_gettoken(&p->p_token);
1042 	PHOLD(p);
1043 
1044 	if ((!ps_argsopen) && p_trespass(cr1, p->p_ucred))
1045 		goto done;
1046 
1047 	if (req->newptr && curproc != p) {
1048 		error = EPERM;
1049 		goto done;
1050 	}
1051 	if (req->oldptr && p->p_args != NULL) {
1052 		error = SYSCTL_OUT(req, p->p_args->ar_args,
1053 				   p->p_args->ar_length);
1054 	}
1055 	if (req->newptr == NULL)
1056 		goto done;
1057 
1058 	if (req->newlen + sizeof(struct pargs) > ps_arg_cache_limit) {
1059 		goto done;
1060 	}
1061 
1062 	pa = kmalloc(sizeof(struct pargs) + req->newlen, M_PARGS, M_WAITOK);
1063 	refcount_init(&pa->ar_ref, 1);
1064 	pa->ar_length = req->newlen;
1065 	error = SYSCTL_IN(req, pa->ar_args, req->newlen);
1066 	if (error) {
1067 		kfree(pa, M_PARGS);
1068 		goto done;
1069 	}
1070 
1071 
1072 	/*
1073 	 * Replace p_args with the new pa.  p_args may have previously
1074 	 * been NULL.
1075 	 */
1076 	opa = p->p_args;
1077 	p->p_args = pa;
1078 
1079 	if (opa) {
1080 		KKASSERT(opa->ar_ref > 0);
1081 		if (refcount_release(&opa->ar_ref)) {
1082 			kfree(opa, M_PARGS);
1083 			/* opa = NULL; */
1084 		}
1085 	}
1086 done:
1087 	PRELE(p);
1088 	lwkt_reltoken(&p->p_token);
1089 done2:
1090 	return (error);
1091 }
1092 
1093 static int
1094 sysctl_kern_proc_cwd(SYSCTL_HANDLER_ARGS)
1095 {
1096 	int *name = (int*) arg1;
1097 	u_int namelen = arg2;
1098 	struct proc *p;
1099 	int error = 0;
1100 	char *fullpath, *freepath;
1101 	struct ucred *cr1 = curproc->p_ucred;
1102 
1103 	if (namelen != 1)
1104 		return (EINVAL);
1105 
1106 	lwkt_gettoken(&proc_token);
1107 	p = pfindn((pid_t)name[0]);
1108 	if (p == NULL)
1109 		goto done;
1110 
1111 	/*
1112 	 * If we are not allowed to see other args, we certainly shouldn't
1113 	 * get the cwd either. Also check the usual trespassing.
1114 	 */
1115 	if ((!ps_argsopen) && p_trespass(cr1, p->p_ucred))
1116 		goto done;
1117 
1118 	PHOLD(p);
1119 	if (req->oldptr && p->p_fd != NULL) {
1120 		error = cache_fullpath(p, &p->p_fd->fd_ncdir,
1121 		    &fullpath, &freepath, 0);
1122 		if (error)
1123 			goto done;
1124 		error = SYSCTL_OUT(req, fullpath, strlen(fullpath) + 1);
1125 		kfree(freepath, M_TEMP);
1126 	}
1127 
1128 	PRELE(p);
1129 
1130 done:
1131 	lwkt_reltoken(&proc_token);
1132 	return (error);
1133 }
1134 
1135 SYSCTL_NODE(_kern, KERN_PROC, proc, CTLFLAG_RD,  0, "Process table");
1136 
1137 SYSCTL_PROC(_kern_proc, KERN_PROC_ALL, all, CTLFLAG_RD|CTLTYPE_STRUCT,
1138 	0, 0, sysctl_kern_proc, "S,proc", "Return entire process table");
1139 
1140 SYSCTL_NODE(_kern_proc, KERN_PROC_PGRP, pgrp, CTLFLAG_RD,
1141 	sysctl_kern_proc, "Process table");
1142 
1143 SYSCTL_NODE(_kern_proc, KERN_PROC_TTY, tty, CTLFLAG_RD,
1144 	sysctl_kern_proc, "Process table");
1145 
1146 SYSCTL_NODE(_kern_proc, KERN_PROC_UID, uid, CTLFLAG_RD,
1147 	sysctl_kern_proc, "Process table");
1148 
1149 SYSCTL_NODE(_kern_proc, KERN_PROC_RUID, ruid, CTLFLAG_RD,
1150 	sysctl_kern_proc, "Process table");
1151 
1152 SYSCTL_NODE(_kern_proc, KERN_PROC_PID, pid, CTLFLAG_RD,
1153 	sysctl_kern_proc, "Process table");
1154 
1155 SYSCTL_NODE(_kern_proc, (KERN_PROC_ALL | KERN_PROC_FLAG_LWP), all_lwp, CTLFLAG_RD,
1156 	sysctl_kern_proc, "Process table");
1157 
1158 SYSCTL_NODE(_kern_proc, (KERN_PROC_PGRP | KERN_PROC_FLAG_LWP), pgrp_lwp, CTLFLAG_RD,
1159 	sysctl_kern_proc, "Process table");
1160 
1161 SYSCTL_NODE(_kern_proc, (KERN_PROC_TTY | KERN_PROC_FLAG_LWP), tty_lwp, CTLFLAG_RD,
1162 	sysctl_kern_proc, "Process table");
1163 
1164 SYSCTL_NODE(_kern_proc, (KERN_PROC_UID | KERN_PROC_FLAG_LWP), uid_lwp, CTLFLAG_RD,
1165 	sysctl_kern_proc, "Process table");
1166 
1167 SYSCTL_NODE(_kern_proc, (KERN_PROC_RUID | KERN_PROC_FLAG_LWP), ruid_lwp, CTLFLAG_RD,
1168 	sysctl_kern_proc, "Process table");
1169 
1170 SYSCTL_NODE(_kern_proc, (KERN_PROC_PID | KERN_PROC_FLAG_LWP), pid_lwp, CTLFLAG_RD,
1171 	sysctl_kern_proc, "Process table");
1172 
1173 SYSCTL_NODE(_kern_proc, KERN_PROC_ARGS, args, CTLFLAG_RW | CTLFLAG_ANYBODY,
1174 	sysctl_kern_proc_args, "Process argument list");
1175 
1176 SYSCTL_NODE(_kern_proc, KERN_PROC_CWD, cwd, CTLFLAG_RD | CTLFLAG_ANYBODY,
1177 	sysctl_kern_proc_cwd, "Process argument list");
1178