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