kernel - Make numerous proc accesses use p->p_token instead of proc_token.
[dragonfly.git] / sys / kern / kern_proc.c
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                  * Scan the active and zombie procs to check whether this pid
586                  * is in use.  Remember the lowest pid that's greater
587                  * than nextpid, so we can avoid checking for a while.
588                  */
589                 p = LIST_FIRST(&allproc);
590 again:
591                 for (; p != 0; p = LIST_NEXT(p, p_list)) {
592                         while (p->p_pid == nextpid ||
593                             p->p_pgrp->pg_id == nextpid ||
594                             p->p_session->s_sid == nextpid) {
595                                 nextpid++;
596                                 if (nextpid >= pidchecked)
597                                         goto retry;
598                         }
599                         if (p->p_pid > nextpid && pidchecked > p->p_pid)
600                                 pidchecked = p->p_pid;
601                         if (p->p_pgrp->pg_id > nextpid &&
602                             pidchecked > p->p_pgrp->pg_id)
603                                 pidchecked = p->p_pgrp->pg_id;
604                         if (p->p_session->s_sid > nextpid &&
605                             pidchecked > p->p_session->s_sid)
606                                 pidchecked = p->p_session->s_sid;
607                 }
608                 if (!doingzomb) {
609                         doingzomb = 1;
610                         p = LIST_FIRST(&zombproc);
611                         goto again;
612                 }
613         }
614         return(nextpid);
615 }
616
617 /*
618  * Called from exit1 to remove a process from the allproc
619  * list and move it to the zombie list.
620  *
621  * No requirements.
622  */
623 void
624 proc_move_allproc_zombie(struct proc *p)
625 {
626         lwkt_gettoken(&proc_token);
627         while (p->p_lock) {
628                 tsleep(p, 0, "reap1", hz / 10);
629         }
630         LIST_REMOVE(p, p_list);
631         LIST_INSERT_HEAD(&zombproc, p, p_list);
632         LIST_REMOVE(p, p_hash);
633         p->p_stat = SZOMB;
634         lwkt_reltoken(&proc_token);
635         dsched_exit_proc(p);
636 }
637
638 /*
639  * This routine is called from kern_wait() and will remove the process
640  * from the zombie list and the sibling list.  This routine will block
641  * if someone has a lock on the proces (p_lock).
642  *
643  * No requirements.
644  */
645 void
646 proc_remove_zombie(struct proc *p)
647 {
648         lwkt_gettoken(&proc_token);
649         while (p->p_lock) {
650                 tsleep(p, 0, "reap1", hz / 10);
651         }
652         LIST_REMOVE(p, p_list); /* off zombproc */
653         LIST_REMOVE(p, p_sibling);
654         lwkt_reltoken(&proc_token);
655 }
656
657 /*
658  * Scan all processes on the allproc list.  The process is automatically
659  * held for the callback.  A return value of -1 terminates the loop.
660  *
661  * No requirements.
662  * The callback is made with the process held and proc_token held.
663  */
664 void
665 allproc_scan(int (*callback)(struct proc *, void *), void *data)
666 {
667         struct proc *p;
668         int r;
669
670         lwkt_gettoken(&proc_token);
671         LIST_FOREACH(p, &allproc, p_list) {
672                 PHOLD(p);
673                 r = callback(p, data);
674                 PRELE(p);
675                 if (r < 0)
676                         break;
677         }
678         lwkt_reltoken(&proc_token);
679 }
680
681 /*
682  * Scan all lwps of processes on the allproc list.  The lwp is automatically
683  * held for the callback.  A return value of -1 terminates the loop.
684  *
685  * No requirements.
686  * The callback is made with the proces and lwp both held, and proc_token held.
687  */
688 void
689 alllwp_scan(int (*callback)(struct lwp *, void *), void *data)
690 {
691         struct proc *p;
692         struct lwp *lp;
693         int r = 0;
694
695         lwkt_gettoken(&proc_token);
696         LIST_FOREACH(p, &allproc, p_list) {
697                 PHOLD(p);
698                 FOREACH_LWP_IN_PROC(lp, p) {
699                         LWPHOLD(lp);
700                         r = callback(lp, data);
701                         LWPRELE(lp);
702                 }
703                 PRELE(p);
704                 if (r < 0)
705                         break;
706         }
707         lwkt_reltoken(&proc_token);
708 }
709
710 /*
711  * Scan all processes on the zombproc list.  The process is automatically
712  * held for the callback.  A return value of -1 terminates the loop.
713  *
714  * No requirements.
715  * The callback is made with the proces held and proc_token held.
716  */
717 void
718 zombproc_scan(int (*callback)(struct proc *, void *), void *data)
719 {
720         struct proc *p;
721         int r;
722
723         lwkt_gettoken(&proc_token);
724         LIST_FOREACH(p, &zombproc, p_list) {
725                 PHOLD(p);
726                 r = callback(p, data);
727                 PRELE(p);
728                 if (r < 0)
729                         break;
730         }
731         lwkt_reltoken(&proc_token);
732 }
733
734 #include "opt_ddb.h"
735 #ifdef DDB
736 #include <ddb/ddb.h>
737
738 /*
739  * Debugging only
740  */
741 DB_SHOW_COMMAND(pgrpdump, pgrpdump)
742 {
743         struct pgrp *pgrp;
744         struct proc *p;
745         int i;
746
747         for (i = 0; i <= pgrphash; i++) {
748                 if (!LIST_EMPTY(&pgrphashtbl[i])) {
749                         kprintf("\tindx %d\n", i);
750                         LIST_FOREACH(pgrp, &pgrphashtbl[i], pg_hash) {
751                                 kprintf(
752                         "\tpgrp %p, pgid %ld, sess %p, sesscnt %d, mem %p\n",
753                                     (void *)pgrp, (long)pgrp->pg_id,
754                                     (void *)pgrp->pg_session,
755                                     pgrp->pg_session->s_count,
756                                     (void *)LIST_FIRST(&pgrp->pg_members));
757                                 LIST_FOREACH(p, &pgrp->pg_members, p_pglist) {
758                                         kprintf("\t\tpid %ld addr %p pgrp %p\n", 
759                                             (long)p->p_pid, (void *)p,
760                                             (void *)p->p_pgrp);
761                                 }
762                         }
763                 }
764         }
765 }
766 #endif /* DDB */
767
768 /*
769  * Locate a process on the zombie list.  Return a process or NULL.
770  * The returned process will be referenced and the caller must release
771  * it with PRELE().
772  *
773  * No other requirements.
774  */
775 struct proc *
776 zpfind(pid_t pid)
777 {
778         struct proc *p;
779
780         lwkt_gettoken(&proc_token);
781         LIST_FOREACH(p, &zombproc, p_list) {
782                 if (p->p_pid == pid) {
783                         PHOLD(p);
784                         lwkt_reltoken(&proc_token);
785                         return (p);
786                 }
787         }
788         lwkt_reltoken(&proc_token);
789         return (NULL);
790 }
791
792 /*
793  * The caller must hold proc_token.
794  */
795 static int
796 sysctl_out_proc(struct proc *p, struct sysctl_req *req, int flags)
797 {
798         struct kinfo_proc ki;
799         struct lwp *lp;
800         int skp = 0, had_output = 0;
801         int error;
802
803         bzero(&ki, sizeof(ki));
804         fill_kinfo_proc(p, &ki);
805         if ((flags & KERN_PROC_FLAG_LWP) == 0)
806                 skp = 1;
807         error = 0;
808         FOREACH_LWP_IN_PROC(lp, p) {
809                 LWPHOLD(lp);
810                 fill_kinfo_lwp(lp, &ki.kp_lwp);
811                 had_output = 1;
812                 error = SYSCTL_OUT(req, &ki, sizeof(ki));
813                 LWPRELE(lp);
814                 if (error)
815                         break;
816                 if (skp)
817                         break;
818         }
819         /* We need to output at least the proc, even if there is no lwp. */
820         if (had_output == 0) {
821                 error = SYSCTL_OUT(req, &ki, sizeof(ki));
822         }
823         return (error);
824 }
825
826 /*
827  * The caller must hold proc_token.
828  */
829 static int
830 sysctl_out_proc_kthread(struct thread *td, struct sysctl_req *req, int flags)
831 {
832         struct kinfo_proc ki;
833         int error;
834
835         fill_kinfo_proc_kthread(td, &ki);
836         error = SYSCTL_OUT(req, &ki, sizeof(ki));
837         if (error)
838                 return error;
839         return(0);
840 }
841
842 /*
843  * No requirements.
844  */
845 static int
846 sysctl_kern_proc(SYSCTL_HANDLER_ARGS)
847 {
848         int *name = (int*) arg1;
849         int oid = oidp->oid_number;
850         u_int namelen = arg2;
851         struct proc *p;
852         struct proclist *plist;
853         struct thread *td;
854         int doingzomb, flags = 0;
855         int error = 0;
856         int n;
857         int origcpu;
858         struct ucred *cr1 = curproc->p_ucred;
859
860         flags = oid & KERN_PROC_FLAGMASK;
861         oid &= ~KERN_PROC_FLAGMASK;
862
863         if ((oid == KERN_PROC_ALL && namelen != 0) ||
864             (oid != KERN_PROC_ALL && namelen != 1))
865                 return (EINVAL);
866
867         lwkt_gettoken(&proc_token);
868         if (oid == KERN_PROC_PID) {
869                 p = pfindn((pid_t)name[0]);
870                 if (p == NULL)
871                         goto post_threads;
872                 if (!PRISON_CHECK(cr1, p->p_ucred))
873                         goto post_threads;
874                 PHOLD(p);
875                 error = sysctl_out_proc(p, req, flags);
876                 PRELE(p);
877                 goto post_threads;
878         }
879
880         if (!req->oldptr) {
881                 /* overestimate by 5 procs */
882                 error = SYSCTL_OUT(req, 0, sizeof (struct kinfo_proc) * 5);
883                 if (error)
884                         goto post_threads;
885         }
886         for (doingzomb = 0; doingzomb <= 1; doingzomb++) {
887                 if (doingzomb)
888                         plist = &zombproc;
889                 else
890                         plist = &allproc;
891                 LIST_FOREACH(p, plist, p_list) {
892                         /*
893                          * Show a user only their processes.
894                          */
895                         if ((!ps_showallprocs) && p_trespass(cr1, p->p_ucred))
896                                 continue;
897                         /*
898                          * Skip embryonic processes.
899                          */
900                         if (p->p_stat == SIDL)
901                                 continue;
902                         /*
903                          * TODO - make more efficient (see notes below).
904                          * do by session.
905                          */
906                         switch (oid) {
907                         case KERN_PROC_PGRP:
908                                 /* could do this by traversing pgrp */
909                                 if (p->p_pgrp == NULL || 
910                                     p->p_pgrp->pg_id != (pid_t)name[0])
911                                         continue;
912                                 break;
913
914                         case KERN_PROC_TTY:
915                                 if ((p->p_flag & P_CONTROLT) == 0 ||
916                                     p->p_session == NULL ||
917                                     p->p_session->s_ttyp == NULL ||
918                                     dev2udev(p->p_session->s_ttyp->t_dev) != 
919                                         (udev_t)name[0])
920                                         continue;
921                                 break;
922
923                         case KERN_PROC_UID:
924                                 if (p->p_ucred == NULL || 
925                                     p->p_ucred->cr_uid != (uid_t)name[0])
926                                         continue;
927                                 break;
928
929                         case KERN_PROC_RUID:
930                                 if (p->p_ucred == NULL || 
931                                     p->p_ucred->cr_ruid != (uid_t)name[0])
932                                         continue;
933                                 break;
934                         }
935
936                         if (!PRISON_CHECK(cr1, p->p_ucred))
937                                 continue;
938                         PHOLD(p);
939                         error = sysctl_out_proc(p, req, flags);
940                         PRELE(p);
941                         if (error)
942                                 goto post_threads;
943                 }
944         }
945
946         /*
947          * Iterate over all active cpus and scan their thread list.  Start
948          * with the next logical cpu and end with our original cpu.  We
949          * migrate our own thread to each target cpu in order to safely scan
950          * its thread list.  In the last loop we migrate back to our original
951          * cpu.
952          */
953         origcpu = mycpu->gd_cpuid;
954         if (!ps_showallthreads || jailed(cr1))
955                 goto post_threads;
956
957         for (n = 1; n <= ncpus; ++n) {
958                 globaldata_t rgd;
959                 int nid;
960
961                 nid = (origcpu + n) % ncpus;
962                 if ((smp_active_mask & CPUMASK(nid)) == 0)
963                         continue;
964                 rgd = globaldata_find(nid);
965                 lwkt_setcpu_self(rgd);
966
967                 TAILQ_FOREACH(td, &mycpu->gd_tdallq, td_allq) {
968                         if (td->td_proc)
969                                 continue;
970                         switch (oid) {
971                         case KERN_PROC_PGRP:
972                         case KERN_PROC_TTY:
973                         case KERN_PROC_UID:
974                         case KERN_PROC_RUID:
975                                 continue;
976                         default:
977                                 break;
978                         }
979                         lwkt_hold(td);
980                         error = sysctl_out_proc_kthread(td, req, doingzomb);
981                         lwkt_rele(td);
982                         if (error)
983                                 goto post_threads;
984                 }
985         }
986 post_threads:
987         lwkt_reltoken(&proc_token);
988         return (error);
989 }
990
991 /*
992  * This sysctl allows a process to retrieve the argument list or process
993  * title for another process without groping around in the address space
994  * of the other process.  It also allow a process to set its own "process 
995  * title to a string of its own choice.
996  *
997  * No requirements.
998  */
999 static int
1000 sysctl_kern_proc_args(SYSCTL_HANDLER_ARGS)
1001 {
1002         int *name = (int*) arg1;
1003         u_int namelen = arg2;
1004         struct proc *p;
1005         struct pargs *pa;
1006         int error = 0;
1007         struct ucred *cr1 = curproc->p_ucred;
1008
1009         if (namelen != 1) 
1010                 return (EINVAL);
1011
1012         lwkt_gettoken(&proc_token);
1013         p = pfindn((pid_t)name[0]);
1014         if (p == NULL)
1015                 goto done;
1016
1017         if ((!ps_argsopen) && p_trespass(cr1, p->p_ucred))
1018                 goto done;
1019
1020         if (req->newptr && curproc != p) {
1021                 error = EPERM;
1022                 goto done;
1023         }
1024
1025         PHOLD(p);
1026         if (req->oldptr && p->p_args != NULL) {
1027                 error = SYSCTL_OUT(req, p->p_args->ar_args,
1028                                    p->p_args->ar_length);
1029         }
1030         if (req->newptr == NULL) {
1031                 PRELE(p);
1032                 goto done;
1033         }
1034
1035         if (p->p_args && --p->p_args->ar_ref == 0) 
1036                 FREE(p->p_args, M_PARGS);
1037         p->p_args = NULL;
1038
1039         if (req->newlen + sizeof(struct pargs) > ps_arg_cache_limit) {
1040                 PRELE(p);
1041                 goto done;
1042         }
1043
1044         MALLOC(pa, struct pargs *, sizeof(struct pargs) + req->newlen, 
1045                M_PARGS, M_WAITOK);
1046         pa->ar_ref = 1;
1047         pa->ar_length = req->newlen;
1048         error = SYSCTL_IN(req, pa->ar_args, req->newlen);
1049         if (!error)
1050                 p->p_args = pa;
1051         else
1052                 FREE(pa, M_PARGS);
1053         PRELE(p);
1054 done:
1055         lwkt_reltoken(&proc_token);
1056         return (error);
1057 }
1058
1059 static int
1060 sysctl_kern_proc_cwd(SYSCTL_HANDLER_ARGS)
1061 {
1062         int *name = (int*) arg1;
1063         u_int namelen = arg2;
1064         struct proc *p;
1065         int error = 0;
1066         char *fullpath, *freepath;
1067         struct ucred *cr1 = curproc->p_ucred;
1068
1069         if (namelen != 1) 
1070                 return (EINVAL);
1071
1072         lwkt_gettoken(&proc_token);
1073         p = pfindn((pid_t)name[0]);
1074         if (p == NULL)
1075                 goto done;
1076
1077         /*
1078          * If we are not allowed to see other args, we certainly shouldn't
1079          * get the cwd either. Also check the usual trespassing.
1080          */
1081         if ((!ps_argsopen) && p_trespass(cr1, p->p_ucred))
1082                 goto done;
1083
1084         PHOLD(p);
1085         if (req->oldptr && p->p_fd != NULL) {
1086                 error = cache_fullpath(p, &p->p_fd->fd_ncdir,
1087                     &fullpath, &freepath, 0);
1088                 if (error)
1089                         goto done;
1090                 error = SYSCTL_OUT(req, fullpath, strlen(fullpath) + 1);
1091                 kfree(freepath, M_TEMP);
1092         }
1093
1094         PRELE(p);
1095
1096 done:
1097         lwkt_reltoken(&proc_token);
1098         return (error);
1099 }
1100
1101 SYSCTL_NODE(_kern, KERN_PROC, proc, CTLFLAG_RD,  0, "Process table");
1102
1103 SYSCTL_PROC(_kern_proc, KERN_PROC_ALL, all, CTLFLAG_RD|CTLTYPE_STRUCT,
1104         0, 0, sysctl_kern_proc, "S,proc", "Return entire process table");
1105
1106 SYSCTL_NODE(_kern_proc, KERN_PROC_PGRP, pgrp, CTLFLAG_RD, 
1107         sysctl_kern_proc, "Process table");
1108
1109 SYSCTL_NODE(_kern_proc, KERN_PROC_TTY, tty, CTLFLAG_RD, 
1110         sysctl_kern_proc, "Process table");
1111
1112 SYSCTL_NODE(_kern_proc, KERN_PROC_UID, uid, CTLFLAG_RD, 
1113         sysctl_kern_proc, "Process table");
1114
1115 SYSCTL_NODE(_kern_proc, KERN_PROC_RUID, ruid, CTLFLAG_RD, 
1116         sysctl_kern_proc, "Process table");
1117
1118 SYSCTL_NODE(_kern_proc, KERN_PROC_PID, pid, CTLFLAG_RD, 
1119         sysctl_kern_proc, "Process table");
1120
1121 SYSCTL_NODE(_kern_proc, (KERN_PROC_ALL | KERN_PROC_FLAG_LWP), all_lwp, CTLFLAG_RD,
1122         sysctl_kern_proc, "Process table");
1123
1124 SYSCTL_NODE(_kern_proc, (KERN_PROC_PGRP | KERN_PROC_FLAG_LWP), pgrp_lwp, CTLFLAG_RD, 
1125         sysctl_kern_proc, "Process table");
1126
1127 SYSCTL_NODE(_kern_proc, (KERN_PROC_TTY | KERN_PROC_FLAG_LWP), tty_lwp, CTLFLAG_RD, 
1128         sysctl_kern_proc, "Process table");
1129
1130 SYSCTL_NODE(_kern_proc, (KERN_PROC_UID | KERN_PROC_FLAG_LWP), uid_lwp, CTLFLAG_RD, 
1131         sysctl_kern_proc, "Process table");
1132
1133 SYSCTL_NODE(_kern_proc, (KERN_PROC_RUID | KERN_PROC_FLAG_LWP), ruid_lwp, CTLFLAG_RD, 
1134         sysctl_kern_proc, "Process table");
1135
1136 SYSCTL_NODE(_kern_proc, (KERN_PROC_PID | KERN_PROC_FLAG_LWP), pid_lwp, CTLFLAG_RD, 
1137         sysctl_kern_proc, "Process table");
1138
1139 SYSCTL_NODE(_kern_proc, KERN_PROC_ARGS, args, CTLFLAG_RW | CTLFLAG_ANYBODY,
1140         sysctl_kern_proc_args, "Process argument list");
1141
1142 SYSCTL_NODE(_kern_proc, KERN_PROC_CWD, cwd, CTLFLAG_RD | CTLFLAG_ANYBODY,
1143         sysctl_kern_proc_cwd, "Process argument list");