Merge branch 'vendor/BINUTILS_ALL'
[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                         pgrp->pg_session = sess;
295                         KASSERT(p == curproc,
296                                 ("enterpgrp: mksession and p != curproc"));
297                         lwkt_gettoken(&p->p_token);
298                         p->p_flags &= ~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  * Caller must hold p->p_token.  We are required to wait until p_lock
638  * becomes zero before we can manipulate the list, allowing allproc
639  * scans to guarantee consistency during a list scan.
640  */
641 void
642 proc_move_allproc_zombie(struct proc *p)
643 {
644         lwkt_gettoken(&proc_token);
645         while (p->p_lock) {
646                 tsleep(p, 0, "reap1", hz / 10);
647         }
648         LIST_REMOVE(p, p_list);
649         LIST_INSERT_HEAD(&zombproc, p, p_list);
650         LIST_REMOVE(p, p_hash);
651         p->p_stat = SZOMB;
652         lwkt_reltoken(&proc_token);
653         dsched_exit_proc(p);
654 }
655
656 /*
657  * This routine is called from kern_wait() and will remove the process
658  * from the zombie list and the sibling list.  This routine will block
659  * if someone has a lock on the proces (p_lock).
660  *
661  * Caller must hold p->p_token.  We are required to wait until p_lock
662  * becomes zero before we can manipulate the list, allowing allproc
663  * scans to guarantee consistency during a list scan.
664  */
665 void
666 proc_remove_zombie(struct proc *p)
667 {
668         lwkt_gettoken(&proc_token);
669         while (p->p_lock) {
670                 tsleep(p, 0, "reap2", hz / 10);
671         }
672         LIST_REMOVE(p, p_list); /* off zombproc */
673         LIST_REMOVE(p, p_sibling);
674         lwkt_reltoken(&proc_token);
675 }
676
677 /*
678  * Scan all processes on the allproc list.  The process is automatically
679  * held for the callback.  A return value of -1 terminates the loop.
680  *
681  * The callback is made with the process held and proc_token held.
682  *
683  * We limit the scan to the number of processes as-of the start of
684  * the scan so as not to get caught up in an endless loop if new processes
685  * are created more quickly than we can scan the old ones.  Add a little
686  * slop to try to catch edge cases since nprocs can race.
687  *
688  * No requirements.
689  */
690 void
691 allproc_scan(int (*callback)(struct proc *, void *), void *data)
692 {
693         struct proc *p;
694         int r;
695         int limit = nprocs + ncpus;
696
697         /*
698          * proc_token protects the allproc list and PHOLD() prevents the
699          * process from being removed from the allproc list or the zombproc
700          * list.
701          */
702         lwkt_gettoken(&proc_token);
703         LIST_FOREACH(p, &allproc, p_list) {
704                 PHOLD(p);
705                 r = callback(p, data);
706                 PRELE(p);
707                 if (r < 0)
708                         break;
709                 if (--limit < 0)
710                         break;
711         }
712         lwkt_reltoken(&proc_token);
713 }
714
715 /*
716  * Scan all lwps of processes on the allproc list.  The lwp is automatically
717  * held for the callback.  A return value of -1 terminates the loop.
718  *
719  * The callback is made with the proces and lwp both held, and proc_token held.
720  *
721  * No requirements.
722  */
723 void
724 alllwp_scan(int (*callback)(struct lwp *, void *), void *data)
725 {
726         struct proc *p;
727         struct lwp *lp;
728         int r = 0;
729
730         /*
731          * proc_token protects the allproc list and PHOLD() prevents the
732          * process from being removed from the allproc list or the zombproc
733          * list.
734          */
735         lwkt_gettoken(&proc_token);
736         LIST_FOREACH(p, &allproc, p_list) {
737                 PHOLD(p);
738                 FOREACH_LWP_IN_PROC(lp, p) {
739                         LWPHOLD(lp);
740                         r = callback(lp, data);
741                         LWPRELE(lp);
742                 }
743                 PRELE(p);
744                 if (r < 0)
745                         break;
746         }
747         lwkt_reltoken(&proc_token);
748 }
749
750 /*
751  * Scan all processes on the zombproc list.  The process is automatically
752  * held for the callback.  A return value of -1 terminates the loop.
753  *
754  * No requirements.
755  * The callback is made with the proces held and proc_token held.
756  */
757 void
758 zombproc_scan(int (*callback)(struct proc *, void *), void *data)
759 {
760         struct proc *p;
761         int r;
762
763         lwkt_gettoken(&proc_token);
764         LIST_FOREACH(p, &zombproc, p_list) {
765                 PHOLD(p);
766                 r = callback(p, data);
767                 PRELE(p);
768                 if (r < 0)
769                         break;
770         }
771         lwkt_reltoken(&proc_token);
772 }
773
774 #include "opt_ddb.h"
775 #ifdef DDB
776 #include <ddb/ddb.h>
777
778 /*
779  * Debugging only
780  */
781 DB_SHOW_COMMAND(pgrpdump, pgrpdump)
782 {
783         struct pgrp *pgrp;
784         struct proc *p;
785         int i;
786
787         for (i = 0; i <= pgrphash; i++) {
788                 if (!LIST_EMPTY(&pgrphashtbl[i])) {
789                         kprintf("\tindx %d\n", i);
790                         LIST_FOREACH(pgrp, &pgrphashtbl[i], pg_hash) {
791                                 kprintf(
792                         "\tpgrp %p, pgid %ld, sess %p, sesscnt %d, mem %p\n",
793                                     (void *)pgrp, (long)pgrp->pg_id,
794                                     (void *)pgrp->pg_session,
795                                     pgrp->pg_session->s_count,
796                                     (void *)LIST_FIRST(&pgrp->pg_members));
797                                 LIST_FOREACH(p, &pgrp->pg_members, p_pglist) {
798                                         kprintf("\t\tpid %ld addr %p pgrp %p\n", 
799                                             (long)p->p_pid, (void *)p,
800                                             (void *)p->p_pgrp);
801                                 }
802                         }
803                 }
804         }
805 }
806 #endif /* DDB */
807
808 /*
809  * Locate a process on the zombie list.  Return a process or NULL.
810  * The returned process will be referenced and the caller must release
811  * it with PRELE().
812  *
813  * No other requirements.
814  */
815 struct proc *
816 zpfind(pid_t pid)
817 {
818         struct proc *p;
819
820         lwkt_gettoken(&proc_token);
821         LIST_FOREACH(p, &zombproc, p_list) {
822                 if (p->p_pid == pid) {
823                         PHOLD(p);
824                         lwkt_reltoken(&proc_token);
825                         return (p);
826                 }
827         }
828         lwkt_reltoken(&proc_token);
829         return (NULL);
830 }
831
832 /*
833  * The caller must hold proc_token.
834  */
835 static int
836 sysctl_out_proc(struct proc *p, struct sysctl_req *req, int flags)
837 {
838         struct kinfo_proc ki;
839         struct lwp *lp;
840         int skp = 0, had_output = 0;
841         int error;
842
843         bzero(&ki, sizeof(ki));
844         lwkt_gettoken(&p->p_token);
845         fill_kinfo_proc(p, &ki);
846         if ((flags & KERN_PROC_FLAG_LWP) == 0)
847                 skp = 1;
848         error = 0;
849         FOREACH_LWP_IN_PROC(lp, p) {
850                 LWPHOLD(lp);
851                 fill_kinfo_lwp(lp, &ki.kp_lwp);
852                 had_output = 1;
853                 error = SYSCTL_OUT(req, &ki, sizeof(ki));
854                 LWPRELE(lp);
855                 if (error)
856                         break;
857                 if (skp)
858                         break;
859         }
860         lwkt_reltoken(&p->p_token);
861         /* We need to output at least the proc, even if there is no lwp. */
862         if (had_output == 0) {
863                 error = SYSCTL_OUT(req, &ki, sizeof(ki));
864         }
865         return (error);
866 }
867
868 /*
869  * The caller must hold proc_token.
870  */
871 static int
872 sysctl_out_proc_kthread(struct thread *td, struct sysctl_req *req, int flags)
873 {
874         struct kinfo_proc ki;
875         int error;
876
877         fill_kinfo_proc_kthread(td, &ki);
878         error = SYSCTL_OUT(req, &ki, sizeof(ki));
879         if (error)
880                 return error;
881         return(0);
882 }
883
884 /*
885  * No requirements.
886  */
887 static int
888 sysctl_kern_proc(SYSCTL_HANDLER_ARGS)
889 {
890         int *name = (int*) arg1;
891         int oid = oidp->oid_number;
892         u_int namelen = arg2;
893         struct proc *p;
894         struct proclist *plist;
895         struct thread *td;
896         struct thread *marker;
897         int doingzomb, flags = 0;
898         int error = 0;
899         int n;
900         int origcpu;
901         struct ucred *cr1 = curproc->p_ucred;
902
903         flags = oid & KERN_PROC_FLAGMASK;
904         oid &= ~KERN_PROC_FLAGMASK;
905
906         if ((oid == KERN_PROC_ALL && namelen != 0) ||
907             (oid != KERN_PROC_ALL && namelen != 1)) {
908                 return (EINVAL);
909         }
910
911         /*
912          * proc_token protects the allproc list and PHOLD() prevents the
913          * process from being removed from the allproc list or the zombproc
914          * list.
915          */
916         lwkt_gettoken(&proc_token);
917         if (oid == KERN_PROC_PID) {
918                 p = pfindn((pid_t)name[0]);
919                 if (p == NULL)
920                         goto post_threads;
921                 if (!PRISON_CHECK(cr1, p->p_ucred))
922                         goto post_threads;
923                 PHOLD(p);
924                 error = sysctl_out_proc(p, req, flags);
925                 PRELE(p);
926                 goto post_threads;
927         }
928
929         if (!req->oldptr) {
930                 /* overestimate by 5 procs */
931                 error = SYSCTL_OUT(req, 0, sizeof (struct kinfo_proc) * 5);
932                 if (error)
933                         goto post_threads;
934         }
935         for (doingzomb = 0; doingzomb <= 1; doingzomb++) {
936                 if (doingzomb)
937                         plist = &zombproc;
938                 else
939                         plist = &allproc;
940                 LIST_FOREACH(p, plist, p_list) {
941                         /*
942                          * Show a user only their processes.
943                          */
944                         if ((!ps_showallprocs) && p_trespass(cr1, p->p_ucred))
945                                 continue;
946                         /*
947                          * Skip embryonic processes.
948                          */
949                         if (p->p_stat == SIDL)
950                                 continue;
951                         /*
952                          * TODO - make more efficient (see notes below).
953                          * do by session.
954                          */
955                         switch (oid) {
956                         case KERN_PROC_PGRP:
957                                 /* could do this by traversing pgrp */
958                                 if (p->p_pgrp == NULL || 
959                                     p->p_pgrp->pg_id != (pid_t)name[0])
960                                         continue;
961                                 break;
962
963                         case KERN_PROC_TTY:
964                                 if ((p->p_flags & P_CONTROLT) == 0 ||
965                                     p->p_session == NULL ||
966                                     p->p_session->s_ttyp == NULL ||
967                                     dev2udev(p->p_session->s_ttyp->t_dev) != 
968                                         (udev_t)name[0])
969                                         continue;
970                                 break;
971
972                         case KERN_PROC_UID:
973                                 if (p->p_ucred == NULL || 
974                                     p->p_ucred->cr_uid != (uid_t)name[0])
975                                         continue;
976                                 break;
977
978                         case KERN_PROC_RUID:
979                                 if (p->p_ucred == NULL || 
980                                     p->p_ucred->cr_ruid != (uid_t)name[0])
981                                         continue;
982                                 break;
983                         }
984
985                         if (!PRISON_CHECK(cr1, p->p_ucred))
986                                 continue;
987                         PHOLD(p);
988                         error = sysctl_out_proc(p, req, flags);
989                         PRELE(p);
990                         if (error)
991                                 goto post_threads;
992                 }
993         }
994
995         /*
996          * Iterate over all active cpus and scan their thread list.  Start
997          * with the next logical cpu and end with our original cpu.  We
998          * migrate our own thread to each target cpu in order to safely scan
999          * its thread list.  In the last loop we migrate back to our original
1000          * cpu.
1001          */
1002         origcpu = mycpu->gd_cpuid;
1003         if (!ps_showallthreads || jailed(cr1))
1004                 goto post_threads;
1005
1006         marker = kmalloc(sizeof(struct thread), M_TEMP, M_WAITOK|M_ZERO);
1007         marker->td_flags = TDF_MARKER;
1008         error = 0;
1009
1010         for (n = 1; n <= ncpus; ++n) {
1011                 globaldata_t rgd;
1012                 int nid;
1013
1014                 nid = (origcpu + n) % ncpus;
1015                 if ((smp_active_mask & CPUMASK(nid)) == 0)
1016                         continue;
1017                 rgd = globaldata_find(nid);
1018                 lwkt_setcpu_self(rgd);
1019
1020                 crit_enter();
1021                 TAILQ_INSERT_TAIL(&rgd->gd_tdallq, marker, td_allq);
1022
1023                 while ((td = TAILQ_PREV(marker, lwkt_queue, td_allq)) != NULL) {
1024                         TAILQ_REMOVE(&rgd->gd_tdallq, marker, td_allq);
1025                         TAILQ_INSERT_BEFORE(td, marker, td_allq);
1026                         if (td->td_flags & TDF_MARKER)
1027                                 continue;
1028                         if (td->td_proc)
1029                                 continue;
1030
1031                         lwkt_hold(td);
1032                         crit_exit();
1033
1034                         switch (oid) {
1035                         case KERN_PROC_PGRP:
1036                         case KERN_PROC_TTY:
1037                         case KERN_PROC_UID:
1038                         case KERN_PROC_RUID:
1039                                 break;
1040                         default:
1041                                 error = sysctl_out_proc_kthread(td, req,
1042                                                                 doingzomb);
1043                                 break;
1044                         }
1045                         lwkt_rele(td);
1046                         crit_enter();
1047                         if (error)
1048                                 break;
1049                 }
1050                 TAILQ_REMOVE(&rgd->gd_tdallq, marker, td_allq);
1051                 crit_exit();
1052
1053                 if (error)
1054                         break;
1055         }
1056         kfree(marker, M_TEMP);
1057
1058 post_threads:
1059         lwkt_reltoken(&proc_token);
1060         return (error);
1061 }
1062
1063 /*
1064  * This sysctl allows a process to retrieve the argument list or process
1065  * title for another process without groping around in the address space
1066  * of the other process.  It also allow a process to set its own "process 
1067  * title to a string of its own choice.
1068  *
1069  * No requirements.
1070  */
1071 static int
1072 sysctl_kern_proc_args(SYSCTL_HANDLER_ARGS)
1073 {
1074         int *name = (int*) arg1;
1075         u_int namelen = arg2;
1076         struct proc *p;
1077         struct pargs *opa;
1078         struct pargs *pa;
1079         int error = 0;
1080         struct ucred *cr1 = curproc->p_ucred;
1081
1082         if (namelen != 1) 
1083                 return (EINVAL);
1084
1085         p = pfind((pid_t)name[0]);
1086         if (p == NULL)
1087                 goto done;
1088         lwkt_gettoken(&p->p_token);
1089
1090         if ((!ps_argsopen) && p_trespass(cr1, p->p_ucred))
1091                 goto done;
1092
1093         if (req->newptr && curproc != p) {
1094                 error = EPERM;
1095                 goto done;
1096         }
1097         if (req->oldptr && (pa = p->p_args) != NULL) {
1098                 refcount_acquire(&pa->ar_ref);
1099                 error = SYSCTL_OUT(req, pa->ar_args, pa->ar_length);
1100                 if (refcount_release(&pa->ar_ref))
1101                         kfree(pa, M_PARGS);
1102         }
1103         if (req->newptr == NULL)
1104                 goto done;
1105
1106         if (req->newlen + sizeof(struct pargs) > ps_arg_cache_limit) {
1107                 goto done;
1108         }
1109
1110         pa = kmalloc(sizeof(struct pargs) + req->newlen, M_PARGS, M_WAITOK);
1111         refcount_init(&pa->ar_ref, 1);
1112         pa->ar_length = req->newlen;
1113         error = SYSCTL_IN(req, pa->ar_args, req->newlen);
1114         if (error) {
1115                 kfree(pa, M_PARGS);
1116                 goto done;
1117         }
1118
1119
1120         /*
1121          * Replace p_args with the new pa.  p_args may have previously
1122          * been NULL.
1123          */
1124         opa = p->p_args;
1125         p->p_args = pa;
1126
1127         if (opa) {
1128                 KKASSERT(opa->ar_ref > 0);
1129                 if (refcount_release(&opa->ar_ref)) {
1130                         kfree(opa, M_PARGS);
1131                         /* opa = NULL; */
1132                 }
1133         }
1134 done:
1135         if (p) {
1136                 lwkt_reltoken(&p->p_token);
1137                 PRELE(p);
1138         }
1139         return (error);
1140 }
1141
1142 static int
1143 sysctl_kern_proc_cwd(SYSCTL_HANDLER_ARGS)
1144 {
1145         int *name = (int*) arg1;
1146         u_int namelen = arg2;
1147         struct proc *p;
1148         int error = 0;
1149         char *fullpath, *freepath;
1150         struct ucred *cr1 = curproc->p_ucred;
1151
1152         if (namelen != 1) 
1153                 return (EINVAL);
1154
1155         p = pfind((pid_t)name[0]);
1156         if (p == NULL)
1157                 goto done;
1158         lwkt_gettoken(&p->p_token);
1159
1160         /*
1161          * If we are not allowed to see other args, we certainly shouldn't
1162          * get the cwd either. Also check the usual trespassing.
1163          */
1164         if ((!ps_argsopen) && p_trespass(cr1, p->p_ucred))
1165                 goto done;
1166
1167         if (req->oldptr && p->p_fd != NULL && p->p_fd->fd_ncdir.ncp) {
1168                 struct nchandle nch;
1169
1170                 cache_copy(&p->p_fd->fd_ncdir, &nch);
1171                 error = cache_fullpath(p, &nch, &fullpath, &freepath, 0);
1172                 cache_drop(&nch);
1173                 if (error)
1174                         goto done;
1175                 error = SYSCTL_OUT(req, fullpath, strlen(fullpath) + 1);
1176                 kfree(freepath, M_TEMP);
1177         }
1178
1179 done:
1180         if (p) {
1181                 lwkt_reltoken(&p->p_token);
1182                 PRELE(p);
1183         }
1184         return (error);
1185 }
1186
1187 SYSCTL_NODE(_kern, KERN_PROC, proc, CTLFLAG_RD,  0, "Process table");
1188
1189 SYSCTL_PROC(_kern_proc, KERN_PROC_ALL, all, CTLFLAG_RD|CTLTYPE_STRUCT,
1190         0, 0, sysctl_kern_proc, "S,proc", "Return entire process table");
1191
1192 SYSCTL_NODE(_kern_proc, KERN_PROC_PGRP, pgrp, CTLFLAG_RD, 
1193         sysctl_kern_proc, "Process table");
1194
1195 SYSCTL_NODE(_kern_proc, KERN_PROC_TTY, tty, CTLFLAG_RD, 
1196         sysctl_kern_proc, "Process table");
1197
1198 SYSCTL_NODE(_kern_proc, KERN_PROC_UID, uid, CTLFLAG_RD, 
1199         sysctl_kern_proc, "Process table");
1200
1201 SYSCTL_NODE(_kern_proc, KERN_PROC_RUID, ruid, CTLFLAG_RD, 
1202         sysctl_kern_proc, "Process table");
1203
1204 SYSCTL_NODE(_kern_proc, KERN_PROC_PID, pid, CTLFLAG_RD, 
1205         sysctl_kern_proc, "Process table");
1206
1207 SYSCTL_NODE(_kern_proc, (KERN_PROC_ALL | KERN_PROC_FLAG_LWP), all_lwp, CTLFLAG_RD,
1208         sysctl_kern_proc, "Process table");
1209
1210 SYSCTL_NODE(_kern_proc, (KERN_PROC_PGRP | KERN_PROC_FLAG_LWP), pgrp_lwp, CTLFLAG_RD, 
1211         sysctl_kern_proc, "Process table");
1212
1213 SYSCTL_NODE(_kern_proc, (KERN_PROC_TTY | KERN_PROC_FLAG_LWP), tty_lwp, CTLFLAG_RD, 
1214         sysctl_kern_proc, "Process table");
1215
1216 SYSCTL_NODE(_kern_proc, (KERN_PROC_UID | KERN_PROC_FLAG_LWP), uid_lwp, CTLFLAG_RD, 
1217         sysctl_kern_proc, "Process table");
1218
1219 SYSCTL_NODE(_kern_proc, (KERN_PROC_RUID | KERN_PROC_FLAG_LWP), ruid_lwp, CTLFLAG_RD, 
1220         sysctl_kern_proc, "Process table");
1221
1222 SYSCTL_NODE(_kern_proc, (KERN_PROC_PID | KERN_PROC_FLAG_LWP), pid_lwp, CTLFLAG_RD, 
1223         sysctl_kern_proc, "Process table");
1224
1225 SYSCTL_NODE(_kern_proc, KERN_PROC_ARGS, args, CTLFLAG_RW | CTLFLAG_ANYBODY,
1226         sysctl_kern_proc_args, "Process argument list");
1227
1228 SYSCTL_NODE(_kern_proc, KERN_PROC_CWD, cwd, CTLFLAG_RD | CTLFLAG_ANYBODY,
1229         sysctl_kern_proc_cwd, "Process argument list");