xref: /dflybsd-src/sys/kern/kern_proc.c (revision 0e1bdf492f13155bc45fb3fcd056ee51d3c763c0)
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 			p->p_flag &= ~P_CONTROLT;
295 			pgrp->pg_session = sess;
296 			KASSERT(p == curproc,
297 				("enterpgrp: mksession and p != curproc"));
298 		} else {
299 			pgrp->pg_session = p->p_session;
300 			sess_hold(pgrp->pg_session);
301 		}
302 		pgrp->pg_id = pgid;
303 		LIST_INIT(&pgrp->pg_members);
304 		LIST_INSERT_HEAD(PGRPHASH(pgid), pgrp, pg_hash);
305 		pgrp->pg_jobc = 0;
306 		SLIST_INIT(&pgrp->pg_sigiolst);
307 		lwkt_token_init(&pgrp->pg_token, "pgrp_token");
308 		refcount_init(&pgrp->pg_refs, 1);
309 		lockinit(&pgrp->pg_lock, "pgwt", 0, 0);
310 	} else if (pgrp == p->p_pgrp) {
311 		pgrel(pgrp);
312 		goto done;
313 	} /* else pgfind() referenced the pgrp */
314 
315 	/*
316 	 * Adjust eligibility of affected pgrps to participate in job control.
317 	 * Increment eligibility counts before decrementing, otherwise we
318 	 * could reach 0 spuriously during the first call.
319 	 */
320 	lwkt_gettoken(&pgrp->pg_token);
321 	lwkt_gettoken(&p->p_token);
322 	fixjobc(p, pgrp, 1);
323 	fixjobc(p, p->p_pgrp, 0);
324 	while ((opgrp = p->p_pgrp) != NULL) {
325 		opgrp = p->p_pgrp;
326 		lwkt_gettoken(&opgrp->pg_token);
327 		LIST_REMOVE(p, p_pglist);
328 		p->p_pgrp = NULL;
329 		lwkt_reltoken(&opgrp->pg_token);
330 		pgrel(opgrp);
331 	}
332 	p->p_pgrp = pgrp;
333 	LIST_INSERT_HEAD(&pgrp->pg_members, p, p_pglist);
334 	lwkt_reltoken(&p->p_token);
335 	lwkt_reltoken(&pgrp->pg_token);
336 done:
337 	error = 0;
338 fatal:
339 	return (error);
340 }
341 
342 /*
343  * Remove process from process group
344  *
345  * No requirements.
346  */
347 int
348 leavepgrp(struct proc *p)
349 {
350 	struct pgrp *pg = p->p_pgrp;
351 
352 	lwkt_gettoken(&p->p_token);
353 	pg = p->p_pgrp;
354 	if (pg) {
355 		pgref(pg);
356 		lwkt_gettoken(&pg->pg_token);
357 		if (p->p_pgrp == pg) {
358 			p->p_pgrp = NULL;
359 			LIST_REMOVE(p, p_pglist);
360 			pgrel(pg);
361 		}
362 		lwkt_reltoken(&pg->pg_token);
363 		lwkt_reltoken(&p->p_token);	/* avoid chaining on rel */
364 		pgrel(pg);
365 	} else {
366 		lwkt_reltoken(&p->p_token);
367 	}
368 	return (0);
369 }
370 
371 /*
372  * Delete a process group.  Must be called only after the last ref has been
373  * released.
374  */
375 static void
376 pgdelete(struct pgrp *pgrp)
377 {
378 	/*
379 	 * Reset any sigio structures pointing to us as a result of
380 	 * F_SETOWN with our pgid.
381 	 */
382 	funsetownlst(&pgrp->pg_sigiolst);
383 
384 	if (pgrp->pg_session->s_ttyp != NULL &&
385 	    pgrp->pg_session->s_ttyp->t_pgrp == pgrp)
386 		pgrp->pg_session->s_ttyp->t_pgrp = NULL;
387 	LIST_REMOVE(pgrp, pg_hash);
388 	sess_rele(pgrp->pg_session);
389 	kfree(pgrp, M_PGRP);
390 }
391 
392 /*
393  * Adjust the ref count on a session structure.  When the ref count falls to
394  * zero the tty is disassociated from the session and the session structure
395  * is freed.  Note that tty assocation is not itself ref-counted.
396  *
397  * No requirements.
398  */
399 void
400 sess_hold(struct session *sp)
401 {
402 	lwkt_gettoken(&tty_token);
403 	++sp->s_count;
404 	lwkt_reltoken(&tty_token);
405 }
406 
407 /*
408  * No requirements.
409  */
410 void
411 sess_rele(struct session *sp)
412 {
413 	struct tty *tp;
414 
415 	KKASSERT(sp->s_count > 0);
416 	lwkt_gettoken(&tty_token);
417 	if (--sp->s_count == 0) {
418 		if (sp->s_ttyp && sp->s_ttyp->t_session) {
419 #ifdef TTY_DO_FULL_CLOSE
420 			/* FULL CLOSE, see ttyclearsession() */
421 			KKASSERT(sp->s_ttyp->t_session == sp);
422 			sp->s_ttyp->t_session = NULL;
423 #else
424 			/* HALF CLOSE, see ttyclearsession() */
425 			if (sp->s_ttyp->t_session == sp)
426 				sp->s_ttyp->t_session = NULL;
427 #endif
428 		}
429 		if ((tp = sp->s_ttyp) != NULL) {
430 			sp->s_ttyp = NULL;
431 			ttyunhold(tp);
432 		}
433 		kfree(sp, M_SESSION);
434 	}
435 	lwkt_reltoken(&tty_token);
436 }
437 
438 /*
439  * Adjust pgrp jobc counters when specified process changes process group.
440  * We count the number of processes in each process group that "qualify"
441  * the group for terminal job control (those with a parent in a different
442  * process group of the same session).  If that count reaches zero, the
443  * process group becomes orphaned.  Check both the specified process'
444  * process group and that of its children.
445  * entering == 0 => p is leaving specified group.
446  * entering == 1 => p is entering specified group.
447  *
448  * No requirements.
449  */
450 void
451 fixjobc(struct proc *p, struct pgrp *pgrp, int entering)
452 {
453 	struct pgrp *hispgrp;
454 	struct session *mysession;
455 	struct proc *np;
456 
457 	/*
458 	 * Check p's parent to see whether p qualifies its own process
459 	 * group; if so, adjust count for p's process group.
460 	 */
461 	lwkt_gettoken(&p->p_token);	/* p_children scan */
462 	lwkt_gettoken(&pgrp->pg_token);
463 
464 	mysession = pgrp->pg_session;
465 	if ((hispgrp = p->p_pptr->p_pgrp) != pgrp &&
466 	    hispgrp->pg_session == mysession) {
467 		if (entering)
468 			pgrp->pg_jobc++;
469 		else if (--pgrp->pg_jobc == 0)
470 			orphanpg(pgrp);
471 	}
472 
473 	/*
474 	 * Check this process' children to see whether they qualify
475 	 * their process groups; if so, adjust counts for children's
476 	 * process groups.
477 	 */
478 	LIST_FOREACH(np, &p->p_children, p_sibling) {
479 		PHOLD(np);
480 		lwkt_gettoken(&np->p_token);
481 		if ((hispgrp = np->p_pgrp) != pgrp &&
482 		    hispgrp->pg_session == mysession &&
483 		    np->p_stat != SZOMB) {
484 			pgref(hispgrp);
485 			lwkt_gettoken(&hispgrp->pg_token);
486 			if (entering)
487 				hispgrp->pg_jobc++;
488 			else if (--hispgrp->pg_jobc == 0)
489 				orphanpg(hispgrp);
490 			lwkt_reltoken(&hispgrp->pg_token);
491 			pgrel(hispgrp);
492 		}
493 		lwkt_reltoken(&np->p_token);
494 		PRELE(np);
495 	}
496 	KKASSERT(pgrp->pg_refs > 0);
497 	lwkt_reltoken(&pgrp->pg_token);
498 	lwkt_reltoken(&p->p_token);
499 }
500 
501 /*
502  * A process group has become orphaned;
503  * if there are any stopped processes in the group,
504  * hang-up all process in that group.
505  *
506  * The caller must hold pg_token.
507  */
508 static void
509 orphanpg(struct pgrp *pg)
510 {
511 	struct proc *p;
512 
513 	LIST_FOREACH(p, &pg->pg_members, p_pglist) {
514 		if (p->p_stat == SSTOP) {
515 			LIST_FOREACH(p, &pg->pg_members, p_pglist) {
516 				ksignal(p, SIGHUP);
517 				ksignal(p, SIGCONT);
518 			}
519 			return;
520 		}
521 	}
522 }
523 
524 /*
525  * Add a new process to the allproc list and the PID hash.  This
526  * also assigns a pid to the new process.
527  *
528  * No requirements.
529  */
530 void
531 proc_add_allproc(struct proc *p)
532 {
533 	int random_offset;
534 
535 	if ((random_offset = randompid) != 0) {
536 		get_mplock();
537 		random_offset = karc4random() % random_offset;
538 		rel_mplock();
539 	}
540 
541 	lwkt_gettoken(&proc_token);
542 	p->p_pid = proc_getnewpid_locked(random_offset);
543 	LIST_INSERT_HEAD(&allproc, p, p_list);
544 	LIST_INSERT_HEAD(PIDHASH(p->p_pid), p, p_hash);
545 	lwkt_reltoken(&proc_token);
546 }
547 
548 /*
549  * Calculate a new process pid.  This function is integrated into
550  * proc_add_allproc() to guarentee that the new pid is not reused before
551  * the new process can be added to the allproc list.
552  *
553  * The caller must hold proc_token.
554  */
555 static
556 pid_t
557 proc_getnewpid_locked(int random_offset)
558 {
559 	static pid_t nextpid;
560 	static pid_t pidchecked;
561 	struct proc *p;
562 
563 	/*
564 	 * Find an unused process ID.  We remember a range of unused IDs
565 	 * ready to use (from nextpid+1 through pidchecked-1).
566 	 */
567 	nextpid = nextpid + 1 + random_offset;
568 retry:
569 	/*
570 	 * If the process ID prototype has wrapped around,
571 	 * restart somewhat above 0, as the low-numbered procs
572 	 * tend to include daemons that don't exit.
573 	 */
574 	if (nextpid >= PID_MAX) {
575 		nextpid = nextpid % PID_MAX;
576 		if (nextpid < 100)
577 			nextpid += 100;
578 		pidchecked = 0;
579 	}
580 	if (nextpid >= pidchecked) {
581 		int doingzomb = 0;
582 
583 		pidchecked = PID_MAX;
584 
585 		/*
586 		 * Scan the active and zombie procs to check whether this pid
587 		 * is in use.  Remember the lowest pid that's greater
588 		 * than nextpid, so we can avoid checking for a while.
589 		 *
590 		 * NOTE: Processes in the midst of being forked may not
591 		 *	 yet have p_pgrp and p_pgrp->pg_session set up
592 		 *	 yet, so we have to check for NULL.
593 		 *
594 		 *	 Processes being torn down should be interlocked
595 		 *	 with proc_token prior to the clearing of their
596 		 *	 p_pgrp.
597 		 */
598 		p = LIST_FIRST(&allproc);
599 again:
600 		for (; p != NULL; p = LIST_NEXT(p, p_list)) {
601 			while (p->p_pid == nextpid ||
602 			    (p->p_pgrp && p->p_pgrp->pg_id == nextpid) ||
603 			    (p->p_pgrp && p->p_session &&
604 			     p->p_session->s_sid == nextpid)) {
605 				nextpid++;
606 				if (nextpid >= pidchecked)
607 					goto retry;
608 			}
609 			if (p->p_pid > nextpid && pidchecked > p->p_pid)
610 				pidchecked = p->p_pid;
611 			if (p->p_pgrp &&
612 			    p->p_pgrp->pg_id > nextpid &&
613 			    pidchecked > p->p_pgrp->pg_id) {
614 				pidchecked = p->p_pgrp->pg_id;
615 			}
616 			if (p->p_pgrp && p->p_session &&
617 			    p->p_session->s_sid > nextpid &&
618 			    pidchecked > p->p_session->s_sid) {
619 				pidchecked = p->p_session->s_sid;
620 			}
621 		}
622 		if (!doingzomb) {
623 			doingzomb = 1;
624 			p = LIST_FIRST(&zombproc);
625 			goto again;
626 		}
627 	}
628 	return(nextpid);
629 }
630 
631 /*
632  * Called from exit1 to remove a process from the allproc
633  * list and move it to the zombie list.
634  *
635  * No requirements.
636  */
637 void
638 proc_move_allproc_zombie(struct proc *p)
639 {
640 	lwkt_gettoken(&proc_token);
641 	while (p->p_lock) {
642 		tsleep(p, 0, "reap1", hz / 10);
643 	}
644 	LIST_REMOVE(p, p_list);
645 	LIST_INSERT_HEAD(&zombproc, p, p_list);
646 	LIST_REMOVE(p, p_hash);
647 	p->p_stat = SZOMB;
648 	lwkt_reltoken(&proc_token);
649 	dsched_exit_proc(p);
650 }
651 
652 /*
653  * This routine is called from kern_wait() and will remove the process
654  * from the zombie list and the sibling list.  This routine will block
655  * if someone has a lock on the proces (p_lock).
656  *
657  * No requirements.
658  */
659 void
660 proc_remove_zombie(struct proc *p)
661 {
662 	lwkt_gettoken(&proc_token);
663 	while (p->p_lock) {
664 		tsleep(p, 0, "reap1", hz / 10);
665 	}
666 	LIST_REMOVE(p, p_list); /* off zombproc */
667 	LIST_REMOVE(p, p_sibling);
668 	lwkt_reltoken(&proc_token);
669 }
670 
671 /*
672  * Scan all processes on the allproc list.  The process is automatically
673  * held for the callback.  A return value of -1 terminates the loop.
674  *
675  * The callback is made with the process held and proc_token held.
676  *
677  * We limit the scan to the number of processes as-of the start of
678  * the scan so as not to get caught up in an endless loop if new processes
679  * are created more quickly than we can scan the old ones.  Add a little
680  * slop to try to catch edge cases since nprocs can race.
681  *
682  * No requirements.
683  */
684 void
685 allproc_scan(int (*callback)(struct proc *, void *), void *data)
686 {
687 	struct proc *p;
688 	int r;
689 	int limit = nprocs + ncpus;
690 
691 	lwkt_gettoken(&proc_token);
692 	LIST_FOREACH(p, &allproc, p_list) {
693 		PHOLD(p);
694 		r = callback(p, data);
695 		PRELE(p);
696 		if (r < 0)
697 			break;
698 		if (--limit < 0)
699 			break;
700 	}
701 	lwkt_reltoken(&proc_token);
702 }
703 
704 /*
705  * Scan all lwps of processes on the allproc list.  The lwp is automatically
706  * held for the callback.  A return value of -1 terminates the loop.
707  *
708  * No requirements.
709  * The callback is made with the proces and lwp both held, and proc_token held.
710  */
711 void
712 alllwp_scan(int (*callback)(struct lwp *, void *), void *data)
713 {
714 	struct proc *p;
715 	struct lwp *lp;
716 	int r = 0;
717 
718 	lwkt_gettoken(&proc_token);
719 	LIST_FOREACH(p, &allproc, p_list) {
720 		PHOLD(p);
721 		FOREACH_LWP_IN_PROC(lp, p) {
722 			LWPHOLD(lp);
723 			r = callback(lp, data);
724 			LWPRELE(lp);
725 		}
726 		PRELE(p);
727 		if (r < 0)
728 			break;
729 	}
730 	lwkt_reltoken(&proc_token);
731 }
732 
733 /*
734  * Scan all processes on the zombproc list.  The process is automatically
735  * held for the callback.  A return value of -1 terminates the loop.
736  *
737  * No requirements.
738  * The callback is made with the proces held and proc_token held.
739  */
740 void
741 zombproc_scan(int (*callback)(struct proc *, void *), void *data)
742 {
743 	struct proc *p;
744 	int r;
745 
746 	lwkt_gettoken(&proc_token);
747 	LIST_FOREACH(p, &zombproc, p_list) {
748 		PHOLD(p);
749 		r = callback(p, data);
750 		PRELE(p);
751 		if (r < 0)
752 			break;
753 	}
754 	lwkt_reltoken(&proc_token);
755 }
756 
757 #include "opt_ddb.h"
758 #ifdef DDB
759 #include <ddb/ddb.h>
760 
761 /*
762  * Debugging only
763  */
764 DB_SHOW_COMMAND(pgrpdump, pgrpdump)
765 {
766 	struct pgrp *pgrp;
767 	struct proc *p;
768 	int i;
769 
770 	for (i = 0; i <= pgrphash; i++) {
771 		if (!LIST_EMPTY(&pgrphashtbl[i])) {
772 			kprintf("\tindx %d\n", i);
773 			LIST_FOREACH(pgrp, &pgrphashtbl[i], pg_hash) {
774 				kprintf(
775 			"\tpgrp %p, pgid %ld, sess %p, sesscnt %d, mem %p\n",
776 				    (void *)pgrp, (long)pgrp->pg_id,
777 				    (void *)pgrp->pg_session,
778 				    pgrp->pg_session->s_count,
779 				    (void *)LIST_FIRST(&pgrp->pg_members));
780 				LIST_FOREACH(p, &pgrp->pg_members, p_pglist) {
781 					kprintf("\t\tpid %ld addr %p pgrp %p\n",
782 					    (long)p->p_pid, (void *)p,
783 					    (void *)p->p_pgrp);
784 				}
785 			}
786 		}
787 	}
788 }
789 #endif /* DDB */
790 
791 /*
792  * Locate a process on the zombie list.  Return a process or NULL.
793  * The returned process will be referenced and the caller must release
794  * it with PRELE().
795  *
796  * No other requirements.
797  */
798 struct proc *
799 zpfind(pid_t pid)
800 {
801 	struct proc *p;
802 
803 	lwkt_gettoken(&proc_token);
804 	LIST_FOREACH(p, &zombproc, p_list) {
805 		if (p->p_pid == pid) {
806 			PHOLD(p);
807 			lwkt_reltoken(&proc_token);
808 			return (p);
809 		}
810 	}
811 	lwkt_reltoken(&proc_token);
812 	return (NULL);
813 }
814 
815 /*
816  * The caller must hold proc_token.
817  */
818 static int
819 sysctl_out_proc(struct proc *p, struct sysctl_req *req, int flags)
820 {
821 	struct kinfo_proc ki;
822 	struct lwp *lp;
823 	int skp = 0, had_output = 0;
824 	int error;
825 
826 	bzero(&ki, sizeof(ki));
827 	fill_kinfo_proc(p, &ki);
828 	if ((flags & KERN_PROC_FLAG_LWP) == 0)
829 		skp = 1;
830 	error = 0;
831 	FOREACH_LWP_IN_PROC(lp, p) {
832 		LWPHOLD(lp);
833 		fill_kinfo_lwp(lp, &ki.kp_lwp);
834 		had_output = 1;
835 		error = SYSCTL_OUT(req, &ki, sizeof(ki));
836 		LWPRELE(lp);
837 		if (error)
838 			break;
839 		if (skp)
840 			break;
841 	}
842 	/* We need to output at least the proc, even if there is no lwp. */
843 	if (had_output == 0) {
844 		error = SYSCTL_OUT(req, &ki, sizeof(ki));
845 	}
846 	return (error);
847 }
848 
849 /*
850  * The caller must hold proc_token.
851  */
852 static int
853 sysctl_out_proc_kthread(struct thread *td, struct sysctl_req *req, int flags)
854 {
855 	struct kinfo_proc ki;
856 	int error;
857 
858 	fill_kinfo_proc_kthread(td, &ki);
859 	error = SYSCTL_OUT(req, &ki, sizeof(ki));
860 	if (error)
861 		return error;
862 	return(0);
863 }
864 
865 /*
866  * No requirements.
867  */
868 static int
869 sysctl_kern_proc(SYSCTL_HANDLER_ARGS)
870 {
871 	int *name = (int*) arg1;
872 	int oid = oidp->oid_number;
873 	u_int namelen = arg2;
874 	struct proc *p;
875 	struct proclist *plist;
876 	struct thread *td;
877 	int doingzomb, flags = 0;
878 	int error = 0;
879 	int n;
880 	int origcpu;
881 	struct ucred *cr1 = curproc->p_ucred;
882 
883 	flags = oid & KERN_PROC_FLAGMASK;
884 	oid &= ~KERN_PROC_FLAGMASK;
885 
886 	if ((oid == KERN_PROC_ALL && namelen != 0) ||
887 	    (oid != KERN_PROC_ALL && namelen != 1))
888 		return (EINVAL);
889 
890 	lwkt_gettoken(&proc_token);
891 	if (oid == KERN_PROC_PID) {
892 		p = pfindn((pid_t)name[0]);
893 		if (p == NULL)
894 			goto post_threads;
895 		if (!PRISON_CHECK(cr1, p->p_ucred))
896 			goto post_threads;
897 		PHOLD(p);
898 		error = sysctl_out_proc(p, req, flags);
899 		PRELE(p);
900 		goto post_threads;
901 	}
902 
903 	if (!req->oldptr) {
904 		/* overestimate by 5 procs */
905 		error = SYSCTL_OUT(req, 0, sizeof (struct kinfo_proc) * 5);
906 		if (error)
907 			goto post_threads;
908 	}
909 	for (doingzomb = 0; doingzomb <= 1; doingzomb++) {
910 		if (doingzomb)
911 			plist = &zombproc;
912 		else
913 			plist = &allproc;
914 		LIST_FOREACH(p, plist, p_list) {
915 			/*
916 			 * Show a user only their processes.
917 			 */
918 			if ((!ps_showallprocs) && p_trespass(cr1, p->p_ucred))
919 				continue;
920 			/*
921 			 * Skip embryonic processes.
922 			 */
923 			if (p->p_stat == SIDL)
924 				continue;
925 			/*
926 			 * TODO - make more efficient (see notes below).
927 			 * do by session.
928 			 */
929 			switch (oid) {
930 			case KERN_PROC_PGRP:
931 				/* could do this by traversing pgrp */
932 				if (p->p_pgrp == NULL ||
933 				    p->p_pgrp->pg_id != (pid_t)name[0])
934 					continue;
935 				break;
936 
937 			case KERN_PROC_TTY:
938 				if ((p->p_flag & P_CONTROLT) == 0 ||
939 				    p->p_session == NULL ||
940 				    p->p_session->s_ttyp == NULL ||
941 				    dev2udev(p->p_session->s_ttyp->t_dev) !=
942 					(udev_t)name[0])
943 					continue;
944 				break;
945 
946 			case KERN_PROC_UID:
947 				if (p->p_ucred == NULL ||
948 				    p->p_ucred->cr_uid != (uid_t)name[0])
949 					continue;
950 				break;
951 
952 			case KERN_PROC_RUID:
953 				if (p->p_ucred == NULL ||
954 				    p->p_ucred->cr_ruid != (uid_t)name[0])
955 					continue;
956 				break;
957 			}
958 
959 			if (!PRISON_CHECK(cr1, p->p_ucred))
960 				continue;
961 			PHOLD(p);
962 			error = sysctl_out_proc(p, req, flags);
963 			PRELE(p);
964 			if (error)
965 				goto post_threads;
966 		}
967 	}
968 
969 	/*
970 	 * Iterate over all active cpus and scan their thread list.  Start
971 	 * with the next logical cpu and end with our original cpu.  We
972 	 * migrate our own thread to each target cpu in order to safely scan
973 	 * its thread list.  In the last loop we migrate back to our original
974 	 * cpu.
975 	 */
976 	origcpu = mycpu->gd_cpuid;
977 	if (!ps_showallthreads || jailed(cr1))
978 		goto post_threads;
979 
980 	for (n = 1; n <= ncpus; ++n) {
981 		globaldata_t rgd;
982 		int nid;
983 
984 		nid = (origcpu + n) % ncpus;
985 		if ((smp_active_mask & CPUMASK(nid)) == 0)
986 			continue;
987 		rgd = globaldata_find(nid);
988 		lwkt_setcpu_self(rgd);
989 
990 		TAILQ_FOREACH(td, &mycpu->gd_tdallq, td_allq) {
991 			if (td->td_proc)
992 				continue;
993 			switch (oid) {
994 			case KERN_PROC_PGRP:
995 			case KERN_PROC_TTY:
996 			case KERN_PROC_UID:
997 			case KERN_PROC_RUID:
998 				continue;
999 			default:
1000 				break;
1001 			}
1002 			lwkt_hold(td);
1003 			error = sysctl_out_proc_kthread(td, req, doingzomb);
1004 			lwkt_rele(td);
1005 			if (error)
1006 				goto post_threads;
1007 		}
1008 	}
1009 post_threads:
1010 	lwkt_reltoken(&proc_token);
1011 	return (error);
1012 }
1013 
1014 /*
1015  * This sysctl allows a process to retrieve the argument list or process
1016  * title for another process without groping around in the address space
1017  * of the other process.  It also allow a process to set its own "process
1018  * title to a string of its own choice.
1019  *
1020  * No requirements.
1021  */
1022 static int
1023 sysctl_kern_proc_args(SYSCTL_HANDLER_ARGS)
1024 {
1025 	int *name = (int*) arg1;
1026 	u_int namelen = arg2;
1027 	struct proc *p;
1028 	struct pargs *opa;
1029 	struct pargs *pa;
1030 	int error = 0;
1031 	struct ucred *cr1 = curproc->p_ucred;
1032 
1033 	if (namelen != 1)
1034 		return (EINVAL);
1035 
1036 	p = pfindn((pid_t)name[0]);
1037 	if (p == NULL)
1038 		goto done2;
1039 	lwkt_gettoken(&p->p_token);
1040 	PHOLD(p);
1041 
1042 	if ((!ps_argsopen) && p_trespass(cr1, p->p_ucred))
1043 		goto done;
1044 
1045 	if (req->newptr && curproc != p) {
1046 		error = EPERM;
1047 		goto done;
1048 	}
1049 	if (req->oldptr && p->p_args != NULL) {
1050 		error = SYSCTL_OUT(req, p->p_args->ar_args,
1051 				   p->p_args->ar_length);
1052 	}
1053 	if (req->newptr == NULL)
1054 		goto done;
1055 
1056 	if (req->newlen + sizeof(struct pargs) > ps_arg_cache_limit) {
1057 		goto done;
1058 	}
1059 
1060 	pa = kmalloc(sizeof(struct pargs) + req->newlen, M_PARGS, M_WAITOK);
1061 	refcount_init(&pa->ar_ref, 1);
1062 	pa->ar_length = req->newlen;
1063 	error = SYSCTL_IN(req, pa->ar_args, req->newlen);
1064 	if (error) {
1065 		kfree(pa, M_PARGS);
1066 		goto done;
1067 	}
1068 
1069 
1070 	/*
1071 	 * Replace p_args with the new pa.  p_args may have previously
1072 	 * been NULL.
1073 	 */
1074 	opa = p->p_args;
1075 	p->p_args = pa;
1076 
1077 	if (opa) {
1078 		KKASSERT(opa->ar_ref > 0);
1079 		if (refcount_release(&opa->ar_ref)) {
1080 			kfree(opa, M_PARGS);
1081 			/* opa = NULL; */
1082 		}
1083 	}
1084 done:
1085 	PRELE(p);
1086 	lwkt_reltoken(&p->p_token);
1087 done2:
1088 	return (error);
1089 }
1090 
1091 static int
1092 sysctl_kern_proc_cwd(SYSCTL_HANDLER_ARGS)
1093 {
1094 	int *name = (int*) arg1;
1095 	u_int namelen = arg2;
1096 	struct proc *p;
1097 	int error = 0;
1098 	char *fullpath, *freepath;
1099 	struct ucred *cr1 = curproc->p_ucred;
1100 
1101 	if (namelen != 1)
1102 		return (EINVAL);
1103 
1104 	lwkt_gettoken(&proc_token);
1105 	p = pfindn((pid_t)name[0]);
1106 	if (p == NULL)
1107 		goto done;
1108 
1109 	/*
1110 	 * If we are not allowed to see other args, we certainly shouldn't
1111 	 * get the cwd either. Also check the usual trespassing.
1112 	 */
1113 	if ((!ps_argsopen) && p_trespass(cr1, p->p_ucred))
1114 		goto done;
1115 
1116 	PHOLD(p);
1117 	if (req->oldptr && p->p_fd != NULL) {
1118 		error = cache_fullpath(p, &p->p_fd->fd_ncdir,
1119 		    &fullpath, &freepath, 0);
1120 		if (error)
1121 			goto done;
1122 		error = SYSCTL_OUT(req, fullpath, strlen(fullpath) + 1);
1123 		kfree(freepath, M_TEMP);
1124 	}
1125 
1126 	PRELE(p);
1127 
1128 done:
1129 	lwkt_reltoken(&proc_token);
1130 	return (error);
1131 }
1132 
1133 SYSCTL_NODE(_kern, KERN_PROC, proc, CTLFLAG_RD,  0, "Process table");
1134 
1135 SYSCTL_PROC(_kern_proc, KERN_PROC_ALL, all, CTLFLAG_RD|CTLTYPE_STRUCT,
1136 	0, 0, sysctl_kern_proc, "S,proc", "Return entire process table");
1137 
1138 SYSCTL_NODE(_kern_proc, KERN_PROC_PGRP, pgrp, CTLFLAG_RD,
1139 	sysctl_kern_proc, "Process table");
1140 
1141 SYSCTL_NODE(_kern_proc, KERN_PROC_TTY, tty, CTLFLAG_RD,
1142 	sysctl_kern_proc, "Process table");
1143 
1144 SYSCTL_NODE(_kern_proc, KERN_PROC_UID, uid, CTLFLAG_RD,
1145 	sysctl_kern_proc, "Process table");
1146 
1147 SYSCTL_NODE(_kern_proc, KERN_PROC_RUID, ruid, CTLFLAG_RD,
1148 	sysctl_kern_proc, "Process table");
1149 
1150 SYSCTL_NODE(_kern_proc, KERN_PROC_PID, pid, CTLFLAG_RD,
1151 	sysctl_kern_proc, "Process table");
1152 
1153 SYSCTL_NODE(_kern_proc, (KERN_PROC_ALL | KERN_PROC_FLAG_LWP), all_lwp, CTLFLAG_RD,
1154 	sysctl_kern_proc, "Process table");
1155 
1156 SYSCTL_NODE(_kern_proc, (KERN_PROC_PGRP | KERN_PROC_FLAG_LWP), pgrp_lwp, CTLFLAG_RD,
1157 	sysctl_kern_proc, "Process table");
1158 
1159 SYSCTL_NODE(_kern_proc, (KERN_PROC_TTY | KERN_PROC_FLAG_LWP), tty_lwp, CTLFLAG_RD,
1160 	sysctl_kern_proc, "Process table");
1161 
1162 SYSCTL_NODE(_kern_proc, (KERN_PROC_UID | KERN_PROC_FLAG_LWP), uid_lwp, CTLFLAG_RD,
1163 	sysctl_kern_proc, "Process table");
1164 
1165 SYSCTL_NODE(_kern_proc, (KERN_PROC_RUID | KERN_PROC_FLAG_LWP), ruid_lwp, CTLFLAG_RD,
1166 	sysctl_kern_proc, "Process table");
1167 
1168 SYSCTL_NODE(_kern_proc, (KERN_PROC_PID | KERN_PROC_FLAG_LWP), pid_lwp, CTLFLAG_RD,
1169 	sysctl_kern_proc, "Process table");
1170 
1171 SYSCTL_NODE(_kern_proc, KERN_PROC_ARGS, args, CTLFLAG_RW | CTLFLAG_ANYBODY,
1172 	sysctl_kern_proc_args, "Process argument list");
1173 
1174 SYSCTL_NODE(_kern_proc, KERN_PROC_CWD, cwd, CTLFLAG_RD | CTLFLAG_ANYBODY,
1175 	sysctl_kern_proc_cwd, "Process argument list");
1176